From 02ee1e8fa1cfab02d6f3180dde2a71eca0525321 Mon Sep 17 00:00:00 2001 From: sauilitired Date: Fri, 10 Aug 2018 16:52:35 +0200 Subject: [PATCH 01/42] Update README.md and commit code style --- README.md | 37 +++-- chinese.yml | 375 ------------------------------------------------- code_style.xml | 337 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 363 insertions(+), 386 deletions(-) delete mode 100644 chinese.yml create mode 100644 code_style.xml diff --git a/README.md b/README.md index 7443d1464..6617e62c8 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ -# PlotSquared [![forthebadge](http://forthebadge.com/images/badges/built-by-developers.svg)](http://forthebadge.com) - -[![Join the chat at https://gitter.im/PlotSquared/Lobby](https://badges.gitter.im/PlotSquared/Lobby.svg)](https://gitter.im/PlotSquared/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# PlotSquared + For the end user, PlotSquared is packed with a tonne of cool features. It allows you to merge plots, and build together with your friends. You can also change a lot of plot specific settings in the form of -flags. Such as: weather, time, gamemodes, pvp status. +flags. Such as: weather, time, game modes, pvp status. Whilst we provide a whole load of unique features, the biggest focus is to provide a lag-free and smooth experience. @@ -13,21 +12,39 @@ is to provide a lag-free and smooth experience. ### Server Owner * [Spigot Page](https://www.spigotmc.org/resources/plotsquared.1177/) +* [Discord](https://discord.gg/a6NZPV2) * [WebChat/IRC]: #IntellectualCrafters on irc.esper.net * [Wiki](https://github.com/intellectualcrafters/plotsquared/wiki) -* [Website](http://plotsquared.com) ### Developer Resources * [JavaDocs] Link Temporarily Unavailable -* [Build Server] [![Build Status](http://ci.plotsquared.com/buildStatus/icon?job=PlotSquared)](http://ci.athion.net/job/PlotSquared/) -* [Maven Repo] Link Temporarily Unavailable +* [Build Server](http://ci.athion.net/job/PlotSquared/) +* [Maven Repo](http://ci.athion.net/job/PlotSquared/ws/mvn/) # Building Gradle is the **recommended** way to build the project. Use `./gradlew build` in the main project directory to build the project. Gradle is required if you intend to build or develop the Sponge module. If you prefer to use maven, a `pom.xml` file is provided for working with the Bukkit part of the plugin. # Contributing -Feel free to contribute, if you feel like you can improve the plugin in any way. Make sure to test your code before sending it away from us, as committing broken code will block you from future contribution. +If you feel like you can improve the plugin any way, then you are +more than welcome to contribute to PlotSquared. It would be highly +appreciated if you made sure to test your code before committing it, +as it will save us a lot of time and effort. + +### Code Style + +If you are planning to commit any changes to the project, +it would be highly appreciated if you were to follow the +project code style conventions. To make this easier we have +provided settings that can be imported into your IDE. + +**Eclipse:** +`Window > Preferences > Java > Code Style > Formatter` +Press `Import` and select `...path/to/project/code_style.xml` + +**IntelliJ:** +`File > Settings > Editor > Code Style`. Next to "Scheme" there is a cog wheel, press that and then +`Import Scheme > IntelliJ IDEA Code Style XML` and then select `..path/to/project/code_style.xml` # Official Addons * [Plot2Dynmap](http://www.spigotmc.org/resources/plot2dynmap.1292/) @@ -38,6 +55,4 @@ Feel free to contribute, if you feel like you can improve the plugin in any way. * [BiomeGenerator](https://www.spigotmc.org/resources/biomegenerator.1663/) * [PlotSquaredMG](https://www.spigotmc.org/resources/plotsquaredmg.8025/) * [BasicPlots](https://www.spigotmc.org/resources/basicplots.6901/) -* [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/) - -[WebChat/IRC]: http://webchat.esper.net/?nick=&channels=IntellectualCrafters&fg_color=000&fg_sec_color=000&bg_color=FFF +* [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/) \ No newline at end of file diff --git a/chinese.yml b/chinese.yml deleted file mode 100644 index 41794c6da..000000000 --- a/chinese.yml +++ /dev/null @@ -1,375 +0,0 @@ -confirm: - failed_confirm: $2你当前没有可以接受的行动! - requires_confirm: '$2你是否要执行: $1%s$2?&-$2该操作不可逆! 如果确定请输入: $1/plot confirm' -move: - move_success: $4成功的移动了地皮。 - copy_success: $4成功的复制了地皮。 - requires_unowned: $2你指定的位置已被占用。 -set: - set_attribute: $4成功将 %s0 设置为 %s1 -web: - generating_link: $1处理地皮中... - generating_link_failed: $2创建下载链接失败了! - save_failed: $2保存失败 - load_null: $2请使用 $4/plot load $2来获取模型列表 - load_failed: $2读取模型失败 - load_list: '$2若要读取一个模型,请使用 $1/plot load #' - save_success: $1成功保存! -compass: - compass_target: $4成功的用指南针指向了地皮! -cluster: - cluster_available_args: "'$1下面的子指令是可行的: $4list$2, $4create$2, - $4delete$2, $4resize$2, $4invite$2, $4kick$2, $4leave$2, $4members$2, $4info$2, - $4tp$2, $4sethome'" - cluster_list_heading: "$2在这个世界中有 $1%s$2 个地皮群" - cluster_list_element: "$2 - $1%s&-" - cluster_intersection: "$2目标区域被 %s0 覆盖'" - cluster_added: "$4成功的创建了群。" - cluster_deleted: "$4成功的删除了群。" - cluster_resized: "$4成功为群重新设置大小。" - cluster_added_user: "$4成功为群增加用户。" - cannot_kick_player: "$2你不能从地皮中移除那位玩家!" - cluster_invited: "$1你被邀请去下列群: $2%s" - cluster_removed: "$1你被该群移除: $2%s" - cluster_kicked_user: "$4成功移除了用户。" - invalid_cluster: "'$1不合法的群名称: $2%s'" - cluster_not_added: "$2那个玩家没有被添加到地皮群中" - cluster_cannot_leave: "$1你在离开之前必须删除或转让群" - cluster_added_helper: "$4成功为地皮群增加了援建者" - cluster_removed_helper: "$4成功为地皮群移除了一位援建者" - cluster_regenerated: "$4成功的开始了地皮群重建任务" - cluster_teleporting: "$4传送中..." - cluster_info: "'$1当前群: $2%id%&-$1名称: $2%name%&-$1所有者: $2%owner%&-$1大小: - $2%size%&-$1权利: $2%rights%'" -border: - border: $2你在当前地图边界之外 -unclaim: - unclaim_success: $4你成功的放弃了地皮 - unclaim_failed: $2不能放弃地皮 -worldedit masks: - worldedit_delayed: "$2请等待我们处理你的 Worldedit 行动..." - worldedit_run: "'$2请等待当前任务完成。当前正在进行的任务:%s'" - require_selection_in_mask: "$2你当前选择范围中 %s 不是你的地皮,你只能在你自己的地皮上更改。" - worldedit_volume: "$2你目前选区中有 %current%个方块,你最大可以一次性编辑的方块数目为 %max%。" - worldedit_iterations: "$2你不能重复 %current% 次。你可以重复的最大次数为 %max%次。" - worldedit_unsafe: "$2那个指令已被禁用" - worldedit_bypass: "$2&o若要解除你的 Worldedit 限制,输入 $4/plot wea" - worldedit_bypassed: "$2当前解除了你的 WorldEdit 限制" - worldedit_unmasked: "$1你的 WorldEdit 现在被解除限制。" - worldedit_restricted: "$1你的 WorldEdit 现在被限制。" -gamemode: - gamemode_was_bypassed: $1你为地皮 $2{plot} $1跳过了游戏模式 —— ($2{gamemode}$1) $1 -height limit: - height_limit: $1这个地皮的建筑高度限制为 $2{limit} -records: - record_play: $2%player $2开始了 $1%name 的记录 - notify_enter: $2%player $2进入了你的地皮 ($1%plot$2) - notify_leave: $2%player $2离开了你的地皮 ($1%plot$2) -swap: - swap_overlap: $2目标区域不允许被覆盖 - swap_dimensions: $2和目标区域必须拥有相同的世界类型 - swap_syntax: $2/plots swap - swap_success: $4成功的交换了地皮 - started_swap: $2交换地皮任务已开始,你将会在完成后收到通知。 -comment: - inbox_notification: '%s 条未读信息。使用 /plot inbox 来读取' - not_valid_inbox_index: $2在第 %s 页没有信息 - inbox_item: $2 - $4%s - comment_syntax: $2请使用 /plots comment [X;Z] <%s> - invalid_inbox: '$2那不是一个正确的收件箱&-$1允许的值: %s' - no_perm_inbox: $2你没有查看那个收件箱的权限 - no_perm_inbox_modify: $2你没有更改那个收件箱的权限 - no_plot_inbox: $2你必须站在或指定一个地皮参数 - comment_removed: $4成功的删除了评论:$2 - '$3%s$2' - comment_added: $4一条评论被留下 - comment_header: $2&m---------&r $1评论 $2&m---------&r - inbox_empty: $2没有评论 -console: - not_console: $2为了安全,这个指令只能由控制台执行。 - is_console: $2这个指令只能由玩家执行。 -inventory: - inventory_usage: '&c使用: &6{usage}' - inventory_desc: '&c描述: &6{desc}' - inventory_category: '&c类型: &6{category}' -clipboard: - clipboard_set: $2当前地皮已被复制到你的剪切板中,使用 $1/plot paste$2 来粘贴。 - pasted: $4地皮已被成功粘贴。它从你的剪切板中被移除。 - paste_failed: '$2粘贴选中区域时失败了,失败原因: $2%s' - no_clipboard: $2你的剪切板中没有选择。 - clipboard_info: '$2当前选择 - 地皮ID: $1%id$2, 宽度: $1%width$2, 总计方块数:$1%total$2' -toggle: - toggle_enabled: '$2启用设置: %s' - toggle_disabled: '$2禁用设置: %s' -blocked command: - command_blocked: $2在这个地皮中那个指令不被允许 -done: - done_already_done: $2这个地皮已经被标记完成。 - done_not_done: $2这个地皮没有被标记完成。 - done_insufficient_complexity: $2这个地皮太过于简单。请在使用这个指令之前增加增加更多细节。 - done_success: $1成功将地皮标记完成。 - done_removed: $1你现在可以继续在地皮中建筑了。 -ratings: - rating_not_valid: $2你需要在 1 - 10 之前指定一个数字 - rating_already_exists: $2你已经为地皮 $2%s 投过票了 - rating_applied: $4你成功的为地皮 $2%s 投了一票 - rating_not_your_own: $2你不能为自己的地皮投票 - rating_not_done: $2你只能为完成的地皮投票。 - rating_not_owned: $2你不能为无主的地皮投票。 -tutorial: - rate_this: $2为这个地皮投票! - comment_this: '$2为这个地皮留一些反馈: %s' -economy: - econ_disabled: $2现在没有启动经济系统 - cannot_afford_plot: $2你没有足够的钱买这块地皮。它需要花费 $1%s - not_for_sale: $2这块地皮没有出售 - cannot_buy_own: $2你不能购买你自己的地皮 - plot_sold: $4你的地皮 $1%s0$4,以 $1$%s2 的价格被卖给了 $1%s1$4 - cannot_afford_merge: $2你没有足够的钱来合并地皮。它需要花费 $1%s - added_balance: $1%s $2被打入你的账户 - removed_balance: $1%s $2从你的账户取出 - removed_granted_plot: $2你使用了 %s 个地皮授权,你还剩下 $1%s $2个 -setup: - setup_init: '$1请使用: $2/plot setup ' - setup_step: '$3[$1第 %s0 $1步$3] $1%s1 $2- $1参数类型: $2%s2 $1默认值: $2%s3' - setup_invalid_arg: '$2%s0 不是对于第 %s1 步的正确的参数。要想取消设置使用: $1/plot setup cancel' - setup_valid_arg: $2你将值 $1%s0 $2设置为了 %s1 - setup_finished: $4你应该被传送到了创建的世界。否则你需要手动设置在 bukkit.yml 中的世界创建器或者你选择的世界的管理插件。 - setup_world_taken: $2%s 是一个已经创建的地皮世界 - setup_missing_world: $2你需要指定一个世界名($1/plot setup &l$1 $2)&-$1附加指令:&-$2 - $1/plot setup &-$2 - $1/plot setup back&-$2 - $1/plot setup cancel - setup_missing_generator: $2你需要指定一个世界生成器 ($1/plot setup &l&r$2)&-$1附加指令:&-$2 - $1/plot setup &-$2 - $1/plot setup back&-$2 - $1/plot setup cancel - setup_invalid_generator: '$2错误的生成器。正确的生成器有: %s' -schematics: - schematic_too_large: $2这个地皮对此行动太大了! - schematic_missing_arg: '$2你需要制定一个参数。正确的值: $1test $2 , $1save$2 , $1paste $2, $1exportall' - schematic_invalid: '$2那不是一个正确的模板。原因: $2%s' - schematic_valid: $2那是一个正确的模板 - schematic_paste_failed: $2粘贴模板失败了 - schematic_paste_success: $4成功的粘贴了模板 -titles: - title_entered_plot: '$1地皮: %world%;%x%;%z%' - title_entered_plot_sub: $4地皮主人 %s - prefix_greeting: '$1%id%$2> ' - prefix_farewell: '$1%id%$2> ' -core: - task_start: 任务开始... - prefix: $3[$1地皮系统$3] $2 - enabled: $1PlotSquared 现已开启 -reload: - reloaded_configs: $1翻译和世界设置被重新读取 - reload_failed: $2读取文件配置失败 -desc: - desc_set: $2地皮的描述被设置 - desc_unset: $2地皮的描述被重置 - missing_desc: $2你需要指定一个描述 -alias: - alias_set_to: $2地皮简称设置为 $1%alias% - missing_alias: $2你需要指定一个简称 - alias_too_long: $2在长度上简称必须小于50字符 - alias_is_taken: $2已经有地皮命名为那个简称了 -position: - missing_position: '$2你需要指定一个方位。正确的值: ×无×' - position_set: $1将家设置为当前位置 - position_unset: $1家的位置重置到默认位置 - home_argument: $2请使用 /plot set home [none] - invalid_position: $2那不是一个正确的位置的值 -cap: - entity_cap: $2你不能再生成更多怪物了! -time: - time_format: $1%hours%, %min%, %sec% -permission: - no_schematic_permission: $2你没有权限来使用模板 $1%s - no_permission: '$2你没有权限! ($1%s)' - no_permission_event: '$2你没有权限这样做! ($1%s)' - no_plot_perms: $2你需要地皮主人权限 - cant_claim_more_plots: $2你不能再领取更多地皮了 - cant_transfer_more_plots: $2你不能给那个玩家更多地皮了 - cant_claim_more_plots_num: $2你不能同时领取超过 $1%s $2个地皮 - you_be_denied: $2你不能进入那个地皮 - merge_request_confirm: 来自 %s 的地皮合并申请 -merge: - merge_not_valid: $2这个合并请求不再合法 - merge_accepted: $2合并请求被接受 - success_merge: $2地皮成功被合并! - merge_requested: $2成功的发送了一个合并请求 - no_perm_merge: '$2你不是地皮 $1%plot% 的主人' - no_available_automerge: $2你在指定位置没有邻近的地皮或不允许你合并成那样大小。 - unlink_required: $2你需要先解除地皮的合并。 - unlink_impossible: $2你只能解除超级地皮的合并 - unlink_success: $2成功的解除了地皮的合并。 -commandconfig: - not_valid_subcommand: $2那不是一个正确的子命令 - did_you_mean: '$2你想输入: $1%s$2吗' - name_little: $2%s0 的名字太短了,$1%s1$2<$1%s3 - no_commands: $2很抱歉,你没有权限使用任何子指令。 - subcommand_set_options_header: '$2正确的值: ' - command_syntax: '$1请使用: $2%s' - flag_tutorial_usage: '$1使一位管理员设置标志: $2%s' -errors: - invalid_player_wait: '$2没有找到玩家:$1%s$2。请稍后再试。' - invalid_player: '$2没有找到玩家: $1%s$2.' - invalid_player_offline: '$2这个玩家必须在线: $1%s.' - error: '$2发生了一个错误: %s' - command_went_wrong: $2当使用指令时发生了错误... - no_free_plots: $2现在没有可获得的免费地皮 - not_in_plot: $2你不在一个地皮中 - not_in_cluster: $2你必须在一个地皮群组中才能使用这个命令 - not_in_plot_world: $2你不在一个地皮世界中 - plotworld_incompatible: $2两个世界必须是兼容的 - not_valid_world: $2那不是一个正确的世界(区分大小写) - not_valid_plot_world: $2那不是一个正确的地皮世界(区分大小写) - no_plots: $2你不拥有任何地皮 - not_using_plotme: $2This server uses the far superior $1PlotSquared $2plot management system. Please use the $1/ps $2or $1/p2 $2or $1/plots $2instead - wait_for_timer: $2A setblock timer is bound to either the current plot or you. Please wait for it to finish -paste: - debug_report_created: '$1U将DEBUG信息粘贴到了: $1%url%' -purge: - purge_success: $4成功的合并了 %s 块地皮 -trim: - trim_in_progress: 已经有一个地皮清理任务在进行! - not_valid_hybrid_plot_world: 要进行这个行动,你需要立方体地皮管理系统。 -block list: - block_list_separater: '$1,$2 ' -biome: - need_biome: $2你需要指定一个正确的生物群系 - biome_set_to: $2地皮的生物群系设置为 $2 -teleport: - teleported_to_plot: $1你已被传送 - teleported_to_road: $2你被传送到了道路上 - teleport_in_seconds: $1传送将在 %s 秒后进行。不要移动... - teleport_failed: $2传送因移动或伤害被取消 -set block: - set_block_action_finished: $1上一个方块设置行动现在完成了。 -unsafe: - debugallowunsafe_on: $2允许了不安全的行动 - debugallowunsafe_off: $2不安全的行动被禁用 -debug: - debug_header: $1Debug 信息&- - debug_section: $2>> $1&l%val% - debug_line: $2>> $1%var%$2:$1 %val%&- -invalid: - not_valid_data: $2那不是一个正确的数据ID - not_valid_block: '$2%s 不是一个正确的方块' - not_allowed_block: '$2这个方块被禁用: %s' - not_valid_number: '$2在范围上这不是一个正确的数值: %s' - not_valid_plot_id: $2那不是一个正确的地皮ID - plot_id_form: '$2地皮 ID 的格式必须为: $1X;Y $2例如: $1-5;7' - not_your_plot: $2那不是你的地皮 - no_such_plot: $2没有这个地皮 - player_has_not_been_on: $2那位玩家不在地皮中 - found_no_plots: $2在你的搜索请求中找不到匹配的地皮 -camera: - camera_started: $2你进入了地皮 $1%s 的摄像机模式 - camera_stopped: $2你退出了摄像机模式 -need: - need_plot_number: $2你需要指定一个地皮ID或地皮简称 - need_block: $2你需要指定一个方块 - need_plot_id: $2你需要指定一个方块 ID。 - need_plot_world: $2你需要指定一个地皮区域。 - need_user: $2你需要指定一个用户名 -info: - none: 无 - now: 现在 - never: 从不 - unknown: 未知 - everyone: 所有人 - plot_unowned: $2执行这个行动当前地皮必须有主人 - plot_info_unclaimed: $2地皮 $1%s$2 还没有被领取 - plot_info_header: $3&m---------&r $1信息 $3&m--------- - plot_info: '$1ID: $2%id%$1&-$1别称: $2%alias%$1&-$1地皮主人: $2%owner%$1&-$1生物群系: - $2%biome%$1&-$1是否可建筑: $2%build%$1&-$1评级: $2%rating%&-$1可见: $2%seen%&-$1援建者: - $2%trusted%$1&-$1成员: $2%members%$1&-$1黑名单: $2%denied%$1&-$1标志: $2%flags%' - plot_info_footer: $3&m---------&r $1信息 $3&m--------- - plot_info_trusted: $1援建者:$2 %trusted% - plot_info_members: $1成员:$2 %members% - plot_info_denied: $1黑名单:$2 %denied% - plot_info_flags: $1标志:$2 %flags% - plot_info_biome: $1生物群系:$2 %biome% - plot_info_rating: $1评级:$2 %rating% - plot_info_owner: $1地皮主人:$2 %owner% - plot_info_id: $1地皮ID:$2 %id% - plot_info_alias: $1地皮别称:$2 %alias% - plot_info_size: $1地皮大小:$2 %size% - plot_info_seen: $1地皮可见:$2 %seen% - plot_user_list: ' $1%user%$2,' - plot_flag_list: $1%s0:%s1$2 - info_syntax_console: $2/plot info X;Y -working: - generating_component: $1从您的设置中开始组成部件 - clearing_plot: $2清除地皮异步处理。 - clearing_done: $4清理完成!花费了 %s 毫秒。 - plot_not_claimed: $2地皮没有被领取 - plot_is_claimed: $2这个地皮已经被领取 - claimed: $4你成功的领取了地皮 -list: - comment_list_header_paged: $2(第 $1%cur$2 页/共 $1%max$2 页) $1列出了 %amount% 条评论 - clickable: ' (可点击)' - area_list_header_paged: $2(第 $1%cur$2 页/共 $1%max$2 页) $1列出了 %amount% 片区域 - plot_list_header_paged: $2(第 $1%cur$2 页/共 $1%max$2 页) $1列出了 %amount% 块地皮 - plot_list_header: $1列出了 %word% 地皮 - plot_list_item: $2>> $1%id$2:$1%world $2- $1%owner - plot_list_item_ordered: $2[$1%in$2] >> $1%id$2:$1%world $2- $1%owner - plot_list_footer: $2>> $1%word% 总计有块 $2%num% $1领取的 %plot%. -left: - left_plot: $2你离开了一个地皮 -chat: - plot_chat_format: '$2[$1地皮聊天$2][$1%plot_id%$2] $1%sender%$2: $1%msg%' - plot_chat_forced: $2这个世界强制所有人使用地皮聊天 - plot_chat_on: $4开启了地皮聊天。 - plot_chat_off: $4关闭了地皮聊天。 -deny: - denied_removed: $4Y你成功的从此地皮黑名单解除了一位玩家 - denied_added: $4你成功的将这位玩家加入此地皮的黑名单中 - denied_need_argument: $2缺少参数。请使用$1/plot denied add $2或者 $1/plot denied remove - was_not_denied: $2那位玩家不在此地皮的黑名单中 - you_got_denied: $4你被所在的地皮加入了黑名单,所以你被传送到了出生点。 -kick: - you_got_kicked: $4你被踢出了地皮! -rain: - need_on_off: '$2你需要指定一个值。正确的值: $1on$2, $1off' - setting_updated: $4你成功的更新了设置。 -flag: - flag_key: '$2关键词: %s' - flag_type: '$2类型: %s' - flag_desc: '$2描述: %s' - not_valid_flag: $2那不是一个正确的标志 - not_valid_flag_suggested: '$2那不是一个正确的标志。你想用: $1%s 吗?' - not_valid_value: $2地皮值必须为代数 - flag_not_in_plot: $2这个地皮目前没有标志 - flag_not_removed: $2这个标志不能被移除 - flag_not_added: $2这个标志不能被添加 - flag_removed: $4成功的移除了标志 - flag_added: $4成功的添加了标志 -trusted: - trusted_added: $4你成功的为地皮添加了一位信任玩家 - trusted_removed: $4你成功的为地皮移除了一位信任玩家 - was_not_added: $2那位玩家在这个地皮中不是信任玩家 - plot_removed_user: $1因为地皮主人的长期不在线,你所作为信任玩家的地皮 %s 已被删除 -member: - removed_players: $2Removed %s players from this plot. - already_owner: '$2玩家 %s0 已经是地皮主人了' - already_added: '$2玩家 %s0 已经被添加到此类了' - member_added: $4那位玩家现在在地皮主人在线时可以编辑地皮 - member_removed: $1你成功的为地皮移除了一位成员 - member_was_not_added: $2那位玩家不是地皮的一位成员 - plot_max_members: $2你不被允许再为地皮增加成员了 -owner: - set_owner: $4你成功的设置了地皮主人 - now_owner: $4你现在是地皮 %s 的主人了 -signs: - owner_sign_line_1: '$1地皮ID: $1%id%' - owner_sign_line_2: '$1所有者:' - owner_sign_line_3: $2%plr% - owner_sign_line_4: $3被领取 -help: - help_header: $3&m---------&r $1地皮系统②帮助文件 $3&m--------- - help_page_header: '$1类型: $2%category%$2,$1 页面: $2%current%$3/$2%max%$2' - help_footer: $3&m---------&r $1地皮系统②帮助文件 $3&m--------- - help_info_item: $1/plots help %category% $3- $2%category_desc% - help_item: $1%usage% [%alias%]&- $3- $2%desc%&- - direction: '$1当前路径: %dir%' -grants: - granted_plots: '$1结果: $1剩余 $2%s' - granted_plot: $1你将 %s0 地皮赠予 $2%s1 - granted_plot_failed: '$1赠予失败了:$2%s' -'-': - custom_string: '-' diff --git a/code_style.xml b/code_style.xml new file mode 100644 index 000000000..44c8beb04 --- /dev/null +++ b/code_style.xml @@ -0,0 +1,337 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 1646cd0f5ad3c3dfa2da6ddeb785289072bfe942 Mon Sep 17 00:00:00 2001 From: sauilitired Date: Fri, 10 Aug 2018 17:01:10 +0200 Subject: [PATCH 02/42] Reformat code --- Bukkit/build.gradle | 12 +- .../plot/api/PlotAPI.java | 222 +-- .../com/plotsquared/bukkit/BukkitMain.java | 339 ++-- .../plotsquared/bukkit/chat/ArrayWrapper.java | 76 +- .../plotsquared/bukkit/chat/FancyMessage.java | 402 ++-- .../bukkit/chat/JsonRepresentedObject.java | 1 + .../plotsquared/bukkit/chat/JsonString.java | 14 +- .../plotsquared/bukkit/chat/MessagePart.java | 130 +- .../plotsquared/bukkit/chat/Reflection.java | 14 +- .../bukkit/chat/TextualComponent.java | 94 +- .../bukkit/commands/DebugUUID.java | 84 +- .../database/plotme/APlotMeConnector.java | 21 +- .../plotme/ClassicPlotMeConnector.java | 44 +- .../database/plotme/LikePlotMeConverter.java | 130 +- .../database/plotme/PlotMeConnector_017.java | 44 +- .../bukkit/events/ClusterFlagRemoveEvent.java | 11 +- .../bukkit/events/PlayerClaimPlotEvent.java | 9 +- .../bukkit/events/PlayerEnterPlotEvent.java | 3 +- .../bukkit/events/PlayerLeavePlotEvent.java | 3 +- .../bukkit/events/PlayerPlotDeniedEvent.java | 3 +- .../bukkit/events/PlayerPlotHelperEvent.java | 3 +- .../bukkit/events/PlayerPlotTrustedEvent.java | 3 +- .../events/PlayerTeleportToPlotEvent.java | 12 +- .../bukkit/events/PlotClearEvent.java | 11 +- .../bukkit/events/PlotComponentSetEvent.java | 4 +- .../bukkit/events/PlotDeleteEvent.java | 4 +- .../bukkit/events/PlotFlagAddEvent.java | 10 +- .../bukkit/events/PlotFlagRemoveEvent.java | 10 +- .../bukkit/events/PlotMergeEvent.java | 9 +- .../bukkit/events/PlotRateEvent.java | 3 +- .../bukkit/events/PlotUnlinkEvent.java | 9 +- .../generator/BukkitAugmentedGenerator.java | 5 +- .../bukkit/generator/BukkitPlotGenerator.java | 124 +- .../bukkit/listeners/ChunkListener.java | 48 +- .../bukkit/listeners/EntityPortal_1_7_9.java | 92 +- .../bukkit/listeners/EntitySpawnListener.java | 7 +- .../bukkit/listeners/ForceFieldListener.java | 20 +- .../bukkit/listeners/PlayerEvents.java | 875 +++++---- .../bukkit/listeners/PlayerEvents_1_8.java | 32 +- .../bukkit/listeners/PlotPlusListener.java | 46 +- .../listeners/PlotPlusListener_1_12.java | 6 +- .../listeners/PlotPlusListener_Legacy.java | 6 +- .../bukkit/listeners/SingleWorldListener.java | 33 +- .../bukkit/listeners/WorldEvents.java | 2 +- .../bukkit/object/BukkitLazyBlock.java | 6 +- .../bukkit/object/BukkitOfflinePlayer.java | 12 +- .../bukkit/object/BukkitPlayer.java | 117 +- .../bukkit/object/entity/EntityWrapper.java | 87 +- .../bukkit/object/schematic/StateWrapper.java | 9 +- .../bukkit/titles/DefaultTitleManager.java | 54 +- .../titles/DefaultTitleManager_183.java | 41 +- .../bukkit/titles/DefaultTitle_111.java | 6 +- .../bukkit/titles/DefaultTitle_19.java | 6 +- .../bukkit/titles/HackTitleManager.java | 64 +- .../bukkit/titles/TitleManager.java | 29 +- .../bukkit/titles/TitleManager_1_11.java | 249 ++- .../bukkit/util/BukkitChatManager.java | 21 +- .../bukkit/util/BukkitChunkManager.java | 454 +++-- .../bukkit/util/BukkitCommand.java | 19 +- .../bukkit/util/BukkitEconHandler.java | 24 +- .../bukkit/util/BukkitEventUtil.java | 73 +- .../bukkit/util/BukkitHybridUtils.java | 55 +- .../bukkit/util/BukkitInventoryUtil.java | 18 +- .../bukkit/util/BukkitSchematicHandler.java | 55 +- .../bukkit/util/BukkitSetupUtils.java | 78 +- .../bukkit/util/BukkitTaskManager.java | 36 +- .../plotsquared/bukkit/util/BukkitUtil.java | 126 +- .../com/plotsquared/bukkit/util/Metrics.java | 89 +- .../plotsquared/bukkit/util/NbtFactory.java | 283 +-- .../bukkit/util/OfflinePlayerUtil.java | 21 +- .../plotsquared/bukkit/util/SendChunk.java | 25 +- .../bukkit/util/block/BukkitLocalQueue.java | 45 +- .../util/block/BukkitLocalQueue_1_7.java | 28 +- .../util/block/BukkitLocalQueue_1_8.java | 42 +- .../util/block/BukkitLocalQueue_1_8_3.java | 595 +++--- .../util/block/BukkitLocalQueue_1_9.java | 550 +++--- .../bukkit/util/block/GenChunk.java | 47 +- .../bukkit/uuid/DatFileFilter.java | 3 +- .../bukkit/uuid/DefaultUUIDWrapper.java | 18 +- .../bukkit/uuid/FileUUIDHandler.java | 65 +- .../bukkit/uuid/LowerOfflineUUIDWrapper.java | 24 +- .../bukkit/uuid/OfflineUUIDWrapper.java | 30 +- .../bukkit/uuid/SQLUUIDHandler.java | 103 +- Core/build.gradle | 6 +- .../configuration/Configuration.java | 26 +- .../configuration/ConfigurationOptions.java | 20 +- .../configuration/ConfigurationSection.java | 166 +- .../InvalidConfigurationException.java | 16 +- .../configuration/MemoryConfiguration.java | 40 +- .../MemoryConfigurationOptions.java | 15 +- .../configuration/MemorySection.java | 197 +- .../configuration/file/FileConfiguration.java | 72 +- .../file/FileConfigurationOptions.java | 47 +- .../configuration/file/YamlConfiguration.java | 24 +- .../file/YamlConfigurationOptions.java | 37 +- .../configuration/file/YamlConstructor.java | 20 +- .../configuration/file/YamlRepresenter.java | 13 +- .../ConfigurationSerializable.java | 4 +- .../ConfigurationSerialization.java | 53 +- .../DelegateDeserialization.java | 3 +- .../serialization/SerializableAs.java | 4 +- .../jnbt/ByteArrayTag.java | 6 +- .../intellectualcrafters/jnbt/ByteTag.java | 6 +- .../jnbt/CompoundTag.java | 35 +- .../jnbt/CompoundTagBuilder.java | 16 +- .../intellectualcrafters/jnbt/DoubleTag.java | 6 +- .../com/intellectualcrafters/jnbt/EndTag.java | 9 +- .../intellectualcrafters/jnbt/FloatTag.java | 6 +- .../jnbt/IntArrayTag.java | 6 +- .../com/intellectualcrafters/jnbt/IntTag.java | 6 +- .../intellectualcrafters/jnbt/ListTag.java | 37 +- .../jnbt/ListTagBuilder.java | 16 +- .../intellectualcrafters/jnbt/LongTag.java | 6 +- .../jnbt/NBTConstants.java | 11 +- .../jnbt/NBTInputStream.java | 13 +- .../jnbt/NBTOutputStream.java | 19 +- .../intellectualcrafters/jnbt/NBTUtils.java | 16 +- .../intellectualcrafters/jnbt/ShortTag.java | 6 +- .../intellectualcrafters/jnbt/StringTag.java | 6 +- .../com/intellectualcrafters/json/CDL.java | 30 +- .../com/intellectualcrafters/json/Cookie.java | 12 +- .../intellectualcrafters/json/CookieList.java | 8 +- .../com/intellectualcrafters/json/HTTP.java | 22 +- .../json/HTTPTokener.java | 7 +- .../intellectualcrafters/json/JSONArray.java | 215 +- .../json/JSONException.java | 9 +- .../com/intellectualcrafters/json/JSONML.java | 44 +- .../intellectualcrafters/json/JSONObject.java | 333 ++-- .../json/JSONStringer.java | 21 +- .../json/JSONTokener.java | 67 +- .../intellectualcrafters/json/JSONWriter.java | 64 +- .../com/intellectualcrafters/json/Kim.java | 58 +- .../intellectualcrafters/json/Property.java | 9 +- .../com/intellectualcrafters/json/XML.java | 38 +- .../intellectualcrafters/json/XMLTokener.java | 43 +- .../intellectualcrafters/plot/IPlotMain.java | 43 +- .../com/intellectualcrafters/plot/PS.java | 462 ++--- .../intellectualcrafters/plot/Platform.java | 5 +- .../plot/PlotVersion.java | 28 +- .../intellectualcrafters/plot/Updater.java | 24 +- .../plot/commands/Add.java | 25 +- .../plot/commands/Alias.java | 113 +- .../plot/commands/Area.java | 243 +-- .../plot/commands/Auto.java | 321 +-- .../plot/commands/BO3.java | 14 +- .../plot/commands/Biome.java | 20 +- .../plot/commands/Buy.java | 19 +- .../plot/commands/Changelog.java | 21 +- .../plot/commands/Chat.java | 11 +- .../plot/commands/Claim.java | 38 +- .../plot/commands/Clear.java | 31 +- .../plot/commands/Cluster.java | 92 +- .../plot/commands/CommandCategory.java | 28 +- .../plot/commands/Comment.java | 27 +- .../plot/commands/Condense.java | 42 +- .../plot/commands/Confirm.java | 11 +- .../plot/commands/Continue.java | 16 +- .../plot/commands/Copy.java | 19 +- .../plot/commands/CreateRoadSchematic.java | 16 +- .../plot/commands/Database.java | 63 +- .../plot/commands/Debug.java | 12 +- .../plot/commands/DebugAllowUnsafe.java | 11 +- .../plot/commands/DebugClaimTest.java | 58 +- .../plot/commands/DebugExec.java | 169 +- .../plot/commands/DebugFixFlags.java | 11 +- .../plot/commands/DebugImportWorlds.java | 16 +- .../plot/commands/DebugLoadTest.java | 11 +- .../plot/commands/DebugPaste.java | 47 +- .../plot/commands/DebugRoadRegen.java | 24 +- .../plot/commands/DebugSaveTest.java | 14 +- .../plot/commands/Delete.java | 42 +- .../plot/commands/Deny.java | 28 +- .../plot/commands/Desc.java | 14 +- .../plot/commands/Done.java | 20 +- .../plot/commands/Download.java | 47 +- .../plot/commands/FlagCmd.java | 57 +- .../plot/commands/GenerateDocs.java | 23 +- .../plot/commands/Grant.java | 25 +- .../plot/commands/Help.java | 27 +- .../plot/commands/Inbox.java | 54 +- .../plot/commands/Info.java | 66 +- .../plot/commands/Kick.java | 21 +- .../plot/commands/Leave.java | 14 +- .../plot/commands/ListCmd.java | 174 +- .../plot/commands/Load.java | 64 +- .../plot/commands/MainCommand.java | 56 +- .../plot/commands/Merge.java | 52 +- .../plot/commands/Middle.java | 12 +- .../plot/commands/Move.java | 24 +- .../plot/commands/Music.java | 24 +- .../plot/commands/Near.java | 11 +- .../plot/commands/Owner.java | 40 +- .../plot/commands/PluginCmd.java | 28 +- .../plot/commands/Purge.java | 18 +- .../plot/commands/Rate.java | 61 +- .../plot/commands/RegenAllRoads.java | 26 +- .../plot/commands/Relight.java | 19 +- .../plot/commands/Reload.java | 20 +- .../plot/commands/Remove.java | 25 +- .../plot/commands/Save.java | 36 +- .../plot/commands/SchematicCmd.java | 92 +- .../plot/commands/Set.java | 71 +- .../plot/commands/SetCommand.java | 9 +- .../plot/commands/SetHome.java | 17 +- .../plot/commands/Setup.java | 117 +- .../plot/commands/SubCommand.java | 8 +- .../plot/commands/Swap.java | 17 +- .../plot/commands/Target.java | 11 +- .../plot/commands/Template.java | 61 +- .../plot/commands/Toggle.java | 63 +- .../plot/commands/Trim.java | 60 +- .../plot/commands/Trust.java | 24 +- .../plot/commands/Unlink.java | 24 +- .../plot/commands/Visit.java | 49 +- .../plot/commands/WE_Anywhere.java | 16 +- .../intellectualcrafters/plot/config/C.java | 990 +++++----- .../plot/config/Config.java | 79 +- .../plot/config/Configuration.java | 173 +- .../plot/config/ConfigurationNode.java | 3 +- .../plot/config/Settings.java | 324 +-- .../plot/config/Storage.java | 20 +- .../plot/database/AbstractDB.java | 144 +- .../plot/database/DBFunc.java | 104 +- .../plot/database/Database.java | 23 +- .../plot/database/MySQL.java | 33 +- .../plot/database/SQLManager.java | 1735 ++++++++--------- .../plot/database/SQLite.java | 27 +- .../plot/flag/EnumFlag.java | 6 +- .../intellectualcrafters/plot/flag/Flag.java | 6 +- .../plot/flag/FlagManager.java | 39 +- .../intellectualcrafters/plot/flag/Flags.java | 30 +- .../plot/flag/GameModeFlag.java | 9 +- .../plot/flag/IntegerListFlag.java | 2 +- .../plot/flag/IntervalFlag.java | 5 +- .../plot/flag/ListFlag.java | 1 + .../plot/flag/PlotBlockListFlag.java | 3 +- .../plot/flag/PlotWeatherFlag.java | 3 +- .../plot/flag/TeleportDenyFlag.java | 3 +- .../plot/generator/AugmentedUtils.java | 27 +- .../plot/generator/ClassicPlotManager.java | 170 +- .../plot/generator/ClassicPlotWorld.java | 65 +- .../plot/generator/GridPlotWorld.java | 3 +- .../plot/generator/HybridGen.java | 42 +- .../plot/generator/HybridPlotManager.java | 78 +- .../plot/generator/HybridPlotWorld.java | 80 +- .../plot/generator/HybridUtils.java | 125 +- .../generator/IndependentPlotGenerator.java | 36 +- .../plot/generator/PlotGenerator.java | 1 + .../plot/generator/SquarePlotManager.java | 42 +- .../plot/generator/SquarePlotWorld.java | 10 +- .../plot/logger/DelegateLogger.java | 3 +- .../intellectualcrafters/plot/object/BO3.java | 15 +- .../plot/object/BlockLoc.java | 9 +- .../plot/object/ChunkLoc.java | 9 +- .../plot/object/ChunkWrapper.java | 14 +- .../plot/object/CmdInstance.java | 2 +- .../plot/object/ConsolePlayer.java | 121 +- .../plot/object/Expression.java | 23 +- .../plot/object/Location.java | 29 +- .../plot/object/OfflinePlotPlayer.java | 4 + .../plot/object/Plot.java | 631 +++--- .../plot/object/PlotArea.java | 192 +- .../plot/object/PlotBlock.java | 18 +- .../plot/object/PlotCluster.java | 53 +- .../plot/object/PlotFilter.java | 2 +- .../plot/object/PlotId.java | 50 +- .../plot/object/PlotItemStack.java | 10 +- .../plot/object/PlotLoc.java | 11 +- .../plot/object/PlotManager.java | 8 +- .../plot/object/PlotMessage.java | 11 +- .../plot/object/PlotPlayer.java | 117 +- .../plot/object/PlotSettings.java | 31 +- .../plot/object/PseudoRandom.java | 4 +- .../plot/object/Rating.java | 3 +- .../plot/object/RegionWrapper.java | 29 +- .../plot/object/RunnableVal.java | 12 +- .../plot/object/RunnableVal2.java | 12 +- .../plot/object/RunnableVal3.java | 12 +- .../plot/object/SetupObject.java | 24 +- .../plot/object/StringWrapper.java | 10 +- .../plot/object/chat/PlainChatManager.java | 26 +- .../plot/object/comment/CommentInbox.java | 17 +- .../plot/object/comment/InboxOwner.java | 9 +- .../plot/object/comment/InboxPublic.java | 13 +- .../plot/object/comment/InboxReport.java | 12 +- .../plot/object/comment/PlotComment.java | 3 +- .../plot/object/schematic/ItemType.java | 867 +++----- .../stream/AbstractDelegateOutputStream.java | 45 +- .../object/worlds/DefaultPlotAreaManager.java | 65 +- .../plot/object/worlds/PlotAreaManager.java | 9 + .../plot/object/worlds/SinglePlot.java | 44 +- .../plot/object/worlds/SinglePlotArea.java | 63 +- .../object/worlds/SinglePlotAreaManager.java | 71 +- .../plot/object/worlds/SinglePlotManager.java | 78 +- .../object/worlds/SingleWorldGenerator.java | 25 +- .../plot/util/AbstractTitle.java | 3 +- .../plot/util/BO3Handler.java | 80 +- .../plot/util/ByteArrayUtilities.java | 5 +- .../plot/util/ChatManager.java | 2 +- .../plot/util/ChunkManager.java | 90 +- .../plot/util/CmdConfirm.java | 9 +- .../plot/util/CommentManager.java | 18 +- .../plot/util/ConsoleColors.java | 27 +- .../plot/util/EventUtil.java | 214 +- .../plot/util/HastebinUtility.java | 14 +- .../plot/util/HttpUtil.java | 3 +- .../plot/util/InventoryUtil.java | 15 +- .../plot/util/MainUtil.java | 181 +- .../plot/util/MathMan.java | 58 +- .../plot/util/Permissions.java | 25 +- .../plot/util/PlotGameMode.java | 9 +- .../plot/util/ReflectionUtils.java | 66 +- .../plot/util/RegExUtil.java | 6 +- .../plot/util/SchematicHandler.java | 183 +- .../plot/util/SetupUtils.java | 11 +- .../plot/util/StringComparison.java | 42 +- .../plot/util/StringMan.java | 37 +- .../plot/util/TaskManager.java | 98 +- .../plot/util/UUIDHandler.java | 17 +- .../plot/util/UUIDHandlerImplementation.java | 56 +- .../plot/util/WorldUtil.java | 65 +- .../plot/util/area/QuadMap.java | 25 +- .../plot/util/block/BasicLocalBlockQueue.java | 79 +- .../util/block/DelegateLocalBlockQueue.java | 68 +- .../plot/util/block/GlobalBlockQueue.java | 65 +- .../plot/util/block/LocalBlockQueue.java | 20 +- .../util/block/OffsetLocalBlockQueue.java | 6 +- .../plot/util/block/QueueProvider.java | 10 +- .../util/block/ScopedLocalBlockQueue.java | 22 +- .../plot/util/expiry/ExpireManager.java | 134 +- .../plot/util/expiry/ExpiryTask.java | 14 +- .../plot/util/expiry/PlotAnalysis.java | 134 +- .../plot/util/helpmenu/HelpMenu.java | 10 +- .../plot/util/helpmenu/HelpObject.java | 22 +- .../plot/util/helpmenu/HelpPage.java | 8 +- .../general/commands/Argument.java | 45 +- .../plotsquared/general/commands/Command.java | 107 +- .../general/commands/CommandCaller.java | 4 +- .../general/commands/CommandDeclaration.java | 23 +- .../plotsquared/listener/ExtentWrapper.java | 4 +- .../listener/PlayerBlockEventType.java | 42 +- .../plotsquared/listener/PlotListener.java | 84 +- .../listener/ProcessedWEExtent.java | 61 +- .../com/plotsquared/listener/WEExtent.java | 24 +- .../com/plotsquared/listener/WEManager.java | 17 +- .../plotsquared/listener/WESubscriber.java | 11 +- Core/src/main/resources/automerge.js | 4 +- .../intellectualcrafters/plot/FlagTest.java | 10 +- .../plot/database/AbstractDBTest.java | 163 +- .../plot/util/EventUtilTest.java | 30 +- Nukkit/build.gradle | 14 +- .../com/plotsquared/nukkit/NukkitMain.java | 158 +- .../nukkit/events/ClusterFlagRemoveEvent.java | 8 +- .../nukkit/events/PlayerClaimPlotEvent.java | 6 +- .../nukkit/events/PlayerPlotDeniedEvent.java | 1 + .../nukkit/events/PlayerPlotHelperEvent.java | 1 + .../nukkit/events/PlayerPlotTrustedEvent.java | 1 + .../events/PlayerTeleportToPlotEvent.java | 6 +- .../nukkit/events/PlotClearEvent.java | 8 +- .../nukkit/events/PlotComponentSetEvent.java | 1 - .../nukkit/events/PlotDeleteEvent.java | 1 - .../nukkit/events/PlotFlagAddEvent.java | 7 +- .../nukkit/events/PlotFlagRemoveEvent.java | 7 +- .../nukkit/events/PlotMergeEvent.java | 7 +- .../nukkit/events/PlotUnlinkEvent.java | 7 +- .../generator/NukkitAugmentedGenerator.java | 9 +- .../nukkit/generator/NukkitPlotGenerator.java | 77 +- .../nukkit/listeners/PlayerEvents.java | 435 ++--- .../nukkit/listeners/WorldEvents.java | 1 + .../nukkit/object/NukkitPlayer.java | 106 +- .../com/plotsquared/nukkit/util/Metrics.java | 52 +- .../nukkit/util/NukkitChunkManager.java | 20 +- .../nukkit/util/NukkitCommand.java | 3 +- .../nukkit/util/NukkitEventUtil.java | 74 +- .../nukkit/util/NukkitHybridUtils.java | 4 +- .../nukkit/util/NukkitInventoryUtil.java | 15 +- .../nukkit/util/NukkitSchematicHandler.java | 42 +- .../nukkit/util/NukkitSetupUtils.java | 40 +- .../nukkit/util/NukkitTaskManager.java | 34 +- .../plotsquared/nukkit/util/NukkitUtil.java | 89 +- .../nukkit/util/block/NukkitHybridGen.java | 1 + .../nukkit/util/block/NukkitLocalQueue.java | 25 +- .../nukkit/util/block/NukkitWrappedChunk.java | 21 +- .../nukkit/uuid/DatFileFilter.java | 3 +- .../nukkit/uuid/FileUUIDHandler.java | 16 +- .../nukkit/uuid/LowerOfflineUUIDWrapper.java | 28 +- README.md | 2 +- Sponge/build.gradle | 2 +- .../com/plotsquared/sponge/SpongeMain.java | 210 +- .../sponge/events/ClusterFlagRemoveEvent.java | 28 +- .../sponge/events/PlayerClaimPlotEvent.java | 26 +- .../sponge/events/PlayerEnterPlotEvent.java | 14 +- .../sponge/events/PlayerEvent.java | 11 +- .../sponge/events/PlayerLeavePlotEvent.java | 9 +- .../sponge/events/PlayerPlotDeniedEvent.java | 20 +- .../sponge/events/PlayerPlotHelperEvent.java | 20 +- .../sponge/events/PlayerPlotTrustedEvent.java | 20 +- .../events/PlayerTeleportToPlotEvent.java | 22 +- .../sponge/events/PlotClearEvent.java | 17 +- .../sponge/events/PlotComponentSetEvent.java | 10 +- .../sponge/events/PlotDeleteEvent.java | 14 +- .../plotsquared/sponge/events/PlotEvent.java | 14 +- .../sponge/events/PlotFlagAddEvent.java | 17 +- .../sponge/events/PlotFlagRemoveEvent.java | 17 +- .../sponge/events/PlotMergeEvent.java | 30 +- .../sponge/events/PlotRateEvent.java | 14 +- .../sponge/events/PlotUnlinkEvent.java | 26 +- .../generator/SpongeAugmentedGenerator.java | 17 +- .../sponge/generator/SpongePlotGenerator.java | 56 +- .../sponge/generator/SpongeTerrainGen.java | 21 +- .../sponge/listener/ForceFieldListener.java | 15 +- .../sponge/listener/MainListener.java | 150 +- .../sponge/listener/WorldEvents.java | 8 +- .../sponge/object/SpongeOfflinePlayer.java | 1 + .../sponge/object/SpongePlayer.java | 145 +- .../sponge/util/SpongeChatManager.java | 21 +- .../sponge/util/SpongeChunkManager.java | 51 +- .../sponge/util/SpongeCommand.java | 25 +- .../sponge/util/SpongeEconHandler.java | 30 +- .../sponge/util/SpongeEventUtil.java | 109 +- .../sponge/util/SpongeHybridUtils.java | 6 +- .../sponge/util/SpongeInventoryUtil.java | 12 +- .../sponge/util/SpongeMetrics.java | 32 +- .../sponge/util/SpongeSchematicHandler.java | 71 +- .../sponge/util/SpongeSetupUtils.java | 80 +- .../sponge/util/SpongeTaskManager.java | 24 +- .../sponge/util/SpongeTitleManager.java | 4 +- .../plotsquared/sponge/util/SpongeUtil.java | 110 +- .../sponge/util/block/GenChunk.java | 23 +- .../sponge/util/block/SpongeLocalQueue.java | 409 ++-- .../uuid/SpongeLowerOfflineUUIDWrapper.java | 55 +- .../sponge/uuid/SpongeOnlineUUIDWrapper.java | 32 +- .../sponge/uuid/SpongeUUIDHandler.java | 21 +- build.gradle | 20 +- code_style.xml | 1063 ++++++---- pom.xml | 199 +- settings.gradle | 2 +- 437 files changed, 12795 insertions(+), 14203 deletions(-) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 4d6bb295c..7b3e5b761 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -1,7 +1,7 @@ repositories { - maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"} - maven { url = "https://oss.sonatype.org/content/repositories/snapshots/"} - maven {url "http://nexus.hc.to/content/repositories/pub_releases"} + maven { url "https://hub.spigotmc.org/nexus/content/groups/public/" } + maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url "http://nexus.hc.to/content/repositories/pub_releases" } mavenLocal() } @@ -20,8 +20,8 @@ processResources { from('src/main/resources') { include 'plugin.yml' expand( - name: project.parent.name, - version: project.parent.version + name: project.parent.name, + version: project.parent.version ) } } @@ -39,7 +39,7 @@ shadowJar { shadowJar.doLast { task -> - ant.checksum file: task.archivePath + ant.checksum file: task.archivePath } build.dependsOn(shadowJar); diff --git a/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java index 519de20ef..22a725ded 100644 --- a/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java @@ -7,16 +7,8 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.util.BukkitUtil; @@ -26,44 +18,41 @@ import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; +import java.util.*; /** * PlotSquared API. - * + *

*

Useful classes: *

    - *
  • {@link BukkitUtil}
  • - *
  • {@link PlotPlayer}
  • - *
  • {@link Plot}
  • - *
  • {@link com.intellectualcrafters.plot.object.Location}
  • - *
  • {@link PlotArea}
  • - *
  • {@link PS}
  • + *
  • {@link BukkitUtil}
  • + *
  • {@link PlotPlayer}
  • + *
  • {@link Plot}
  • + *
  • {@link com.intellectualcrafters.plot.object.Location}
  • + *
  • {@link PlotArea}
  • + *
  • {@link PS}
  • *
+ * * @version 3.3.3 */ public class PlotAPI { /** * Deprecated, does nothing. + * * @param plugin not needed * @deprecated Not needed */ - @Deprecated - public PlotAPI(JavaPlugin plugin) {} + @Deprecated public PlotAPI(JavaPlugin plugin) { + } - public PlotAPI(){} + public PlotAPI() { + } /** * Get all plots. * * @return all plots - * * @see PS#getPlots() */ public Set getAllPlots() { @@ -74,7 +63,6 @@ public class PlotAPI { * Return all plots for a player. * * @param player Player, whose plots to search for - * * @return all plots that a player owns */ public Set getPlayerPlots(Player player) { @@ -93,8 +81,8 @@ public class PlotAPI { /** * Returns the PlotSquared configurations file. - * @return main configuration * + * @return main configuration * @see PS#config */ public YamlConfiguration getConfig() { @@ -103,8 +91,8 @@ public class PlotAPI { /** * Get the PlotSquared storage file. - * @return storage configuration * + * @return storage configuration * @see PS#storage */ public YamlConfiguration getStorage() { @@ -115,7 +103,6 @@ public class PlotAPI { * Get the main class for this plugin. Only use this if you really need it. * * @return PlotSquared PlotSquared Main Class - * * @see PS */ public PS getMain() { @@ -125,15 +112,14 @@ public class PlotAPI { /** * ChunkManager class contains several useful methods. *
    - *
  • Chunk deletion
  • - *
  • Moving or copying regions
  • - *
  • Plot swapping
  • - *
  • Entity Tracking
  • - *
  • Region Regeneration
  • + *
  • Chunk deletion
  • + *
  • Moving or copying regions
  • + *
  • Plot swapping
  • + *
  • Entity Tracking
  • + *
  • Region Regeneration
  • *
* * @return ChunkManager - * * @see ChunkManager */ public ChunkManager getChunkManager() { @@ -142,6 +128,7 @@ public class PlotAPI { /** * Get the block/biome set queue + * * @return GlobalBlockQueue.IMP */ public GlobalBlockQueue getBlockQueue() { @@ -153,7 +140,6 @@ public class PlotAPI { * to use the UUIDHandler class instead. * * @return UUIDWrapper - * * @see UUIDWrapper */ public UUIDWrapper getUUIDWrapper() { @@ -162,14 +148,12 @@ public class PlotAPI { /** * Do not use this. Instead use FlagManager.[method] in your code. - * - Flag related stuff + * - Flag related stuff * * @return FlagManager - * * @deprecated Use {@link FlagManager} directly */ - @Deprecated - public FlagManager getFlagManager() { + @Deprecated public FlagManager getFlagManager() { return new FlagManager(); } @@ -179,8 +163,7 @@ public class PlotAPI { * @return MainUtil * @deprecated Use {@link MainUtil} directly */ - @Deprecated - public MainUtil getMainUtil() { + @Deprecated public MainUtil getMainUtil() { return new MainUtil(); } @@ -188,12 +171,10 @@ public class PlotAPI { * Do not use this. Instead use C.PERMISSION_[method] in your code. * * @return Array of strings - * * @see Permissions * @deprecated Use {@link C} to list all the permissions */ - @Deprecated - public String[] getPermissions() { + @Deprecated public String[] getPermissions() { ArrayList perms = new ArrayList<>(); for (C caption : C.values()) { if ("static.permissions".equals(caption.getCategory())) { @@ -208,7 +189,6 @@ public class PlotAPI { * and writing schematics. * * @return SchematicHandler - * * @see SchematicHandler */ public SchematicHandler getSchematicHandler() { @@ -221,8 +201,7 @@ public class PlotAPI { * @return C * @deprecated Use {@link C} */ - @Deprecated - public C[] getCaptions() { + @Deprecated public C[] getCaptions() { return C.values(); } @@ -231,15 +210,11 @@ public class PlotAPI { * through the MainUtil. * * @param world the world to retrieve the manager from - * * @return PlotManager - * * @see PlotManager * @see PS#getPlotManager(Plot) */ - @SuppressWarnings("deprecation") - @Deprecated - public PlotManager getPlotManager(World world) { + @SuppressWarnings("deprecation") @Deprecated public PlotManager getPlotManager(World world) { if (world == null) { return null; } @@ -248,6 +223,7 @@ public class PlotAPI { /** * Get a list of PlotAreas in the world. + * * @param world The world to check for plot areas * @return A set of PlotAreas */ @@ -263,14 +239,11 @@ public class PlotAPI { * plot merging, clearing, and tessellation. * * @param world The world - * * @return PlotManager - * * @see PS#getPlotManager(Plot) * @see PlotManager */ - @Deprecated - public PlotManager getPlotManager(String world) { + @Deprecated public PlotManager getPlotManager(String world) { Set areas = PS.get().getPlotAreas(world); switch (areas.size()) { case 0: @@ -278,7 +251,8 @@ public class PlotAPI { case 1: return areas.iterator().next().manager; default: - PS.debug("PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); + PS.debug( + "PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); return null; } } @@ -289,15 +263,11 @@ public class PlotAPI { * DefaultPlotWorld class implements PlotArea * * @param world The World - * * @return The {@link PlotArea} for the world or null if not in plotworld - * * @see #getPlotAreas(World) * @see PlotArea */ - @SuppressWarnings("deprecation") - @Deprecated - public PlotArea getWorldSettings(World world) { + @SuppressWarnings("deprecation") @Deprecated public PlotArea getWorldSettings(World world) { if (world == null) { return null; } @@ -308,14 +278,11 @@ public class PlotAPI { * Get the settings for a world. * * @param world the world to retrieve settings from - * * @return The {@link PlotArea} for the world or null if not in plotworld - * * @see PS#getPlotArea(String, String) * @see PlotArea */ - @Deprecated - public PlotArea getWorldSettings(String world) { + @Deprecated public PlotArea getWorldSettings(String world) { if (world == null) { return null; } @@ -326,7 +293,8 @@ public class PlotAPI { case 1: return areas.iterator().next(); default: - PS.debug("PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); + PS.debug( + "PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); return null; } } @@ -334,9 +302,8 @@ public class PlotAPI { /** * Send a message to a player. * - * @param player the recipient of the message + * @param player the recipient of the message * @param caption the message - * * @see MainUtil#sendMessage(PlotPlayer, C, String...) */ public void sendMessage(Player player, C caption) { @@ -348,7 +315,6 @@ public class PlotAPI { * * @param player the recipient of the message * @param string the message - * * @see MainUtil#sendMessage(PlotPlayer, String) */ public void sendMessage(Player player, String string) { @@ -359,7 +325,6 @@ public class PlotAPI { * Send a message to the console. The message supports color codes. * * @param message the message - * * @see MainUtil#sendConsoleMessage(C, String...) */ public void sendConsoleMessage(String message) { @@ -370,7 +335,6 @@ public class PlotAPI { * Send a message to the console. * * @param caption the message - * * @see #sendConsoleMessage(String) * @see C */ @@ -382,7 +346,6 @@ public class PlotAPI { * Registers a flag for use in plots. * * @param flag the flag to register - * */ public void addFlag(Flag flag) { Flags.registerFlag(flag); @@ -392,16 +355,12 @@ public class PlotAPI { * Gets a plot based on the ID. * * @param world the world the plot is located in - * @param x The PlotID x coordinate - * @param z The PlotID y coordinate - * + * @param x The PlotID x coordinate + * @param z The PlotID y coordinate * @return plot, null if ID is wrong - * * @see PlotArea#getPlot(PlotId) */ - @SuppressWarnings("deprecation") - @Deprecated - public Plot getPlot(World world, int x, int z) { + @SuppressWarnings("deprecation") @Deprecated public Plot getPlot(World world, int x, int z) { if (world == null) { return null; } @@ -416,9 +375,7 @@ public class PlotAPI { * Get a plot based on the location. * * @param location the location to check - * * @return plot if found, otherwise it creates a temporary plot - * * @see Plot */ public Plot getPlot(Location location) { @@ -432,9 +389,7 @@ public class PlotAPI { * Get a plot based on the player location. * * @param player the player to check - * * @return plot if found, otherwise it creates a temporary plot - * * @see #getPlot(Location) * @see Plot */ @@ -446,27 +401,24 @@ public class PlotAPI { * Check whether or not a player has a plot. * * @param player Player that you want to check for - * @param world The world to check + * @param world The world to check * @return true if player has a plot, false if not. - * * @see #getPlots(World, Player, boolean) */ - @SuppressWarnings("deprecation") - @Deprecated - public boolean hasPlot(World world, Player player) { + @SuppressWarnings("deprecation") @Deprecated public boolean hasPlot(World world, + Player player) { return getPlots(world, player, true).length > 0; } /** * Get all plots for the player. * - * @param world The world to retrieve plots from - * @param player The player to search for + * @param world The world to retrieve plots from + * @param player The player to search for * @param justOwner should we just search for owner? Or with rights? * @return An array of plots for the player */ - @Deprecated - public Plot[] getPlots(World world, Player player, boolean justOwner) { + @Deprecated public Plot[] getPlots(World world, Player player, boolean justOwner) { ArrayList pPlots = new ArrayList<>(); UUID uuid = BukkitUtil.getPlayer(player).getUUID(); for (Plot plot : PS.get().getPlots(world.getName())) { @@ -485,14 +437,11 @@ public class PlotAPI { * Get all plots for the world. * * @param world to get plots of - * * @return Plot[] - array of plot objects in world - * * @see PS#getPlots(String) * @see Plot */ - @Deprecated - public Plot[] getPlots(World world) { + @Deprecated public Plot[] getPlots(World world) { if (world == null) { return new Plot[0]; } @@ -504,11 +453,8 @@ public class PlotAPI { * Get all plot worlds. * * @return World[] - array of plot worlds - * */ - @SuppressWarnings("deprecation") - @Deprecated - public String[] getPlotWorlds() { + @SuppressWarnings("deprecation") @Deprecated public String[] getPlotWorlds() { Set plotWorldStrings = PS.get().getPlotWorldStrings(); return plotWorldStrings.toArray(new String[plotWorldStrings.size()]); } @@ -517,13 +463,10 @@ public class PlotAPI { * Get if plotworld. * * @param world The world to check - * * @return boolean (if plot world or not) - * * @see PS#hasPlotArea(String) */ - @Deprecated - public boolean isPlotWorld(World world) { + @Deprecated public boolean isPlotWorld(World world) { return PS.get().hasPlotArea(world.getName()); } @@ -531,29 +474,22 @@ public class PlotAPI { * Get plot locations. * * @param plot Plot to get the locations for - * * @return [0] = bottomLc, [1] = topLoc, [2] = home - * - * @deprecated As merged plots may not have a rectangular shape - * * @see Plot + * @deprecated As merged plots may not have a rectangular shape */ - @SuppressWarnings("deprecation") - @Deprecated - public Location[] getLocations(Plot plot) { + @SuppressWarnings("deprecation") @Deprecated public Location[] getLocations(Plot plot) { Location bukkitBottom = BukkitUtil.getLocation(plot.getCorners()[0]); Location bukkitTop = BukkitUtil.getLocation(plot.getCorners()[1]); Location bukkitHome = BukkitUtil.getLocation(plot.getHome()); - return new Location[]{bukkitBottom, bukkitTop, bukkitHome}; + return new Location[] {bukkitBottom, bukkitTop, bukkitHome}; } /** * Get home location. * * @param plot Plot that you want to get the location for - * * @return plot bottom location - * * @see Plot */ public Location getHomeLocation(Plot plot) { @@ -564,16 +500,11 @@ public class PlotAPI { * Get Bottom Location (min, min, min). * * @param plot Plot that you want to get the location for - * * @return plot bottom location - * - * @deprecated As merged plots may not have a rectangular shape - * * @see Plot + * @deprecated As merged plots may not have a rectangular shape */ - @SuppressWarnings("deprecation") - @Deprecated - public Location getBottomLocation(Plot plot) { + @SuppressWarnings("deprecation") @Deprecated public Location getBottomLocation(Plot plot) { return BukkitUtil.getLocation(plot.getCorners()[0]); } @@ -581,16 +512,11 @@ public class PlotAPI { * Get Top Location (max, max, max). * * @param plot Plot that you want to get the location for - * * @return plot top location - * - * @deprecated As merged plots may not have a rectangular shape - * * @see Plot + * @deprecated As merged plots may not have a rectangular shape */ - @SuppressWarnings("deprecation") - @Deprecated - public Location getTopLocation(Plot plot) { + @SuppressWarnings("deprecation") @Deprecated public Location getTopLocation(Plot plot) { return BukkitUtil.getLocation(plot.getCorners()[1]); } @@ -598,9 +524,7 @@ public class PlotAPI { * Check whether or not a player is in a plot. * * @param player who we're checking for - * * @return true if the player is in a plot, false if not- - * */ public boolean isInPlot(Player player) { return getPlot(player) != null; @@ -608,12 +532,12 @@ public class PlotAPI { /** * Register a subcommand. - * @deprecated Command registration is done on object creation + * * @param c SubCommand, that we want to register * @see SubCommand + * @deprecated Command registration is done on object creation */ - @Deprecated - public void registerCommand(SubCommand c) { + @Deprecated public void registerCommand(SubCommand c) { PS.debug("SubCommands are now registered on creation"); } @@ -621,7 +545,6 @@ public class PlotAPI { * Gets the PlotSquared class. * * @return PlotSquared Class - * * @see PS */ public PS getPlotSquared() { @@ -633,9 +556,7 @@ public class PlotAPI { * * @param world Specify the world we want to select the plots from * @param player Player, for whom we're getting the plot count - * * @return the number of plots the player has - * */ public int getPlayerPlotCount(World world, Player player) { if (world == null) { @@ -649,11 +570,8 @@ public class PlotAPI { * * @param world Specify the world we want to select the plots from * @param player Player, for whom we're getting the plots - * * @return a set containing the players plots - * * @see PS#getPlots(String, PlotPlayer) - * * @see Plot */ public Set getPlayerPlots(World world, Player player) { @@ -667,9 +585,7 @@ public class PlotAPI { * Gets the number of plots, which the player is able to build in. * * @param player player, for whom we're getting the plots - * * @return the number of allowed plots - * */ public int getAllowedPlots(Player player) { PlotPlayer plotPlayer = PlotPlayer.wrap(player); @@ -680,10 +596,9 @@ public class PlotAPI { * Gets the PlotPlayer for a player. The PlotPlayer is usually cached and * will provide useful functions relating to players. * - * @see PlotPlayer#wrap(Object) - * * @param player the player to wrap * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) */ public PlotPlayer wrapPlayer(Player player) { return PlotPlayer.wrap(player); @@ -691,14 +606,13 @@ public class PlotAPI { /** * Get the PlotPlayer for a UUID. - * + *

*

Please note that PlotSquared can be configured to provide * different UUIDs than bukkit * - * @see PlotPlayer#wrap(Object) - * * @param uuid the uuid of the player to wrap * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) */ public PlotPlayer wrapPlayer(UUID uuid) { return PlotPlayer.wrap(uuid); @@ -707,10 +621,9 @@ public class PlotAPI { /** * Get the PlotPlayer for a username. * - * @see PlotPlayer#wrap(Object) - * * @param player the player to wrap * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) */ public PlotPlayer wrapPlayer(String player) { return PlotPlayer.wrap(player); @@ -718,14 +631,13 @@ public class PlotAPI { /** * Get the PlotPlayer for an offline player. - * + *

*

Note that this will work if the player is offline, however not all * functionality will work. * - * @see PlotPlayer#wrap(Object) - * * @param player the player to wrap * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) */ public PlotPlayer wrapPlayer(OfflinePlayer player) { return PlotPlayer.wrap(player); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index 059d65d46..d8e13d446 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -1,7 +1,5 @@ package com.plotsquared.bukkit; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.plot.IPlotMain; import com.intellectualcrafters.plot.PS; @@ -12,89 +10,27 @@ import com.intellectualcrafters.plot.generator.GeneratorWrapper; import com.intellectualcrafters.plot.generator.HybridGen; import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.SetupObject; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.object.chat.PlainChatManager; import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; import com.intellectualcrafters.plot.object.worlds.SingleWorldGenerator; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChatManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.ConsoleColors; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.block.QueueProvider; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.database.plotme.ClassicPlotMeConnector; import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter; import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; -import com.plotsquared.bukkit.listeners.ChunkListener; -import com.plotsquared.bukkit.listeners.EntityPortal_1_7_9; -import com.plotsquared.bukkit.listeners.EntitySpawnListener; -import com.plotsquared.bukkit.listeners.PlayerEvents; -import com.plotsquared.bukkit.listeners.PlayerEvents183; -import com.plotsquared.bukkit.listeners.PlayerEvents_1_8; -import com.plotsquared.bukkit.listeners.PlayerEvents_1_9; -import com.plotsquared.bukkit.listeners.PlotPlusListener; -import com.plotsquared.bukkit.listeners.PlotPlusListener_1_12; -import com.plotsquared.bukkit.listeners.PlotPlusListener_Legacy; -import com.plotsquared.bukkit.listeners.SingleWorldListener; -import com.plotsquared.bukkit.listeners.WorldEvents; +import com.plotsquared.bukkit.listeners.*; import com.plotsquared.bukkit.titles.DefaultTitle_111; -import com.plotsquared.bukkit.util.BukkitChatManager; -import com.plotsquared.bukkit.util.BukkitChunkManager; -import com.plotsquared.bukkit.util.BukkitCommand; -import com.plotsquared.bukkit.util.BukkitEconHandler; -import com.plotsquared.bukkit.util.BukkitEventUtil; -import com.plotsquared.bukkit.util.BukkitHybridUtils; -import com.plotsquared.bukkit.util.BukkitInventoryUtil; -import com.plotsquared.bukkit.util.BukkitSchematicHandler; -import com.plotsquared.bukkit.util.BukkitSetupUtils; -import com.plotsquared.bukkit.util.BukkitTaskManager; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.BukkitVersion; -import com.plotsquared.bukkit.util.Metrics; -import com.plotsquared.bukkit.util.SendChunk; -import com.plotsquared.bukkit.util.SetGenCB; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_7; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8_3; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_9; -import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper; -import com.plotsquared.bukkit.uuid.FileUUIDHandler; -import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; -import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; -import com.plotsquared.bukkit.uuid.SQLUUIDHandler; +import com.plotsquared.bukkit.util.*; +import com.plotsquared.bukkit.util.block.*; +import com.plotsquared.bukkit.uuid.*; import com.sk89q.worldedit.WorldEdit; -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; +import org.bukkit.*; import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -107,8 +43,17 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain { + public static WorldEdit worldEdit; private static ConcurrentHashMap pluginMap; static { @@ -128,14 +73,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain iter.remove(); } } - Map lookupNames = (Map) lookupNamesField.get(manager); + Map lookupNames = + (Map) lookupNamesField.get(manager); lookupNames.remove("PlotMe"); lookupNames.remove("PlotMe-DefaultGenerator"); pluginsField.set(manager, new ArrayList(plugins) { - @Override - public boolean add(Plugin plugin) { + @Override public boolean add(Plugin plugin) { if (plugin.getName().startsWith("PlotMe")) { - System.out.print("Disabling `" + plugin.getName() + "` for PlotMe conversion (configure in PlotSquared settings.yml)"); + System.out.print("Disabling `" + plugin.getName() + + "` for PlotMe conversion (configure in PlotSquared settings.yml)"); } else { return super.add(plugin); } @@ -143,8 +89,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } }); pluginMap = new ConcurrentHashMap(lookupNames) { - @Override - public Plugin put(String key, Plugin plugin) { + @Override public Plugin put(String key, Plugin plugin) { if (!plugin.getName().startsWith("PlotMe")) { return super.put(key, plugin); } @@ -153,17 +98,17 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain }; lookupNamesField.set(manager, pluginMap); } - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } } - public static WorldEdit worldEdit; - private int[] version; private String name; private SingleWorldListener singleWorldListener; + private Method methodUnloadChunk0; + private boolean methodUnloadSetup = false; - @Override - public int[] getServerVersion() { + @Override public int[] getServerVersion() { if (this.version == null) { try { this.version = new int[3]; @@ -177,14 +122,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain e.printStackTrace(); PS.debug(StringMan.getString(Bukkit.getBukkitVersion())); PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\."))); - return new int[]{1, 13, 0}; + return new int[] {1, 13, 0}; } } return this.version; } - @Override - public void onEnable() { + @Override public void onEnable() { if (pluginMap != null) { pluginMap.put("PlotMe-DefaultGenerator", this); } @@ -199,8 +143,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } if (Settings.Enabled_Components.WORLDS) { TaskManager.IMP.taskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { unload(); } }, 20); @@ -216,15 +159,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return singleWorldListener; } - private Method methodUnloadChunk0; - private boolean methodUnloadSetup = false; - public void unload() { if (!methodUnloadSetup) { methodUnloadSetup = true; try { ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - methodUnloadChunk0 = classCraftWorld.getRealClass().getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); + methodUnloadChunk0 = classCraftWorld.getRealClass() + .getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); methodUnloadChunk0.setAccessible(true); } catch (Throwable ignore) { ignore.printStackTrace(); @@ -238,7 +179,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain for (World world : Bukkit.getWorlds()) { String name = world.getName(); char char0 = name.charAt(0); - if (!Character.isDigit(char0) && char0 != '-') continue; + if (!Character.isDigit(char0) && char0 != '-') + continue; if (!world.getPlayers().isEmpty()) { continue; } @@ -265,19 +207,22 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain boolean result; if (methodUnloadChunk0 != null) { try { - result = (boolean) methodUnloadChunk0.invoke(world, chunkI.getX(), chunkI.getZ(), true); + result = (boolean) methodUnloadChunk0 + .invoke(world, chunkI.getX(), chunkI.getZ(), true); } catch (Throwable e) { methodUnloadChunk0 = null; e.printStackTrace(); continue outer; } } else { - result = world.unloadChunk(chunkI.getX(), chunkI.getZ(), true, false); + result = world + .unloadChunk(chunkI.getX(), chunkI.getZ(), true, false); } if (!result) { continue outer; } - } while (index < chunks.length && System.currentTimeMillis() - start < 5); + } while (index < chunks.length + && System.currentTimeMillis() - start < 5); return; } } @@ -287,14 +232,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public void onDisable() { + @Override public void onDisable() { PS.get().disable(); Bukkit.getScheduler().cancelTasks(this); } - @Override - public void log(String message) { + @Override public void log(String message) { try { message = C.color(message); if (!Settings.Chat.CONSOLE_COLOR) { @@ -306,32 +249,29 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public void disable() { + @Override public void disable() { onDisable(); } - @Override - public int[] getPluginVersion() { + @Override public int[] getPluginVersion() { String ver = getDescription().getVersion(); if (ver.contains("-")) { ver = ver.split("-")[0]; } String[] split = ver.split("\\."); - return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; + return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]), + Integer.parseInt(split[2])}; } @Override public String getPluginVersionString() { return getDescription().getVersion(); } - @Override - public String getPluginName() { + @Override public String getPluginName() { return name; } - @Override - public void registerCommands() { + @Override public void registerCommands() { BukkitCommand bukkitCommand = new BukkitCommand(); PluginCommand plotCommand = getCommand("plots"); plotCommand.setExecutor(bukkitCommand); @@ -339,30 +279,24 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain plotCommand.setTabCompleter(bukkitCommand); } - @Override - public File getDirectory() { + @Override public File getDirectory() { return getDataFolder(); } - @Override - public File getWorldContainer() { + @Override public File getWorldContainer() { return Bukkit.getWorldContainer(); } - @Override - public TaskManager getTaskManager() { + @Override public TaskManager getTaskManager() { return new BukkitTaskManager(this); } - @Override - public void runEntityTask() { + @Override public void runEntityTask() { PS.log(C.PREFIX + "KillAllEntities started."); TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea plotArea) { + @Override public void run(PlotArea plotArea) { World world = Bukkit.getWorld(plotArea.worldname); try { if (world == null) { @@ -416,7 +350,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain case MINECART_TNT: case BOAT: if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation()); + com.intellectualcrafters.plot.object.Location location = + BukkitUtil.getLocation(entity.getLocation()); Plot plot = location.getPlot(); if (plot == null) { if (location.isPlotArea()) { @@ -503,10 +438,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain Location location = entity.getLocation(); if (BukkitUtil.getLocation(location).isPlotRoad()) { if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) { + LivingEntity livingEntity = + (LivingEntity) entity; + if (!livingEntity.isLeashed() || !entity + .hasMetadata("keep")) { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity + .getMetadata("keep").isEmpty()) { iterator.remove(); entity.remove(); continue; @@ -514,7 +452,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } else { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity + .getMetadata("keep").isEmpty()) { iterator.remove(); entity.remove(); continue; @@ -529,18 +468,28 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain LivingEntity livingEntity = (LivingEntity) entity; List meta = entity.getMetadata("plot"); if (meta != null && !meta.isEmpty()) { - if (livingEntity.isLeashed()) continue; + if (livingEntity.isLeashed()) + continue; - List keep = entity.getMetadata("keep"); - if (keep != null && !keep.isEmpty()) continue; + List keep = + entity.getMetadata("keep"); + if (keep != null && !keep.isEmpty()) + continue; - PlotId originalPlotId = (PlotId) meta.get(0).value(); + PlotId originalPlotId = + (PlotId) meta.get(0).value(); if (originalPlotId != null) { - com.intellectualcrafters.plot.object.Location pLoc = BukkitUtil.getLocation(entity.getLocation()); + com.intellectualcrafters.plot.object.Location + pLoc = BukkitUtil + .getLocation(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { - PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc)); - if (!originalPlotId.equals(currentPlotId) && (currentPlotId == null || !area.getPlot(originalPlotId).equals(area.getPlot(currentPlotId)))) { + PlotId currentPlotId = + PlotId.of(area.getPlotAbs(pLoc)); + if (!originalPlotId.equals(currentPlotId) + && (currentPlotId == null || !area + .getPlot(originalPlotId) + .equals(area.getPlot(currentPlotId)))) { iterator.remove(); entity.remove(); } @@ -548,12 +497,17 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } else { //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) - com.intellectualcrafters.plot.object.Location pLoc = BukkitUtil.getLocation(entity.getLocation()); + com.intellectualcrafters.plot.object.Location pLoc = + BukkitUtil.getLocation(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { - PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc)); + PlotId currentPlotId = + PlotId.of(area.getPlotAbs(pLoc)); if (currentPlotId != null) { - entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, currentPlotId)); + entity.setMetadata("plot", + new FixedMetadataValue( + (Plugin) PS.get().IMP, + currentPlotId)); } } } @@ -571,8 +525,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain }, 20); } - @Override - public final ChunkGenerator getDefaultWorldGenerator(String world, String id) { + @Override public final ChunkGenerator getDefaultWorldGenerator(String world, String id) { if (Settings.Enabled_Components.PLOTME_CONVERTER) { initPlotMeConverter(); Settings.Enabled_Components.PLOTME_CONVERTER = false; @@ -589,8 +542,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return (ChunkGenerator) result.specify(world); } - @Override - public void registerPlayerEvents() { + @Override public void registerPlayerEvents() { PlayerEvents main = new PlayerEvents(); getServer().getPluginManager().registerEvents(main, this); try { @@ -630,13 +582,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public void registerInventoryEvents() { + @Override public void registerInventoryEvents() { // Part of PlayerEvents - can be moved if necessary } - @Override - public void registerPlotPlusEvents() { + @Override public void registerPlotPlusEvents() { PlotPlusListener.startRunnable(this); getServer().getPluginManager().registerEvents(new PlotPlusListener(), this); if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_12_0)) { @@ -646,12 +596,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public void registerForceFieldEvents() { + @Override public void registerForceFieldEvents() { } - @Override - public boolean initWorldEdit() { + @Override public boolean initWorldEdit() { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { worldEdit = WorldEdit.getInstance(); return true; @@ -659,8 +607,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return false; } - @Override - public EconHandler getEconomyHandler() { + @Override public EconHandler getEconomyHandler() { try { BukkitEconHandler econ = new BukkitEconHandler(); if (econ.init()) { @@ -672,16 +619,16 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return null; } - @Override - public QueueProvider initBlockQueue() { + @Override public QueueProvider initBlockQueue() { try { new SendChunk(); MainUtil.canSendChunk = true; } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) { - PS.debug(SendChunk.class + " does not support " + StringMan.getString(getServerVersion())); + PS.debug( + SendChunk.class + " does not support " + StringMan.getString(getServerVersion())); MainUtil.canSendChunk = false; } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_13_0)) { + if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_13_0)) { return QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class); } if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_9_0)) { @@ -696,13 +643,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return QueueProvider.of(BukkitLocalQueue_1_7.class, BukkitLocalQueue.class); } - @Override - public WorldUtil initWorldUtil() { + @Override public WorldUtil initWorldUtil() { return new BukkitUtil(); } - @Override - public boolean initPlotMeConverter() { + @Override public boolean initPlotMeConverter() { if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) { return true; } else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) { @@ -711,8 +656,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return false; } - @Override - public GeneratorWrapper getGenerator(String world, String name) { + @Override public GeneratorWrapper getGenerator(String world, String name) { if (name == null) { return null; } @@ -728,23 +672,21 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public HybridUtils initHybridUtils() { + @Override public HybridUtils initHybridUtils() { return new BukkitHybridUtils(); } - @Override - public SetupUtils initSetupUtils() { + @Override public SetupUtils initSetupUtils() { return new BukkitSetupUtils(); } - @Override - public UUIDHandlerImplementation initUUIDHandler() { + @Override public UUIDHandlerImplementation initUUIDHandler() { boolean checkVersion = false; try { OfflinePlayer.class.getDeclaredMethod("getUniqueId"); checkVersion = true; - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } UUIDWrapper wrapper; if (Settings.UUID.OFFLINE) { if (Settings.UUID.FORCE_LOWERCASE) { @@ -765,18 +707,20 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain Settings.UUID.OFFLINE = true; } if (!checkVersion) { - PS.log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature."); + PS.log(C.PREFIX + + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature."); Settings.TITLES = false; } else { AbstractTitle.TITLE_CLASS = new DefaultTitle_111(); - if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { + if (wrapper instanceof DefaultUUIDWrapper + || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { Settings.UUID.NATIVE_UUID_PROVIDER = true; } } if (Settings.UUID.OFFLINE) { - PS.log(C.PREFIX - + " &6" + getPluginName() + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " - + "Bukkit"); + PS.log(C.PREFIX + " &6" + getPluginName() + + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " + + "Bukkit"); } else { PS.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs"); } @@ -787,53 +731,45 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public ChunkManager initChunkManager() { + @Override public ChunkManager initChunkManager() { return new BukkitChunkManager(); } - @Override - public EventUtil initEventUtil() { + @Override public EventUtil initEventUtil() { return new BukkitEventUtil(); } - @Override - public void unregister(PlotPlayer player) { + @Override public void unregister(PlotPlayer player) { BukkitUtil.removePlayer(player.getName()); } - @Override - public void registerChunkProcessor() { + @Override public void registerChunkProcessor() { getServer().getPluginManager().registerEvents(new ChunkListener(), this); } - @Override - public void registerWorldEvents() { + @Override public void registerWorldEvents() { getServer().getPluginManager().registerEvents(new WorldEvents(), this); } - @Override - public IndependentPlotGenerator getDefaultGenerator() { + @Override public IndependentPlotGenerator getDefaultGenerator() { return new HybridGen(); } - @Override - public InventoryUtil initInventoryUtil() { + @Override public InventoryUtil initInventoryUtil() { return new BukkitInventoryUtil(); } - @Override - public void startMetrics() { + @Override public void startMetrics() { new Metrics(this).start(); PS.log(C.PREFIX + "&6Metrics enabled."); } - @Override - public void setGenerator(String worldName) { + @Override public void setGenerator(String worldName) { World world = BukkitUtil.getWorld(worldName); if (world == null) { // create world - ConfigurationSection worldConfig = PS.get().worlds.getConfigurationSection("worlds." + worldName); + ConfigurationSection worldConfig = + PS.get().worlds.getConfigurationSection("worlds." + worldName); String manager = worldConfig.getString("generator.plugin", getPluginName()); SetupObject setup = new SetupObject(); setup.plotManager = manager; @@ -865,19 +801,16 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public SchematicHandler initSchematicHandler() { + @Override public SchematicHandler initSchematicHandler() { return new BukkitSchematicHandler(); } - @Override - public AbstractTitle initTitleManager() { + @Override public AbstractTitle initTitleManager() { // Already initialized in UUID handler return AbstractTitle.TITLE_CLASS; } - @Override - public PlotPlayer wrapPlayer(Object player) { + @Override public PlotPlayer wrapPlayer(Object player) { if (player instanceof Player) { return BukkitUtil.getPlayer((Player) player); } @@ -893,14 +826,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return null; } - @Override - public String getNMSPackage() { + @Override public String getNMSPackage() { String name = Bukkit.getServer().getClass().getPackage().getName(); return name.substring(name.lastIndexOf('.') + 1); } - @Override - public ChatManager initChatManager() { + @Override public ChatManager initChatManager() { if (Settings.Chat.INTERACTIVE) { return new BukkitChatManager(); } else { @@ -913,12 +844,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return new BukkitPlotGenerator(generator); } - @Override - public List getPluginIds() { + @Override public List getPluginIds() { ArrayList names = new ArrayList<>(); for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin.isEnabled()); + names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin + .isEnabled()); } return names; } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java index 2dd68fa4e..269588f01 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java @@ -19,6 +19,8 @@ import java.util.Collection; */ public final class ArrayWrapper { + private E[] _array; + /** * Creates an array wrapper with some elements. * @@ -28,7 +30,38 @@ public final class ArrayWrapper { setArray(elements); } - private E[] _array; + /** + * Converts an iterable element collection to an array of elements. + * The iteration order of the specified object will be used as the array element order. + * + * @param list The iterable of objects which will be converted to an array. + * @param c The type of the elements of the array. + * @return An array of elements in the specified iterable. + */ + @SuppressWarnings("unchecked") public static T[] toArray(Iterable list, + Class c) { + int size = -1; + if (list instanceof Collection) { + @SuppressWarnings("rawtypes") Collection coll = (Collection) list; + size = coll.size(); + } + + + if (size < 0) { + size = 0; + // Ugly hack: Count it ourselves + for (@SuppressWarnings("unused") T element : list) { + size++; + } + } + + T[] result = (T[]) Array.newInstance(c, size); + int i = 0; + for (T element : list) { // Assumes iteration order is consistent + result[i++] = element; // Assign array element at index THEN increment counter + } + return result; + } /** * Retrieves a reference to the wrapped array instance. @@ -54,9 +87,7 @@ public final class ArrayWrapper { * * @see Arrays#equals(Object[], Object[]) */ - @SuppressWarnings("rawtypes") - @Override - public boolean equals(Object other) { + @SuppressWarnings("rawtypes") @Override public boolean equals(Object other) { if (!(other instanceof ArrayWrapper)) { return false; } @@ -69,43 +100,8 @@ public final class ArrayWrapper { * @return This object's hash code. * @see Arrays#hashCode(Object[]) */ - @Override - public int hashCode() { + @Override public int hashCode() { return Arrays.hashCode(_array); } - /** - * Converts an iterable element collection to an array of elements. - * The iteration order of the specified object will be used as the array element order. - * - * @param list The iterable of objects which will be converted to an array. - * @param c The type of the elements of the array. - * @return An array of elements in the specified iterable. - */ - @SuppressWarnings("unchecked") - public static T[] toArray(Iterable list, Class c) { - int size = -1; - if (list instanceof Collection) { - @SuppressWarnings("rawtypes") - Collection coll = (Collection) list; - size = coll.size(); - } - - - if (size < 0) { - size = 0; - // Ugly hack: Count it ourselves - for (@SuppressWarnings("unused") T element : list) { - size++; - } - } - - T[] result = (T[]) Array.newInstance(c, size); - int i = 0; - for (T element : list) { // Assumes iteration order is consistent - result[i++] = element; // Assign array element at index THEN increment counter - } - return result; - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java index 0f1b0d529..544713a9c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java @@ -1,17 +1,11 @@ package com.plotsquared.bukkit.chat; -import static com.plotsquared.bukkit.chat.TextualComponent.rawText; - import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; -import org.bukkit.Achievement; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.Statistic; +import org.bukkit.*; import org.bukkit.Statistic.Type; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -22,19 +16,12 @@ import org.bukkit.inventory.ItemStack; import java.io.IOException; import java.io.StringWriter; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.lang.reflect.*; +import java.util.*; import java.util.logging.Level; +import static com.plotsquared.bukkit.chat.TextualComponent.rawText; + /** * Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features provided by the vanilla Minecraft JSON message formatter. * This class allows plugins to emulate the functionality of the vanilla Minecraft tellraw command. @@ -45,7 +32,14 @@ import java.util.logging.Level; * optionally initializing it with text. Further property-setting method calls will affect that editing component. *

*/ -public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable { +public class FancyMessage + implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable { + + private static Constructor nmsPacketPlayOutChatConstructor; + // The ChatSerializer's instance of Gson + private static Object nmsChatSerializerGsonInstance; + private static Method fromJsonMethod; + private static JsonParser _stringParser = new JsonParser(); static { ConfigurationSerialization.registerClass(FancyMessage.class); @@ -55,20 +49,6 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< private String jsonString; private boolean dirty; - private static Constructor nmsPacketPlayOutChatConstructor; - - @Override - public FancyMessage clone() throws CloneNotSupportedException { - FancyMessage instance = (FancyMessage) super.clone(); - instance.messageParts = new ArrayList<>(messageParts.size()); - for (int i = 0; i < messageParts.size(); i++) { - instance.messageParts.add(i, messageParts.get(i).clone()); - } - instance.dirty = false; - instance.jsonString = null; - return instance; - } - /** * Creates a JSON message with text. * @@ -85,10 +65,12 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< dirty = false; if (nmsPacketPlayOutChatConstructor == null) { try { - nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); + nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat") + .getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); nmsPacketPlayOutChatConstructor.setAccessible(true); } catch (NoSuchMethodException e) { - Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e); + Bukkit.getLogger() + .log(Level.SEVERE, "Could not find Minecraft method or constructor.", e); } catch (SecurityException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e); } @@ -102,6 +84,112 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< this((TextualComponent) null); } + /** + * Deserializes a JSON-represented message from a mapping of key-value pairs. + * This is called by the Bukkit serialization API. + * It is not intended for direct public API consumption. + * + * @param serialized The key-value mapping which represents a fancy message. + */ + @SuppressWarnings("unchecked") public static FancyMessage deserialize( + Map serialized) { + FancyMessage msg = new FancyMessage(); + msg.messageParts = (List) serialized.get("messageParts"); + msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null; + msg.dirty = !serialized.containsKey("JSON"); + return msg; + } + + /** + * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of + * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs. + * + * @param json The JSON string which represents a fancy message. + * @return A {@code FancyMessage} representing the parameterized JSON message. + */ + public static FancyMessage deserialize(String json) { + JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); + JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component + FancyMessage returnVal = new FancyMessage(); + returnVal.messageParts.clear(); + for (JsonElement mPrt : extra) { + MessagePart component = new MessagePart(); + JsonObject messagePart = mPrt.getAsJsonObject(); + for (Map.Entry entry : messagePart.entrySet()) { + // Deserialize text + if (TextualComponent.isTextKey(entry.getKey())) { + // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields + Map serializedMapForm = + new HashMap<>(); // Must be object due to Bukkit serializer API compliance + serializedMapForm.put("key", entry.getKey()); + if (entry.getValue().isJsonPrimitive()) { + // Assume string + serializedMapForm.put("value", entry.getValue().getAsString()); + } else { + // Composite object, but we assume each element is a string + for (Map.Entry compositeNestedElement : entry + .getValue().getAsJsonObject().entrySet()) { + serializedMapForm.put("value." + compositeNestedElement.getKey(), + compositeNestedElement.getValue().getAsString()); + } + } + component.text = TextualComponent.deserialize(serializedMapForm); + } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { + if (entry.getValue().getAsBoolean()) { + component.styles + .add(MessagePart.stylesToNames.inverse().get(entry.getKey())); + } + } else if (entry.getKey().equals("color")) { + component.color = + ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); + } else if (entry.getKey().equals("clickEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.clickActionName = object.get("action").getAsString(); + component.clickActionData = object.get("value").getAsString(); + } else if (entry.getKey().equals("hoverEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.hoverActionName = object.get("action").getAsString(); + if (object.get("value").isJsonPrimitive()) { + // Assume string + component.hoverActionData = + new JsonString(object.get("value").getAsString()); + } else { + // Assume composite type + // The only composite type we currently store is another FancyMessage + // Therefore, recursion time! + component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */); + } + } else if (entry.getKey().equals("insertion")) { + component.insertionData = entry.getValue().getAsString(); + } else if (entry.getKey().equals("with")) { + for (JsonElement object : entry.getValue().getAsJsonArray()) { + if (object.isJsonPrimitive()) { + component.translationReplacements + .add(new JsonString(object.getAsString())); + } else { + // Only composite type stored in this array is - again - FancyMessages + // Recurse within this function to parse this as a translation replacement + component.translationReplacements.add(deserialize(object.toString())); + } + } + } + } + returnVal.messageParts.add(component); + } + return returnVal; + } + + @Override public FancyMessage clone() throws CloneNotSupportedException { + FancyMessage instance = (FancyMessage) super.clone(); + instance.messageParts = new ArrayList<>(messageParts.size()); + for (int i = 0; i < messageParts.size(); i++) { + instance.messageParts.add(i, messageParts.get(i).clone()); + } + instance.dirty = false; + instance.jsonString = null; + return instance; + } + /** * Sets the text of the current editing component to a value. * @@ -242,8 +330,12 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< */ public FancyMessage achievementTooltip(final Achievement which) { try { - Object achievement = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement)); + Object achievement = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", + Achievement.class).invoke(null, which); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name") + .get(achievement)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -251,7 +343,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -267,11 +360,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< public FancyMessage statisticTooltip(final Statistic which) { Type type = which.getType(); if (type != Type.UNTYPED) { - throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!"); + throw new IllegalArgumentException( + "That statistic requires an additional " + type + " parameter!"); } try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); + Object statistic = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", + Statistic.class).invoke(null, which); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name") + .get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -279,7 +377,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -299,11 +398,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if ((type == Type.BLOCK && item.isBlock()) || type == Type.ENTITY) { - throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); + throw new IllegalArgumentException( + "Wrong parameter type for that statistic - needs " + type + "!"); } try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); + Object statistic = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", + Statistic.class, Material.class).invoke(null, which, item); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name") + .get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -311,7 +415,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -331,11 +436,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if (type != Type.ENTITY) { - throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); + throw new IllegalArgumentException( + "Wrong parameter type for that statistic - needs " + type + "!"); } try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); + Object statistic = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", + Statistic.class, EntityType.class).invoke(null, which, entity); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name") + .get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -343,7 +453,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -356,7 +467,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage itemTooltip(final String itemJSON) { - onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter + onHover("show_item", new JsonString( + itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter return this; } @@ -369,8 +481,13 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< */ public FancyMessage itemTooltip(final ItemStack itemStack) { try { - Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack); - return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString()); + Object nmsItem = Reflection + .getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", + ItemStack.class).invoke(null, itemStack); + return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", + Reflection.getNMSClass("NBTTagCompound")) + .invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()) + .toString()); } catch (Exception e) { e.printStackTrace(); return this; @@ -400,6 +517,22 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< tooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, String.class)); return this; } + /* + + /** + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * @param replacements The replacements, in order, that will be used in the language-specific message. + * @return This builder instance. + */ /* ------------ + public FancyMessage translationReplacements(final Iterable replacements){ + for(CharSequence str : replacements){ + latest().translationReplacements.add(new JsonString(str)); + } + + return this; + } + + */ /** * Set the behavior of the current editing component to display raw text when the client hovers over the text. @@ -453,15 +586,19 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } FancyMessage result = new FancyMessage(); - result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object + result.messageParts + .clear(); // Remove the one existing text component that exists by default, which destabilizes the object for (int i = 0; i < lines.length; i++) { try { for (MessagePart component : lines[i]) { if (component.clickActionData != null && component.clickActionName != null) { - throw new IllegalArgumentException("The tooltip text cannot have click data."); - } else if (component.hoverActionData != null && component.hoverActionName != null) { - throw new IllegalArgumentException("The tooltip text cannot have a tooltip."); + throw new IllegalArgumentException( + "The tooltip text cannot have click data."); + } else if (component.hoverActionData != null + && component.hoverActionName != null) { + throw new IllegalArgumentException( + "The tooltip text cannot have a tooltip."); } if (component.hasText()) { result.messageParts.add(component.clone()); @@ -475,7 +612,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return this; } } - return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended + return formattedTooltip( + result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended } /** @@ -486,7 +624,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage formattedTooltip(final Iterable lines) { - return formattedTooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class)); + return formattedTooltip( + com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class)); } /** @@ -503,22 +642,6 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return this; } - /* - - /** - * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. - * @param replacements The replacements, in order, that will be used in the language-specific message. - * @return This builder instance. - */ /* ------------ - public FancyMessage translationReplacements(final Iterable replacements){ - for(CharSequence str : replacements){ - latest().translationReplacements.add(new JsonString(str)); - } - - return this; - } - - */ /** * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. @@ -543,7 +666,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage translationReplacements(final Iterable replacements) { - return translationReplacements(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class)); + return translationReplacements( + com.plotsquared.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class)); } /** @@ -588,8 +712,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return this; } - @Override - public void writeJson(JsonWriter writer) throws IOException { + @Override public void writeJson(JsonWriter writer) throws IOException { if (messageParts.size() == 1) { latest().writeJson(writer); } else { @@ -641,8 +764,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Player player = (Player) sender; try { Object handle = Reflection.getHandle(player); - Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle); - Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString)); + Object connection = + Reflection.getField(handle.getClass(), "playerConnection").get(handle); + Reflection + .getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")) + .invoke(connection, createChatPacket(jsonString)); } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); } catch (IllegalAccessException e) { @@ -650,7 +776,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } catch (InstantiationException e) { Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e); } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); } catch (NoSuchMethodException e) { Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e); } catch (ClassNotFoundException e) { @@ -658,11 +785,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } } - // The ChatSerializer's instance of Gson - private static Object nmsChatSerializerGsonInstance; - private static Method fromJsonMethod; - - private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + private Object createChatPacket(String json) + throws IllegalArgumentException, IllegalAccessException, InstantiationException, + InvocationTargetException, NoSuchMethodException, ClassNotFoundException { if (nmsChatSerializerGsonInstance == null) { // Find the field and its value, completely bypassing obfuscation Class chatSerializerClazz; @@ -673,7 +798,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< // Y = minor // Z = revision final String version = Reflection.getVersion(); - String[] split = version.substring(1, version.length() - 1).split("_"); // Remove trailing dot + String[] split = + version.substring(1, version.length() - 1).split("_"); // Remove trailing dot //int majorVersion = Integer.parseInt(split[0]); int minorVersion = Integer.parseInt(split[1]); int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R @@ -689,11 +815,14 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } for (Field declaredField : chatSerializerClazz.getDeclaredFields()) { - if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().getName().endsWith("Gson")) { + if (Modifier.isFinal(declaredField.getModifiers()) && Modifier + .isStatic(declaredField.getModifiers()) && declaredField.getType().getName() + .endsWith("Gson")) { // We've found our field declaredField.setAccessible(true); nmsChatSerializerGsonInstance = declaredField.get(null); - fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class, Class.class); + fromJsonMethod = nmsChatSerializerGsonInstance.getClass() + .getMethod("fromJson", String.class, Class.class); break; } } @@ -701,7 +830,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< // Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it // Of course, the implementation may change, but fuzzy matches might break with signature changes - Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent")); + Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, + Reflection.getNMSClass("IChatBaseComponent")); return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent); } @@ -782,26 +912,10 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< public Map serialize() { HashMap map = new HashMap<>(); map.put("messageParts", messageParts); -// map.put("JSON", toJSONString()); + // map.put("JSON", toJSONString()); return map; } - /** - * Deserializes a JSON-represented message from a mapping of key-value pairs. - * This is called by the Bukkit serialization API. - * It is not intended for direct public API consumption. - * - * @param serialized The key-value mapping which represents a fancy message. - */ - @SuppressWarnings("unchecked") - public static FancyMessage deserialize(Map serialized) { - FancyMessage msg = new FancyMessage(); - msg.messageParts = (List) serialized.get("messageParts"); - msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null; - msg.dirty = !serialized.containsKey("JSON"); - return msg; - } - /** * Internally called method. Not for API consumption. */ @@ -809,78 +923,4 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return messageParts.iterator(); } - private static JsonParser _stringParser = new JsonParser(); - - /** - * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of - * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs. - * - * @param json The JSON string which represents a fancy message. - * @return A {@code FancyMessage} representing the parameterized JSON message. - */ - public static FancyMessage deserialize(String json) { - JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); - JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component - FancyMessage returnVal = new FancyMessage(); - returnVal.messageParts.clear(); - for (JsonElement mPrt : extra) { - MessagePart component = new MessagePart(); - JsonObject messagePart = mPrt.getAsJsonObject(); - for (Map.Entry entry : messagePart.entrySet()) { - // Deserialize text - if (TextualComponent.isTextKey(entry.getKey())) { - // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields - Map serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance - serializedMapForm.put("key", entry.getKey()); - if (entry.getValue().isJsonPrimitive()) { - // Assume string - serializedMapForm.put("value", entry.getValue().getAsString()); - } else { - // Composite object, but we assume each element is a string - for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) { - serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString()); - } - } - component.text = TextualComponent.deserialize(serializedMapForm); - } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { - if (entry.getValue().getAsBoolean()) { - component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey())); - } - } else if (entry.getKey().equals("color")) { - component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); - } else if (entry.getKey().equals("clickEvent")) { - JsonObject object = entry.getValue().getAsJsonObject(); - component.clickActionName = object.get("action").getAsString(); - component.clickActionData = object.get("value").getAsString(); - } else if (entry.getKey().equals("hoverEvent")) { - JsonObject object = entry.getValue().getAsJsonObject(); - component.hoverActionName = object.get("action").getAsString(); - if (object.get("value").isJsonPrimitive()) { - // Assume string - component.hoverActionData = new JsonString(object.get("value").getAsString()); - } else { - // Assume composite type - // The only composite type we currently store is another FancyMessage - // Therefore, recursion time! - component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */); - } - } else if (entry.getKey().equals("insertion")) { - component.insertionData = entry.getValue().getAsString(); - } else if (entry.getKey().equals("with")) { - for (JsonElement object : entry.getValue().getAsJsonArray()) { - if (object.isJsonPrimitive()) { - component.translationReplacements.add(new JsonString(object.getAsString())); - } else { - // Only composite type stored in this array is - again - FancyMessages - // Recurse within this function to parse this as a translation replacement - component.translationReplacements.add(deserialize(object.toString())); - } - } - } - } - returnVal.messageParts.add(component); - } - return returnVal; - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java index 6092bce60..a4a66d3bf 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java @@ -11,6 +11,7 @@ interface JsonRepresentedObject { /** * Writes the JSON representation of this object to the specified writer. + * * @param writer The JSON writer which will receive the object. * @throws IOException If an error occurs writing to the stream. */ diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java index 1fb197e8b..931ab9394 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java @@ -20,8 +20,11 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab _value = value == null ? null : value.toString(); } - @Override - public void writeJson(JsonWriter writer) throws IOException { + public static JsonString deserialize(Map map) { + return new JsonString(map.get("stringValue").toString()); + } + + @Override public void writeJson(JsonWriter writer) throws IOException { writer.value(getValue()); } @@ -35,12 +38,7 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab return theSingleValue; } - public static JsonString deserialize(Map map) { - return new JsonString(map.get("stringValue").toString()); - } - - @Override - public String toString() { + @Override public String toString() { return _value; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java index a3ed7fa2b..31f6d2522 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java @@ -19,43 +19,6 @@ import java.util.logging.Level; */ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable { - ChatColor color = ChatColor.WHITE; - ArrayList styles = new ArrayList<>(); - String clickActionName = null; - String clickActionData = null; - String hoverActionName = null; - JsonRepresentedObject hoverActionData = null; - TextualComponent text = null; - String insertionData = null; - ArrayList translationReplacements = new ArrayList<>(); - - MessagePart(final TextualComponent text) { - this.text = text; - } - - MessagePart() { - this.text = null; - } - - boolean hasText() { - return text != null; - } - - @Override - @SuppressWarnings("unchecked") - public MessagePart clone() throws CloneNotSupportedException { - MessagePart obj = (MessagePart) super.clone(); - obj.styles = (ArrayList) styles.clone(); - if (hoverActionData instanceof JsonString) { - obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); - } else if (hoverActionData instanceof FancyMessage) { - obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); - } - obj.translationReplacements = (ArrayList) translationReplacements.clone(); - return obj; - - } - static final BiMap stylesToNames; static { @@ -83,6 +46,62 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa stylesToNames = builder.build(); } + static { + ConfigurationSerialization.registerClass(MessagePart.class); + } + + ChatColor color = ChatColor.WHITE; + ArrayList styles = new ArrayList<>(); + String clickActionName = null; + String clickActionData = null; + String hoverActionName = null; + JsonRepresentedObject hoverActionData = null; + TextualComponent text = null; + String insertionData = null; + ArrayList translationReplacements = new ArrayList<>(); + + MessagePart(final TextualComponent text) { + this.text = text; + } + + MessagePart() { + this.text = null; + } + + @SuppressWarnings("unchecked") + public static MessagePart deserialize(Map serialized) { + MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); + part.styles = (ArrayList) serialized.get("styles"); + part.color = ChatColor.getByChar(serialized.get("color").toString()); + part.hoverActionName = (String) serialized.get("hoverActionName"); + part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData"); + part.clickActionName = (String) serialized.get("clickActionName"); + part.clickActionData = (String) serialized.get("clickActionData"); + part.insertionData = (String) serialized.get("insertion"); + part.translationReplacements = + (ArrayList) serialized.get("translationReplacements"); + return part; + } + + boolean hasText() { + return text != null; + } + + @Override @SuppressWarnings("unchecked") public MessagePart clone() + throws CloneNotSupportedException { + MessagePart obj = (MessagePart) super.clone(); + obj.styles = (ArrayList) styles.clone(); + if (hoverActionData instanceof JsonString) { + obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); + } else if (hoverActionData instanceof FancyMessage) { + obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); + } + obj.translationReplacements = + (ArrayList) translationReplacements.clone(); + return obj; + + } + public void writeJson(JsonWriter json) { try { json.beginObject(); @@ -92,24 +111,20 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa json.name(stylesToNames.get(style)).value(true); } if (clickActionName != null && clickActionData != null) { - json.name("clickEvent") - .beginObject() - .name("action").value(clickActionName) - .name("value").value(clickActionData) - .endObject(); + json.name("clickEvent").beginObject().name("action").value(clickActionName) + .name("value").value(clickActionData).endObject(); } if (hoverActionName != null && hoverActionData != null) { - json.name("hoverEvent") - .beginObject() - .name("action").value(hoverActionName) - .name("value"); + json.name("hoverEvent").beginObject().name("action").value(hoverActionName) + .name("value"); hoverActionData.writeJson(json); json.endObject(); } if (insertionData != null) { json.name("insertion").value(insertionData); } - if (translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)) { + if (translationReplacements.size() > 0 && text != null && TextualComponent + .isTranslatableText(text)) { json.name("with").beginArray(); for (JsonRepresentedObject obj : translationReplacements) { obj.writeJson(json); @@ -118,7 +133,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa } json.endObject(); } catch (IOException e) { - Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e); + Bukkit.getLogger() + .log(Level.WARNING, "A problem occured during writing of JSON string", e); } } @@ -136,22 +152,4 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa return map; } - @SuppressWarnings("unchecked") - public static MessagePart deserialize(Map serialized) { - MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); - part.styles = (ArrayList) serialized.get("styles"); - part.color = ChatColor.getByChar(serialized.get("color").toString()); - part.hoverActionName = (String) serialized.get("hoverActionName"); - part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData"); - part.clickActionName = (String) serialized.get("clickActionName"); - part.clickActionData = (String) serialized.get("clickActionData"); - part.insertionData = (String) serialized.get("insertion"); - part.translationReplacements = (ArrayList) serialized.get("translationReplacements"); - return part; - } - - static { - ConfigurationSerialization.registerClass(MessagePart.class); - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java index de315c06e..7ef4b5160 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java @@ -28,10 +28,12 @@ public final class Reflection { * Contains loaded methods in a cache. * The map maps [types to maps of [method names to maps of [parameter types to method instances]]]. */ - private static final Map, Map>, Method>>> _loadedMethods = new HashMap<>(); + private static final Map, Map>, Method>>> + _loadedMethods = new HashMap<>(); private static String _versionString; - private Reflection() { } + private Reflection() { + } /** * Gets the version string from the package name of the CraftBukkit server implementation. @@ -109,8 +111,9 @@ public final class Reflection { * @param obj The object for which to retrieve an NMS handle. * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}. */ - public synchronized static Object getHandle(Object obj) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException { - return getMethod(obj.getClass(), "getHandle").invoke(obj); + public synchronized static Object getHandle(Object obj) + throws InvocationTargetException, IllegalAccessException, IllegalArgumentException { + return getMethod(obj.getClass(), "getHandle").invoke(obj); } /** @@ -181,7 +184,8 @@ public final class Reflection { _loadedMethods.put(clazz, new HashMap>, Method>>()); } - Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); + Map>, Method>> loadedMethodNames = + _loadedMethods.get(clazz); if (!loadedMethodNames.containsKey(name)) { loadedMethodNames.put(name, new HashMap>, Method>()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java index 44005ed39..cd62548df 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java @@ -27,7 +27,8 @@ public abstract class TextualComponent implements Cloneable { if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) { // Arbitrary text component return ArbitraryTextTypeComponent.deserialize(map); - } else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) { + } else if (map.size() >= 2 && map.containsKey("key") && !map + .containsKey("value") /* It contains keys that START WITH value */) { // Complex JSON object return ComplexTextTypeComponent.deserialize(map); } @@ -36,16 +37,18 @@ public abstract class TextualComponent implements Cloneable { } static boolean isTextKey(String key) { - return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); + return key.equals("translate") || key.equals("text") || key.equals("score") || key + .equals("selector"); } static boolean isTranslatableText(TextualComponent component) { - return component instanceof ComplexTextTypeComponent && component.getKey().equals("translate"); + return component instanceof ComplexTextTypeComponent && component.getKey() + .equals("translate"); } /** * Create a textual component representing a string literal. - * + *

*

This is the default type of textual component when a single string * literal is given to a method. * @@ -73,7 +76,8 @@ public abstract class TextualComponent implements Cloneable { } private static void throwUnsupportedSnapshot() { - throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); + throw new UnsupportedOperationException( + "This feature is only supported in snapshot releases."); } /** @@ -94,15 +98,15 @@ public abstract class TextualComponent implements Cloneable { /** * Create a textual component representing a scoreboard value. * The client will see the score of the specified player for the specified objective as the text represented by this component. - * + *

*

This method is currently guaranteed to throw an {@code UnsupportedOperationException} * as it is only supported on snapshot clients. * - * @param playerName The name of the player whos score will be shown. If - * this string represents the single-character sequence - * "*", the viewing player's score will be displayed. - * Standard minecraft selectors (@a, @p, etc) - * are not supported. + * @param playerName The name of the player whos score will be shown. If + * this string represents the single-character sequence + * "*", the viewing player's score will be displayed. + * Standard minecraft selectors (@a, @p, etc) + * are not supported. * @param scoreboardObjective The name of the objective for * which to display the score. * @return The text component representing the specified scoreboard score @@ -112,10 +116,9 @@ public abstract class TextualComponent implements Cloneable { throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE // OVERLOADS documentation accordingly - return new ComplexTextTypeComponent("score", ImmutableMap.builder() - .put("name", playerName) - .put("objective", scoreboardObjective) - .build()); + return new ComplexTextTypeComponent("score", + ImmutableMap.builder().put("name", playerName) + .put("objective", scoreboardObjective).build()); } /** @@ -126,7 +129,7 @@ public abstract class TextualComponent implements Cloneable { *

* * @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in - * the place of this text component. + * the place of this text component. * @return The text component representing the name of the entities captured by the selector. */ public static TextualComponent selector(String selector) { @@ -136,8 +139,7 @@ public abstract class TextualComponent implements Cloneable { return new ArbitraryTextTypeComponent("selector", selector); } - @Override - public String toString() { + @Override public String toString() { return getReadableString(); } @@ -155,8 +157,7 @@ public abstract class TextualComponent implements Cloneable { * Clones a textual component instance. * The returned object should not reference this textual component instance, but should maintain the same key and value. */ - @Override - public abstract TextualComponent clone() throws CloneNotSupportedException; + @Override public abstract TextualComponent clone() throws CloneNotSupportedException; /** * Writes the text data represented by this textual component to the specified JSON writer object. @@ -171,7 +172,8 @@ public abstract class TextualComponent implements Cloneable { * Internal class used to represent all types of text components. * Exception validating done is on keys and values. */ - private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable { + private static final class ArbitraryTextTypeComponent extends TextualComponent + implements ConfigurationSerializable { private String key; private String value; @@ -182,16 +184,17 @@ public abstract class TextualComponent implements Cloneable { } public static ArbitraryTextTypeComponent deserialize(Map map) { - return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString()); + return new ArbitraryTextTypeComponent(map.get("key").toString(), + map.get("value").toString()); } - @Override - public String getKey() { + @Override public String getKey() { return key; } public void setKey(String key) { - Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified."); + Preconditions + .checkArgument(key != null && !key.isEmpty(), "The key must be specified."); this.key = key; } @@ -204,20 +207,16 @@ public abstract class TextualComponent implements Cloneable { this.value = value; } - @Override - public TextualComponent clone() throws CloneNotSupportedException { + @Override public TextualComponent clone() throws CloneNotSupportedException { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone return new ArbitraryTextTypeComponent(getKey(), getValue()); } - @Override - public void writeJson(JsonWriter writer) throws IOException { + @Override public void writeJson(JsonWriter writer) throws IOException { writer.name(getKey()).value(getValue()); } - @Override - @SuppressWarnings("serial") - public Map serialize() { + @Override @SuppressWarnings("serial") public Map serialize() { return new HashMap() { { put("key", getKey()); @@ -226,19 +225,20 @@ public abstract class TextualComponent implements Cloneable { }; } - @Override - public String getReadableString() { + @Override public String getReadableString() { return getValue(); } } + /** * Internal class used to represent a text component with a nested JSON * value. - * + *

*

Exception validating done is on keys and values. */ - private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable { + private static final class ComplexTextTypeComponent extends TextualComponent + implements ConfigurationSerializable { private String key; private Map value; @@ -255,19 +255,20 @@ public abstract class TextualComponent implements Cloneable { if (valEntry.getKey().equals("key")) { key = (String) valEntry.getValue(); } else if (valEntry.getKey().startsWith("value.")) { - value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); + value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, + valEntry.getValue().toString()); } } return new ComplexTextTypeComponent(key, value); } - @Override - public String getKey() { + @Override public String getKey() { return key; } public void setKey(String key) { - Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified."); + Preconditions + .checkArgument(key != null && !key.isEmpty(), "The key must be specified."); this.key = key; } @@ -280,14 +281,12 @@ public abstract class TextualComponent implements Cloneable { this.value = value; } - @Override - public TextualComponent clone() { + @Override public TextualComponent clone() { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone return new ComplexTextTypeComponent(getKey(), getValue()); } - @Override - public void writeJson(JsonWriter writer) throws IOException { + @Override public void writeJson(JsonWriter writer) throws IOException { writer.name(getKey()); writer.beginObject(); for (Map.Entry jsonPair : value.entrySet()) { @@ -296,9 +295,7 @@ public abstract class TextualComponent implements Cloneable { writer.endObject(); } - @Override - @SuppressWarnings("serial") - public Map serialize() { + @Override @SuppressWarnings("serial") public Map serialize() { return new java.util.HashMap() { { put("key", getKey()); @@ -309,8 +306,7 @@ public abstract class TextualComponent implements Cloneable { }; } - @Override - public String getReadableString() { + @Override public String getReadableString() { return getKey(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java index b3934109a..fb664103a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java @@ -11,11 +11,7 @@ import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.uuid.DatFileFilter; import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper; @@ -23,32 +19,22 @@ import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -@CommandDeclaration( - command = "uuidconvert", - permission = "plots.admin", - description = "Debug UUID conversion", - usage = "/plot uuidconvert ", - requiredType = RequiredType.CONSOLE, - category = CommandCategory.DEBUG) +@CommandDeclaration(command = "uuidconvert", permission = "plots.admin", description = "Debug UUID conversion", usage = "/plot uuidconvert ", requiredType = RequiredType.CONSOLE, category = CommandCategory.DEBUG) public class DebugUUID extends SubCommand { public DebugUUID() { super(Argument.String); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper(); final UUIDWrapper newWrapper; @@ -67,7 +53,8 @@ public class DebugUUID extends SubCommand { Class clazz = Class.forName(args[0]); newWrapper = (UUIDWrapper) clazz.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot uuidconvert "); return false; } } @@ -75,23 +62,29 @@ public class DebugUUID extends SubCommand { if (args.length != 2 || !"-o".equals(args[1])) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o"); MainUtil.sendMessage(player, "&cBe aware of the following!"); - MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand"); - MainUtil.sendMessage(player, "&8 - &cIf the process is interrupted, all plots could be deleted"); + MainUtil.sendMessage(player, + "&8 - &cUse the database command or another method to backup your plots beforehand"); + MainUtil.sendMessage(player, + "&8 - &cIf the process is interrupted, all plots could be deleted"); MainUtil.sendMessage(player, "&8 - &cIf an error occurs, all plots could be deleted"); MainUtil.sendMessage(player, "&8 - &cPlot settings WILL be lost upon conversion"); - MainUtil.sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!"); - MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)"); + MainUtil + .sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!"); + MainUtil.sendMessage(player, + "&7Retype the command with the override parameter when ready :)"); return false; } - if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) { + if (currentUUIDWrapper.getClass().getCanonicalName() + .equals(newWrapper.getClass().getCanonicalName())) { MainUtil.sendMessage(player, "&cUUID mode already in use!"); return false; } MainUtil.sendMessage(player, "&6Beginning UUID mode conversion"); MainUtil.sendMessage(player, "&7 - Disconnecting players"); for (Entry entry : UUIDHandler.getPlayers().entrySet()) { - entry.getValue().kick("UUID conversion has been initiated. You may reconnect when finished."); + entry.getValue() + .kick("UUID conversion has been initiated. You may reconnect when finished."); } MainUtil.sendMessage(player, "&7 - Initializing map"); @@ -135,12 +128,14 @@ public class DebugUUID extends SubCommand { OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid); uuid = currentUUIDWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op); - if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) { + if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse + .containsKey(uuid2)) { uCMap.put(uuid, uuid2); uCReverse.put(uuid2, uuid); } } catch (Throwable ignored) { - MainUtil.sendMessage(player, C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); + MainUtil.sendMessage(player, + C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } for (String name : names) { @@ -175,8 +170,7 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Replacing cache"); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { for (Entry entry : uCMap.entrySet()) { String name = UUIDHandler.getName(entry.getKey()); if (name != null) { @@ -189,7 +183,8 @@ public class DebugUUID extends SubCommand { File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); if (file.exists()) { try { - List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + List lines = + Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); for (String line : lines) { try { line = line.trim(); @@ -199,7 +194,8 @@ public class DebugUUID extends SubCommand { line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); String[] split = line.split("\\|"); String name = split[0]; - if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) { + if (name.isEmpty() || name.length() > 16 || !StringMan + .isAlphanumericUnd(name)) { continue; } UUID old = currentUUIDWrapper.getUUID(name); @@ -249,12 +245,12 @@ public class DebugUUID extends SubCommand { plot.owner = value; } } - DBFunc.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, "&6Recovery was successful!"); - } - }); + DBFunc.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), + new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&6Recovery was successful!"); + } + }); return; } } catch (Exception e) { @@ -272,18 +268,17 @@ public class DebugUUID extends SubCommand { try { PS.get().worlds.save(PS.get().worldsFile); } catch (IOException ignored) { - MainUtil.sendMessage(player, "Could not save configuration. It will need to be manual set!"); + MainUtil.sendMessage(player, + "Could not save configuration. It will need to be manual set!"); } MainUtil.sendMessage(player, "&7 - Populating tables"); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { ArrayList plots = new ArrayList<>(PS.get().getPlots()); DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&aConversion complete!"); } }); @@ -291,7 +286,8 @@ public class DebugUUID extends SubCommand { }); MainUtil.sendMessage(player, "&aIt is now safe for players to join"); - MainUtil.sendMessage(player, "&cConversion is still in progress, you will be notified when it is complete"); + MainUtil.sendMessage(player, + "&cConversion is still in progress, you will be notified when it is complete"); } }); return true; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java index 1ebae3a93..8d006a943 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java @@ -13,9 +13,11 @@ import java.util.HashMap; public abstract class APlotMeConnector { - public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder); + public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, + String dataFolder); - public abstract HashMap> getPlotMePlots(Connection connection) throws SQLException; + public abstract HashMap> getPlotMePlots(Connection connection) + throws SQLException; public abstract boolean accepts(String version); @@ -31,9 +33,11 @@ public abstract class APlotMeConnector { String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); // PS.get().worlds.set("worlds." + actualWorldName + ".wall.block", wallBlock); String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); // - PS.get().worlds.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor)); + PS.get().worlds + .set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor)); String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); // - PS.get().worlds.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling)); + PS.get().worlds + .set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling)); String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId"); PS.get().worlds.set("worlds." + actualWorldName + ".road.block", road); int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); // @@ -58,25 +62,26 @@ public abstract class APlotMeConnector { return new Location(null, x, 1, z); } - public void setMerged(HashMap> merges, String world, PlotId id, int direction) { + public void setMerged(HashMap> merges, String world, + PlotId id, int direction) { HashMap plots = merges.get(world); PlotId id2 = new PlotId(id.x, id.y); boolean[] merge1; if (plots.containsKey(id)) { merge1 = plots.get(id); } else { - merge1 = new boolean[] { false, false, false, false }; + merge1 = new boolean[] {false, false, false, false}; } boolean[] merge2; if (plots.containsKey(id2)) { merge2 = plots.get(id2); } else { - merge2 = new boolean[] { false, false, false, false }; + merge2 = new boolean[] {false, false, false, false}; } merge1[direction] = true; merge2[(direction + 2) % 4] = true; plots.put(id, merge1); plots.put(id2, merge1); } - + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java index 11cea6ddb..a67b0256e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java @@ -6,20 +6,12 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.UUIDHandler; import java.io.File; import java.nio.ByteBuffer; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.HashMap; import java.util.Map.Entry; import java.util.UUID; @@ -29,8 +21,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { private String plugin = "PlotMe"; private String prefix; - @Override - public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) { + @Override public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, + String dataFolder) { this.plugin = plugin.toLowerCase(); this.prefix = plotConfig.getString("mySQLprefix", this.plugin.toLowerCase()); try { @@ -40,7 +32,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { String con = plotConfig.getString("mySQLconn"); return DriverManager.getConnection(con, user, password); } else { - return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection(); + return new SQLite(new File(dataFolder + File.separator + "plots.db")) + .openConnection(); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); @@ -48,13 +41,14 @@ public class ClassicPlotMeConnector extends APlotMeConnector { return null; } - @Override - public HashMap> getPlotMePlots(Connection connection) throws SQLException { + @Override public HashMap> getPlotMePlots(Connection connection) + throws SQLException { HashMap plotWidth = new HashMap<>(); HashMap roadWidth = new HashMap<>(); HashMap> plots = new HashMap<>(); HashMap> merges = new HashMap<>(); - PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`"); + PreparedStatement statement = + connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`"); ResultSet resultSet = statement.executeQuery(); String column = null; boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerid"); @@ -64,7 +58,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } else if (checkUUID2) { column = "ownerId"; } - boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; + boolean merge = + !"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; int missing = 0; while (resultSet.next()) { PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ")); @@ -122,7 +117,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { missing++; continue; } - owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); + owner = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); } } else { UUIDHandler.add(new StringWrapper(name), owner); @@ -134,7 +130,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { PS.log("&cSome names could not be identified:"); PS.log("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database"); PS.log("&7 - Names you have never seen before could be from people mistyping commands"); - PS.log("&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will " + PS.log( + "&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will " + "remain unknown until the player connects)"); } @@ -228,12 +225,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector { resultSet.close(); statement.close(); - } catch (SQLException ignored) {} + } catch (SQLException ignored) { + } return plots; } - @Override - public boolean accepts(String version) { - return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version); + @Override public boolean accepts(String version) { + return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get() + .canUpdate("0.999.999", version); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java index 05d8f4a20..16fe01f39 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java @@ -12,6 +12,11 @@ import com.intellectualcrafters.plot.object.PlotArea; import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.command.CommandException; + import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -20,17 +25,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.WorldCreator; -import org.bukkit.command.CommandException; public class LikePlotMeConverter { @@ -54,7 +51,8 @@ public class LikePlotMeConverter { } public String getPlotMePath() { - return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; + return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + + plugin + File.separator; } public FileConfiguration getPlotMeConfig(String dataFolder) { @@ -71,8 +69,9 @@ public class LikePlotMeConverter { public void mergeWorldYml(FileConfiguration plotConfig) { try { - File genConfig = - new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); + File genConfig = new File( + "plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + + File.separator + "config.yml"); if (genConfig.exists()) { YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig); for (String key : yml.getKeys(true)) { @@ -103,7 +102,8 @@ public class LikePlotMeConverter { content = content.replace("AthionPlots", pluginName); content = content.replace("PlotZWorld", pluginName); Files.write(path, content.getBytes(StandardCharsets.UTF_8)); - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } private void copyConfig(ConfigurationSection plotmeDgYml, String world) throws IOException { @@ -111,20 +111,25 @@ public class LikePlotMeConverter { String plotMeWorldName = world.toLowerCase(); Integer pathWidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); // PS.get().worlds.set("worlds." + world + ".road.width", pathWidth); - int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); // + int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", + plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); // PS.get().worlds.set("worlds." + world + ".road.height", height); PS.get().worlds.set("worlds." + world + ".wall.height", height); PS.get().worlds.set("worlds." + world + ".plot.height", height); int plotSize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize", 32); // PS.get().worlds.set("worlds." + world + ".plot.size", plotSize); - String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder", plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); // + String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder", + plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); // PS.get().worlds.set("worlds." + world + ".wall.block", wallblock); - String claimed = plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); // + String claimed = + plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); // PS.get().worlds.set("worlds." + world + ".wall.block_claimed", claimed); - String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); // + String floor = + plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); // PS.get().worlds.set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); // - PS.get().worlds.set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); + PS.get().worlds + .set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5"); PS.get().worlds.set("worlds." + world + ".road.block", road); PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height); @@ -151,14 +156,15 @@ public class LikePlotMeConverter { PS.debug("&3Using connector: " + connector.getClass().getCanonicalName()); - Connection connection = connector.getPlotMeConnection(plugin,plotConfig, dataFolder); + Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder); if (!connector.isValidConnection(connection)) { sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue"); return false; } - sendMessage("PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'"); + sendMessage( + "PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'"); mergeWorldYml(plotConfig); @@ -185,7 +191,7 @@ public class LikePlotMeConverter { } catch (IOException e) { e.printStackTrace(); sendMessage("&c-- &lFailed to save configuration for world '" + world - + "'\nThis will need to be done using the setup command, or manually"); + + "'\nThis will need to be done using the setup command, or manually"); } } } @@ -201,7 +207,9 @@ public class LikePlotMeConverter { sendMessage(" - " + dbPrefix + "Allowed"); sendMessage("Collected " + plotCount + " plots from PlotMe"); - File plotmeDgFile = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); + File plotmeDgFile = new File( + dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + + "config.yml"); if (plotmeDgFile.exists()) { YamlConfiguration plotmeDgYml = YamlConfiguration.loadConfiguration(plotmeDgFile); try { @@ -227,8 +235,9 @@ public class LikePlotMeConverter { } } if (duplicate > 0) { - PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world - + "'. Have you run the converter already?"); + PS.debug("&c[WARNING] Found " + duplicate + + " duplicate plots already in DB for world: '" + world + + "'. Have you run the converter already?"); } } else { if (PS.get().plots_tmp != null) { @@ -242,8 +251,9 @@ public class LikePlotMeConverter { } } if (duplicate > 0) { - PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world - + "'. Have you run the converter already?"); + PS.debug("&c[WARNING] Found " + duplicate + + " duplicate plots already in DB for world: '" + world + + "'. Have you run the converter already?"); } continue; } @@ -255,18 +265,20 @@ public class LikePlotMeConverter { Thread.sleep(1000); final AtomicBoolean done = new AtomicBoolean(false); DBFunc.createPlotsAndData(createdPlots, new Runnable() { - @Override - public void run() { + @Override public void run() { if (done.get()) { done(); sendMessage("&aDatabase conversion is now complete!"); PS.debug("&c - Stop the server"); - PS.debug("&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); - PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PS.debug( + "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); + PS.debug( + "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); PS.debug("&c - Start the server"); PS.get().setPlots(DBFunc.getPlots()); } else { - sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + sendMessage( + "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); done.set(true); } } @@ -278,57 +290,70 @@ public class LikePlotMeConverter { sendMessage(" - &cFailed to save configuration."); } TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { try { boolean mv = false; boolean mw = false; - if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core") - .isEnabled()) { + if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) + && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { mv = true; - } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld") - .isEnabled()) { + } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) + && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { mw = true; } for (String worldName : worlds) { World world = Bukkit.getWorld(getWorld(worldName)); if (world == null) { - sendMessage("&cInvalid world in PlotMe configuration: " + worldName); + sendMessage( + "&cInvalid world in PlotMe configuration: " + worldName); continue; } String actualWorldName = world.getName(); - sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); - if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName().equals(worldName)) { - sendMessage("&cYou need to stop the server to reload this world properly"); + sendMessage( + "Reloading generator for world: '" + actualWorldName + "'..."); + if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName() + .equals(worldName)) { + sendMessage( + "&cYou need to stop the server to reload this world properly"); } else { PS.get().removePlotAreas(actualWorldName); if (mv) { // unload world with MV - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv unload " + actualWorldName); try { Thread.sleep(1000); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } // load world with MV - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mv import " + actualWorldName + " normal -g " + PS.imp().getPluginName()); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv import " + actualWorldName + " normal -g " + PS + .imp().getPluginName()); } else if (mw) { // unload world with MW - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw unload " + actualWorldName); try { Thread.sleep(1000); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } // load world with MW - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mw create " + actualWorldName + " plugin:" + PS.imp().getPluginName()); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw create " + actualWorldName + " plugin:" + PS.imp() + .getPluginName()); } else { // Load using Bukkit API // - User must set generator manually Bukkit.getServer().unloadWorld(world, true); - World myWorld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator())).createWorld(); + World myWorld = WorldCreator.name(actualWorldName).generator( + new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator())) + .createWorld(); myWorld.save(); } } @@ -340,11 +365,14 @@ public class LikePlotMeConverter { done(); sendMessage("&aDatabase conversion is now complete!"); PS.debug("&c - Stop the server"); - PS.debug("&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); - PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PS.debug( + "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); + PS.debug( + "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); PS.debug("&c - Start the server"); } else { - sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + sendMessage( + "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); done.set(true); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java index 9567ebb8f..5617c1f9e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java @@ -5,19 +5,11 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.UUIDHandler; import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.HashMap; import java.util.UUID; @@ -25,8 +17,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { private String plugin; - @Override - public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) { + @Override public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, + String dataFolder) { this.plugin = plugin.toLowerCase(); try { if (plotConfig.getBoolean("usemySQL")) { @@ -39,7 +31,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { if (file.exists()) { return new SQLite(file).openConnection(); } - return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection(); + return new SQLite(new File(dataFolder + File.separator + "plots.db")) + .openConnection(); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); @@ -47,8 +40,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { return null; } - @Override - public HashMap> getPlotMePlots(Connection connection) throws SQLException { + @Override public HashMap> getPlotMePlots(Connection connection) + throws SQLException { ResultSet resultSet; PreparedStatement statement; HashMap plotWidth = new HashMap<>(); @@ -56,18 +49,21 @@ public class PlotMeConnector_017 extends APlotMeConnector { HashMap plots = new HashMap<>(); HashMap> merges = new HashMap<>(); try { - statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`"); + statement = + connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`"); resultSet = statement.executeQuery(); } catch (SQLException e) { PS.debug("========= Table does not exist ========="); e.printStackTrace(); PS.debug("======================================="); - PS.debug("&8 - &7The database does not match the version specified in the PlotMe config"); + PS.debug( + "&8 - &7The database does not match the version specified in the PlotMe config"); PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3"); return null; } boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID"); - boolean merge = !"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; + boolean merge = + !"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; while (resultSet.next()) { int key = resultSet.getInt("plot_id"); PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ")); @@ -115,7 +111,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { } } if (owner == null) { - PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + '\''); + PS.log( + "&cCould not identify owner for plot: " + id + " -> '" + name + '\''); continue; } } @@ -137,7 +134,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { statement.close(); try { PS.log(" - " + this.plugin + "core_denied"); - statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`"); + statement = + connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`"); resultSet = statement.executeQuery(); while (resultSet.next()) { @@ -153,7 +151,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { } PS.log(" - " + this.plugin + "core_allowed"); - statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`"); + statement = + connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`"); resultSet = statement.executeQuery(); while (resultSet.next()) { @@ -186,8 +185,7 @@ public class PlotMeConnector_017 extends APlotMeConnector { return processed; } - @Override - public boolean accepts(String version) { + @Override public boolean accepts(String version) { if (version == null) { return false; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java index 40e4a4e43..10ae21dac 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java @@ -19,7 +19,7 @@ public class ClusterFlagRemoveEvent extends Event implements Cancellable { /** * PlotFlagRemoveEvent: Called when a flag is removed from a plot. * - * @param flag Flag that was removed + * @param flag Flag that was removed * @param cluster PlotCluster from which the flag was removed */ public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) { @@ -49,18 +49,15 @@ public class ClusterFlagRemoveEvent extends Event implements Cancellable { return this.flag; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java index 6972e1b56..e209849d5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java @@ -45,18 +45,15 @@ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { return this.auto; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java index db860f35a..34c0f4f97 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java @@ -34,8 +34,7 @@ public class PlayerEnterPlotEvent extends PlayerEvent { return this.plot; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java index 225d89042..0b9f671aa 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java @@ -38,8 +38,7 @@ public class PlayerLeavePlotEvent extends PlayerEvent { return this.plot; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java index ab9b43b8b..a06962c16 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java @@ -59,8 +59,7 @@ public class PlayerPlotDeniedEvent extends PlotEvent { return this.initiator; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java index 8fc635494..0e7b33200 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java @@ -63,8 +63,7 @@ public class PlayerPlotHelperEvent extends PlotEvent { return this.initiator; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java index 2af07a33a..824c1d2d7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java @@ -63,8 +63,7 @@ public class PlayerPlotTrustedEvent extends PlotEvent { return this.initiator; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java index 069ade2ca..776fa0074 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java @@ -9,9 +9,6 @@ import org.bukkit.event.player.PlayerEvent; /** * Called when a player teleports to a plot - * - - */ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable { @@ -37,8 +34,7 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl return handlers; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } @@ -60,13 +56,11 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl return this.plot; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean cancelled) { + @Override public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java index 20ab1d519..124cccaa2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java @@ -7,12 +7,12 @@ import org.bukkit.event.HandlerList; /** * Called when a plot is cleared - * */ public class PlotClearEvent extends PlotEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled; + public PlotClearEvent(Plot plot) { super(plot); } @@ -39,18 +39,15 @@ public class PlotClearEvent extends PlotEvent implements Cancellable { return getPlot().getWorldName(); } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java index d7b33a06b..2578007ab 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java @@ -6,7 +6,6 @@ import org.bukkit.event.HandlerList; /** * Called when a plot component is set - * */ public class PlotComponentSetEvent extends PlotEvent { @@ -49,8 +48,7 @@ public class PlotComponentSetEvent extends PlotEvent { return this.component; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java index 126b735d7..3be92f7c8 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java @@ -6,7 +6,6 @@ import org.bukkit.event.HandlerList; /** * Called when a plot is deleted - * */ public class PlotDeleteEvent extends PlotEvent { @@ -38,8 +37,7 @@ public class PlotDeleteEvent extends PlotEvent { return getPlot().getWorldName(); } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java index 3ab3fc822..35249b696 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java @@ -7,7 +7,6 @@ import org.bukkit.event.HandlerList; /** * Called when a Flag is added to a plot. - * */ public class PlotFlagAddEvent extends PlotEvent implements Cancellable { @@ -39,18 +38,15 @@ public class PlotFlagAddEvent extends PlotEvent implements Cancellable { return this.flag; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public final boolean isCancelled() { + @Override public final boolean isCancelled() { return this.cancelled; } - @Override - public final void setCancelled(boolean cancelled) { + @Override public final void setCancelled(boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java index 0a8e9679b..bfa3850f7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java @@ -7,7 +7,6 @@ import org.bukkit.event.HandlerList; /** * Called when a flag is removed from a plot - * */ public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable { @@ -39,18 +38,15 @@ public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable { return this.flag; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public final boolean isCancelled() { + @Override public final boolean isCancelled() { return this.cancelled; } - @Override - public final void setCancelled(boolean cancelled) { + @Override public final void setCancelled(boolean cancelled) { this.cancelled = cancelled; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java index c03733ef8..f7f4f9ef2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java @@ -45,18 +45,15 @@ public class PlotMergeEvent extends PlotEvent implements Cancellable { return this.world; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java index 29aef2de8..801ab400d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java @@ -33,8 +33,7 @@ public class PlotRateEvent extends PlotEvent { this.rating = rating; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java index fb37b3a39..d9caab923 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java @@ -50,18 +50,15 @@ public class PlotUnlinkEvent extends Event implements Cancellable { return this.area; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java index 231d9c51c..9993e9eb9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java @@ -8,7 +8,7 @@ import org.bukkit.generator.BlockPopulator; import java.util.Random; public class BukkitAugmentedGenerator extends BlockPopulator { - + private static BukkitAugmentedGenerator generator; public static BukkitAugmentedGenerator get(World world) { @@ -24,8 +24,7 @@ public class BukkitAugmentedGenerator extends BlockPopulator { return generator; } - @Override - public void populate(World world, Random r, Chunk chunk) { + @Override public void populate(World world, Random r, Chunk chunk) { AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index c9b7c3169..c7ebefff7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -3,14 +3,7 @@ package com.plotsquared.bukkit.generator; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.generator.GeneratorWrapper; import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.object.SetupObject; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.object.worlds.SingleWorldGenerator; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.MainUtil; @@ -20,26 +13,24 @@ import com.intellectualcrafters.plot.util.block.LocalBlockQueue; import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.block.GenChunk; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Random; -import java.util.Set; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; -public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper { - +import java.util.*; + +public class BukkitPlotGenerator extends ChunkGenerator + implements GeneratorWrapper { + private final GenChunk chunkSetter; private final PseudoRandom random = new PseudoRandom(); private final IndependentPlotGenerator plotGenerator; - private List populators; private final ChunkGenerator platformGenerator; private final boolean full; private final HashMap dataMap = new HashMap<>(); + private List populators; private boolean loaded = false; public BukkitPlotGenerator(IndependentPlotGenerator generator) { @@ -53,12 +44,12 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap private LocalBlockQueue queue; - @Override - public void populate(World world, Random r, Chunk c) { + @Override public void populate(World world, Random r, Chunk c) { if (queue == null) { queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false); } - byte[][] resultData = dataMap.isEmpty() ? null : dataMap.remove(new ChunkLoc(c.getX(), c.getZ())); + byte[][] resultData = + dataMap.isEmpty() ? null : dataMap.remove(new ChunkLoc(c.getX(), c.getZ())); if (resultData == null) { GenChunk result = BukkitPlotGenerator.this.chunkSetter; // Set the chunk location @@ -90,7 +81,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap PlotArea area = PS.get().getPlotArea(world.getName(), null); ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ()); ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z); - if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) { + if (BukkitPlotGenerator.this.plotGenerator + .populateChunk(chunk, area, BukkitPlotGenerator.this.random)) { queue.flush(); } } @@ -99,51 +91,49 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap this.full = true; MainUtil.initCache(); } - + public BukkitPlotGenerator(final String world, final ChunkGenerator cg) { if (cg instanceof BukkitPlotGenerator) { - throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + " is already a BukkitPlotGenerator!"); + throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + + " is already a BukkitPlotGenerator!"); } this.full = false; PS.debug("BukkitPlotGenerator does not fully support: " + cg); this.platformGenerator = cg; this.plotGenerator = new IndependentPlotGenerator() { - @Override - public void processSetup(SetupObject setup) {} - - @Override - public void initialize(PlotArea area) {} - - @Override - public PlotManager getNewPlotManager() { + @Override public void processSetup(SetupObject setup) { + } + + @Override public void initialize(PlotArea area) { + } + + @Override public PlotManager getNewPlotManager() { return PS.get().IMP.getDefaultGenerator().getNewPlotManager(); } - - @Override - public String getName() { + + @Override public String getName() { return cg.getClass().getName(); } - + @Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) { return PS.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max); } - + @Override - public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, PseudoRandom random) { + public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, + PseudoRandom random) { World w = BukkitUtil.getWorld(world); Location min = result.getMin(); int cx = min.getX() >> 4; int cz = min.getZ() >> 4; Random r = new Random(MathMan.pair((short) cx, (short) cz)); BiomeGrid grid = new BiomeGrid() { - @Override - public void setBiome(int x, int z, Biome biome) { + @Override public void setBiome(int x, int z, Biome biome) { result.setBiome(x, z, biome.name()); } - - @Override - public Biome getBiome(int arg0, int arg1) { + + @Override public Biome getBiome(int arg0, int arg1) { return Biome.FOREST; } }; @@ -153,7 +143,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap if (data != null) { return; } - } catch (Throwable ignored) {} + } catch (Throwable ignored) { + } // Populator spillage short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid); if (tmp != null) { @@ -187,29 +178,24 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0)); MainUtil.initCache(); } - - @Override - public void augment(PlotArea area) { + + @Override public void augment(PlotArea area) { BukkitAugmentedGenerator.get(BukkitUtil.getWorld(area.worldname)); } - - @Override - public boolean isFull() { + + @Override public boolean isFull() { return this.full; } - - @Override - public IndependentPlotGenerator getPlotGenerator() { + + @Override public IndependentPlotGenerator getPlotGenerator() { return this.plotGenerator; } - - @Override - public ChunkGenerator getPlatformGenerator() { + + @Override public ChunkGenerator getPlatformGenerator() { return this.platformGenerator; } - @Override - public List getDefaultPopulators(World world) { + @Override public List getDefaultPopulators(World world) { try { if (!this.loaded) { String name = world.getName(); @@ -308,9 +294,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } ChunkManager.postProcessChunk(result); } - - @Override - public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) { + + @Override public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, + BiomeGrid grid) { GenChunk result = this.chunkSetter; // Set the chunk location result.setChunk(new ChunkWrapper(world.getName(), cx, cz)); @@ -339,21 +325,20 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap // Return the result data return result.result; } - + /** * Allow spawning everywhere. + * * @param world Ignored - * @param x Ignored - * @param z Ignored + * @param x Ignored + * @param z Ignored * @return always true */ - @Override - public boolean canSpawn(World world, int x, int z) { + @Override public boolean canSpawn(World world, int x, int z) { return true; } - - @Override - public String toString() { + + @Override public String toString() { if (this.platformGenerator == this) { return this.plotGenerator.getName(); } @@ -363,9 +348,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap return this.platformGenerator.getClass().getName(); } } - - @Override - public boolean equals(Object obj) { + + @Override public boolean equals(Object obj) { if (obj == null) { return false; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java index ca0dc871e..4448517cb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java @@ -9,8 +9,6 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; import com.intellectualcrafters.plot.util.TaskManager; -import java.lang.reflect.Method; -import java.util.HashSet; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; @@ -29,6 +27,8 @@ import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; +import java.lang.reflect.Method; +import java.util.HashSet; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; @@ -37,6 +37,7 @@ public class ChunkListener implements Listener { private RefMethod methodGetHandleChunk; private RefField mustSave; private Chunk lastChunk; + private boolean ignoreUnload = false; public ChunkListener() { if (Settings.Chunk_Processor.AUTO_TRIM) { @@ -46,7 +47,8 @@ public class ChunkListener implements Listener { this.mustSave = classChunk.getField("mustSave"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); } catch (Throwable ignored) { - PS.debug(PS.imp().getPluginName() + "/Server not compatible for chunk processor trim/gc"); + PS.debug(PS.imp().getPluginName() + + "/Server not compatible for chunk processor trim/gc"); Settings.Chunk_Processor.AUTO_TRIM = false; } } @@ -57,8 +59,7 @@ public class ChunkListener implements Listener { world.setAutoSave(false); } TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { try { HashSet toUnload = new HashSet<>(); for (World world : Bukkit.getWorlds()) { @@ -67,11 +68,14 @@ public class ChunkListener implements Listener { continue; } Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world); - Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); - Method methodIsChunkInUse = chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class); + Object chunkMap = + w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); + Method methodIsChunkInUse = chunkMap.getClass() + .getDeclaredMethod("isChunkInUse", int.class, int.class); Chunk[] chunks = world.getLoadedChunks(); for (Chunk chunk : chunks) { - if ((boolean) methodIsChunkInUse.invoke(chunkMap, chunk.getX(), chunk.getZ())) { + if ((boolean) methodIsChunkInUse + .invoke(chunkMap, chunk.getX(), chunk.getZ())) { continue; } int x = chunk.getX(); @@ -100,8 +104,6 @@ public class ChunkListener implements Listener { }, 1); } - private boolean ignoreUnload = false; - public boolean unloadChunk(String world, Chunk chunk, boolean safe) { if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) { return false; @@ -144,8 +146,7 @@ public class ChunkListener implements Listener { return plot != null && plot.hasOwner(); } - @EventHandler - public void onChunkUnload(ChunkUnloadEvent event) { + @EventHandler public void onChunkUnload(ChunkUnloadEvent event) { if (ignoreUnload) { return; } @@ -162,14 +163,12 @@ public class ChunkListener implements Listener { event.setCancelled(true); } } - - @EventHandler - public void onChunkLoad(ChunkLoadEvent event) { + + @EventHandler public void onChunkLoad(ChunkLoadEvent event) { processChunk(event.getChunk(), false); } - - @EventHandler(priority = EventPriority.LOWEST) - public void onItemSpawn(ItemSpawnEvent event) { + + @EventHandler(priority = EventPriority.LOWEST) public void onItemSpawn(ItemSpawnEvent event) { Item entity = event.getEntity(); Chunk chunk = entity.getLocation().getChunk(); if (chunk == this.lastChunk) { @@ -189,14 +188,14 @@ public class ChunkListener implements Listener { this.lastChunk = null; } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPhysics(BlockPhysicsEvent event) { if (Settings.Chunk_Processor.DISABLE_PHYSICS) { event.setCancelled(true); } } - + @EventHandler(priority = EventPriority.LOWEST) public void onEntitySpawn(CreatureSpawnEvent event) { LivingEntity entity = event.getEntity(); @@ -223,8 +222,7 @@ public class ChunkListener implements Listener { TaskManager.index.incrementAndGet(); final Integer currentIndex = TaskManager.index.get(); Integer task = TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { if (!chunk.isLoaded()) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); @@ -270,11 +268,13 @@ public class ChunkListener implements Listener { ent.remove(); } } - PS.debug(C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); + PS.debug(C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) + + "," + (chunk.getX() << 4)); } if (tiles.length > Settings.Chunk_Processor.MAX_TILES) { if (unload) { - PS.debug(C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); + PS.debug(C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + ( + chunk.getX() << 4)); cleanChunk(chunk); return true; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java index 20f029a3f..4429dd64b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java @@ -1,7 +1,6 @@ package com.plotsquared.bukkit.listeners; import com.intellectualcrafters.plot.PS; -import java.util.List; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.ArmorStand; @@ -17,62 +16,21 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; +import java.util.List; + public class EntityPortal_1_7_9 implements Listener { + private static boolean ignoreTP = false; + public EntityPortal_1_7_9() { } - @EventHandler - public void onVehicle(VehicleUpdateEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleDestroyEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleEntityCollisionEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleCreateEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleBlockCollisionEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onTeleport(EntityTeleportEvent event) { - Entity ent = event.getEntity(); - if (ent instanceof Vehicle || ent instanceof ArmorStand) test(event.getEntity()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { - test(event.getVehicle()); - } - - @EventHandler - public void spawn(CreatureSpawnEvent event) { - switch (event.getEntityType()) { - case ARMOR_STAND: - test(event.getEntity()); - } - } - - private static boolean ignoreTP = false; - public static void test(Entity entity) { List meta = entity.getMetadata("plotworld"); World world = entity.getLocation().getWorld(); if (meta == null || meta.isEmpty()) { if (PS.get().isPlotWorld(world.getName())) { - entity.setMetadata("plotworld", new FixedMetadataValue((Plugin) PS.get().IMP, entity.getLocation())); + entity.setMetadata("plotworld", + new FixedMetadataValue((Plugin) PS.get().IMP, entity.getLocation())); } } else { Location origin = (Location) meta.get(0).value(); @@ -96,4 +54,42 @@ public class EntityPortal_1_7_9 implements Listener { } } } + + @EventHandler public void onVehicle(VehicleUpdateEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleDestroyEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleEntityCollisionEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleCreateEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleBlockCollisionEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onTeleport(EntityTeleportEvent event) { + Entity ent = event.getEntity(); + if (ent instanceof Vehicle || ent instanceof ArmorStand) + test(event.getEntity()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { + test(event.getVehicle()); + } + + @EventHandler public void spawn(CreatureSpawnEvent event) { + switch (event.getEntityType()) { + case ARMOR_STAND: + test(event.getEntity()); + } + } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java index 32bebe45b..aba9934f3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java @@ -52,9 +52,10 @@ public class EntitySpawnListener implements Listener { event.setCancelled(true); } case SHULKER: - if(!entity.hasMetadata("plot")) { - entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot.getId())); - } + if (!entity.hasMetadata("plot")) { + entity.setMetadata("plot", + new FixedMetadataValue((Plugin) PS.get().IMP, plot.getId())); + } } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java index 32b421a56..7280c2b20 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java @@ -9,19 +9,22 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.util.BukkitUtil; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + import java.util.HashSet; import java.util.Set; import java.util.UUID; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; public class ForceFieldListener { private static Set getNearbyPlayers(Player player, Plot plot) { Set players = new HashSet<>(); - for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) { + for (Player nearPlayer : Iterables + .filter(player.getNearbyEntities(5d, 5d, 5d), Player.class)) { PlotPlayer plotPlayer; - if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) { + if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot + .equals(plotPlayer.getCurrentPlot())) { continue; } if (!plot.isAdded(plotPlayer.getUUID())) { @@ -32,9 +35,11 @@ public class ForceFieldListener { } private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) { - for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) { + for (Player nearPlayer : Iterables + .filter(player.getNearbyEntities(5d, 5d, 5d), Player.class)) { PlotPlayer plotPlayer; - if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) { + if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot + .equals(plotPlayer.getCurrentPlot())) { continue; } if (plot.isAdded(plotPlayer.getUUID())) { @@ -81,7 +86,8 @@ public class ForceFieldListener { Set players = getNearbyPlayers(player, plot); for (PlotPlayer oPlayer : players) { if (!Permissions.hasPermission(oPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { - ((BukkitPlayer) oPlayer).player.setVelocity(calculateVelocity(plotPlayer, oPlayer)); + ((BukkitPlayer) oPlayer).player + .setVelocity(calculateVelocity(plotPlayer, oPlayer)); } } } else { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java index fa4577e26..b7bf4a884 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java @@ -15,18 +15,6 @@ import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.BukkitVersion; import com.plotsquared.listener.PlayerBlockEventType; import com.plotsquared.listener.PlotListener; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -35,75 +23,17 @@ import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.command.PluginCommand; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Creature; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.Hanging; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.Vehicle; -import org.bukkit.entity.Villager; +import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockBurnEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockGrowEvent; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.block.EntityBlockFormEvent; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -import org.bukkit.event.entity.PotionSplashEvent; -import org.bukkit.event.entity.ProjectileHitEvent; -import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.*; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerEggThrowEvent; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.*; import org.bukkit.event.vehicle.VehicleCreateEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; @@ -117,9 +47,15 @@ import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.Vector; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Pattern; + /** * Player Events involving plots. - * */ public class PlayerEvents extends PlotListener implements Listener { @@ -127,11 +63,24 @@ public class PlayerEvents extends PlotListener implements Listener { private float lastRadius; // To prevent recursion private boolean tmpTeleport = true; + private Field fieldPlayer; + private PlayerMoveEvent moveTmp; + private boolean v112 = + PS.get().checkVersion(PS.imp().getServerVersion(), BukkitVersion.v1_12_0); - public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) { + { + try { + fieldPlayer = PlayerEvent.class.getDeclaredField("player"); + fieldPlayer.setAccessible(true); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } + } + + public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, + final byte data) { TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { + @Override public void run() { String world = bloc.getWorld().getName(); int x = bloc.getBlockX(); int z = bloc.getBlockZ(); @@ -140,7 +89,8 @@ public class PlayerEvents extends PlotListener implements Listener { PlotPlayer player = entry.getValue(); Location loc = player.getLocation(); if (loc.getWorld().equals(world)) { - if (16 * Math.abs(loc.getX() - x) / 16 > distance || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { + if (16 * Math.abs(loc.getX() - x) / 16 > distance + || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { continue; } ((BukkitPlayer) player).player.sendBlockChange(bloc, type, data); @@ -150,8 +100,213 @@ public class PlayerEvents extends PlotListener implements Listener { }, 3); } - @EventHandler - public void onRedstoneEvent(BlockRedstoneEvent event) { + public static boolean checkEntity(Plot plot, IntegerFlag... flags) { + if (Settings.Done.RESTRICT_BUILDING && Flags.DONE.isSet(plot)) { + return true; + } + int[] mobs = null; + for (IntegerFlag flag : flags) { + int i; + switch (flag.getName()) { + case "entity-cap": + i = 0; + break; + case "mob-cap": + i = 3; + break; + case "hostile-cap": + i = 2; + break; + case "animal-cap": + i = 1; + break; + case "vehicle-cap": + i = 4; + break; + case "misc-cap": + i = 5; + break; + default: + i = 0; + } + int cap = plot.getFlag(flag, Integer.MAX_VALUE); + if (cap == Integer.MAX_VALUE) { + continue; + } + if (cap == 0) { + return true; + } + if (mobs == null) { + mobs = plot.countEntities(); + } + if (mobs[i] >= cap) { + plot.setMeta("EntityCount", mobs); + plot.setMeta("EntityCountTime", System.currentTimeMillis()); + return true; + } + } + if (mobs != null) { + for (IntegerFlag flag : flags) { + int i; + switch (flag.getName()) { + case "entity-cap": + i = 0; + break; + case "mob-cap": + i = 3; + break; + case "hostile-cap": + i = 2; + break; + case "animal-cap": + i = 1; + break; + case "vehicle-cap": + i = 4; + break; + case "misc-cap": + i = 5; + break; + default: + i = 0; + } + mobs[i]++; + } + plot.setMeta("EntityCount", mobs); + plot.setMeta("EntityCountTime", System.currentTimeMillis()); + } + return false; + } + + public static boolean checkEntity(Entity entity, Plot plot) { + if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot + .getArea().DEFAULT_FLAGS.isEmpty()) { + return false; + } + switch (entity.getType()) { + case PLAYER: + return false; + case LLAMA_SPIT: + case SMALL_FIREBALL: + case FIREBALL: + case DROPPED_ITEM: + case EGG: + case THROWN_EXP_BOTTLE: + case SPLASH_POTION: + case LINGERING_POTION: + case SNOWBALL: + case ENDER_PEARL: + case ARROW: + case TIPPED_ARROW: + case SPECTRAL_ARROW: + case SHULKER_BULLET: + case DRAGON_FIREBALL: + // projectile + case PRIMED_TNT: + case FALLING_BLOCK: + // Block entities + case ENDER_CRYSTAL: + case COMPLEX_PART: + case FISHING_HOOK: + case ENDER_SIGNAL: + case EXPERIENCE_ORB: + case LEASH_HITCH: + case FIREWORK: + case WEATHER: + case AREA_EFFECT_CLOUD: + case LIGHTNING: + case WITHER_SKULL: + case EVOKER_FANGS: + case UNKNOWN: + // non moving / unmovable + return checkEntity(plot, Flags.ENTITY_CAP); + case ITEM_FRAME: + case PAINTING: + case ARMOR_STAND: + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); + // misc + case MINECART: + case MINECART_CHEST: + case MINECART_COMMAND: + case MINECART_FURNACE: + case MINECART_HOPPER: + case MINECART_MOB_SPAWNER: + case MINECART_TNT: + case BOAT: + return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); + case POLAR_BEAR: + case RABBIT: + case SHEEP: + case MUSHROOM_COW: + case OCELOT: + case PIG: + case SQUID: + case VILLAGER: + case IRON_GOLEM: + case WOLF: + case CHICKEN: + case COW: + case SNOWMAN: + case BAT: + case HORSE: + case DONKEY: + case LLAMA: + case MULE: + case ZOMBIE_HORSE: + case SKELETON_HORSE: + // animal + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); + case BLAZE: + case CAVE_SPIDER: + case CREEPER: + case ENDERMAN: + case ENDERMITE: + case ENDER_DRAGON: + case GHAST: + case GIANT: + case GUARDIAN: + case MAGMA_CUBE: + case PIG_ZOMBIE: + case SILVERFISH: + case SKELETON: + case SLIME: + case SPIDER: + case WITCH: + case WITHER: + case ZOMBIE: + case SHULKER: + case HUSK: + case STRAY: + case ELDER_GUARDIAN: + case WITHER_SKELETON: + case VINDICATOR: + case EVOKER: + case VEX: + case ZOMBIE_VILLAGER: + // monster + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); + default: + if (entity instanceof LivingEntity) { + if (entity instanceof Animals) { + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); + } else if (entity instanceof Monster) { + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, + Flags.HOSTILE_CAP); + } else { + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP); + } + } + if (entity instanceof Vehicle) { + return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); + } + if (entity instanceof Hanging) { + return checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); + } + return checkEntity(plot, Flags.ENTITY_CAP); + } + } + + @EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { Block block = event.getBlock(); switch (block.getType()) { case OBSERVER: @@ -312,14 +467,13 @@ public class PlayerEvents extends PlotListener implements Listener { event.setCancelled(true); return; } + } } - } - break; + break; } } - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent event) { + @EventHandler public void onProjectileLaunch(ProjectileLaunchEvent event) { Projectile entity = event.getEntity(); if (!(entity instanceof ThrownPotion)) { return; @@ -340,8 +494,7 @@ public class PlayerEvents extends PlotListener implements Listener { } } - @EventHandler - public boolean onProjectileHit(ProjectileHitEvent event) { + @EventHandler public boolean onProjectileHit(ProjectileHitEvent event) { Projectile entity = event.getEntity(); Location loc = BukkitUtil.getLocation(entity); if (!PS.get().hasPlotArea(loc.getWorld())) { @@ -362,7 +515,8 @@ public class PlayerEvents extends PlotListener implements Listener { } return true; } - if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { + if (plot.isAdded(pp.getUUID()) || Permissions + .hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { return true; } entity.remove(); @@ -373,7 +527,8 @@ public class PlayerEvents extends PlotListener implements Listener { entity.remove(); return false; } - Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + Location sLoc = + BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); if (!area.contains(sLoc.getX(), sLoc.getZ())) { entity.remove(); return false; @@ -408,7 +563,8 @@ public class PlayerEvents extends PlotListener implements Listener { case "/up": case "worldedit:up": case "worldedit:/up": - if (plot == null || (!plot.isAdded(pp.getUUID()) && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER, true))) { + if (plot == null || (!plot.isAdded(pp.getUUID()) && !Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER, true))) { event.setCancelled(true); return; } @@ -418,7 +574,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } Optional> flag = plot.getFlag(Flags.BLOCKED_CMDS); - if (flag.isPresent() && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + if (flag.isPresent() && !Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { List blocked_cmds = flag.get(); String c = parts[0]; if (parts[0].contains(":")) { @@ -501,8 +658,7 @@ public class PlayerEvents extends PlotListener implements Listener { // Async TaskManager.runTaskLaterAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { if (!player.hasPlayedBefore() && player.isOnline()) { player.saveData(); } @@ -520,7 +676,8 @@ public class PlayerEvents extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld().equals(event.getTo().getWorld())) { + if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld() + .equals(event.getTo().getWorld())) { BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location"); BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot"); org.bukkit.Location to = event.getTo(); @@ -542,25 +699,14 @@ public class PlayerEvents extends PlotListener implements Listener { playerMove(event); } - private Field fieldPlayer; - { - try { - fieldPlayer = PlayerEvent.class.getDeclaredField("player"); - fieldPlayer.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } - } - private PlayerMoveEvent moveTmp; - private boolean v112 = PS.get().checkVersion(PS.imp().getServerVersion(), BukkitVersion.v1_12_0); - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { final org.bukkit.Location from = event.getFrom(); final org.bukkit.Location to = event.getTo(); int toX, toZ; - if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { + if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) + | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { Vehicle vehicle = event.getVehicle(); // Check allowed @@ -571,21 +717,25 @@ public class PlayerEvents extends PlotListener implements Listener { if (passenger instanceof Player) { final Player player = (Player) passenger; // reset - if (moveTmp == null) moveTmp = new PlayerMoveEvent(null, from, to); + if (moveTmp == null) + moveTmp = new PlayerMoveEvent(null, from, to); moveTmp.setFrom(from); moveTmp.setTo(to); moveTmp.setCancelled(false); fieldPlayer.set(moveTmp, player); List passengers; - if (v112) passengers = vehicle.getPassengers(); - else passengers = null; + if (v112) + passengers = vehicle.getPassengers(); + else + passengers = null; this.playerMove(moveTmp); org.bukkit.Location dest; if (moveTmp.isCancelled()) { dest = from; - } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { + } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX + || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { dest = to; } else { dest = null; @@ -595,7 +745,8 @@ public class PlayerEvents extends PlotListener implements Listener { vehicle.eject(); vehicle.setVelocity(new Vector(0d, 0d, 0d)); vehicle.teleport(dest); - for (final Entity entity : passengers) vehicle.addPassenger(entity); + for (final Entity entity : passengers) + vehicle.addPassenger(entity); } else { vehicle.eject(); vehicle.setVelocity(new Vector(0d, 0d, 0d)); @@ -624,7 +775,8 @@ public class PlayerEvents extends PlotListener implements Listener { vehicle.remove(); } } else if (toPlot != null) { - vehicle.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, toPlot)); + vehicle.setMetadata("plot", + new FixedMetadataValue((Plugin) PS.get().IMP, toPlot)); } } } @@ -788,7 +940,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } } - String partial = ChatColor.translateAlternateColorCodes('&',format.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender)); + String partial = ChatColor.translateAlternateColorCodes('&', + format.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender)); if (plotPlayer.hasPermission("plots.chat.color")) { message = C.color(message); } @@ -797,7 +950,8 @@ public class PlayerEvents extends PlotListener implements Listener { receiver.sendMessage(full); } if (!spies.isEmpty()) { - String spyMessage = C.PLOT_CHAT_SPY_FORMAT.s().replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender).replace("%msg%", message); + String spyMessage = C.PLOT_CHAT_SPY_FORMAT.s().replace("%plot_id%", id.x + ";" + id.y) + .replace("%sender%", sender).replace("%msg%", message); for (Player player : spies) { player.sendMessage(spyMessage); } @@ -805,8 +959,7 @@ public class PlayerEvents extends PlotListener implements Listener { PS.debug(full); } - @EventHandler(priority = EventPriority.LOWEST) - public void blockDestroy(BlockBreakEvent event) { + @EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) { Player player = event.getPlayer(); Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); @@ -817,21 +970,27 @@ public class PlayerEvents extends PlotListener implements Listener { if (plot != null) { PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); if (event.getBlock().getY() == 0) { - if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); + if (!Permissions + .hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); event.setCancelled(true); return; } - } else if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) && !Permissions + } else if ( + (location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) + && !Permissions .hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(plotPlayer, C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); + MainUtil.sendMessage(plotPlayer, + C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); return; } @@ -839,17 +998,19 @@ public class PlayerEvents extends PlotListener implements Listener { Optional> destroy = plot.getFlag(Flags.BREAK); Block block = event.getBlock(); if (destroy.isPresent() && destroy.get() - .contains(PlotBlock.get((short) block.getTypeId(), block.getData()))) { + .contains(PlotBlock.get((short) block.getTypeId(), block.getData()))) { return; } if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } else if (Settings.Done.RESTRICT_BUILDING && plot.getFlags().containsKey(Flags.DONE)) { if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } @@ -861,7 +1022,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (PS.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getItemInHand().getTypeId() == PS.get().worldedit.getConfiguration().wandItem) { + if (player.getItemInHand().getTypeId() == PS.get().worldedit + .getConfiguration().wandItem) { return; } } @@ -897,11 +1059,14 @@ public class PlayerEvents extends PlotListener implements Listener { origin = (Plot) meta.get(0).value(); } if (this.lastRadius != 0) { - List nearby = event.getEntity().getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); + List nearby = event.getEntity() + .getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); for (Entity near : nearby) { - if (near instanceof TNTPrimed || near.getType().equals(EntityType.MINECART_TNT)) { + if (near instanceof TNTPrimed || near.getType() + .equals(EntityType.MINECART_TNT)) { if (!near.hasMetadata("plot")) { - near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + near.setMetadata("plot", + new FixedMetadataValue((Plugin) PS.get().IMP, plot)); } } } @@ -911,7 +1076,8 @@ public class PlayerEvents extends PlotListener implements Listener { while (iterator.hasNext()) { Block block = iterator.next(); location = BukkitUtil.getLocation(block.getLocation()); - if (!area.contains(location.getX(), location.getZ()) || !origin.equals(area.getOwnedPlot(location))) { + if (!area.contains(location.getX(), location.getZ()) || !origin + .equals(area.getOwnedPlot(location))) { iterator.remove(); } } @@ -960,7 +1126,8 @@ public class PlayerEvents extends PlotListener implements Listener { PlotArea area = location.getPlotArea(); if (area != null) { Plot plot = area.getOwnedPlot(location); - if (plot != null && Flags.MOB_BREAK.isTrue(plot)) return; + if (plot != null && Flags.MOB_BREAK.isTrue(plot)) + return; event.setCancelled(true); } } @@ -1113,8 +1280,9 @@ public class PlayerEvents extends PlotListener implements Listener { if (!plot.isAdded(plotPlayer.getUUID())) { Optional> destroy = plot.getFlag(Flags.BREAK); Block block = event.getBlock(); - if (destroy.isPresent() && destroy.get().contains(PlotBlock.get((short) block.getTypeId(), block.getData())) || Permissions - .hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + if (destroy.isPresent() && destroy.get() + .contains(PlotBlock.get((short) block.getTypeId(), block.getData())) + || Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } event.setCancelled(true); @@ -1176,7 +1344,8 @@ public class PlayerEvents extends PlotListener implements Listener { if (Flags.DISABLE_PHYSICS.isFalse(plot)) { event.setCancelled(true); return; - } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) { + } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects + .equals(plot, area.getOwnedPlot(fLocation))) { event.setCancelled(true); return; } @@ -1189,7 +1358,8 @@ public class PlayerEvents extends PlotListener implements Listener { event.setCancelled(true); } } - } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) { + } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects + .equals(plot, area.getOwnedPlot(fLocation))) { event.setCancelled(true); } } @@ -1230,11 +1400,13 @@ public class PlayerEvents extends PlotListener implements Listener { List blocks = event.getBlocks(); for (Block b : blocks) { Location bloc = BukkitUtil.getLocation(b.getLocation()); - if (!area.contains(bloc.getX(), bloc.getZ()) || !area.contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { + if (!area.contains(bloc.getX(), bloc.getZ()) || !area + .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { event.setCancelled(true); return; } - if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot(bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( + bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { event.setCancelled(true); return; } @@ -1265,7 +1437,8 @@ public class PlayerEvents extends PlotListener implements Listener { } if (!this.pistonBlocks && block.getType() != Material.PISTON_BASE) { BlockFace dir = event.getDirection(); - location = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); + location = BukkitUtil.getLocation(block.getLocation() + .add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (location.getPlotArea() != null) { event.setCancelled(true); return; @@ -1275,17 +1448,18 @@ public class PlayerEvents extends PlotListener implements Listener { } Plot plot = area.getOwnedPlot(location); BlockFace dir = event.getDirection(); -// Location head = location.add(-dir.getModX(), -dir.getModY(), -dir.getModZ()); -// -// if (!Objects.equals(plot, area.getOwnedPlot(head))) { -// // FIXME: cancelling the event doesn't work here. See issue #1484 -// event.setCancelled(true); -// return; -// } + // Location head = location.add(-dir.getModX(), -dir.getModY(), -dir.getModZ()); + // + // if (!Objects.equals(plot, area.getOwnedPlot(head))) { + // // FIXME: cancelling the event doesn't work here. See issue #1484 + // event.setCancelled(true); + // return; + // } if (this.pistonBlocks) { try { for (Block pulled : event.getBlocks()) { - Location from = BukkitUtil.getLocation(pulled.getLocation().add(dir.getModX(), dir.getModY(), dir.getModZ())); + Location from = BukkitUtil.getLocation( + pulled.getLocation().add(dir.getModX(), dir.getModY(), dir.getModZ())); Location to = BukkitUtil.getLocation(pulled.getLocation()); if (!area.contains(to.getX(), to.getZ())) { event.setCancelled(true); @@ -1303,7 +1477,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } if (!this.pistonBlocks && block.getType() != Material.PISTON_BASE) { - location = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); + location = BukkitUtil.getLocation( + block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (!area.contains(location)) { event.setCancelled(true); return; @@ -1321,14 +1496,18 @@ public class PlayerEvents extends PlotListener implements Listener { switch (type) { case WATER_BUCKET: case LAVA_BUCKET: { - if (event.getBlock().getType() == Material.DROPPER) return; - BlockFace targetFace = ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()).getFacing(); - Location location = BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); + if (event.getBlock().getType() == Material.DROPPER) + return; + BlockFace targetFace = + ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()) + .getFacing(); + Location location = + BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); if (location.isPlotRoad()) { event.setCancelled(true); } } - } + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -1494,7 +1673,8 @@ public class PlayerEvents extends PlotListener implements Listener { } lb = new BukkitLazyBlock(blockId, block); ItemStack hand = player.getItemInHand(); - if (eventType != null && (eventType != PlayerBlockEventType.INTERACT_BLOCK || !player.isSneaking())) { + if (eventType != null && (eventType != PlayerBlockEventType.INTERACT_BLOCK + || !player.isSneaking())) { break; } Material type = (hand == null) ? null : hand.getType(); @@ -1504,7 +1684,8 @@ public class PlayerEvents extends PlotListener implements Listener { break; } if (id < 198) { - location = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_BLOCK; lb = new BukkitLazyBlock(id, block); break; @@ -1518,7 +1699,8 @@ public class PlayerEvents extends PlotListener implements Listener { eventType = PlayerBlockEventType.SPAWN_MOB; break; case ARMOR_STAND: - location = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_MISC; break; case WRITTEN_BOOK: @@ -1560,7 +1742,8 @@ public class PlayerEvents extends PlotListener implements Listener { break; case PAINTING: case ITEM_FRAME: - location = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_HANGING; break; default: @@ -1579,7 +1762,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (PS.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getItemInHand().getTypeId() == PS.get().worldedit.getConfiguration().wandItem) { + if (player.getItemInHand().getTypeId() == PS.get().worldedit + .getConfiguration().wandItem) { return; } } @@ -1673,219 +1857,15 @@ public class PlayerEvents extends PlotListener implements Listener { entity.remove(); } } else if (event.getTo() == Material.AIR) { - event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + event.getEntity() + .setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); } } - @EventHandler - public void onPrime(ExplosionPrimeEvent event) { + @EventHandler public void onPrime(ExplosionPrimeEvent event) { this.lastRadius = event.getRadius() + 1; } - public static boolean checkEntity(Plot plot, IntegerFlag... flags) { - if (Settings.Done.RESTRICT_BUILDING && Flags.DONE.isSet(plot)) { - return true; - } - int[] mobs = null; - for (IntegerFlag flag : flags) { - int i; - switch (flag.getName()) { - case "entity-cap": - i = 0; - break; - case "mob-cap": - i = 3; - break; - case "hostile-cap": - i = 2; - break; - case "animal-cap": - i = 1; - break; - case "vehicle-cap": - i = 4; - break; - case "misc-cap": - i = 5; - break; - default: - i = 0; - } - int cap = plot.getFlag(flag, Integer.MAX_VALUE); - if (cap == Integer.MAX_VALUE) { - continue; - } - if (cap == 0) { - return true; - } - if (mobs == null) { - mobs = plot.countEntities(); - } - if (mobs[i] >= cap) { - plot.setMeta("EntityCount", mobs); - plot.setMeta("EntityCountTime", System.currentTimeMillis()); - return true; - } - } - if (mobs != null) { - for (IntegerFlag flag : flags) { - int i; - switch (flag.getName()) { - case "entity-cap": - i = 0; - break; - case "mob-cap": - i = 3; - break; - case "hostile-cap": - i = 2; - break; - case "animal-cap": - i = 1; - break; - case "vehicle-cap": - i = 4; - break; - case "misc-cap": - i = 5; - break; - default: - i = 0; - } - mobs[i]++; - } - plot.setMeta("EntityCount", mobs); - plot.setMeta("EntityCountTime", System.currentTimeMillis()); - } - return false; - } - - public static boolean checkEntity(Entity entity, Plot plot) { - if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS.isEmpty()) { - return false; - } - switch (entity.getType()) { - case PLAYER: - return false; - case LLAMA_SPIT: - case SMALL_FIREBALL: - case FIREBALL: - case DROPPED_ITEM: - case EGG: - case THROWN_EXP_BOTTLE: - case SPLASH_POTION: - case LINGERING_POTION: - case SNOWBALL: - case ENDER_PEARL: - case ARROW: - case TIPPED_ARROW: - case SPECTRAL_ARROW: - case SHULKER_BULLET: - case DRAGON_FIREBALL: - // projectile - case PRIMED_TNT: - case FALLING_BLOCK: - // Block entities - case ENDER_CRYSTAL: - case COMPLEX_PART: - case FISHING_HOOK: - case ENDER_SIGNAL: - case EXPERIENCE_ORB: - case LEASH_HITCH: - case FIREWORK: - case WEATHER: - case AREA_EFFECT_CLOUD: - case LIGHTNING: - case WITHER_SKULL: - case EVOKER_FANGS: - case UNKNOWN: - // non moving / unmovable - return checkEntity(plot, Flags.ENTITY_CAP); - case ITEM_FRAME: - case PAINTING: - case ARMOR_STAND: - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); - // misc - case MINECART: - case MINECART_CHEST: - case MINECART_COMMAND: - case MINECART_FURNACE: - case MINECART_HOPPER: - case MINECART_MOB_SPAWNER: - case MINECART_TNT: - case BOAT: - return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); - case POLAR_BEAR: - case RABBIT: - case SHEEP: - case MUSHROOM_COW: - case OCELOT: - case PIG: - case SQUID: - case VILLAGER: - case IRON_GOLEM: - case WOLF: - case CHICKEN: - case COW: - case SNOWMAN: - case BAT: - case HORSE: - case DONKEY: - case LLAMA: - case MULE: - case ZOMBIE_HORSE: - case SKELETON_HORSE: - // animal - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); - case BLAZE: - case CAVE_SPIDER: - case CREEPER: - case ENDERMAN: - case ENDERMITE: - case ENDER_DRAGON: - case GHAST: - case GIANT: - case GUARDIAN: - case MAGMA_CUBE: - case PIG_ZOMBIE: - case SILVERFISH: - case SKELETON: - case SLIME: - case SPIDER: - case WITCH: - case WITHER: - case ZOMBIE: - case SHULKER: - case HUSK: - case STRAY: - case ELDER_GUARDIAN: - case WITHER_SKELETON: - case VINDICATOR: - case EVOKER: - case VEX: - case ZOMBIE_VILLAGER: - // monster - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); - default: - if (entity instanceof LivingEntity) { - if (entity instanceof Animals) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); - } else if (entity instanceof Monster) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); - } else { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP); - } - } - if (entity instanceof Vehicle) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); - } - if (entity instanceof Hanging) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); - } - return checkEntity(plot, Flags.ENTITY_CAP); - } - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBurn(BlockBurnEvent event) { Block b = event.getBlock(); @@ -1939,7 +1919,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -1956,7 +1937,7 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (ignitingEntity != null) { - if (!plot.getFlag(Flags.BLOCK_IGNITION,false)) { + if (!plot.getFlag(Flags.BLOCK_IGNITION, false)) { event.setCancelled(true); return; } @@ -1968,7 +1949,8 @@ public class PlayerEvents extends PlotListener implements Listener { Entity shooter = (Entity) fireball.getShooter(); location = BukkitUtil.getLocation(shooter.getLocation()); } else if (fireball.getShooter() instanceof BlockProjectileSource) { - Block shooter = ((BlockProjectileSource) fireball.getShooter()).getBlock(); + Block shooter = + ((BlockProjectileSource) fireball.getShooter()).getBlock(); location = BukkitUtil.getLocation(shooter.getLocation()); } if (location != null && !plot.equals(location.getPlot())) { @@ -1980,10 +1962,13 @@ public class PlayerEvents extends PlotListener implements Listener { } else if (event.getIgnitingBlock() != null) { Block ignitingBlock = event.getIgnitingBlock(); Plot plotIgnited = BukkitUtil.getLocation(ignitingBlock.getLocation()).getPlot(); - if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && (!plot.getFlag(Flags.BLOCK_IGNITION,false) - || plotIgnited == null || !plotIgnited.equals(plot)) - || (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( - !plot.getFlag(Flags.BLOCK_IGNITION).or(false) || plotIgnited == null || !plotIgnited.equals(plot))) { + if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && ( + !plot.getFlag(Flags.BLOCK_IGNITION, false) || plotIgnited == null + || !plotIgnited.equals(plot)) || + (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD + || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( + !plot.getFlag(Flags.BLOCK_IGNITION).or(false) || plotIgnited == null + || !plotIgnited.equals(plot))) { event.setCancelled(true); } } @@ -1993,7 +1978,9 @@ public class PlayerEvents extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBucketEmpty(PlayerBucketEmptyEvent event) { BlockFace bf = event.getBlockFace(); - Block b = event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + Block b = + event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()) + .getBlock(); Location location = BukkitUtil.getLocation(b.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { @@ -2052,8 +2039,7 @@ public class PlayerEvents extends PlotListener implements Listener { BukkitUtil.getPlayer(player).deleteMeta("inventory"); } - @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(PlayerQuitEvent event) { + @EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { if (TaskManager.TELEPORT_QUEUE.contains(event.getPlayer().getName())) { TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); } @@ -2082,12 +2068,14 @@ public class PlayerEvents extends PlotListener implements Listener { if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(plotPlayer.getUUID())) { Optional> use = plot.getFlag(Flags.USE); Block block = event.getBlockClicked(); - if (use.isPresent() && use.get().contains(PlotBlock.get(block.getTypeId(), block.getData()))) { + if (use.isPresent() && use.get() + .contains(PlotBlock.get(block.getTypeId(), block.getData()))) { return; } if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_OTHER)) { @@ -2135,15 +2123,17 @@ public class PlayerEvents extends PlotListener implements Listener { } else { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } return; } if (!plot.isAdded(pp.getUUID())) { - if (!plot.getFlag(Flags.HANGING_PLACE,false)) { + if (!plot.getFlag(Flags.HANGING_PLACE, false)) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } return; @@ -2170,12 +2160,14 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(location); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); event.setCancelled(true); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -2183,7 +2175,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } } @@ -2200,14 +2193,18 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(BukkitUtil.getLocation(event.getEntity())); if (plot != null) { if (!plot.hasOwner()) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + if (!Permissions + .hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(player.getUUID())) { if (!plot.getFlag(Flags.HANGING_BREAK, false)) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + if (!Permissions + .hasPermission(player, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } } @@ -2236,7 +2233,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -2247,7 +2245,8 @@ public class PlayerEvents extends PlotListener implements Listener { if (entity instanceof Animals && plot.getFlag(Flags.ANIMAL_INTERACT, false)) { return; } - if (entity instanceof Tameable && ((Tameable) entity).isTamed() && plot.getFlag(Flags.TAMED_INTERACT, false)) { + if (entity instanceof Tameable && ((Tameable) entity).isTamed() && plot + .getFlag(Flags.TAMED_INTERACT, false)) { return; } if (entity instanceof Vehicle && plot.getFlag(Flags.VEHICLE_USE, false)) { @@ -2283,13 +2282,15 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(l); if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); event.setCancelled(true); } } else { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.unowned"); + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.unowned"); event.setCancelled(true); return; } @@ -2300,7 +2301,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.other"); + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.other"); event.setCancelled(true); } } @@ -2327,19 +2329,19 @@ public class PlayerEvents extends PlotListener implements Listener { } } - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.HIGHEST) + @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { EntityDamageByEntityEvent eventChange = null; if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_11_0)) { eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, (double)event.getDuration()); + EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); } else { try { - Constructor constructor = EntityDamageByEntityEvent.class.getConstructor(Entity.class, - Entity.class, EntityDamageEvent.DamageCause.class, Integer.TYPE); + Constructor constructor = EntityDamageByEntityEvent.class + .getConstructor(Entity.class, Entity.class, EntityDamageEvent.DamageCause.class, + Integer.TYPE); eventChange = constructor.newInstance(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); + EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { e.printStackTrace(); } @@ -2379,7 +2381,8 @@ public class PlayerEvents extends PlotListener implements Listener { Location dloc = BukkitUtil.getLocation(damager); Location vloc = BukkitUtil.getLocation(victim); PlotArea dArea = dloc.getPlotArea(); - PlotArea vArea = dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); + PlotArea vArea = + dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); if (dArea == null && vArea == null) { return true; } @@ -2435,7 +2438,8 @@ public class PlayerEvents extends PlotListener implements Listener { player = (Player) shooter; } else { // shooter is not player if (shooter instanceof BlockProjectileSource) { - Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + Location sLoc = BukkitUtil + .getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); dplot = dArea.getPlot(sLoc); } player = null; @@ -2446,76 +2450,92 @@ public class PlayerEvents extends PlotListener implements Listener { if (player != null) { PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); if (victim instanceof Hanging) { // hanging - if (plot != null && (plot.getFlag(Flags.HANGING_BREAK, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.HANGING_BREAK, false) || plot + .isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.destroy." + stub); return false; } } else if (victim.getEntityId() == 30) { - if (plot != null && (plot.getFlag(Flags.MISC_BREAK, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.MISC_BREAK, false) || plot + .isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.destroy." + stub); return false; } - } else if (victim instanceof Monster || victim instanceof EnderDragon) { // victim is monster - if (plot != null && (plot.getFlag(Flags.HOSTILE_ATTACK, false) || plot.getFlag(Flags.PVE, false) || plot - .isAdded(plotPlayer.getUUID()))) { + } else if (victim instanceof Monster + || victim instanceof EnderDragon) { // victim is monster + if (plot != null && (plot.getFlag(Flags.HOSTILE_ATTACK, false) || plot + .getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } else if (victim instanceof Tameable) { // victim is tameable - if (plot != null && (plot.getFlag(Flags.TAMED_ATTACK, false) || plot.getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.TAMED_ATTACK, false) || plot + .getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } else if (victim instanceof Player) { if (plot != null) { - if (Flags.PVP.isFalse(plot) && !Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); + if (Flags.PVP.isFalse(plot) && !Permissions + .hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.pvp." + stub); return false; } else { return true; } } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); return false; } } else if (victim instanceof Creature) { // victim is animal - if (plot != null && (plot.getFlag(Flags.ANIMAL_ATTACK, false) || plot.getFlag(Flags.PVE, false) || plot - .isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.ANIMAL_ATTACK, false) || plot + .getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event return true; } else { // victim is something else - if (plot != null && (plot.getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.PVE, false) || plot + .isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } return true; - } else if (dplot != null && (!(dplot.equals(vplot)) || (vplot != null && Objects.equals(dplot.owner, vplot.owner)))) { + } else if (dplot != null && (!(dplot.equals(vplot)) || (vplot != null && Objects + .equals(dplot.owner, vplot.owner)))) { return vplot != null && Flags.PVE.isTrue(vplot); } - return ((vplot != null && Flags.PVE.isTrue(vplot)) || !(damager instanceof Arrow && !(victim instanceof Creature))); + return ((vplot != null && Flags.PVE.isTrue(vplot)) || !(damager instanceof Arrow + && !(victim instanceof Creature))); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -2530,17 +2550,20 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(l); if (plot == null) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.road")) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); event.setHatching(false); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.unowned")) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.projectile.unowned"); event.setHatching(false); } } else if (!plot.isAdded(plotPlayer.getUUID())) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.other")) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); event.setHatching(false); } } @@ -2557,14 +2580,16 @@ public class PlayerEvents extends PlotListener implements Listener { PlotPlayer pp = BukkitUtil.getPlayer(player); Plot plot = area.getPlot(location); if (plot != null) { - if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) && !Permissions - .hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { + if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) + && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); + MainUtil.sendMessage(pp, + C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); return; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java index ffc23d1e1..e221af62b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java @@ -11,9 +11,6 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.listener.PlotListener; -import java.util.HashSet; -import java.util.List; -import java.util.UUID; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -31,12 +28,17 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; +import java.util.HashSet; +import java.util.List; +import java.util.UUID; + public class PlayerEvents_1_8 extends PlotListener implements Listener { - + @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent event) { - if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) { + if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event + .isShiftClick()) { return; } HumanEntity entity = event.getWhoClicked(); @@ -71,7 +73,8 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener { switch (newItem.getType()) { case BANNER: case SKULL_ITEM: - if (newMeta != null) break; + if (newMeta != null) + break; default: return; } @@ -89,9 +92,11 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener { switch (stateType) { case STANDING_BANNER: case WALL_BANNER: - if (itemType == Material.BANNER) break; + if (itemType == Material.BANNER) + break; case SKULL: - if (itemType == Material.SKULL_ITEM) break; + if (itemType == Material.SKULL_ITEM) + break; default: return; } @@ -124,15 +129,18 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener { } } if (cancelled) { - if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem.getDurability())) { - event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem + .getDurability())) { + event.setCursor( + new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); event.setCancelled(true); return; } - event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + event.setCursor( + new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInteract(PlayerInteractAtEntityEvent e) { Entity entity = e.getRightClicked(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java index 7b9d43100..f22ee5aa6 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -8,10 +8,6 @@ import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.listener.PlotListener; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.block.Block; @@ -27,6 +23,11 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.UUID; + public class PlotPlusListener extends PlotListener implements Listener { private static final HashMap feedRunnable = new HashMap<>(); @@ -34,10 +35,10 @@ public class PlotPlusListener extends PlotListener implements Listener { public static void startRunnable(JavaPlugin plugin) { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { + @Override public void run() { if (!healRunnable.isEmpty()) { - for (Iterator> iterator = healRunnable.entrySet().iterator(); iterator.hasNext(); ) { + for (Iterator> iterator = + healRunnable.entrySet().iterator(); iterator.hasNext(); ) { Entry entry = iterator.next(); Interval value = entry.getValue(); ++value.count; @@ -56,7 +57,8 @@ public class PlotPlusListener extends PlotListener implements Listener { } } if (!feedRunnable.isEmpty()) { - for (Iterator> iterator = feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { + for (Iterator> iterator = + feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { Entry entry = iterator.next(); Interval value = entry.getValue(); ++value.count; @@ -78,8 +80,7 @@ public class PlotPlusListener extends PlotListener implements Listener { }, 0L, 20L); } - @EventHandler(priority = EventPriority.HIGH) - public void onInteract(BlockDamageEvent event) { + @EventHandler(priority = EventPriority.HIGH) public void onInteract(BlockDamageEvent event) { Player player = event.getPlayer(); if (player.getGameMode() != GameMode.SURVIVAL) { return; @@ -97,9 +98,8 @@ public class PlotPlusListener extends PlotListener implements Listener { } } } - - @EventHandler(priority = EventPriority.HIGH) - public void onDamage(EntityDamageEvent event) { + + @EventHandler(priority = EventPriority.HIGH) public void onDamage(EntityDamageEvent event) { if (event.getEntityType() != EntityType.PLAYER) { return; } @@ -112,9 +112,8 @@ public class PlotPlusListener extends PlotListener implements Listener { event.setCancelled(true); } } - - @EventHandler - public void onItemDrop(PlayerDropItemEvent event) { + + @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); @@ -128,9 +127,8 @@ public class PlotPlusListener extends PlotListener implements Listener { } } } - - @EventHandler - public void onPlotEnter(PlayerEnterPlotEvent event) { + + @EventHandler public void onPlotEnter(PlayerEnterPlotEvent event) { Player player = event.getPlayer(); Plot plot = event.getPlot(); Optional feed = plot.getFlag(Flags.FEED); @@ -144,17 +142,15 @@ public class PlotPlusListener extends PlotListener implements Listener { healRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); } } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { + + @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); String name = player.getName(); feedRunnable.remove(name); healRunnable.remove(name); } - - @EventHandler - public void onPlotLeave(PlayerLeavePlotEvent event) { + + @EventHandler public void onPlotLeave(PlayerLeavePlotEvent event) { Player leaver = event.getPlayer(); Plot plot = event.getPlot(); if (!plot.hasOwner()) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java index 12cc6ab7e..b83f1b1c5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java @@ -4,16 +4,16 @@ import com.intellectualcrafters.plot.flag.Flags; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.UUID; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityPickupItemEvent; +import java.util.UUID; + public class PlotPlusListener_1_12 implements Listener { - @EventHandler - public void onItemPickup(EntityPickupItemEvent event) { + @EventHandler public void onItemPickup(EntityPickupItemEvent event) { LivingEntity ent = event.getEntity(); if (ent instanceof Player) { Player player = (Player) ent; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java index ce0c57f4e..a5d2eb634 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java @@ -4,15 +4,15 @@ import com.intellectualcrafters.plot.flag.Flags; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.UUID; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerPickupItemEvent; +import java.util.UUID; + public class PlotPlusListener_Legacy implements Listener { - @EventHandler - public void onItemPickup(PlayerPickupItemEvent event) { + @EventHandler public void onItemPickup(PlayerPickupItemEvent event) { Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java index 146d30f53..9e68384f1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java @@ -4,8 +4,6 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; import com.intellectualcrafters.plot.util.ReflectionUtils; -import java.lang.reflect.Field; -import java.lang.reflect.Method; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; @@ -16,6 +14,8 @@ import org.bukkit.event.world.ChunkEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.plugin.Plugin; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; @@ -42,10 +42,14 @@ public class SingleWorldListener implements Listener { public void markChunkAsClean(Chunk chunk) { try { Object nmsChunk = methodGetHandleChunk.invoke(chunk); - if (done != null) this.done.set(nmsChunk, true); - if (mustSave != null) this.mustSave.set(nmsChunk, false); - if (lit != null) this.lit.set(nmsChunk, false); - if (s != null) this.s.set(nmsChunk, false); + if (done != null) + this.done.set(nmsChunk, true); + if (mustSave != null) + this.mustSave.set(nmsChunk, false); + if (lit != null) + this.lit.set(nmsChunk, false); + if (s != null) + this.s.set(nmsChunk, false); } catch (Throwable e) { e.printStackTrace(); } @@ -55,19 +59,20 @@ public class SingleWorldListener implements Listener { World world = event.getWorld(); String name = world.getName(); PlotAreaManager man = PS.get().getPlotAreaManager(); - if (!(man instanceof SinglePlotAreaManager)) return; - if (!isPlotId(name)) return; + if (!(man instanceof SinglePlotAreaManager)) + return; + if (!isPlotId(name)) + return; markChunkAsClean(event.getChunk()); } -// @EventHandler -// public void onPopulate(ChunkPopulateEvent event) { -// handle(event); -// } + // @EventHandler + // public void onPopulate(ChunkPopulateEvent event) { + // handle(event); + // } - @EventHandler(priority = EventPriority.LOWEST) - public void onChunkLoad(ChunkLoadEvent event) { + @EventHandler(priority = EventPriority.LOWEST) public void onChunkLoad(ChunkLoadEvent event) { handle(event); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java index 1e80cc19b..44f884372 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java @@ -13,7 +13,7 @@ import org.bukkit.event.world.WorldInitEvent; import org.bukkit.generator.ChunkGenerator; public class WorldEvents implements Listener { - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onWorldInit(WorldInitEvent event) { World world = event.getWorld(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java index 7a26d21a5..2a1a44314 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java @@ -24,8 +24,7 @@ public class BukkitLazyBlock extends LazyBlock { this.block = block; } - @Override - public PlotBlock getPlotBlock() { + @Override public PlotBlock getPlotBlock() { if (this.pb != null) { return this.pb; } @@ -127,8 +126,7 @@ public class BukkitLazyBlock extends LazyBlock { } - @Override - public int getId() { + @Override public int getId() { if (this.id == 0) { this.id = this.block.getTypeId(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java index 715b92bee..8b770badd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java @@ -19,23 +19,19 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { this.player = player; } - @Override - public UUID getUUID() { + @Override public UUID getUUID() { return this.player.getUniqueId(); } - @Override - public long getLastPlayed() { + @Override public long getLastPlayed() { return this.player.getLastPlayed(); } - @Override - public boolean isOnline() { + @Override public boolean isOnline() { return this.player.isOnline(); } - @Override - public String getName() { + @Override public String getName() { return this.player.getName(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java index efeb04e11..7814c8706 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java @@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.*; import com.plotsquared.bukkit.util.BukkitUtil; -import org.apache.commons.lang.StringUtils; import org.bukkit.Effect; import org.bukkit.GameMode; import org.bukkit.WeatherType; @@ -14,15 +13,14 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventException; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.RegisteredListener; import java.util.Set; import java.util.UUID; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.RegisteredListener; - public class BukkitPlayer extends PlotPlayer { - + public final Player player; public boolean offline; private UUID uuid; @@ -31,6 +29,7 @@ public class BukkitPlayer extends PlotPlayer { /** *

Please do not use this method. Instead use * BukkitUtil.getPlayer(Player), as it caches player objects.

+ * * @param player */ public BukkitPlayer(Player player) { @@ -44,14 +43,12 @@ public class BukkitPlayer extends PlotPlayer { super.populatePersistentMetaMap(); } - @Override - public Location getLocation() { + @Override public Location getLocation() { Location location = super.getLocation(); return location == null ? BukkitUtil.getLocation(this.player) : location; } - - @Override - public UUID getUUID() { + + @Override public UUID getUUID() { if (this.uuid == null) { this.uuid = UUIDHandler.getUUID(this); } @@ -62,8 +59,7 @@ public class BukkitPlayer extends PlotPlayer { return this.player.getLastPlayed(); } - @Override - public boolean canTeleport(Location loc) { + @Override public boolean canTeleport(Location loc) { org.bukkit.Location to = BukkitUtil.getLocation(loc); org.bukkit.Location from = player.getLocation(); PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to); @@ -95,16 +91,14 @@ public class BukkitPlayer extends PlotPlayer { return true; } - @Override - public boolean hasPermission(String permission) { + @Override public boolean hasPermission(String permission) { if (this.offline && EconHandler.manager != null) { return EconHandler.manager.hasPermission(getName(), permission); } return this.player.hasPermission(permission); } - @Override - public int hasPermissionRange(String stub, int range) { + @Override public int hasPermissionRange(String stub, int range) { if (hasPermission(C.PERMISSION_ADMIN.s())) { return Integer.MAX_VALUE; } @@ -131,8 +125,10 @@ public class BukkitPlayer extends PlotPlayer { String end = perm.substring(stubPlus.length()); if (MathMan.isInteger(end)) { int val = Integer.parseInt(end); - if (val > range) return val; - if (val > max) max = val; + if (val > range) + return val; + if (val > max) + max = val; } } } @@ -146,57 +142,52 @@ public class BukkitPlayer extends PlotPlayer { return max; } - @Override - public boolean isPermissionSet(String permission) { + @Override public boolean isPermissionSet(String permission) { return this.player.isPermissionSet(permission); } - @Override - public void sendMessage(String message) { - if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || (System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { + @Override public void sendMessage(String message) { + if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( + System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { setMeta("lastMessage", message); setMeta("lastMessageTime", System.currentTimeMillis()); this.player.sendMessage(message); } } - - @Override - public void teleport(Location location) { + + @Override public void teleport(Location location) { if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) { return; } this.player.teleport( - new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, location.getY(), location.getZ() + 0.5, - location.getYaw(), location.getPitch()), TeleportCause.COMMAND); + new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, + location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch()), + TeleportCause.COMMAND); } - - @Override - public String getName() { + + @Override public String getName() { if (this.name == null) { this.name = this.player.getName(); } return this.name; } - - @Override - public boolean isOnline() { + + @Override public boolean isOnline() { return !this.offline && this.player.isOnline(); } - - @Override - public void setCompassTarget(Location location) { + + @Override public void setCompassTarget(Location location) { this.player.setCompassTarget( - new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ())); - + new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), + location.getY(), location.getZ())); + } - - @Override - public Location getLocationFull() { + + @Override public Location getLocationFull() { return BukkitUtil.getLocationFull(this.player); } - @Override - public void setWeather(PlotWeather weather) { + @Override public void setWeather(PlotWeather weather) { switch (weather) { case CLEAR: this.player.setPlayerWeather(WeatherType.CLEAR); @@ -212,9 +203,8 @@ public class BukkitPlayer extends PlotPlayer { break; } } - - @Override - public PlotGameMode getGameMode() { + + @Override public PlotGameMode getGameMode() { switch (this.player.getGameMode()) { case ADVENTURE: return PlotGameMode.ADVENTURE; @@ -228,9 +218,8 @@ public class BukkitPlayer extends PlotPlayer { return PlotGameMode.NOT_SET; } } - - @Override - public void setGameMode(PlotGameMode gameMode) { + + @Override public void setGameMode(PlotGameMode gameMode) { switch (gameMode) { case ADVENTURE: this.player.setGameMode(GameMode.ADVENTURE); @@ -249,34 +238,29 @@ public class BukkitPlayer extends PlotPlayer { break; } } - - @Override - public void setTime(long time) { + + @Override public void setTime(long time) { if (time != Long.MAX_VALUE) { this.player.setPlayerTime(time, false); } else { this.player.resetPlayerTime(); } } - - @Override - public void setFlight(boolean fly) { - this.player.setAllowFlight(fly); - } - @Override - public boolean getFlight() { + @Override public boolean getFlight() { return player.getAllowFlight(); } - @Override - public void playMusic(Location location, int id) { + @Override public void setFlight(boolean fly) { + this.player.setAllowFlight(fly); + } + + @Override public void playMusic(Location location, int id) { //noinspection deprecation this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id); } - - @Override - public void kick(String message) { + + @Override public void kick(String message) { this.player.kickPlayer(message); } @@ -286,8 +270,7 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override - public boolean isBanned() { + @Override public boolean isBanned() { return this.player.isBanned(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java index 33dc737ab..a96d62db0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java @@ -2,34 +2,11 @@ package com.plotsquared.bukkit.object.entity; import com.intellectualcrafters.plot.PS; import com.plotsquared.bukkit.util.BukkitVersion; -import org.bukkit.Art; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.Rotation; -import org.bukkit.TreeSpecies; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.block.BlockFace; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Bat; -import org.bukkit.entity.Boat; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.Horse; -import org.bukkit.entity.IronGolem; -import org.bukkit.entity.Item; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Painting; -import org.bukkit.entity.Rabbit; +import org.bukkit.entity.*; import org.bukkit.entity.Rabbit.Type; -import org.bukkit.entity.Sheep; -import org.bukkit.entity.Skeleton; import org.bukkit.entity.Skeleton.SkeletonType; -import org.bukkit.entity.Slime; -import org.bukkit.entity.Tameable; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; @@ -87,7 +64,8 @@ public class EntityWrapper { if (depth == 1) { return; } - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) { + if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) + || entity instanceof ArmorStand) { if (!entity.hasGravity()) { this.noGravity = true; } @@ -220,13 +198,16 @@ public class EntityWrapper { storeLiving((LivingEntity) entity); return; case SKELETON: - this.dataByte = getOrdinal(SkeletonType.values(),((Skeleton)entity).getSkeletonType()); + this.dataByte = + getOrdinal(SkeletonType.values(), ((Skeleton) entity).getSkeletonType()); storeLiving((LivingEntity) entity); return; case ARMOR_STAND: ArmorStand stand = (ArmorStand) entity; - this.inventory = new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), - stand.getLeggings().clone(), stand.getBoots().clone()}; + this.inventory = + new ItemStack[] {stand.getItemInHand().clone(), stand.getHelmet().clone(), + stand.getChestplate().clone(), stand.getLeggings().clone(), + stand.getBoots().clone()}; storeLiving(stand); this.stand = new ArmorStandStats(); @@ -315,13 +296,11 @@ public class EntityWrapper { } } - @Override - public boolean equals(Object obj) { + @Override public boolean equals(Object obj) { return this.hash == obj.hashCode(); } - @Override - public int hashCode() { + @Override public int hashCode() { return this.hash; } @@ -473,7 +452,8 @@ public class EntityWrapper { if (this.base.passenger != null) { try { entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); - } catch (Exception ignored) { } + } catch (Exception ignored) { + } } if (this.base.fall != 0) { entity.setFallDistance(this.base.fall); @@ -488,7 +468,8 @@ public class EntityWrapper { if (this.depth == 1) { return entity; } - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) { + if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) + || entity instanceof ArmorStand) { if (this.noGravity) { entity.setGravity(false); } @@ -642,27 +623,37 @@ public class EntityWrapper { stand.setBoots(this.inventory[4]); } if (this.stand.head[0] != 0 || this.stand.head[1] != 0 || this.stand.head[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); + EulerAngle pose = + new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); stand.setHeadPose(pose); } if (this.stand.body[0] != 0 || this.stand.body[1] != 0 || this.stand.body[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); + EulerAngle pose = + new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); stand.setBodyPose(pose); } - if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 || this.stand.leftLeg[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]); + if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 + || this.stand.leftLeg[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], + this.stand.leftLeg[2]); stand.setLeftLegPose(pose); } - if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 || this.stand.rightLeg[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]); + if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 + || this.stand.rightLeg[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], + this.stand.rightLeg[2]); stand.setRightLegPose(pose); } - if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 || this.stand.leftArm[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]); + if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 + || this.stand.leftArm[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], + this.stand.leftArm[2]); stand.setLeftArmPose(pose); } - if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 || this.stand.rightArm[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]); + if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 + || this.stand.rightArm[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], + this.stand.rightArm[2]); stand.setRightArmPose(pose); } if (this.stand.invisible) { @@ -716,7 +707,7 @@ public class EntityWrapper { } restoreLiving((LivingEntity) entity); return entity; - // END LIVING + // END LIVING } } @@ -729,9 +720,7 @@ public class EntityWrapper { return 0; } - @SuppressWarnings("deprecation") - @Override - public String toString() { + @SuppressWarnings("deprecation") @Override public String toString() { return String.format("[%s, x=%s, y=%s, z=%s]", type.getName(), x, y, z); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java index 3431e6b77..35f58e446 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -1,10 +1,6 @@ package com.plotsquared.bukkit.object.schematic; -import com.intellectualcrafters.jnbt.ByteTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.ListTag; -import com.intellectualcrafters.jnbt.ShortTag; -import com.intellectualcrafters.jnbt.Tag; +import com.intellectualcrafters.jnbt.*; import com.intellectualcrafters.plot.object.schematic.ItemType; import com.intellectualcrafters.plot.util.MathMan; import com.plotsquared.bukkit.util.BukkitUtil; @@ -89,7 +85,8 @@ public class StateWrapper { InventoryHolder inv = (InventoryHolder) this.state; ItemStack[] contents = inv.getInventory().getContents(); Map values = new HashMap<>(); - values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents))); + values.put("Items", + new ListTag("Items", CompoundTag.class, serializeInventory(contents))); return new CompoundTag(values); } return null; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java index 98ea32db9..0bb28c81e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java @@ -12,13 +12,14 @@ public class DefaultTitleManager extends TitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ - DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { + DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, + int fadeOutTime) { super(title, subtitle, fadeInTime, stayTime, fadeOutTime); } @@ -32,7 +33,8 @@ public class DefaultTitleManager extends TitleManager { this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer"); } - @Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if (this.packetTitle != null) { // First reset previous settings resetTitle(player); @@ -41,38 +43,44 @@ public class DefaultTitleManager extends TitleManager { Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE) - .newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), - this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); + Object packet = this.packetTitle + .getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, + Integer.TYPE, Integer.TYPE) + .newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); // Send if set if (this.fadeInTime != -1 && this.fadeOutTime != -1 && this.stayTime != -1) { sendPacket.invoke(connection, packet); } // Send title Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase() - + '}'); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + + "\",color:" + this.titleColor.name().toLowerCase() + '}'); + packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); if (!this.getSubtitle().isEmpty()) { // Send subtitle if present serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name() - .toLowerCase() + '}'); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + + "\",color:" + this.subtitleColor.name().toLowerCase() + '}'); + packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } } } - @Override - public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void clearTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null); + Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[3], null); sendPacket.invoke(connection, packet); } @@ -84,14 +92,15 @@ public class DefaultTitleManager extends TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - @Override - public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void resetTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null); + Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[4], null); sendPacket.invoke(connection, packet); } @@ -108,7 +117,8 @@ public class DefaultTitleManager extends TitleManager { Method getMethod(Class clazz, String name, Class... args) { for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && (args.length == 0 || classListEqual(args, m.getParameterTypes()))) { + if (m.getName().equals(name) && (args.length == 0 || classListEqual(args, + m.getParameterTypes()))) { m.setAccessible(true); return m; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java index 559e296fd..5a5a0dd3f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java @@ -11,29 +11,29 @@ public class DefaultTitleManager_183 extends DefaultTitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ - DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { + DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, + int fadeOutTime) { super(title, subtitle, fadeInTime, stayTime, fadeOutTime); } /** * Load spigot and NMS classes. */ - @Override - void loadClasses() { + @Override void loadClasses() { this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle"); this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent"); this.packetActions = Reflection.getNMSClass("PacketPlayOutTitle$EnumTitleAction"); this.nmsChatSerializer = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer"); } - @Override - public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if (this.packetTitle != null) { // First reset previous settings resetTitle(player); @@ -43,26 +43,29 @@ public class DefaultTitleManager_183 extends DefaultTitleManager { Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); Object packet = this.packetTitle - .getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE) - .newInstance(actions[2], null, - this.fadeInTime * (this.ticks ? 1 : 20), - this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); + .getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, + Integer.TYPE, Integer.TYPE) + .newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); // Send if set if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { sendPacket.invoke(connection, packet); } // Send title Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase() - + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + + "\",color:" + this.titleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); if (!this.getSubtitle().isEmpty()) { // Send subtitle if present serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name() - .toLowerCase() + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + + "\",color:" + this.subtitleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java index be6cfc568..274b0e96c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java @@ -7,8 +7,7 @@ import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.util.BukkitVersion; import org.bukkit.entity.Player; -@SuppressWarnings("deprecation") -public class DefaultTitle_111 extends AbstractTitle { +@SuppressWarnings("deprecation") public class DefaultTitle_111 extends AbstractTitle { private final boolean valid; @@ -24,7 +23,8 @@ public class DefaultTitle_111 extends AbstractTitle { TitleManager_1_11 title = new TitleManager_1_11(head, sub, in, delay, out); title.send(playerObj); return; - } catch (Throwable ignored) {} + } catch (Throwable ignored) { + } } AbstractTitle.TITLE_CLASS = new DefaultTitle_180(); AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java index f6f90c2f2..cf88d7fd5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java @@ -6,8 +6,7 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.object.BukkitPlayer; import org.bukkit.entity.Player; -@SuppressWarnings("deprecation") -public class DefaultTitle_19 extends AbstractTitle { +@SuppressWarnings("deprecation") public class DefaultTitle_19 extends AbstractTitle { @Override public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { @@ -15,8 +14,7 @@ public class DefaultTitle_19 extends AbstractTitle { final Player playerObj = ((BukkitPlayer) player).player; playerObj.sendTitle(head, sub); TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { + @Override public void run() { playerObj.sendTitle("", ""); } }, delay * 20); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java index cf8e87b95..98a093646 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java @@ -13,10 +13,10 @@ public class HackTitleManager extends TitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { @@ -26,14 +26,14 @@ public class HackTitleManager extends TitleManager { /** * Load spigot and NMS classes. */ - @Override - void loadClasses() { + @Override void loadClasses() { this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer"); } - @Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { // First reset previous settings resetTitle(player); @@ -42,8 +42,9 @@ public class HackTitleManager extends TitleManager { Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], - this.fadeInTime * (this.ticks ? 1 : 20), + Object packet = this.packetTitle + .getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE) + .newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); // Send if set @@ -52,43 +53,49 @@ public class HackTitleManager extends TitleManager { } // Send title Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase() - + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) - .newInstance(actions[0], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + + "\",color:" + this.titleColor.name().toLowerCase() + "}"); + packet = this.packetTitle + .getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); if (!this.getSubtitle().isEmpty()) { // Send subtitle if present serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name() - .toLowerCase() + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) - .newInstance(actions[1], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + + "\",color:" + this.subtitleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, + Reflection.getNMSClass("IChatBaseComponent")) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } } } - @Override public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void clearTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if ((getProtocolVersion(player) >= 47) && isSpigot()) { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); + Object packet = + this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); sendPacket.invoke(connection, packet); } } - @Override public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void resetTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if ((getProtocolVersion(player) >= 47) && isSpigot()) { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); + Object packet = + this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); sendPacket.invoke(connection, packet); } } @@ -102,7 +109,8 @@ public class HackTitleManager extends TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - private int getProtocolVersion(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + private int getProtocolVersion(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object networkManager = getValue("networkManager", connection); @@ -127,15 +135,18 @@ public class HackTitleManager extends TitleManager { private Class getClass(String namespace) { try { return Class.forName(namespace); - } catch (ClassNotFoundException ignored) {} + } catch (ClassNotFoundException ignored) { + } return null; } - private Field getField(String name, Class clazz) throws NoSuchFieldException, SecurityException { + private Field getField(String name, Class clazz) + throws NoSuchFieldException, SecurityException { return clazz.getDeclaredField(name); } - private Object getValue(String name, Object obj) throws ReflectiveOperationException, SecurityException, IllegalArgumentException { + private Object getValue(String name, Object obj) + throws ReflectiveOperationException, SecurityException, IllegalArgumentException { Field f = getField(name, obj.getClass()); f.setAccessible(true); return f.get(obj); @@ -154,7 +165,8 @@ public class HackTitleManager extends TitleManager { private Method getMethod(Class clazz, String name, Class... args) { for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args, m.getParameterTypes()))) { + if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args, + m.getParameterTypes()))) { m.setAccessible(true); return m; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java index 91a5d68a0..ccc870dd9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java @@ -12,17 +12,13 @@ import java.util.Map; public abstract class TitleManager { private static final Map, Class> CORRESPONDING_TYPES = new HashMap<>(); - /* Title packet */ - Class packetTitle; - /* Title packet actions ENUM */ - Class packetActions; - /* Chat serializer */ - Class nmsChatSerializer; + /* Title packet */ Class packetTitle; + /* Title packet actions ENUM */ Class packetActions; + /* Chat serializer */ Class nmsChatSerializer; Class chatBaseComponent; ChatColor titleColor = ChatColor.WHITE; ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ - int fadeInTime = -1; + /* Title timings */ int fadeInTime = -1; int stayTime = -1; int fadeOutTime = -1; boolean ticks = false; @@ -34,10 +30,10 @@ public abstract class TitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ TitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { @@ -154,7 +150,8 @@ public abstract class TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - public abstract void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException; + public abstract void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException; /** * Broadcasts the title to all players. @@ -175,7 +172,8 @@ public abstract class TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - public abstract void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException; + public abstract void clearTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException; /** * Resets the title settings. @@ -185,7 +183,8 @@ public abstract class TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - public abstract void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException; + public abstract void resetTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException; private Class getPrimitiveType(Class clazz) { if (CORRESPONDING_TYPES.containsKey(clazz)) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java index 935f3d850..a1ed0ec61 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java @@ -1,14 +1,14 @@ package com.plotsquared.bukkit.titles; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - /** * Minecraft 1.8 Title * For 1.11 @@ -17,6 +17,8 @@ import org.bukkit.entity.Player; * @version 1.1.0 */ public class TitleManager_1_11 { + private static final Map, Class> CORRESPONDING_TYPES = + new HashMap, Class>(); /* Title packet */ private static Class packetTitle; /* Title packet actions ENUM */ @@ -43,8 +45,6 @@ public class TitleManager_1_11 { private int fadeOutTime = -1; private boolean ticks = false; - private static final Map, Class> CORRESPONDING_TYPES = new HashMap, Class>(); - public TitleManager_1_11() { loadClasses(); } @@ -98,7 +98,8 @@ public class TitleManager_1_11 { * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ - public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { + public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime, + int fadeOutTime) { this.title = title; this.subtitle = subtitle; this.fadeInTime = fadeInTime; @@ -107,6 +108,15 @@ public class TitleManager_1_11 { loadClasses(); } + private static boolean equalsTypeArray(Class[] a, Class[] o) { + if (a.length != o.length) + return false; + for (int i = 0; i < a.length; i++) + if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) + return false; + return true; + } + /** * Load spigot and NMS classes */ @@ -118,23 +128,13 @@ public class TitleManager_1_11 { nmsChatSerializer = getNMSClass("ChatComponentText"); nmsPlayer = getNMSClass("EntityPlayer"); nmsPlayerConnection = getNMSClass("PlayerConnection"); - playerConnection = getField(nmsPlayer, - "playerConnection"); + playerConnection = getField(nmsPlayer, "playerConnection"); sendPacket = getMethod(nmsPlayerConnection, "sendPacket"); obcPlayer = getOBCClass("entity.CraftPlayer"); methodPlayerGetHandle = getMethod("getHandle", obcPlayer); } } - /** - * Set title text - * - * @param title Title - */ - public void setTitle(String title) { - this.title = title; - } - /** * Get title text * @@ -145,12 +145,12 @@ public class TitleManager_1_11 { } /** - * Set subtitle text + * Set title text * - * @param subtitle Subtitle text + * @param title Title */ - public void setSubtitle(String subtitle) { - this.subtitle = subtitle; + public void setTitle(String title) { + this.title = title; } /** @@ -163,48 +163,12 @@ public class TitleManager_1_11 { } /** - * Set the title color + * Set subtitle text * - * @param color Chat color + * @param subtitle Subtitle text */ - public void setTitleColor(ChatColor color) { - this.titleColor = color; - } - - /** - * Set the subtitle color - * - * @param color Chat color - */ - public void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } - - /** - * Set title fade in time - * - * @param time Time - */ - public void setFadeInTime(int time) { - this.fadeInTime = time; - } - - /** - * Set title fade out time - * - * @param time Time - */ - public void setFadeOutTime(int time) { - this.fadeOutTime = time; - } - - /** - * Set title stay time - * - * @param time Time - */ - public void setStayTime(int time) { - this.stayTime = time; + public void setSubtitle(String subtitle) { + this.subtitle = subtitle; } /** @@ -235,12 +199,10 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent, Integer.TYPE, Integer.TYPE, - Integer.TYPE).newInstance(actions[3], null, - fadeInTime * (ticks ? 1 : 20), - stayTime * (ticks ? 1 : 20), - fadeOutTime * (ticks ? 1 : 20)); + Object packet = packetTitle + .getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, + Integer.TYPE).newInstance(actions[3], null, fadeInTime * (ticks ? 1 : 20), + stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20)); // Send if set if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) sendPacket.invoke(connection, packet); @@ -248,22 +210,18 @@ public class TitleManager_1_11 { Object serialized; if (!subtitle.equals("")) { // Send subtitle if present - serialized = nmsChatSerializer.getConstructor(String.class) - .newInstance(subtitleColor + - ChatColor.translateAlternateColorCodes('&', - subtitle)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[1], - serialized); + serialized = nmsChatSerializer.getConstructor(String.class).newInstance( + subtitleColor + ChatColor.translateAlternateColorCodes('&', subtitle)); + packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } // Send title - serialized = nmsChatSerializer.getConstructor( - String.class).newInstance(titleColor + - ChatColor.translateAlternateColorCodes('&', title)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[0], serialized); + serialized = nmsChatSerializer.getConstructor(String.class) + .newInstance(titleColor + ChatColor.translateAlternateColorCodes('&', title)); + packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -278,19 +236,12 @@ public class TitleManager_1_11 { Object connection = playerConnection.get(handle); Object[] actions = TitleManager_1_11.packetActions.getEnumConstants(); Object packet = TitleManager_1_11.packetTitle.getConstructor( - new Class[]{TitleManager_1_11.packetActions, chatBaseComponent, - Integer.TYPE, Integer.TYPE, Integer.TYPE}) - .newInstance( - actions[3], - null, - this.fadeInTime - * (this.ticks ? 1 : 20), - this.stayTime - * (this.ticks ? 1 : 20), - this.fadeOutTime - * (this.ticks ? 1 : 20)); - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) - && (this.stayTime != -1)) { + new Class[] {TitleManager_1_11.packetActions, chatBaseComponent, Integer.TYPE, + Integer.TYPE, Integer.TYPE}) + .newInstance(actions[3], null, this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); + if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { sendPacket.invoke(connection, packet); } } catch (Exception e) { @@ -303,21 +254,14 @@ public class TitleManager_1_11 { if (TitleManager_1_11.packetTitle != null) { try { Object handle = getHandle(player); - Object connection = getField(handle.getClass(), - "playerConnection").get(handle); + Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = TitleManager_1_11.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), - "sendPacket"); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance(titleColor + - ChatColor.translateAlternateColorCodes('&', - this.title)); - Object packet = TitleManager_1_11.packetTitle - .getConstructor( - new Class[]{TitleManager_1_11.packetActions, - chatBaseComponent}).newInstance( - actions[0], serialized); + Method sendPacket = getMethod(connection.getClass(), "sendPacket"); + Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance( + titleColor + ChatColor.translateAlternateColorCodes('&', this.title)); + Object packet = TitleManager_1_11.packetTitle.getConstructor( + new Class[] {TitleManager_1_11.packetActions, chatBaseComponent}) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -331,16 +275,11 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = TitleManager_1_11.packetActions.getEnumConstants(); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance(subtitleColor + - ChatColor.translateAlternateColorCodes('&', - this.subtitle)); - Object packet = TitleManager_1_11.packetTitle - .getConstructor( - new Class[]{TitleManager_1_11.packetActions, - chatBaseComponent}).newInstance( - actions[1], serialized); + Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance( + subtitleColor + ChatColor.translateAlternateColorCodes('&', this.subtitle)); + Object packet = TitleManager_1_11.packetTitle.getConstructor( + new Class[] {TitleManager_1_11.packetActions, chatBaseComponent}) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -368,8 +307,8 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[4], null); + Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[4], null); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -387,8 +326,8 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[5], null); + Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[5], null); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -396,8 +335,7 @@ public class TitleManager_1_11 { } private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES - .get(clazz) : clazz; + return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; } private Class[] toPrimitiveTypeArray(Class[] classes) { @@ -408,15 +346,6 @@ public class TitleManager_1_11 { return types; } - private static boolean equalsTypeArray(Class[] a, Class[] o) { - if (a.length != o.length) - return false; - for (int i = 0; i < a.length; i++) - if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) - return false; - return true; - } - private Object getHandle(Player player) { try { return methodPlayerGetHandle.invoke(player); @@ -426,8 +355,7 @@ public class TitleManager_1_11 { } } - private Method getMethod(String name, Class clazz, - Class... paramTypes) { + private Method getMethod(String name, Class clazz, Class... paramTypes) { Class[] t = toPrimitiveTypeArray(paramTypes); for (Method m : clazz.getMethods()) { Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); @@ -465,7 +393,6 @@ public class TitleManager_1_11 { return clazz; } - private Field getField(Class clazz, String name) { try { Field field = clazz.getDeclaredField(name); @@ -479,9 +406,8 @@ public class TitleManager_1_11 { private Method getMethod(Class clazz, String name, Class... args) { for (Method m : clazz.getMethods()) - if (m.getName().equals(name) - && (args.length == 0 || ClassListEqual(args, - m.getParameterTypes()))) { + if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args, + m.getParameterTypes()))) { m.setAccessible(true); return m; } @@ -504,23 +430,68 @@ public class TitleManager_1_11 { return titleColor; } + /** + * Set the title color + * + * @param color Chat color + */ + public void setTitleColor(ChatColor color) { + this.titleColor = color; + } + public ChatColor getSubtitleColor() { return subtitleColor; } + /** + * Set the subtitle color + * + * @param color Chat color + */ + public void setSubtitleColor(ChatColor color) { + this.subtitleColor = color; + } + public int getFadeInTime() { return fadeInTime; } + /** + * Set title fade in time + * + * @param time Time + */ + public void setFadeInTime(int time) { + this.fadeInTime = time; + } + public int getFadeOutTime() { return fadeOutTime; } + /** + * Set title fade out time + * + * @param time Time + */ + public void setFadeOutTime(int time) { + this.fadeOutTime = time; + } + public int getStayTime() { return stayTime; } + /** + * Set title stay time + * + * @param time Time + */ + public void setStayTime(int time) { + this.stayTime = time; + } + public boolean isTicks() { return ticks; } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java index 3e7c226f5..7c6a6b4a0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java @@ -15,18 +15,15 @@ import java.util.List; public class BukkitChatManager extends ChatManager { - @Override - public FancyMessage builder() { + @Override public FancyMessage builder() { return new FancyMessage(""); } - @Override - public void color(PlotMessage message, String color) { + @Override public void color(PlotMessage message, String color) { message.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); } - @Override - public void tooltip(PlotMessage message, PlotMessage... tooltips) { + @Override public void tooltip(PlotMessage message, PlotMessage... tooltips) { List lines = new ArrayList<>(); for (PlotMessage tooltip : tooltips) { lines.add(tooltip.$(this)); @@ -34,18 +31,15 @@ public class BukkitChatManager extends ChatManager { message.$(this).formattedTooltip(lines); } - @Override - public void command(PlotMessage message, String command) { + @Override public void command(PlotMessage message, String command) { message.$(this).command(command); } - @Override - public void text(PlotMessage message, String text) { + @Override public void text(PlotMessage message, String text) { message.$(this).then(ChatColor.stripColor(text)); } - @Override - public void send(PlotMessage plotMessage, PlotPlayer player) { + @Override public void send(PlotMessage plotMessage, PlotPlayer player) { if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) { player.sendMessage(plotMessage.$(this).toOldMessageFormat()); } else { @@ -53,8 +47,7 @@ public class BukkitChatManager extends ChatManager { } } - @Override - public void suggest(PlotMessage plotMessage, String command) { + @Override public void suggest(PlotMessage plotMessage, String command) { plotMessage.$(this).suggest(command); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index e39ab5f4e..24369a585 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -2,61 +2,23 @@ package com.plotsquared.bukkit.util; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.generator.AugmentedUtils; -import com.intellectualcrafters.plot.object.BlockLoc; -import com.intellectualcrafters.plot.object.ChunkLoc; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotLoc; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.intellectualcrafters.plot.util.block.LocalBlockQueue; import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue; import com.plotsquared.bukkit.object.entity.EntityWrapper; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.Note; -import org.bukkit.SkullType; -import org.bukkit.World; -import org.bukkit.block.Banner; -import org.bukkit.block.Beacon; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.BrewingStand; -import org.bukkit.block.CommandBlock; -import org.bukkit.block.CreatureSpawner; -import org.bukkit.block.Dispenser; -import org.bukkit.block.Dropper; -import org.bukkit.block.Furnace; -import org.bukkit.block.Hopper; -import org.bukkit.block.Jukebox; -import org.bukkit.block.NoteBlock; -import org.bukkit.block.Sign; -import org.bukkit.block.Skull; +import org.bukkit.*; +import org.bukkit.block.*; import org.bukkit.block.banner.Pattern; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Creature; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; +import org.bukkit.entity.*; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; public class BukkitChunkManager extends ChunkManager { @@ -73,7 +35,8 @@ public class BukkitChunkManager extends ChunkManager { return 0; } - public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, RegionWrapper r1, RegionWrapper r2) { + public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, + RegionWrapper r1, RegionWrapper r2) { ContentMap map = new ContentMap(); int relX = r2.minX - r1.minX; int relZ = r2.minZ - r1.minZ; @@ -127,8 +90,7 @@ public class BukkitChunkManager extends ChunkManager { return map; } - @Override - public Set getChunkChunks(String world) { + @Override public Set getChunkChunks(String world) { Set chunks = super.getChunkChunks(world); for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); @@ -139,13 +101,15 @@ public class BukkitChunkManager extends ChunkManager { return chunks; } - @Override - public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) { + @Override public boolean copyRegion(Location pos1, Location pos2, Location newPos, + final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - Location pos4 = new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ); + Location pos4 = + new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ); - final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + final RegionWrapper region = + new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); final World oldWorld = Bukkit.getWorld(pos1.getWorld()); final World newWorld = Bukkit.getWorld(newPos.getWorld()); final String newWorldName = newWorld.getName(); @@ -153,8 +117,7 @@ public class BukkitChunkManager extends ChunkManager { final ContentMap map = new ContentMap(); final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { int bx = value[2]; int bz = value[3]; int tx = value[4]; @@ -171,8 +134,7 @@ public class BukkitChunkManager extends ChunkManager { } } }, new Runnable() { - @Override - public void run() { + @Override public void run() { for (Entry entry : map.allBlocks.entrySet()) { PlotLoc loc = entry.getKey(); PlotBlock[] blocks = entry.getValue(); @@ -185,8 +147,7 @@ public class BukkitChunkManager extends ChunkManager { } queue.enqueue(); GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override - public void run() { + @Override public void run() { map.restoreBlocks(newWorld, 0, 0); map.restoreEntities(newWorld, relX, relZ); TaskManager.runTask(whenDone); @@ -197,8 +158,8 @@ public class BukkitChunkManager extends ChunkManager { return true; } - @Override - public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { + @Override public boolean regenerateRegion(final Location pos1, final Location pos2, + final boolean ignoreAugment, final Runnable whenDone) { final String world = pos1.getWorld(); final int p1x = pos1.getX(); @@ -219,8 +180,7 @@ public class BukkitChunkManager extends ChunkManager { } final World worldObj = Bukkit.getWorld(world); TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { long start = System.currentTimeMillis(); while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { final ChunkLoc chunk = chunks.remove(0); @@ -235,11 +195,11 @@ public class BukkitChunkManager extends ChunkManager { continue; } final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); - RegionWrapper currentPlotClear = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + RegionWrapper currentPlotClear = + new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { AugmentedUtils.bypass(ignoreAugment, new Runnable() { - @Override - public void run() { + @Override public void run() { queue.regenChunkSafe(chunk.x, chunk.z); } }); @@ -306,11 +266,9 @@ public class BukkitChunkManager extends ChunkManager { } map.saveEntitiesOut(chunkObj, currentPlotClear); AugmentedUtils.bypass(ignoreAugment, new Runnable() { - @Override - public void run() { + @Override public void run() { setChunkInPlotArea(null, new RunnableVal() { - @Override - public void run(ScopedLocalBlockQueue value) { + @Override public void run(ScopedLocalBlockQueue value) { Location min = value.getMin(); int bx = min.getX(); int bz = min.getZ(); @@ -319,7 +277,8 @@ public class BukkitChunkManager extends ChunkManager { PlotLoc loc = new PlotLoc(bx + x, bz + z); PlotBlock[] ids = map.allBlocks.get(loc); if (ids != null) { - for (int y = 0; y < Math.min(128, ids.length); y++) { + for (int y = 0; + y < Math.min(128, ids.length); y++) { PlotBlock id = ids[y]; if (id != null) { value.setBlock(x, y, z, id); @@ -327,7 +286,8 @@ public class BukkitChunkManager extends ChunkManager { value.setBlock(x, y, z, 0, (byte) 0); } } - for (int y = Math.min(128, ids.length); y < ids.length; y++) { + for (int y = Math.min(128, ids.length); + y < ids.length; y++) { PlotBlock id = ids[y]; if (id != null) { value.setBlock(x, y, z, id); @@ -353,8 +313,7 @@ public class BukkitChunkManager extends ChunkManager { return true; } - @Override - public void clearAllEntities(Location pos1, Location pos2) { + @Override public void clearAllEntities(Location pos1, Location pos2) { String world = pos1.getWorld(); List entities = BukkitUtil.getEntities(world); int bx = pos1.getX(); @@ -364,26 +323,24 @@ public class BukkitChunkManager extends ChunkManager { for (Entity entity : entities) { if (!(entity instanceof Player)) { org.bukkit.Location location = entity.getLocation(); - if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz && location.getZ() <= tz) { + if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz + && location.getZ() <= tz) { entity.remove(); } } } } - @Override - public boolean loadChunk(String world, ChunkLoc loc, boolean force) { + @Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) { return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force); } - @SuppressWarnings("deprecation") - @Override - public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe) { + @SuppressWarnings("deprecation") @Override + public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, + final boolean safe) { if (!PS.get().isMainThread(Thread.currentThread())) { TaskManager.runTask(new Runnable() { - @SuppressWarnings("deprecation") - @Override - public void run() { + @SuppressWarnings("deprecation") @Override public void run() { BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe); } }); @@ -392,10 +349,12 @@ public class BukkitChunkManager extends ChunkManager { } } - @Override - public void swap(Location bot1, Location top1, Location bot2, Location top2, final Runnable whenDone) { - RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); - RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); + @Override public void swap(Location bot1, Location top1, Location bot2, Location top2, + final Runnable whenDone) { + RegionWrapper region1 = + new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); + RegionWrapper region2 = + new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); final World world1 = Bukkit.getWorld(bot1.getWorld()); World world2 = Bukkit.getWorld(bot2.getWorld()); @@ -412,8 +371,7 @@ public class BukkitChunkManager extends ChunkManager { } } GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override - public void run() { + @Override public void run() { for (ContentMap map : maps) { map.restoreBlocks(world1, 0, 0); map.restoreEntities(world1, 0, 0); @@ -423,10 +381,10 @@ public class BukkitChunkManager extends ChunkManager { }); } - @Override - public int[] countEntities(Plot plot) { + @Override public int[] countEntities(Plot plot) { int[] existing = (int[]) plot.getMeta("EntityCount"); - if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") < 1000)) { + if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") + < 1000)) { return existing; } PlotArea area = plot.getArea(); @@ -542,7 +500,7 @@ public class BukkitChunkManager extends ChunkManager { case ARMOR_STAND: count[5]++; break; - // misc + // misc case MINECART: case MINECART_CHEST: case MINECART_COMMAND: @@ -705,7 +663,8 @@ public class BukkitChunkManager extends ChunkManager { } } - public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, boolean delete) { + public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, + boolean delete) { for (Entity entity : chunk.getEntities()) { Location loc = BukkitUtil.getLocation(entity); int x = loc.getX(); @@ -743,26 +702,30 @@ public class BukkitChunkManager extends ChunkManager { public void restoreBlocks(World world, int xOffset, int zOffset) { for (Entry blockLocEntry : this.chestContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof InventoryHolder) { InventoryHolder chest = (InventoryHolder) state; chest.getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.signContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Sign) { Sign sign = (Sign) state; @@ -773,95 +736,105 @@ public class BukkitChunkManager extends ChunkManager { } state.update(true); } else { - PS.debug( - "&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y - + ',' + ( - blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IndexOutOfBoundsException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y - + ',' + ( - blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.dispenserContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Dispenser) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.dropperContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Dropper) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.beaconContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Beacon) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocMaterialEntry : this.jukeboxDisc.entrySet()) { try { - Block block = - world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry - .getKey().z + zOffset); + Block block = world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, + blockLocMaterialEntry.getKey().y, + blockLocMaterialEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Jukebox) { ((Jukebox) state).setPlaying(blockLocMaterialEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + xOffset) + ',' - + blockLocMaterialEntry - .getKey().y + ',' + ( - blockLocMaterialEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + ( + blockLocMaterialEntry.getKey().x + xOffset) + ',' + + blockLocMaterialEntry.getKey().y + ',' + ( + blockLocMaterialEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + xOffset) + ',' - + blockLocMaterialEntry - .getKey().y + ',' + ( - blockLocMaterialEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + ( + blockLocMaterialEntry.getKey().x + xOffset) + ',' + blockLocMaterialEntry + .getKey().y + ',' + (blockLocMaterialEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.skullData.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Skull) { Object[] data = blockLocEntry.getValue(); @@ -872,193 +845,210 @@ public class BukkitChunkManager extends ChunkManager { ((Skull) state).setSkullType((SkullType) data[3]); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore skull: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); e.printStackTrace(); } } for (Entry blockLocEntry : this.hopperContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Hopper) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocNoteEntry : this.noteBlockContents.entrySet()) { try { - Block block = world.getBlockAt( - blockLocNoteEntry.getKey().x + xOffset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocNoteEntry.getKey().x + xOffset, + blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof NoteBlock) { ((NoteBlock) state).setNote(blockLocNoteEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + xOffset) + ',' - + blockLocNoteEntry - .getKey().y + ',' + ( - blockLocNoteEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + ( + blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry + .getKey().y + ',' + (blockLocNoteEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + xOffset) + ',' - + blockLocNoteEntry - .getKey().y + ',' + ( - blockLocNoteEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + ( + blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry.getKey().y + + ',' + (blockLocNoteEntry.getKey().z + zOffset)); } } for (Entry blockLocShortEntry : this.brewTime.entrySet()) { try { - Block block = world.getBlockAt( - blockLocShortEntry.getKey().x + xOffset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocShortEntry.getKey().x + xOffset, + blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof BrewingStand) { ((BrewingStand) state).setBrewingTime(blockLocShortEntry.getValue()); } else { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + xOffset) + ',' - + blockLocShortEntry - .getKey().y + ',' + ( - blockLocShortEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + ( + blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry + .getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + xOffset) + ',' - + blockLocShortEntry.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + ( + blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry + .getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset)); } } - for (Entry blockLocEntityTypeEntry : this.spawnerData.entrySet()) { + for (Entry blockLocEntityTypeEntry : this.spawnerData + .entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry - .getKey().z + zOffset); + Block block = world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, + blockLocEntityTypeEntry.getKey().y, + blockLocEntityTypeEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof CreatureSpawner) { - ((CreatureSpawner) state).setSpawnedType(blockLocEntityTypeEntry.getValue()); + ((CreatureSpawner) state) + .setSpawnedType(blockLocEntityTypeEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ',' - + blockLocEntityTypeEntry - .getKey().y + ',' + ( - blockLocEntityTypeEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + ( + blockLocEntityTypeEntry.getKey().x + xOffset) + ',' + + blockLocEntityTypeEntry.getKey().y + ',' + ( + blockLocEntityTypeEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ',' - + blockLocEntityTypeEntry.getKey().y + ',' + (blockLocEntityTypeEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + ( + blockLocEntityTypeEntry.getKey().x + xOffset) + ',' + + blockLocEntityTypeEntry.getKey().y + ',' + ( + blockLocEntityTypeEntry.getKey().z + zOffset)); } } for (Entry blockLocStringEntry : this.cmdData.entrySet()) { try { - Block block = world.getBlockAt( - blockLocStringEntry.getKey().x + xOffset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocStringEntry.getKey().x + xOffset, + blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof CommandBlock) { ((CommandBlock) state).setCommand(blockLocStringEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + xOffset) + ',' - + blockLocStringEntry - .getKey().y + ',' + ( - blockLocStringEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore command block: " + ( + blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry + .getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + xOffset) + ',' - + blockLocStringEntry - .getKey().y + ',' + ( - blockLocStringEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + ( + blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry + .getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset)); } } - for (Entry blockLocEntry : this.brewingStandContents.entrySet()) { + for (Entry blockLocEntry : this.brewingStandContents + .entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof BrewingStand) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + xOffset) + ',' - + blockLocEntry - .getKey().y + ',' + ( - blockLocEntry.getKey().z - + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + xOffset) + ',' - + blockLocEntry.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.furnaceTime.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Furnace) { Short[] time = blockLocEntry.getValue(); ((Furnace) state).setBurnTime(time[0]); ((Furnace) state).setCookTime(time[1]); } else { - PS.debug( - "&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore furnace cooking: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug( - "&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to restore furnace cooking (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.furnaceContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Furnace) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocByteEntry : this.bannerBase.entrySet()) { try { - Block block = world.getBlockAt( - blockLocByteEntry.getKey().x + xOffset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocByteEntry.getKey().x + xOffset, + blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Banner) { Banner banner = (Banner) state; DyeColor base = blockLocByteEntry.getValue(); - List patterns = this.bannerPatterns.get(blockLocByteEntry.getKey()); + List patterns = + this.bannerPatterns.get(blockLocByteEntry.getKey()); banner.setBaseColor(base); banner.setPatterns(patterns); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + xOffset) + ',' - + blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + ( + blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry + .getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + xOffset) + ',' - + blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset)); + PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + ( + blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry.getKey().y + + ',' + (blockLocByteEntry.getKey().z + zOffset)); } } } - public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, boolean storeNormal) { + public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, + boolean storeNormal) { maxY = Math.min(255, maxY); PlotBlock[] ids; if (storeNormal) { @@ -1082,7 +1072,8 @@ public class BukkitChunkManager extends ChunkManager { BlockLoc bl = new BlockLoc(x + offsetX, y, z + offsetZ); if (block.getState() instanceof InventoryHolder) { InventoryHolder inventoryHolder = (InventoryHolder) block.getState(); - ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone(); + ItemStack[] inventory = + inventoryHolder.getInventory().getContents().clone(); switch (id) { case CHEST: this.chestContents.put(bl, inventory); @@ -1105,7 +1096,8 @@ public class BukkitChunkManager extends ChunkManager { if (time > 0) { this.brewTime.put(bl, time); } - ItemStack[] invBre = brewingStand.getInventory().getContents().clone(); + ItemStack[] invBre = + brewingStand.getInventory().getContents().clone(); this.brewingStandContents.put(bl, invBre); break; case FURNACE: @@ -1113,10 +1105,11 @@ public class BukkitChunkManager extends ChunkManager { Furnace furnace = (Furnace) inventoryHolder; short burn = furnace.getBurnTime(); short cook = furnace.getCookTime(); - ItemStack[] invFur = furnace.getInventory().getContents().clone(); + ItemStack[] invFur = + furnace.getInventory().getContents().clone(); this.furnaceContents.put(bl, invFur); if (cook != 0) { - this.furnaceTime.put(bl, new Short[]{burn, cook}); + this.furnaceTime.put(bl, new Short[] {burn, cook}); } break; } @@ -1144,7 +1137,8 @@ public class BukkitChunkManager extends ChunkManager { } } else if (block.getState() instanceof Skull) { Skull skull = (Skull) block.getState(); - this.skullData.put(bl, new Object[]{skull.hasOwner(), skull.getOwner(), skull.getRotation(), skull.getSkullType()}); + this.skullData.put(bl, new Object[] {skull.hasOwner(), skull.getOwner(), + skull.getRotation(), skull.getSkullType()}); } else if (block.getState() instanceof Banner) { Banner banner = (Banner) block.getState(); DyeColor base = banner.getBaseColor(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java index d97271f4b..5dc54c5a4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java @@ -4,13 +4,7 @@ import com.intellectualcrafters.plot.commands.MainCommand; import com.intellectualcrafters.plot.object.ConsolePlayer; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.bukkit.commands.DebugUUID; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.ProxiedCommandSender; -import org.bukkit.command.RemoteConsoleCommandSender; -import org.bukkit.command.TabCompleter; +import org.bukkit.command.*; import org.bukkit.entity.Player; import java.util.ArrayList; @@ -25,19 +19,22 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } @Override - public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args) { + public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, + String[] args) { if (commandSender instanceof Player) { return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), args); } - if (commandSender instanceof ConsoleCommandSender || commandSender instanceof ProxiedCommandSender - || commandSender instanceof RemoteConsoleCommandSender) { + if (commandSender instanceof ConsoleCommandSender + || commandSender instanceof ProxiedCommandSender + || commandSender instanceof RemoteConsoleCommandSender) { return MainCommand.onCommand(ConsolePlayer.getConsole(), args); } return false; } @Override - public List onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { + public List onTabComplete(CommandSender commandSender, Command command, String s, + String[] args) { if (!(commandSender instanceof Player)) { return null; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java index 830afe93c..248a88ca0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java @@ -24,7 +24,8 @@ public class BukkitEconHandler extends EconHandler { } private boolean setupPermissions() { - RegisteredServiceProvider permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); if (permissionProvider != null) { this.perms = permissionProvider.getProvider(); } @@ -35,15 +36,15 @@ public class BukkitEconHandler extends EconHandler { if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { return false; } - RegisteredServiceProvider economyProvider = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + RegisteredServiceProvider economyProvider = + Bukkit.getServer().getServicesManager().getRegistration(Economy.class); if (economyProvider != null) { this.econ = economyProvider.getProvider(); } return this.econ != null; } - @Override - public double getMoney(PlotPlayer player) { + @Override public double getMoney(PlotPlayer player) { double bal = super.getMoney(player); if (Double.isNaN(bal)) { return this.econ.getBalance(((BukkitPlayer) player).player); @@ -51,28 +52,23 @@ public class BukkitEconHandler extends EconHandler { return bal; } - @Override - public void withdrawMoney(PlotPlayer player, double amount) { + @Override public void withdrawMoney(PlotPlayer player, double amount) { this.econ.withdrawPlayer(((BukkitPlayer) player).player, amount); } - @Override - public void depositMoney(PlotPlayer player, double amount) { + @Override public void depositMoney(PlotPlayer player, double amount) { this.econ.depositPlayer(((BukkitPlayer) player).player, amount); } - @Override - public void depositMoney(OfflinePlotPlayer player, double amount) { + @Override public void depositMoney(OfflinePlotPlayer player, double amount) { this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); } - @Override - public boolean hasPermission(String world, String player, String perm) { + @Override public boolean hasPermission(String world, String player, String perm) { return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); } - @Override - public double getBalance(PlotPlayer player) { + @Override public double getBalance(PlotPlayer player) { return this.econ.getBalance(player.getName()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java index b004e6ff4..4fe906beb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java @@ -1,30 +1,9 @@ package com.plotsquared.bukkit.util; import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.EventUtil; -import com.plotsquared.bukkit.events.ClusterFlagRemoveEvent; -import com.plotsquared.bukkit.events.PlayerClaimPlotEvent; -import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; -import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; -import com.plotsquared.bukkit.events.PlayerPlotDeniedEvent; -import com.plotsquared.bukkit.events.PlayerPlotHelperEvent; -import com.plotsquared.bukkit.events.PlayerPlotTrustedEvent; -import com.plotsquared.bukkit.events.PlayerTeleportToPlotEvent; -import com.plotsquared.bukkit.events.PlotClearEvent; -import com.plotsquared.bukkit.events.PlotComponentSetEvent; -import com.plotsquared.bukkit.events.PlotDeleteEvent; -import com.plotsquared.bukkit.events.PlotFlagAddEvent; -import com.plotsquared.bukkit.events.PlotFlagRemoveEvent; -import com.plotsquared.bukkit.events.PlotMergeEvent; -import com.plotsquared.bukkit.events.PlotRateEvent; -import com.plotsquared.bukkit.events.PlotUnlinkEvent; +import com.plotsquared.bukkit.events.*; import com.plotsquared.bukkit.object.BukkitPlayer; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -48,83 +27,67 @@ public class BukkitEventUtil extends EventUtil { return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); } - @Override - public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { + @Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); } - @Override - public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { + @Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); } - @Override - public boolean callComponentSet(Plot plot, String component) { + @Override public boolean callComponentSet(Plot plot, String component) { return callEvent(new PlotComponentSetEvent(plot, component)); } - @Override - public boolean callClear(Plot plot) { + @Override public boolean callClear(Plot plot) { return callEvent(new PlotClearEvent(plot)); } - @Override - public void callDelete(Plot plot) { + @Override public void callDelete(Plot plot) { callEvent(new PlotDeleteEvent(plot)); } - @Override - public boolean callFlagAdd(Flag flag, Plot plot) { + @Override public boolean callFlagAdd(Flag flag, Plot plot) { return callEvent(new PlotFlagAddEvent(flag, plot)); } - @Override - public boolean callFlagRemove(Flag flag, Plot plot, Object value) { + @Override public boolean callFlagRemove(Flag flag, Plot plot, Object value) { return callEvent(new PlotFlagRemoveEvent(flag, plot)); } - @Override - public boolean callMerge(Plot plot, ArrayList plots) { + @Override public boolean callMerge(Plot plot, ArrayList plots) { return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots)); } - @Override - public boolean callUnlink(PlotArea area, ArrayList plots) { + @Override public boolean callUnlink(PlotArea area, ArrayList plots) { return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); } - @Override - public void callEntry(PlotPlayer player, Plot plot) { + @Override public void callEntry(PlotPlayer player, Plot plot) { callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); } - @Override - public void callLeave(PlotPlayer player, Plot plot) { + @Override public void callLeave(PlotPlayer player, Plot plot) { callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); } - @Override - public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + @Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); } - @Override - public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + @Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); } - @Override - public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + @Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); } - @Override - public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) { + @Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) { return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); } - @Override - public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { + @Override public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { PlotRateEvent event = new PlotRateEvent(player, rating, plot); Bukkit.getServer().getPluginManager().callEvent(event); return event.getRating(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java index 225998ab2..68b729948 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -26,8 +26,8 @@ import java.util.Random; public class BukkitHybridUtils extends HybridUtils { - @Override - public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal whenDone) { + @Override public void analyzeRegion(final String world, final RegionWrapper region, + final RunnableVal whenDone) { // int diff, int variety, int vertices, int rotation, int height_sd /* * diff: compare to base by looping through all blocks @@ -41,8 +41,7 @@ public class BukkitHybridUtils extends HybridUtils { * */ TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); final World worldObj = Bukkit.getWorld(world); final ChunkGenerator gen = worldObj.getGenerator(); @@ -50,12 +49,10 @@ public class BukkitHybridUtils extends HybridUtils { return; } final BiomeGrid nullBiomeGrid = new BiomeGrid() { - @Override - public void setBiome(int a, int b, Biome c) { + @Override public void setBiome(int a, int b, Biome c) { } - @Override - public Biome getBiome(int a, int b) { + @Override public Biome getBiome(int a, int b) { return null; } }; @@ -82,15 +79,14 @@ public class BukkitHybridUtils extends HybridUtils { final short[][][] newBlocks = new short[256][width][length]; final Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { ChunkManager.chunkTask(bot, top, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { // [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] int X = value[0]; int Z = value[1]; - short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); + short[][] result = + gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); int xb = (X << 4) - bx; int zb = (Z << 4) - bz; for (int i = 0; i < result.length; i++) { @@ -125,11 +121,9 @@ public class BukkitHybridUtils extends HybridUtils { } }, new Runnable() { - @Override - public void run() { + @Override public void run() { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { int size = width * length; int[] changes = new int[size]; int[] faces = new int[size]; @@ -151,7 +145,8 @@ public class BukkitHybridUtils extends HybridUtils { } else { // check vertices // modifications_adjacent - if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) { + if (x > 0 && z > 0 && y > 0 && x < width - 1 + && z < length - 1 && y < 255) { if (newBlocks[y - 1][x][z] == 0) { faces[i]++; } @@ -172,12 +167,15 @@ public class BukkitHybridUtils extends HybridUtils { } } - Material material = Material.getMaterial(now); + Material material = + Material.getMaterial(now); if (material != null) { - Class md = material.getData(); + Class md = + material.getData(); if (md.equals(Directional.class)) { data[i] += 8; - } else if (!md.equals(MaterialData.class)) { + } else if (!md + .equals(MaterialData.class)) { data[i]++; } } @@ -199,11 +197,14 @@ public class BukkitHybridUtils extends HybridUtils { analysis.air = (int) (MathMan.getMean(air) * 100); analysis.variety = (int) (MathMan.getMean(variety) * 100); - analysis.changes_sd = (int) MathMan.getSD(changes, analysis.changes); - analysis.faces_sd = (int) MathMan.getSD(faces, analysis.faces); + analysis.changes_sd = + (int) MathMan.getSD(changes, analysis.changes); + analysis.faces_sd = + (int) MathMan.getSD(faces, analysis.faces); analysis.data_sd = (int) MathMan.getSD(data, analysis.data); analysis.air_sd = (int) MathMan.getSD(air, analysis.air); - analysis.variety_sd = (int) MathMan.getSD(variety, analysis.variety); + analysis.variety_sd = + (int) MathMan.getSD(variety, analysis.variety); System.gc(); System.gc(); whenDone.value = analysis; @@ -219,8 +220,7 @@ public class BukkitHybridUtils extends HybridUtils { MainUtil.initCache(); ChunkManager.chunkTask(bot, top, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { int X = value[0]; int Z = value[1]; worldObj.loadChunk(X, Z); @@ -269,8 +269,7 @@ public class BukkitHybridUtils extends HybridUtils { worldObj.unloadChunkRequest(X, Z, true); } }, new Runnable() { - @Override - public void run() { + @Override public void run() { TaskManager.runTaskAsync(run); } }, 5); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java index cd2c12d51..0de2e354b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -45,8 +45,7 @@ public class BukkitInventoryUtil extends InventoryUtil { return stack; } - @Override - public void open(PlotInventory inv) { + @Override public void open(PlotInventory inv) { BukkitPlayer bp = (BukkitPlayer) inv.player; Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); PlotItemStack[] items = inv.getItems(); @@ -60,8 +59,7 @@ public class BukkitInventoryUtil extends InventoryUtil { bp.player.openInventory(inventory); } - @Override - public void close(PlotInventory inv) { + @Override public void close(PlotInventory inv) { if (!inv.isOpen()) { return; } @@ -70,8 +68,7 @@ public class BukkitInventoryUtil extends InventoryUtil { bp.player.closeInventory(); } - @Override - public void setItem(PlotInventory inv, int index, PlotItemStack item) { + @Override public void setItem(PlotInventory inv, int index, PlotItemStack item) { BukkitPlayer bp = (BukkitPlayer) inv.player; InventoryView opened = bp.player.getOpenInventory(); if (!inv.isOpen()) { @@ -103,8 +100,7 @@ public class BukkitInventoryUtil extends InventoryUtil { return new PlotItemStack(id, data, amount, name, lore); } - @Override - public PlotItemStack[] getItems(PlotPlayer player) { + @Override public PlotItemStack[] getItems(PlotPlayer player) { BukkitPlayer bp = (BukkitPlayer) player; PlayerInventory inv = bp.player.getInventory(); PlotItemStack[] items = new PlotItemStack[36]; @@ -114,13 +110,13 @@ public class BukkitInventoryUtil extends InventoryUtil { return items; } - @Override - public boolean isOpen(PlotInventory inv) { + @Override public boolean isOpen(PlotInventory inv) { if (!inv.isOpen()) { return false; } BukkitPlayer bp = (BukkitPlayer) inv.player; InventoryView opened = bp.player.getOpenInventory(); - return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null; + return inv.isOpen() && opened.getType() == InventoryType.CRAFTING + && opened.getTitle() == null; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java index df957892e..ab2e815ce 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java @@ -1,12 +1,6 @@ package com.plotsquared.bukkit.util; -import com.intellectualcrafters.jnbt.ByteArrayTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.IntTag; -import com.intellectualcrafters.jnbt.ListTag; -import com.intellectualcrafters.jnbt.ShortTag; -import com.intellectualcrafters.jnbt.StringTag; -import com.intellectualcrafters.jnbt.Tag; +import com.intellectualcrafters.jnbt.*; import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.RegionWrapper; @@ -22,24 +16,18 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * Schematic Handler. */ public class BukkitSchematicHandler extends SchematicHandler { - @Override - public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { + @Override public void getCompoundTag(final String world, final Set regions, + final RunnableVal whenDone) { // async TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { // Main positions Location[] corners = MainUtil.getCorners(world, regions); final Location bot = corners[0]; @@ -67,16 +55,18 @@ public class BukkitSchematicHandler extends SchematicHandler { // Queue final ArrayDeque queue = new ArrayDeque<>(regions); TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { if (queue.isEmpty()) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); schematic.put("Data", new ByteArrayTag("Data", blockData)); - schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); - schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities)); + schematic.put("Entities", + new ListTag("Entities", CompoundTag.class, + new ArrayList())); + schematic.put("TileEntities", + new ListTag("TileEntities", CompoundTag.class, + tileEntities)); whenDone.value = new CompoundTag("Schematic", schematic); TaskManager.runTask(whenDone); System.gc(); @@ -111,10 +101,10 @@ public class BukkitSchematicHandler extends SchematicHandler { final World worldObj = Bukkit.getWorld(world); // Main thread TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { long start = System.currentTimeMillis(); - while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) { + while (!chunks.isEmpty() + && System.currentTimeMillis() - start < 20) { // save schematics ChunkLoc chunk = chunks.remove(0); Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); @@ -259,15 +249,20 @@ public class BukkitSchematicHandler extends SchematicHandler { // TODO implement fully BlockState state = block.getState(); if (state != null) { - StateWrapper wrapper = new StateWrapper(state); + StateWrapper wrapper = + new StateWrapper(state); CompoundTag rawTag = wrapper.getTag(); if (rawTag != null) { - Map values = new HashMap<>(rawTag.getValue()); - values.put("id", new StringTag("id", wrapper.getId())); + Map values = + new HashMap<>( + rawTag.getValue()); + values.put("id", new StringTag("id", + wrapper.getId())); values.put("x", new IntTag("x", x)); values.put("y", new IntTag("y", y)); values.put("z", new IntTag("z", z)); - CompoundTag tileEntityTag = new CompoundTag(values); + CompoundTag tileEntityTag = + new CompoundTag(values); tileEntities.add(tileEntityTag); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java index 04d1b2d07..27d93b81b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -9,25 +9,21 @@ import com.intellectualcrafters.plot.object.PlotArea; import com.intellectualcrafters.plot.object.SetupObject; import com.intellectualcrafters.plot.util.SetupUtils; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; +import org.bukkit.*; +import org.bukkit.World.Environment; +import org.bukkit.entity.Player; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; + import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.Objects; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.World.Environment; -import org.bukkit.WorldCreator; -import org.bukkit.WorldType; -import org.bukkit.entity.Player; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.Plugin; public class BukkitSetupUtils extends SetupUtils { - @Override - public void updateGenerators() { + @Override public void updateGenerators() { if (!SetupUtils.generators.isEmpty()) { return; } @@ -54,8 +50,7 @@ public class BukkitSetupUtils extends SetupUtils { } } - @Override - public void unload(String worldName, boolean save) { + @Override public void unload(String worldName, boolean save) { World world = Bukkit.getWorld(worldName); if (world == null) { return; @@ -76,8 +71,7 @@ public class BukkitSetupUtils extends SetupUtils { Bukkit.unloadWorld(world, false); } - @Override - public String setupWorld(SetupObject object) { + @Override public String setupWorld(SetupObject object) { SetupUtils.manager.updateGenerators(); ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step; String world = object.world; @@ -89,13 +83,15 @@ public class BukkitSetupUtils extends SetupUtils { if (!PS.get().worlds.contains(worldPath)) { PS.get().worlds.createSection(worldPath); } - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath); + ConfigurationSection worldSection = + PS.get().worlds.getConfigurationSection(worldPath); String areaName = object.id + "-" + object.min + "-" + object.max; String areaPath = "areas." + areaName; if (!worldSection.contains(areaPath)) { worldSection.createSection(areaPath); } - ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath); + ConfigurationSection areaSection = + worldSection.getConfigurationSection(areaPath); HashMap options = new HashMap<>(); for (ConfigurationNode step : steps) { options.put(step.getConstant(), step.getValue()); @@ -103,7 +99,8 @@ public class BukkitSetupUtils extends SetupUtils { options.put("generator.type", object.type); options.put("generator.terrain", object.terrain); options.put("generator.plugin", object.plotManager); - if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) { + if (object.setupGenerator != null && !object.setupGenerator + .equals(object.plotManager)) { options.put("generator.init", object.setupGenerator); } for (Entry entry : options.entrySet()) { @@ -129,15 +126,18 @@ public class BukkitSetupUtils extends SetupUtils { if (!PS.get().worlds.contains(worldPath)) { PS.get().worlds.createSection(worldPath); } - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath); + ConfigurationSection worldSection = + PS.get().worlds.getConfigurationSection(worldPath); for (ConfigurationNode step : steps) { worldSection.set(step.getConstant(), step.getValue()); } PS.get().worlds.set("worlds." + world + ".generator.type", object.type); PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain); PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager); - if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) { - PS.get().worlds.set("worlds." + world + ".generator.init", object.setupGenerator); + if (object.setupGenerator != null && !object.setupGenerator + .equals(object.plotManager)) { + PS.get().worlds + .set("worlds." + world + ".generator.init", object.setupGenerator); } GeneratorWrapper gen = SetupUtils.generators.get(object.setupGenerator); if (gen != null && gen.isFull()) { @@ -150,7 +150,8 @@ public class BukkitSetupUtils extends SetupUtils { if (!PS.get().worlds.contains(worldPath)) { PS.get().worlds.createSection(worldPath); } - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath); + ConfigurationSection worldSection = + PS.get().worlds.getConfigurationSection(worldPath); for (ConfigurationNode step : steps) { worldSection.set(step.getConstant(), step.getValue()); } @@ -164,17 +165,19 @@ public class BukkitSetupUtils extends SetupUtils { e.printStackTrace(); } if (object.setupGenerator != null) { - if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core") - .isEnabled()) { - Bukkit.getServer() - .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); + if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit + .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv create " + world + " normal -g " + object.setupGenerator); setGenerator(world, object.setupGenerator); if (Bukkit.getWorld(world) != null) { return world; } } - if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator); + if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit + .getPluginManager().getPlugin("MultiWorld").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw create " + world + " plugin:" + object.setupGenerator); setGenerator(world, object.setupGenerator); if (Bukkit.getWorld(world) != null) { return world; @@ -187,20 +190,24 @@ public class BukkitSetupUtils extends SetupUtils { Bukkit.createWorld(wc); setGenerator(world, object.setupGenerator); } else { - if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core") - .isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal"); + if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit + .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv create " + world + " normal"); if (Bukkit.getWorld(world) != null) { return world; } } - if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world); + if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit + .getPluginManager().getPlugin("MultiWorld").isEnabled()) { + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world); if (Bukkit.getWorld(world) != null) { return world; } } - World bw = Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL)); + World bw = + Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL)); } return object.world; } @@ -219,8 +226,7 @@ public class BukkitSetupUtils extends SetupUtils { } } - @Override - public String getGenerator(PlotArea plotArea) { + @Override public String getGenerator(PlotArea plotArea) { if (SetupUtils.generators.isEmpty()) { updateGenerators(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java index 7a6c89ded..13325772b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java @@ -12,39 +12,37 @@ public class BukkitTaskManager extends TaskManager { this.bukkitMain = bukkitMain; } - @Override - public int taskRepeat(Runnable runnable, int interval) { - return this.bukkitMain.getServer().getScheduler().scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval); + @Override public int taskRepeat(Runnable runnable, int interval) { + return this.bukkitMain.getServer().getScheduler() + .scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval); } - @SuppressWarnings("deprecation") - @Override + @SuppressWarnings("deprecation") @Override public int taskRepeatAsync(Runnable runnable, int interval) { - return this.bukkitMain.getServer().getScheduler().scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval); + return this.bukkitMain.getServer().getScheduler() + .scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval); } - @Override - public void taskAsync(Runnable runnable) { - this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable).getTaskId(); + @Override public void taskAsync(Runnable runnable) { + this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable) + .getTaskId(); } - @Override - public void task(Runnable runnable) { + @Override public void task(Runnable runnable) { this.bukkitMain.getServer().getScheduler().runTask(this.bukkitMain, runnable).getTaskId(); } - @Override - public void taskLater(Runnable runnable, int delay) { - this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay).getTaskId(); + @Override public void taskLater(Runnable runnable, int delay) { + this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay) + .getTaskId(); } - @Override - public void taskLaterAsync(Runnable runnable, int delay) { - this.bukkitMain.getServer().getScheduler().runTaskLaterAsynchronously(this.bukkitMain, runnable, delay); + @Override public void taskLaterAsync(Runnable runnable, int delay) { + this.bukkitMain.getServer().getScheduler() + .runTaskLaterAsynchronously(this.bukkitMain, runnable, delay); } - @Override - public void cancelTask(int task) { + @Override public void cancelTask(int task) { if (task != -1) { Bukkit.getScheduler().cancelTask(task); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 83511ac0a..e1abb1b08 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -10,9 +10,6 @@ import com.intellectualcrafters.plot.util.StringComparison; import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.bukkit.object.BukkitPlayer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.OfflinePlayer; @@ -26,12 +23,11 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.material.Sandstone; -import org.bukkit.material.Step; -import org.bukkit.material.Tree; -import org.bukkit.material.WoodenStep; -import org.bukkit.material.Wool; +import org.bukkit.material.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; public class BukkitUtil extends WorldUtil { @@ -71,12 +67,13 @@ public class BukkitUtil extends WorldUtil { } public static Location getLocation(org.bukkit.Location location) { - return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), - MathMan.roundInt(location.getZ())); + return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), + MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ())); } public static org.bukkit.Location getLocation(Location location) { - return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()); + return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), + location.getY(), location.getZ()); } public static World getWorld(String string) { @@ -95,37 +92,40 @@ public class BukkitUtil extends WorldUtil { public static Location getLocation(Entity entity) { org.bukkit.Location location = entity.getLocation(); String world = location.getWorld().getName(); - return new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); + return new Location(world, location.getBlockX(), location.getBlockY(), + location.getBlockZ()); } public static Location getLocationFull(Entity entity) { org.bukkit.Location location = entity.getLocation(); - return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), - location.getYaw(), location.getPitch()); + return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), + MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(), + location.getPitch()); } - @Override - public boolean isWorld(String worldName) { + @Override public boolean isWorld(String worldName) { return getWorld(worldName) != null; } - @Override - public String getBiome(String world, int x, int z) { + @Override public String getBiome(String world, int x, int z) { return getWorld(world).getBiome(x, z).name(); } - @Override - public void setSign(String worldName, int x, int y, int z, String[] lines) { + @Override public void setSign(String worldName, int x, int y, int z, String[] lines) { World world = getWorld(worldName); Block block = world.getBlockAt(x, y, z); // block.setType(Material.AIR); Material type = block.getType(); if (type != Material.SIGN && type != Material.SIGN_POST) { int data = 2; - if (world.getBlockAt(x, y, z + 1).getType().isSolid()) data = 2; - else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) data = 4; - else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) data = 3; - else if (world.getBlockAt(x - 1, y, z).getType().isSolid()) data = 5; + if (world.getBlockAt(x, y, z + 1).getType().isSolid()) + data = 2; + else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) + data = 4; + else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) + data = 3; + else if (world.getBlockAt(x - 1, y, z).getType().isSolid()) + data = 5; block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) data, false); } BlockState blockstate = block.getState(); @@ -138,9 +138,9 @@ public class BukkitUtil extends WorldUtil { } } - @Override - public String[] getSign(Location location) { - Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ()); + @Override public String[] getSign(Location location) { + Block block = getWorld(location.getWorld()) + .getBlockAt(location.getX(), location.getY(), location.getZ()); if (block != null) { if (block.getState() instanceof Sign) { Sign sign = (Sign) block.getState(); @@ -150,35 +150,31 @@ public class BukkitUtil extends WorldUtil { return null; } - @Override - public Location getSpawn(PlotPlayer player) { + @Override public Location getSpawn(PlotPlayer player) { return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation()); } - @Override - public Location getSpawn(String world) { + @Override public Location getSpawn(String world) { org.bukkit.Location temp = getWorld(world).getSpawnLocation(); - return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); + return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), + temp.getYaw(), temp.getPitch()); } - @Override - public void setSpawn(Location location) { + @Override public void setSpawn(Location location) { World world = getWorld(location.getWorld()); if (world != null) { world.setSpawnLocation(location.getX(), location.getY(), location.getZ()); } } - @Override - public void saveWorld(String worldName) { + @Override public void saveWorld(String worldName) { World world = getWorld(worldName); if (world != null) { world.save(); } } - @Override - public int getHighestBlock(String world, int x, int z) { + @Override public int getHighestBlock(String world, int x, int z) { World bukkitWorld = getWorld(world); // Skip top and bottom block int air = 1; @@ -187,7 +183,8 @@ public class BukkitUtil extends WorldUtil { if (block != null) { Material type = block.getType(); if (type.isSolid()) { - if (air > 1) return y; + if (air > 1) + return y; air = 0; } else { switch (type) { @@ -204,8 +201,7 @@ public class BukkitUtil extends WorldUtil { return bukkitWorld.getMaxHeight() - 1; } - @Override - public int getBiomeFromString(String biomeString) { + @Override public int getBiomeFromString(String biomeString) { try { Biome biome = Biome.valueOf(biomeString.toUpperCase()); return Arrays.asList(Biome.values()).indexOf(biome); @@ -214,8 +210,7 @@ public class BukkitUtil extends WorldUtil { } } - @Override - public String[] getBiomeList() { + @Override public String[] getBiomeList() { Biome[] biomes = Biome.values(); String[] list = new String[biomes.length]; for (int i = 0; i < biomes.length; i++) { @@ -224,8 +219,7 @@ public class BukkitUtil extends WorldUtil { return list; } - @Override - public boolean addItems(String worldName, PlotItem items) { + @Override public boolean addItems(String worldName, PlotItem items) { World world = getWorld(worldName); Block block = world.getBlockAt(items.x, items.y, items.z); if (block == null) { @@ -245,18 +239,15 @@ public class BukkitUtil extends WorldUtil { return false; } - @Override - public boolean isBlockSolid(PlotBlock block) { + @Override public boolean isBlockSolid(PlotBlock block) { try { Material material = Material.getMaterial(block.id); if (material.isBlock() && material.isSolid() && !material.hasGravity()) { Class data = material.getData(); - if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding() - || data.equals(Tree.class) - || data.equals(Sandstone.class) - || data.equals(Wool.class) - || data.equals(Step.class) - || data.equals(WoodenStep.class)) { + if (data.equals(MaterialData.class) && !material.isTransparent() && material + .isOccluding() || data.equals(Tree.class) || data.equals(Sandstone.class) + || data.equals(Wool.class) || data.equals(Step.class) || data + .equals(WoodenStep.class)) { switch (material) { case NOTE_BLOCK: case MOB_SPAWNER: @@ -272,8 +263,7 @@ public class BukkitUtil extends WorldUtil { } } - @Override - public String getClosestMatchingName(PlotBlock block) { + @Override public String getClosestMatchingName(PlotBlock block) { try { return Material.getMaterial(block.id).name(); } catch (Exception ignored) { @@ -281,12 +271,13 @@ public class BukkitUtil extends WorldUtil { } } - @Override - public StringComparison.ComparisonResult getClosestBlock(String name) { + @Override public StringComparison.ComparisonResult getClosestBlock(String name) { try { Material material = Material.valueOf(name.toUpperCase()); - return new StringComparison().new ComparisonResult(0, PlotBlock.get((short) material.getId(), (byte) 0)); - } catch (IllegalArgumentException ignored) {} + return new StringComparison().new ComparisonResult(0, + PlotBlock.get((short) material.getId(), (byte) 0)); + } catch (IllegalArgumentException ignored) { + } try { byte data; String[] split = name.split(":"); @@ -302,7 +293,8 @@ public class BukkitUtil extends WorldUtil { id = Short.parseShort(split[0]); match = 0; } else { - StringComparison.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); + StringComparison.ComparisonResult comparison = + new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); match = comparison.match; id = (short) comparison.best.getId(); } @@ -310,12 +302,12 @@ public class BukkitUtil extends WorldUtil { StringComparison outer = new StringComparison<>(); return outer.new ComparisonResult(match, block); - } catch (NumberFormatException ignored) {} + } catch (NumberFormatException ignored) { + } return null; } - @Override - public void setBiomes(String worldName, RegionWrapper region, String biomeString) { + @Override public void setBiomes(String worldName, RegionWrapper region, String biomeString) { World world = getWorld(worldName); Biome biome = Biome.valueOf(biomeString.toUpperCase()); for (int x = region.minX; x <= region.maxX; x++) { @@ -325,8 +317,7 @@ public class BukkitUtil extends WorldUtil { } } - @Override - public PlotBlock getBlock(Location location) { + @Override public PlotBlock getBlock(Location location) { World world = getWorld(location.getWorld()); Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ()); if (block == null) { @@ -335,8 +326,7 @@ public class BukkitUtil extends WorldUtil { return PlotBlock.get((short) block.getTypeId(), block.getData()); } - @Override - public String getMainWorld() { + @Override public String getMainWorld() { return Bukkit.getWorlds().get(0).getName(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java index d1b30c50c..276ee0c78 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java @@ -6,12 +6,7 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.scheduler.BukkitTask; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLConnection; @@ -22,19 +17,33 @@ import java.util.zip.GZIPOutputStream; public class Metrics { - /** The current revision number. */ + /** + * The current revision number. + */ private static final int REVISION = 7; - /** The base url of the metrics domain.*/ + /** + * The base url of the metrics domain. + */ private static final String BASE_URL = "http://report.mcstats.org"; - /** The url used to report a server's status. */ + /** + * The url used to report a server's status. + */ private static final String REPORT_URL = "/plugin/%s"; - /** Interval of time to ping (in minutes). */ + /** + * Interval of time to ping (in minutes). + */ private static final int PING_INTERVAL = 15; - /** The plugin this metrics submits for. */ + /** + * The plugin this metrics submits for. + */ private final Plugin plugin; - /** Unique server id. */ + /** + * Unique server id. + */ private final String guid; - /** The scheduled task. */ + /** + * The scheduled task. + */ private volatile BukkitTask task = null; public Metrics(Plugin plugin) { @@ -46,7 +55,6 @@ public class Metrics { * GZip compress a string of bytes. * * @param input - * * @return byte[] the file as a byte array */ public static byte[] gzip(String input) { @@ -61,7 +69,8 @@ public class Metrics { if (gzos != null) { try { gzos.close(); - } catch (IOException ignore) {} + } catch (IOException ignore) { + } } } return baos.toByteArray(); @@ -73,7 +82,6 @@ public class Metrics { * @param json * @param key * @param value - * */ private static void appendJSONPair(StringBuilder json, String key, String value) { boolean isValueNumeric = false; @@ -101,7 +109,6 @@ public class Metrics { * Escape a string to create a valid JSON string * * @param text - * * @return String */ private static String escapeJSON(String text) { @@ -145,7 +152,6 @@ public class Metrics { * Encode text as UTF-8 * * @param text the text to encode - * * @return the encoded text, as UTF-8 */ private static String urlEncode(String text) throws UnsupportedEncodingException { @@ -165,22 +171,22 @@ public class Metrics { return true; } // Begin hitting the server with glorious data - this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { - private boolean firstPost = true; + this.task = this.plugin.getServer().getScheduler() + .runTaskTimerAsynchronously(this.plugin, new Runnable() { + private boolean firstPost = true; - @Override - public void run() { - try { - postPlugin(!this.firstPost); - // After the first post we set firstPost to - // false - // Each post thereafter will be a ping - this.firstPost = false; - } catch (IOException e) { - e.printStackTrace(); + @Override public void run() { + try { + postPlugin(!this.firstPost); + // After the first post we set firstPost to + // false + // Each post thereafter will be a ping + this.firstPost = false; + } catch (IOException e) { + e.printStackTrace(); + } } - } - }, 0, PING_INTERVAL * 1200); + }, 0, PING_INTERVAL * 1200); return true; } @@ -196,10 +202,15 @@ public class Metrics { String serverVersion = Bukkit.getVersion(); int playersOnline = 0; try { - if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() == Collection.class) { - playersOnline = ((Collection) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).size(); + if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() + == Collection.class) { + playersOnline = + ((Collection) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]) + .invoke(null)).size(); } else { - playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).length; + playersOnline = + ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]) + .invoke(null)).length; } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { ex.printStackTrace(); @@ -256,7 +267,8 @@ public class Metrics { os.flush(); } String response; - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(connection.getInputStream()))) { response = reader.readLine(); } if (response == null || response.startsWith("ERR") || response.startsWith("7")) { @@ -267,6 +279,7 @@ public class Metrics { } throw new IOException(response); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java index 69690cc8c..54cdfdf7a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java @@ -8,36 +8,18 @@ import com.google.common.collect.MapMaker; import com.google.common.io.ByteSink; import com.google.common.io.Closeables; import com.google.common.primitives.Primitives; -import java.io.BufferedInputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.AbstractList; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.io.*; +import java.lang.reflect.*; +import java.util.*; +import java.util.concurrent.ConcurrentMap; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + public class NbtFactory { // Convert between NBT type and the equivalent class in java @@ -73,14 +55,16 @@ public class NbtFactory { ClassLoader loader = NbtFactory.class.getClassLoader(); String packageName = getPackageName(); - String craftpackageName = getCraftPackageName(); + String craftpackageName = getCraftPackageName(); Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); // Prepare NBT - this.COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); + this.COMPOUND_CLASS = + getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); this.BASE_CLASS = loader.loadClass(craftpackageName + ".NBTBase"); this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId"); - this.NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class); + this.NBT_CREATE_TAG = + getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class); // Prepare CraftItemStack this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); @@ -92,11 +76,14 @@ public class NbtFactory { initializeNMS(loader, nmsPackage); if (this.READ_LIMITER_CLASS != null) { - this.LOAD_COMPOUND = new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS); + this.LOAD_COMPOUND = + new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS); } else { this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS); } - this.SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class); + this.SAVE_COMPOUND = + getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, + DataOutput.class); } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to find offline player.", e); @@ -106,6 +93,7 @@ public class NbtFactory { /** * Retrieve or construct a shared NBT factory. + * * @return The factory. */ private static NbtFactory get() { @@ -117,6 +105,7 @@ public class NbtFactory { /** * Construct a new NBT list of an unspecified type. + * * @return The NBT list. */ public static NbtList createList(Object... content) { @@ -125,6 +114,7 @@ public class NbtFactory { /** * Construct a new NBT list of an unspecified type. + * * @return The NBT list. */ public static NbtList createList(Iterable iterable) { @@ -148,6 +138,7 @@ public class NbtFactory { /** * Construct a new NBT wrapper from a list. + * * @param nmsList - the NBT list. * @return The wrapper. */ @@ -158,12 +149,13 @@ public class NbtFactory { /** * Load the content of a file from a stream. * - * @param input - the stream. + * @param input - the stream. * @param option - whether or not to decompress the input stream. * @return The decoded NBT compound. * @throws IOException If anything went wrong. */ - public static NbtCompound fromStream(InputStream input, StreamOptions option) throws IOException { + public static NbtCompound fromStream(InputStream input, StreamOptions option) + throws IOException { DataInputStream data = null; boolean suppress = true; @@ -195,14 +187,16 @@ public class NbtFactory { * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException { + public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) + throws IOException { OutputStream output = null; DataOutputStream data = null; boolean suppress = true; try { output = stream.openStream(); - data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); + data = new DataOutputStream( + option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); suppress = false; @@ -218,6 +212,7 @@ public class NbtFactory { /** * Construct a new NBT wrapper from a compound. + * * @param nmsCompound - the NBT compound. * @return The wrapper. */ @@ -228,7 +223,8 @@ public class NbtFactory { /** * Set the NBT compound tag of a given item stack. *

- * @param stack - the item stack, cannot be air. + * + * @param stack - the item stack, cannot be air. * @param compound - the new NBT compound, or NULL to remove it. * @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air. */ @@ -246,6 +242,7 @@ public class NbtFactory { * material, damage value or count. *

* The item stack must be a wrapper for a CraftItemStack. + * * @param stack - the item stack. * @return A wrapper for its NBT tag. */ @@ -265,6 +262,7 @@ public class NbtFactory { /** * Retrieve a CraftItemStack version of the stack. + * * @param stack - the stack to convert. * @return The CraftItemStack version. */ @@ -279,12 +277,14 @@ public class NbtFactory { caller.setAccessible(true); return (ItemStack) caller.newInstance(stack); } catch (Exception ignored) { - throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); + throw new IllegalStateException( + "Unable to convert " + stack + " + to a CraftItemStack."); } } /** * Ensure that the given stack can store arbitrary NBT information. + * * @param stack - the stack to check. */ private static void checkItemStack(ItemStack stack) { @@ -295,12 +295,14 @@ public class NbtFactory { throw new IllegalArgumentException("Stack must be a CraftItemStack."); } if (stack.getType() == Material.AIR) { - throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information."); + throw new IllegalArgumentException( + "ItemStacks representing air cannot store NMS information."); } } /** * Invoke a method on the given target instance using the provided parameters. + * * @param method - the method to invoke. * @param target - the target. * @param params - the parameters to supply. @@ -332,22 +334,23 @@ public class NbtFactory { /** * Search for the first publicly and privately defined method of the given name and parameter count. + * * @param requireMod - modifiers that are required. - * @param bannedMod - modifiers that are banned. - * @param clazz - a class to start with. + * @param bannedMod - modifiers that are banned. + * @param clazz - a class to start with. * @param methodName - the method name, or NULL to skip. - * @param params - the expected parameters. + * @param params - the expected parameters. * @return The first method by this name. * @throws IllegalStateException If we cannot find this method. */ - private static Method getMethod(int requireMod, int bannedMod, Class clazz, String methodName, - Class... params) { + private static Method getMethod(int requireMod, int bannedMod, Class clazz, + String methodName, Class... params) { for (Method method : clazz.getDeclaredMethods()) { // Limitation: Doesn't handle overloads - if (((method.getModifiers() & requireMod) == requireMod) - && ((method.getModifiers() & bannedMod) == 0) - && ((methodName == null) || method.getName().equals(methodName)) - && Arrays.equals(method.getParameterTypes(), params)) { + if (((method.getModifiers() & requireMod) == requireMod) && ( + (method.getModifiers() & bannedMod) == 0) && ((methodName == null) || method + .getName().equals(methodName)) && Arrays + .equals(method.getParameterTypes(), params)) { method.setAccessible(true); return method; @@ -357,13 +360,15 @@ public class NbtFactory { if (clazz.getSuperclass() != null) { return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params); } - throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); + throw new IllegalStateException( + String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); } /** * Search for the first publicly and privately defined field of the given name. - * @param instance - an instance of the class with the field. - * @param clazz - an optional class to start with, or NULL to deduce it from instance. + * + * @param instance - an instance of the class with the field. + * @param clazz - an optional class to start with, or NULL to deduce it from instance. * @param fieldName - the field name. * @return The first field by this name. * @throws IllegalStateException If we cannot find this field. @@ -390,7 +395,8 @@ public class NbtFactory { try { this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); - } catch (ClassNotFoundException ignored) {} + } catch (ClassNotFoundException ignored) { + } } private String getPackageName() { @@ -404,24 +410,25 @@ public class NbtFactory { return "org.bukkit.craftbukkit.v1_13_R1"; } } - - private String getCraftPackageName() { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - return "net.minecraft.server." + version; + + private String getCraftPackageName() { + String version = + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + return "net.minecraft.server." + version; } - @SuppressWarnings("unchecked") - private Map getDataMap(Object handle) { - return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle); + @SuppressWarnings("unchecked") private Map getDataMap(Object handle) { + return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), + handle); } - @SuppressWarnings("unchecked") - private List getDataList(Object handle) { + @SuppressWarnings("unchecked") private List getDataList(Object handle) { return (List) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); } /** * Convert wrapped List and Map objects into their respective NBT counterparts. + * * @param value - the value of the element to create. Can be a List or a Map. * @return The NBT element. */ @@ -444,6 +451,7 @@ public class NbtFactory { /** * Convert a given NBT element to a primitive wrapper or List/Map equivalent. *

All changes to any mutable objects will be reflected in the underlying NBT element(s). + * * @param nms - the NBT element. * @return The wrapper equivalent. */ @@ -470,7 +478,8 @@ public class NbtFactory { /** * Construct a new NMS NBT tag initialized with the given value. - * @param type - the NBT type. + * + * @param type - the NBT type. * @param value - the value, or NULL to keep the original value. * @return The created tag. */ @@ -485,8 +494,9 @@ public class NbtFactory { /** * Retrieve the field where the NBT class stores its value. + * * @param type - the NBT type. - * @param nms - the NBT class instance. + * @param nms - the NBT class instance. * @return The corresponding field. */ private Field getDataField(NbtType type, Object nms) { @@ -498,6 +508,7 @@ public class NbtFactory { /** * Retrieve the NBT type from a given NMS NBT tag. + * * @param nms - the native NBT tag. * @return The corresponding type. */ @@ -508,40 +519,38 @@ public class NbtFactory { /** * Retrieve the nearest NBT type for a given primitive type. + * * @param primitive - the primitive type. * @return The corresponding type. */ private NbtType getPrimitiveType(Object primitive) { - NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); + NbtType type = + NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); // Display the illegal value at least if (type == null) { - throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); + throw new IllegalArgumentException( + String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); } return type; } /** * Whether or not to enable stream compression. + * * @author Kristian */ public enum StreamOptions { NO_COMPRESSION, GZIP_COMPRESSION, } + private enum NbtType { - TAG_END(0, Void.class), - TAG_BYTE(1, byte.class), - TAG_SHORT(2, short.class), - TAG_INT(3, int.class), - TAG_LONG(4, long.class), - TAG_FLOAT(5, float.class), - TAG_DOUBLE(6, double.class), - TAG_BYTE_ARRAY(7, byte[].class), - TAG_INT_ARRAY(11, int[].class), - TAG_STRING(8, String.class), - TAG_LIST(9, List.class), - TAG_COMPOUND(10, Map.class); + TAG_END(0, Void.class), TAG_BYTE(1, byte.class), TAG_SHORT(2, short.class), TAG_INT(3, + int.class), TAG_LONG(4, long.class), TAG_FLOAT(5, float.class), TAG_DOUBLE(6, + double.class), TAG_BYTE_ARRAY(7, byte[].class), TAG_INT_ARRAY(11, + int[].class), TAG_STRING(8, String.class), TAG_LIST(9, List.class), TAG_COMPOUND(10, + Map.class); // Unique NBT type public final int id; @@ -563,21 +572,26 @@ public class NbtFactory { } } + /** * Represents an object that provides a view of a native NMS class. + * * @author Kristian */ public interface Wrapper { /** * Retrieve the underlying native NBT tag. + * * @return The underlying NBT. */ Object getHandle(); } + /** * Represents a method for loading an NBT compound. + * * @author Kristian */ private static abstract class LoadCompoundMethod { @@ -591,12 +605,14 @@ public class NbtFactory { /** * Load an NBT compound from a given stream. + * * @param input - the input stream. * @return The loaded NBT compound. */ public abstract Object loadNbt(DataInput input); } + /** * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.2 - 1.7.5 */ @@ -606,12 +622,12 @@ public class NbtFactory { setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class)); } - @Override - public Object loadNbt(DataInput input) { + @Override public Object loadNbt(DataInput input) { return invokeMethod(this.staticMethod, null, input); } } + /** * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.8 */ @@ -620,7 +636,8 @@ public class NbtFactory { private Object readLimiter; LoadMethodSkinUpdate(Class streamClass, Class readLimiterClass) { - setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass)); + setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, + readLimiterClass)); // Find the unlimited read limiter for (Field field : readLimiterClass.getDeclaredFields()) { @@ -634,27 +651,28 @@ public class NbtFactory { } } - @Override - public Object loadNbt(DataInput input) { + @Override public Object loadNbt(DataInput input) { return invokeMethod(this.staticMethod, null, input, this.readLimiter); } } + /** * Represents a root NBT compound. *

All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: *

    - *
  • Primitive types
  • - *
  • {@link String String}
  • - *
  • {@link NbtList}
  • - *
  • {@link NbtCompound}
  • + *
  • Primitive types
  • + *
  • {@link String String}
  • + *
  • {@link NbtList}
  • + *
  • {@link NbtCompound}
  • *
*

* See also: *

    - *
  • {@link NbtFactory#createCompound()}
  • - *
  • {@link NbtFactory#fromCompound(Object)}
  • + *
  • {@link NbtFactory#createCompound()}
  • + *
  • {@link NbtFactory#fromCompound(Object)}
  • *
+ * * @author Kristian */ public final class NbtCompound extends ConvertedMap { @@ -702,7 +720,8 @@ public class NbtFactory { /** * Retrieve the list by the given name. - * @param key - the name of the list. + * + * @param key - the name of the list. * @param createNew - whether or not to create a new list if its missing. * @return An existing list, a new list or NULL. */ @@ -717,7 +736,8 @@ public class NbtFactory { /** * Retrieve the map by the given name. - * @param key - the name of the map. + * + * @param key - the name of the map. * @param createNew - whether or not to create a new map if its missing. * @return An existing map, a new map or NULL. */ @@ -732,7 +752,8 @@ public class NbtFactory { *

* Every element of the path (except the end) are assumed to be compounds, and will * be created if they are missing. - * @param path - the path to the entry. + * + * @param path - the path to the entry. * @param value - the new value of this entry. * @return This compound, for chaining. */ @@ -749,11 +770,11 @@ public class NbtFactory { *

* Every element of the path (except the end) are assumed to be compounds. The * retrieval operation will be cancelled if any of them are missing. + * * @param path - path to the entry. * @return The value, or NULL if not found. */ - @SuppressWarnings("unchecked") - public T getPath(String path) { + @SuppressWarnings("unchecked") public T getPath(String path) { List entries = getPathElements(path); NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); @@ -765,6 +786,7 @@ public class NbtFactory { /** * Save the content of a NBT compound to a stream. + * * @param stream - the output stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. @@ -775,7 +797,8 @@ public class NbtFactory { /** * Retrieve a map from a given path. - * @param path - path of compounds to look up. + * + * @param path - path of compounds to look up. * @param createNew - whether or not to create new compounds on the way. * @return The map at this location. */ @@ -798,6 +821,7 @@ public class NbtFactory { /** * Split the path into separate elements. + * * @param path - the path to split. * @return The elements. */ @@ -806,13 +830,15 @@ public class NbtFactory { } } + /** * Represents a root NBT list. * See also: *

    - *
  • {@link NbtFactory#createList(Iterable)}}
  • - *
  • {@link NbtFactory#fromList(Object)}
  • + *
  • {@link NbtFactory#createList(Iterable)}}
  • + *
  • {@link NbtFactory#fromList(Object)}
  • *
+ * * @author Kristian */ public final class NbtList extends ConvertedList { @@ -822,8 +848,10 @@ public class NbtFactory { } } + /** * Represents a class for caching wrappers. + * * @author Kristian */ private final class CachedNativeWrapper { @@ -846,9 +874,11 @@ public class NbtFactory { } } + /** * Represents a map that wraps another map and automatically * converts entries of its type and another exposed type. + * * @author Kristian */ private class ConvertedMap extends AbstractMap implements Wrapper { @@ -873,32 +903,26 @@ public class NbtFactory { } // Modification - @Override - public Object put(String key, Object value) { + @Override public Object put(String key, Object value) { return wrapOutgoing(this.original.put(key, unwrapIncoming(value))); } // Performance - @Override - public Object get(Object key) { + @Override public Object get(Object key) { return wrapOutgoing(this.original.get(key)); } - @Override - public Object remove(Object key) { + @Override public Object remove(Object key) { return wrapOutgoing(this.original.remove(key)); } - @Override - public boolean containsKey(Object key) { + @Override public boolean containsKey(Object key) { return this.original.containsKey(key); } - @Override - public Set> entrySet() { + @Override public Set> entrySet() { return new AbstractSet>() { - @Override - public boolean add(Entry e) { + @Override public boolean add(Entry e) { String key = e.getKey(); Object value = e.getValue(); @@ -906,13 +930,11 @@ public class NbtFactory { return true; } - @Override - public int size() { + @Override public int size() { return ConvertedMap.this.original.size(); } - @Override - public Iterator> iterator() { + @Override public Iterator> iterator() { return ConvertedMap.this.iterator(); } }; @@ -922,34 +944,33 @@ public class NbtFactory { final Iterator> proxy = this.original.entrySet().iterator(); return new Iterator>() { - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return proxy.hasNext(); } - @Override - public Entry next() { + @Override public Entry next() { Entry entry = proxy.next(); - return new SimpleEntry(entry.getKey(), wrapOutgoing(entry.getValue())); + return new SimpleEntry(entry.getKey(), + wrapOutgoing(entry.getValue())); } - @Override - public void remove() { + @Override public void remove() { proxy.remove(); } }; } - @Override - public Object getHandle() { + @Override public Object getHandle() { return this.handle; } } + /** * Represents a list that wraps another list and converts elements * of its type and another exposed type. + * * @author Kristian */ private class ConvertedList extends AbstractList implements Wrapper { @@ -975,44 +996,38 @@ public class NbtFactory { return unwrapValue(wrapped); } - @Override - public Object get(int index) { + @Override public Object get(int index) { return wrapOutgoing(this.original.get(index)); } - @Override - public int size() { + @Override public int size() { return this.original.size(); } - @Override - public Object set(int index, Object element) { + @Override public Object set(int index, Object element) { return wrapOutgoing(this.original.set(index, unwrapIncoming(element))); } - @Override - public void add(int index, Object element) { + @Override public void add(int index, Object element) { Object nbt = unwrapIncoming(element); // Set the list type if its the first element if (size() == 0) { - setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) getNbtType(nbt).id); + setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, + (byte) getNbtType(nbt).id); } this.original.add(index, nbt); } - @Override - public Object remove(int index) { + @Override public Object remove(int index) { return wrapOutgoing(this.original.remove(index)); } - @Override - public boolean remove(Object o) { + @Override public boolean remove(Object o) { return this.original.remove(unwrapIncoming(o)); } - @Override - public Object getHandle() { + @Override public Object getHandle() { return this.handle; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java index ae235b3b0..607a607ad 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java @@ -1,13 +1,5 @@ package com.plotsquared.bukkit.util; -import static com.intellectualcrafters.plot.util.ReflectionUtils.callConstructor; -import static com.intellectualcrafters.plot.util.ReflectionUtils.callMethod; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getCbClass; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getNmsClass; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getUtilClass; -import static com.intellectualcrafters.plot.util.ReflectionUtils.makeConstructor; -import static com.intellectualcrafters.plot.util.ReflectionUtils.makeMethod; - import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Entity; @@ -17,6 +9,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.UUID; +import static com.intellectualcrafters.plot.util.ReflectionUtils.*; + public class OfflinePlayerUtil { public static Player loadPlayer(String name) { @@ -43,10 +37,12 @@ public class OfflinePlayerUtil { Object worldServer = getWorldServer(); Object profile = newGameProfile(id, name); Class entityPlayerClass = getNmsClass("EntityPlayer"); - Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), - getUtilClass("com.mojang.authlib.GameProfile"), + Constructor entityPlayerConstructor = + makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), + getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), getNmsClass("PlayerInteractManager")); - Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); + Object entityPlayer = + callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); return (Player) getBukkitEntity(entityPlayer); } @@ -55,7 +51,8 @@ public class OfflinePlayerUtil { if (gameProfileClass == null) { //Before uuids return name; } - Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class); + Constructor gameProfileConstructor = + makeConstructor(gameProfileClass, UUID.class, String.class); if (gameProfileConstructor == null) { //Version has string constructor gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class); return callConstructor(gameProfileConstructor, id.toString(), name); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java index 2a68579ce..6c843639b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java @@ -1,7 +1,5 @@ package com.plotsquared.bukkit.util; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.Location; @@ -25,6 +23,8 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + /** * An utility that can be used to send chunks, rather than using bukkit code * to do so (uses heavy NMS). @@ -52,12 +52,14 @@ public class SendChunk { RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) { //this works for 1.9.4 and 1.10 - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),int.class); + tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), int.class); } else { try { - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); + tempMapChunk = classMapChunk + .getConstructor(classChunk.getRealClass(), boolean.class, int.class); } catch (NoSuchMethodException ignored) { - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),boolean.class, int.class, int.class); + tempMapChunk = classMapChunk + .getConstructor(classChunk.getRealClass(), boolean.class, int.class, int.class); } } this.mapChunk = tempMapChunk; @@ -118,8 +120,9 @@ public class SendChunk { Object packet = null; if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) { try { - packet = this.mapChunk.create(c,65535); - } catch (Exception ignored) {} + packet = this.mapChunk.create(c, 65535); + } catch (Exception ignored) { + } } else { try { packet = this.mapChunk.create(c, true, 65535); @@ -139,16 +142,16 @@ public class SendChunk { } for (final Chunk chunk : chunks) { TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { try { chunk.unload(true, false); } catch (Throwable ignored) { String worldName = chunk.getWorld().getName(); - PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk.getZ()); + PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + + chunk.getZ()); PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); PS.debug("$3 - $4" + worldName + "/level.dat or " + worldName - + "/level_old.dat may be corrupt (try repairing or removing these)"); + + "/level_old.dat may be corrupt (try repairing or removing these)"); } } }); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java index 0e0b296da..0c398f55c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java @@ -4,34 +4,35 @@ import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue; -import java.lang.reflect.Field; -import java.lang.reflect.Method; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + public class BukkitLocalQueue extends BasicLocalBlockQueue { + private Field fieldNeighbors; + private Method chunkGetHandle; + public BukkitLocalQueue(String world) { super(world); } - @Override - public LocalChunk getLocalChunk(int x, int z) { + @Override public LocalChunk getLocalChunk(int x, int z) { return (LocalChunk) new BasicLocalChunk(this, x, z) { // Custom stuff? }; } - @Override - public void optimize() { + @Override public void optimize() { } - @Override - public PlotBlock getBlock(int x, int y, int z) { + @Override public PlotBlock getBlock(int x, int y, int z) { World worldObj = Bukkit.getWorld(getWorld()); Block block = worldObj.getBlockAt(x, y, z); if (block == null) { @@ -44,25 +45,21 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { return PlotBlock.get(id, block.getData()); } - @Override - public void refreshChunk(int x, int z) { + @Override public void refreshChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); worldObj.refreshChunk(x, z); } - @Override - public void fixChunkLighting(int x, int z) { + @Override public void fixChunkLighting(int x, int z) { // Do nothing } - @Override - public final void regenChunk(int x, int z) { + @Override public final void regenChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); worldObj.regenerateChunk(x, z); } - @Override - public final void setComponents(LocalChunk lc) { + @Override public final void setComponents(LocalChunk lc) { setBlocks(lc); setBiomes(lc); } @@ -129,13 +126,11 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { } } - private Field fieldNeighbors; - private Method chunkGetHandle; - /** * Exploiting a bug in the vanilla lighting algorithm for faster block placement - * - Could have been achieved without reflection by force unloading specific chunks - * - Much faster just setting the variable manually though + * - Could have been achieved without reflection by force unloading specific chunks + * - Much faster just setting the variable manually though + * * @param chunk * @return */ @@ -153,7 +148,8 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { Object value = fieldNeighbors.get(nmsChunk); fieldNeighbors.set(nmsChunk, 0); return new Object[] {nmsChunk, value}; - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } return null; } @@ -181,7 +177,8 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { if (disableResult != null) { try { fieldNeighbors.set(disableResult[0], 0x739C0); - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } } } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java index c1cb7eae9..57f9bcecc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java @@ -6,16 +6,11 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.ReflectionUtils; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.util.SendChunk; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; +import java.util.*; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; @@ -36,24 +31,26 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue { private final HashMap toUpdate = new HashMap<>(); - public BukkitLocalQueue_1_7(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { + public BukkitLocalQueue_1_7(String world) + throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { super(world); this.methodGetHandle = this.classCraftWorld.getMethod("getHandle"); this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class); - this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class); + this.methodA = this.classChunk + .getMethod("a", int.class, int.class, int.class, this.classBlock, int.class); this.methodGetById = this.classBlock.getMethod("getById", int.class); this.methodGetHandleChunk = this.classCraftChunk.getMethod("getHandle"); this.methodInitLighting = this.classChunk.getMethod("initLighting"); this.sendChunk = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { if (BukkitLocalQueue_1_7.this.toUpdate.isEmpty()) { return; } int count = 0; ArrayList chunks = new ArrayList<>(); - Iterator> i = BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator(); + Iterator> i = + BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator(); while (i.hasNext() && (count < 128)) { chunks.add(i.next().getValue()); i.remove(); @@ -88,14 +85,12 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue { } } - @Override - public void fixChunkLighting(int x, int z) { + @Override public void fixChunkLighting(int x, int z) { Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); this.methodInitLighting.of(c).call(); } - @Override - public void setBlocks(LocalChunk lc) { + @Override public void setBlocks(LocalChunk lc) { Chunk chunk = getChunk(lc.getX(), lc.getZ()); chunk.load(true); World world = chunk.getWorld(); @@ -128,8 +123,7 @@ public class BukkitLocalQueue_1_7 extends BukkitLocalQueue { fixChunkLighting(lc.getX(), lc.getZ()); } - @Override - public void refreshChunk(int x, int z) { + @Override public void refreshChunk(int x, int z) { update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java index 3212742ad..ebc93186d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java @@ -1,7 +1,5 @@ package com.plotsquared.bukkit.util.block; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - import com.intellectualcrafters.plot.object.ChunkWrapper; import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; @@ -10,17 +8,15 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.bukkit.util.SendChunk; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Block; +import java.util.*; + +import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; + public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { private final ReflectionUtils.RefMethod methodInitLighting; @@ -39,26 +35,29 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { private final SendChunk sendChunk; private final RefMethod methodGetHandleChunk; - public BukkitLocalQueue_1_8(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { + public BukkitLocalQueue_1_8(String world) + throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { super(world); this.methodInitLighting = this.classChunk.getMethod("initLighting"); - this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class); + this.constructorBlockPosition = + this.classBlockPosition.getConstructor(int.class, int.class, int.class); this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class); this.methodGetHandle = this.classCraftWorld.getMethod("getHandle"); RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class); - this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData); + this.methodA = + this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData); this.sendChunk = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { if (BukkitLocalQueue_1_8.this.toUpdate.isEmpty()) { return; } int count = 0; ArrayList chunks = new ArrayList<>(); - Iterator> i = BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator(); + Iterator> i = + BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator(); while (i.hasNext() && count < 128) { chunks.add(i.next().getValue()); i.remove(); @@ -73,14 +72,12 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { MainUtil.initCache(); } - @Override - public void fixChunkLighting(int x, int z) { + @Override public void fixChunkLighting(int x, int z) { Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); this.methodInitLighting.of(c).call(); } - @Override - public void setBlocks(LocalChunk lc) { + @Override public void setBlocks(LocalChunk lc) { Chunk chunk = getChunk(lc.getX(), lc.getZ()); chunk.load(true); World world = chunk.getWorld(); @@ -100,7 +97,8 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { int y = MainUtil.y_loc[i][j]; int z = MainUtil.z_loc[i][j]; PlotBlock newBlock = result2[j]; - if (newBlock == null) continue; + if (newBlock == null) + continue; if (newBlock.id == -1) { chunk.getBlock(x, y, z).setData(newBlock.data, false); @@ -309,7 +307,8 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { } catch (ReflectiveOperationException e) { e.printStackTrace(); } - Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); + Object combined = + this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); this.methodA.of(c).call(pos, combined); } } @@ -336,8 +335,7 @@ public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { } } - @Override - public void refreshChunk(int x, int z) { + @Override public void refreshChunk(int x, int z) { update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java index 90982a1cc..ddb18f549 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java @@ -9,20 +9,14 @@ import com.intellectualcrafters.plot.util.ReflectionUtils; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue; import com.plotsquared.bukkit.util.SendChunk; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; @@ -43,7 +37,8 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { private final ReflectionUtils.RefMethod methodGetWorld; private final ReflectionUtils.RefField tileEntityListTick; - public BukkitLocalQueue_1_8_3(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { + public BukkitLocalQueue_1_8_3(String world) + throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { super(world); ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); @@ -51,7 +46,8 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); this.methodInitLighting = classChunk.getMethod("initLighting"); ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); + this.classBlockPositionConstructor = + classBlockPosition.getConstructor(int.class, int.class, int.class); ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World"); this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass()); this.fieldSections = classChunk.getField("sections"); @@ -59,20 +55,21 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); this.methodGetIdArray = classChunkSection.getMethod("getIdArray"); this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); - this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); + this.classChunkSectionConstructor = + classChunkSection.getConstructor(int.class, boolean.class, char[].class); this.tileEntityListTick = classWorld.getField("tileEntityList"); this.methodGetHandleWorld = classCraftWorld.getMethod("getHandle"); this.methodGetWorld = classChunk.getMethod("getWorld"); this.sendChunk = new SendChunk(); TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { if (BukkitLocalQueue_1_8_3.this.toUpdate.isEmpty()) { return; } int count = 0; ArrayList chunks = new ArrayList<>(); - Iterator> i = BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator(); + Iterator> i = + BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator(); while (i.hasNext() && count < 128) { chunks.add(i.next().getValue()); i.remove(); @@ -87,11 +84,290 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { MainUtil.initCache(); } - @Override - public LocalChunk getLocalChunk(int x, int z) { + @Override public LocalChunk getLocalChunk(int x, int z) { return new CharLocalChunk_1_8_3(this, x, z); } + @Override public void setBlocks(LocalChunk lc) { + CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc; + Chunk chunk = getChunk(lc.getX(), lc.getZ()); + chunk.load(true); + World world = chunk.getWorld(); + ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ()); + if (!this.toUpdate.containsKey(wrapper)) { + this.toUpdate.put(wrapper, chunk); + } + try { + boolean flag = world.getEnvironment() == World.Environment.NORMAL; + + // Sections + Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); + Object c = getHandle.invoke(chunk); + Object w = this.methodGetWorld.of(c).call(); + Class clazz = c.getClass(); + Field sections1 = clazz.getDeclaredField("sections"); + sections1.setAccessible(true); + Field tileEntities = clazz.getDeclaredField("tileEntities"); + Field entitySlices = clazz.getDeclaredField("entitySlices"); + Object[] sections = (Object[]) sections1.get(c); + Map tiles = (Map) tileEntities.get(c); + Collection[] entities = (Collection[]) entitySlices.get(c); + + Method getX = null; + Method getY = null; + Method getZ = null; + + // Trim tiles + boolean removed = false; + Set> entrySet = (Set>) (Set) tiles.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Map.Entry tile = iterator.next(); + Object pos = tile.getKey(); + if (getX == null) { + Class clazz2 = pos.getClass().getSuperclass(); + getX = clazz2.getDeclaredMethod("getX"); + getY = clazz2.getDeclaredMethod("getY"); + getZ = clazz2.getDeclaredMethod("getZ"); + } + int lx = (int) getX.invoke(pos) & 15; + int ly = (int) getY.invoke(pos); + int lz = (int) getZ.invoke(pos) & 15; + int j = MainUtil.CACHE_I[ly][lx][lz]; + int k = MainUtil.CACHE_J[ly][lx][lz]; + char[] array = fs.getIdArray(j); + if (array == null) { + continue; + } + if (array[k] != 0) { + removed = true; + iterator.remove(); + } + } + if (removed) { + ((Collection) this.tileEntityListTick.of(w).get()).clear(); + } + + // Trim entities + for (int i = 0; i < 16; i++) { + if ((entities[i] != null) && (fs.getCount(i) >= 4096)) { + entities[i].clear(); + } + } + + // Efficiently merge sections + for (int j = 0; j < sections.length; j++) { + if (fs.getCount(j) == 0) { + continue; + } + char[] newArray = fs.getIdArray(j); + if (newArray == null) { + continue; + } + Object section = sections[j]; + if ((section == null) || (fs.getCount(j) >= 4096)) { + section = sections[j] = newChunkSection(j << 4, flag, newArray); + continue; + } + char[] currentArray = getIdArray(section); + boolean fill = true; + for (int k = 0; k < newArray.length; k++) { + char n = newArray[k]; + switch (n) { + case 0: + fill = false; + continue; + case 1: + fill = false; + currentArray[k] = 0; + continue; + default: + currentArray[k] = n; + continue; + } + } + if (fill) { + fs.setCount(j, Short.MAX_VALUE); + } + } + // Clear + } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) { + e.printStackTrace(); + } + fixLighting(chunk, fs, true); + } + + public Object newChunkSection(int i, boolean flag, char[] ids) + throws ReflectiveOperationException { + return this.classChunkSectionConstructor.create(i, flag, ids); + } + + public char[] getIdArray(Object obj) { + return (char[]) this.methodGetIdArray.of(obj).call(); + } + + @Override public void fixChunkLighting(int x, int z) { + Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); + this.methodInitLighting.of(c).call(); + } + + public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) { + try { + if (!chunk.isLoaded()) { + chunk.load(false); + } else { + chunk.unload(true, false); + chunk.load(false); + } + + // Initialize lighting + Object c = this.methodGetHandleChunk.of(chunk).call(); + + if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) { + World world = chunk.getWorld(); + ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()); + for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) { + for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) { + if (x != 0 && z != 0) { + Chunk other = world.getChunkAt(x, z); + while (!other.isLoaded()) { + other.load(true); + } + ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true); + } + } + } + /* + if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) { + return false; + } + */ + } + + this.methodInitLighting.of(c).call(); + + if (bc.getTotalRelight() == 0 && !fixAll) { + return true; + } + + Object[] sections = (Object[]) this.fieldSections.of(c).get(); + Object w = this.fieldWorld.of(c).get(); + + int X = chunk.getX() << 4; + int Z = chunk.getZ() << 4; + + ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w); + for (int j = 0; j < sections.length; j++) { + Object section = sections[j]; + if (section == null) { + continue; + } + if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || ( + bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) { + continue; + } + char[] array = getIdArray(section); + int l = PseudoRandom.random.random(2); + for (int k = 0; k < array.length; k++) { + int i = array[k]; + if (i < 16) { + continue; + } + short id = (short) (i >> 4); + switch (id) { // Lighting + default: + if (!fixAll) { + continue; + } + if ((k & 1) == l) { + l = 1 - l; + continue; + } + case 10: + case 11: + case 39: + case 40: + case 50: + case 51: + case 62: + case 74: + case 76: + case 89: + case 122: + case 124: + case 130: + case 138: + case 169: + int x = MainUtil.x_loc[j][k]; + int y = MainUtil.y_loc[j][k]; + int z = MainUtil.z_loc[j][k]; + if (isSurrounded(sections, x, y, z)) { + continue; + } + Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); + relight.call(pos); + } + } + } + return true; + } catch (Throwable e) { + e.printStackTrace(); + } + return false; + } + + public boolean isSurrounded(Object[] sections, int x, int y, int z) { + return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z)) + && isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1)) + && isSolid(getId(sections, x, y, z - 1)); + } + + public boolean isSolid(int i) { + return i != 0 && Material.getMaterial(i).isOccluding(); + } + + public int getId(Object[] sections, int x, int y, int z) { + if (x < 0 || x > 15 || z < 0 || z > 15) { + return 1; + } + if (y < 0 || y > 255) { + return 1; + } + int i = MainUtil.CACHE_I[y][x][z]; + Object section = sections[i]; + if (section == null) { + return 0; + } + char[] array = getIdArray(section); + int j = MainUtil.CACHE_J[y][x][z]; + return array[j] >> 4; + } + + public void update(Collection chunks) { + if (chunks.isEmpty()) { + return; + } + if (!MainUtil.canSendChunk) { + for (Chunk chunk : chunks) { + chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); + chunk.unload(true, false); + chunk.load(); + } + return; + } + try { + this.sendChunk.sendChunk(chunks); + } catch (Throwable e) { + e.printStackTrace(); + MainUtil.canSendChunk = false; + } + } + + @Override public void refreshChunk(int x, int z) { + update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); + } + + public class CharLocalChunk_1_8_3 extends CharLocalChunk { public short[] count; public short[] air; @@ -104,8 +380,7 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { this.relight = new short[16]; } - @Override - public void setBlock(int x, int y, int z, int id, int data) { + @Override public void setBlock(int x, int y, int z, int id, int data) { int i = MainUtil.CACHE_I[y][x][z]; int j = MainUtil.CACHE_J[y][x][z]; char[] vs = this.blocks[i]; @@ -252,286 +527,4 @@ public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { return total; } } - - @Override - public void setBlocks(LocalChunk lc) { - CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc; - Chunk chunk = getChunk(lc.getX(), lc.getZ()); - chunk.load(true); - World world = chunk.getWorld(); - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ()); - if (!this.toUpdate.containsKey(wrapper)) { - this.toUpdate.put(wrapper, chunk); - } - try { - boolean flag = world.getEnvironment() == World.Environment.NORMAL; - - // Sections - Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); - Object c = getHandle.invoke(chunk); - Object w = this.methodGetWorld.of(c).call(); - Class clazz = c.getClass(); - Field sections1 = clazz.getDeclaredField("sections"); - sections1.setAccessible(true); - Field tileEntities = clazz.getDeclaredField("tileEntities"); - Field entitySlices = clazz.getDeclaredField("entitySlices"); - Object[] sections = (Object[]) sections1.get(c); - Map tiles = (Map) tileEntities.get(c); - Collection[] entities = (Collection[]) entitySlices.get(c); - - Method getX = null; - Method getY = null; - Method getZ = null; - - // Trim tiles - boolean removed = false; - Set> entrySet = (Set>) (Set) tiles.entrySet(); - Iterator> iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Map.Entry tile = iterator.next(); - Object pos = tile.getKey(); - if (getX == null) { - Class clazz2 = pos.getClass().getSuperclass(); - getX = clazz2.getDeclaredMethod("getX"); - getY = clazz2.getDeclaredMethod("getY"); - getZ = clazz2.getDeclaredMethod("getZ"); - } - int lx = (int) getX.invoke(pos) & 15; - int ly = (int) getY.invoke(pos); - int lz = (int) getZ.invoke(pos) & 15; - int j = MainUtil.CACHE_I[ly][lx][lz]; - int k = MainUtil.CACHE_J[ly][lx][lz]; - char[] array = fs.getIdArray(j); - if (array == null) { - continue; - } - if (array[k] != 0) { - removed = true; - iterator.remove(); - } - } - if (removed) { - ((Collection) this.tileEntityListTick.of(w).get()).clear(); - } - - // Trim entities - for (int i = 0; i < 16; i++) { - if ((entities[i] != null) && (fs.getCount(i) >= 4096)) { - entities[i].clear(); - } - } - - // Efficiently merge sections - for (int j = 0; j < sections.length; j++) { - if (fs.getCount(j) == 0) { - continue; - } - char[] newArray = fs.getIdArray(j); - if (newArray == null) { - continue; - } - Object section = sections[j]; - if ((section == null) || (fs.getCount(j) >= 4096)) { - section = sections[j] = newChunkSection(j << 4, flag, newArray); - continue; - } - char[] currentArray = getIdArray(section); - boolean fill = true; - for (int k = 0; k < newArray.length; k++) { - char n = newArray[k]; - switch (n) { - case 0: - fill = false; - continue; - case 1: - fill = false; - currentArray[k] = 0; - continue; - default: - currentArray[k] = n; - continue; - } - } - if (fill) { - fs.setCount(j, Short.MAX_VALUE); - } - } - // Clear - } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) { - e.printStackTrace(); - } - fixLighting(chunk, fs, true); - } - - public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException { - return this.classChunkSectionConstructor.create(i, flag, ids); - } - - public char[] getIdArray(Object obj) { - return (char[]) this.methodGetIdArray.of(obj).call(); - } - - @Override - public void fixChunkLighting(int x, int z) { - Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); - this.methodInitLighting.of(c).call(); - } - - public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) { - try { - if (!chunk.isLoaded()) { - chunk.load(false); - } else { - chunk.unload(true, false); - chunk.load(false); - } - - // Initialize lighting - Object c = this.methodGetHandleChunk.of(chunk).call(); - - if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) { - World world = chunk.getWorld(); - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()); - for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) { - for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) { - if (x != 0 && z != 0) { - Chunk other = world.getChunkAt(x, z); - while (!other.isLoaded()) { - other.load(true); - } - ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true); - } - } - } - /* - if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) { - return false; - } - */ - } - - this.methodInitLighting.of(c).call(); - - if (bc.getTotalRelight() == 0 && !fixAll) { - return true; - } - - Object[] sections = (Object[]) this.fieldSections.of(c).get(); - Object w = this.fieldWorld.of(c).get(); - - int X = chunk.getX() << 4; - int Z = chunk.getZ() << 4; - - ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w); - for (int j = 0; j < sections.length; j++) { - Object section = sections[j]; - if (section == null) { - continue; - } - if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) { - continue; - } - char[] array = getIdArray(section); - int l = PseudoRandom.random.random(2); - for (int k = 0; k < array.length; k++) { - int i = array[k]; - if (i < 16) { - continue; - } - short id = (short) (i >> 4); - switch (id) { // Lighting - default: - if (!fixAll) { - continue; - } - if ((k & 1) == l) { - l = 1 - l; - continue; - } - case 10: - case 11: - case 39: - case 40: - case 50: - case 51: - case 62: - case 74: - case 76: - case 89: - case 122: - case 124: - case 130: - case 138: - case 169: - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - if (isSurrounded(sections, x, y, z)) { - continue; - } - Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); - relight.call(pos); - } - } - } - return true; - } catch (Throwable e) { - e.printStackTrace(); - } - return false; - } - - public boolean isSurrounded(Object[] sections, int x, int y, int z) { - return isSolid(getId(sections, x, y + 1, z)) - && isSolid(getId(sections, x + 1, y - 1, z)) - && isSolid(getId(sections, x - 1, y, z)) - && isSolid(getId(sections, x, y, z + 1)) - && isSolid(getId(sections, x, y, z - 1)); - } - - public boolean isSolid(int i) { - return i != 0 && Material.getMaterial(i).isOccluding(); - } - - public int getId(Object[] sections, int x, int y, int z) { - if (x < 0 || x > 15 || z < 0 || z > 15) { - return 1; - } - if (y < 0 || y > 255) { - return 1; - } - int i = MainUtil.CACHE_I[y][x][z]; - Object section = sections[i]; - if (section == null) { - return 0; - } - char[] array = getIdArray(section); - int j = MainUtil.CACHE_J[y][x][z]; - return array[j] >> 4; - } - - public void update(Collection chunks) { - if (chunks.isEmpty()) { - return; - } - if (!MainUtil.canSendChunk) { - for (Chunk chunk : chunks) { - chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); - chunk.unload(true, false); - chunk.load(); - } - return; - } - try { - this.sendChunk.sendChunk(chunks); - } catch (Throwable e) { - e.printStackTrace(); - MainUtil.canSendChunk = false; - } - } - - @Override - public void refreshChunk(int x, int z) { - update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); - } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java index 351a69243..5897efb81 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java @@ -5,17 +5,13 @@ import com.intellectualcrafters.plot.object.PseudoRandom; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.ReflectionUtils; import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; @@ -40,14 +36,16 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue { private final ReflectionUtils.RefField tileEntityListTick; - public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { + public BukkitLocalQueue_1_9(String world) + throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { super(world); ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); this.methodInitLighting = classChunk.getMethod("initLighting"); ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); + this.classBlockPositionConstructor = + classBlockPosition.getConstructor(int.class, int.class, int.class); ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World"); this.tileEntityListTick = classWorld.getField("tileEntityListTick"); this.methodGetWorld = classChunk.getMethod("getWorld"); @@ -56,23 +54,284 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue { this.fieldWorld = classChunk.getField("world"); ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block"); ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData"); - this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass()); + this.methodGetCombinedId = + classBlock.getMethod("getCombinedId", classIBlockData.getRealClass()); this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); this.methodGetBlocks = classChunkSection.getMethod("getBlocks"); - this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class); - this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass()); + this.methodGetType = + classChunkSection.getMethod("getType", int.class, int.class, int.class); + this.methodSetType = classChunkSection + .getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass()); this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); - this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); + this.classChunkSectionConstructor = + classChunkSection.getConstructor(int.class, boolean.class, char[].class); this.air = this.methodGetByCombinedId.call(0); MainUtil.initCache(); } - @Override - public LocalChunk getLocalChunk(int x, int z) { + @Override public LocalChunk getLocalChunk(int x, int z) { return new CharLocalChunk_1_8_3(this, x, z); } + @Override public void setBlocks(LocalChunk lc) { + CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc; + Chunk chunk = getChunk(lc.getX(), lc.getZ()); + chunk.load(true); + World world = chunk.getWorld(); + try { + boolean flag = world.getEnvironment() == World.Environment.NORMAL; + + // Sections + Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); + Object c = getHandle.invoke(chunk); + Object w = this.methodGetWorld.of(c).call(); + Class clazz = c.getClass(); + Field sf = clazz.getDeclaredField("sections"); + sf.setAccessible(true); + Field tf = clazz.getDeclaredField("tileEntities"); + Field entitySlices = clazz.getDeclaredField("entitySlices"); + Object[] sections = (Object[]) sf.get(c); + Map tiles = (Map) tf.get(c); + Collection[] entities = (Collection[]) entitySlices.get(c); + + Method xm = null; + Method ym = null; + Method zm = null; + // Trim tiles + Collection tickList = ((Collection) this.tileEntityListTick.of(w).get()); + Set> entrySet = (Set>) (Set) tiles.entrySet(); + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Map.Entry tile = iterator.next(); + Object pos = tile.getKey(); + if (xm == null) { + Class clazz2 = pos.getClass().getSuperclass(); + xm = clazz2.getDeclaredMethod("getX"); + ym = clazz2.getDeclaredMethod("getY"); + zm = clazz2.getDeclaredMethod("getZ"); + } + int lx = (int) xm.invoke(pos) & 15; + int ly = (int) ym.invoke(pos); + int lz = (int) zm.invoke(pos) & 15; + int j = MainUtil.CACHE_I[ly][lx][lz]; + int k = MainUtil.CACHE_J[ly][lx][lz]; + char[] array = fs.getIdArray(j); + if (array == null) { + continue; + } + if (array[k] != 0) { + tickList.remove(tile.getValue()); + iterator.remove(); + } + } + + // Trim entities + for (int i = 0; i < 16; i++) { + if (entities[i] != null && fs.getCount(i) >= 4096) { + entities[i].clear(); + } + } + + // Efficiently merge sections + for (int j = 0; j < sections.length; j++) { + if (fs.getCount(j) == 0) { + continue; + } + char[] newArray = fs.getIdArray(j); + if (newArray == null) { + continue; + } + Object section = sections[j]; + if (section == null || fs.getCount(j) >= 4096) { + section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j)); + continue; + } + Object currentArray = getBlocks(section); + ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section); + boolean fill = true; + for (int k = 0; k < newArray.length; k++) { + char n = newArray[k]; + switch (n) { + case 0: + fill = false; + continue; + case 1: { + fill = false; + int x = MainUtil.x_loc[j][k]; + int y = MainUtil.y_loc[j][k]; + int z = MainUtil.z_loc[j][k]; + setType.call(x, y & 15, z, this.air); + continue; + } + default: + int x = MainUtil.x_loc[j][k]; + int y = MainUtil.y_loc[j][k]; + int z = MainUtil.z_loc[j][k]; + int id = n >> 4; + int data = n & 15; + Object iBlock = + this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12)); + setType.call(x, y & 15, z, iBlock); + } + } + if (fill) { + fs.setCount(j, Short.MAX_VALUE); + } + } + // Clear + } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) { + e.printStackTrace(); + } + fixLighting(chunk, fs, true); + refreshChunk(fs.getX(), fs.getZ()); + } + + public Object newChunkSection(int i, boolean flag, char[] ids) + throws ReflectiveOperationException { + return this.classChunkSectionConstructor.create(i, flag, ids); + } + + public Object getBlocks(Object obj) { + return this.methodGetBlocks.of(obj).call(); + } + + @Override public void fixChunkLighting(int x, int z) { + Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); + this.methodInitLighting.of(c).call(); + } + + public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) { + try { + if (!chunk.isLoaded()) { + chunk.load(false); + } else { + chunk.unload(true, false); + chunk.load(false); + } + + // Initialize lighting + Object c = this.methodGetHandleChunk.of(chunk).call(); + + ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ()); + Object[] result = disableLighting(chunk); + enableLighting(result); + + this.methodInitLighting.of(c).call(); + + if (bc.getTotalRelight() != 0 || fixAll) { + Object[] sections = (Object[]) this.fieldSections.of(c).get(); + Object w = this.fieldWorld.of(c).get(); + + int X = chunk.getX() << 4; + int Z = chunk.getZ() << 4; + ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w); + for (int j = 0; j < sections.length; j++) { + Object section = sections[j]; + if (section == null) { + continue; + } + if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 + || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) { + continue; + } + char[] array = bc.getIdArray(j); + if (array != null) { + int l = PseudoRandom.random.random(2); + for (int k = 0; k < array.length; k++) { + int i = array[k]; + if (i < 16) { + continue; + } + short id = (short) (i >> 4); + switch (id) { // Lighting + default: + if (!fixAll) { + continue; + } + if ((k & 1) == l) { + l = 1 - l; + continue; + } + case 10: + case 11: + case 39: + case 40: + case 50: + case 51: + case 62: + case 74: + case 76: + case 89: + case 122: + case 124: + case 130: + case 138: + case 169: + int x = MainUtil.x_loc[j][k]; + int y = MainUtil.y_loc[j][k]; + int z = MainUtil.z_loc[j][k]; + if (isSurrounded(bc.blocks, x, y, z)) { + continue; + } + Object pos = + this.classBlockPositionConstructor.create(X + x, y, Z + z); + relight.call(pos); + } + } + } + } + } + resetLighting(result); + return true; + } catch (Throwable e) { + e.printStackTrace(); + } + return false; + } + + @Override public void refreshChunk(int x, int z) { + getBukkitWorld().refreshChunk(x, z); + } + + public boolean isSurrounded(char[][] sections, int x, int y, int z) { + return isSolid(getId(sections, x, y + 1, z)) && isSolid(getId(sections, x + 1, y - 1, z)) + && isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x, y, z + 1)) + && isSolid(getId(sections, x, y, z - 1)); + } + + public boolean isSolid(int i) { + if (i != 0) { + Material material = Material.getMaterial(i); + return material != null && Material.getMaterial(i).isOccluding(); + } + return false; + } + + public int getId(char[] section, int x, int y, int z) { + if (section == null) { + return 0; + } + int j = MainUtil.CACHE_J[y][x][z]; + return section[j] >> 4; + } + + public int getId(char[][] sections, int x, int y, int z) { + if (x < 0 || x > 15 || z < 0 || z > 15) { + return 1; + } + if (y < 0 || y > 255) { + return 1; + } + int i = MainUtil.CACHE_I[y][x][z]; + char[] section = sections[i]; + if (section == null) { + return 0; + } + return getId(section, x, y, z); + } + + public class CharLocalChunk_1_8_3 extends CharLocalChunk { public short[] count; public short[] air; @@ -85,8 +344,7 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue { this.relight = new short[16]; } - @Override - public void setBlock(int x, int y, int z, int id, int data) { + @Override public void setBlock(int x, int y, int z, int id, int data) { int i = MainUtil.CACHE_I[y][x][z]; int j = MainUtil.CACHE_J[y][x][z]; char[] vs = this.blocks[i]; @@ -233,262 +491,4 @@ public class BukkitLocalQueue_1_9 extends BukkitLocalQueue { return total; } } - - @Override - public void setBlocks(LocalChunk lc) { - CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc; - Chunk chunk = getChunk(lc.getX(), lc.getZ()); - chunk.load(true); - World world = chunk.getWorld(); - try { - boolean flag = world.getEnvironment() == World.Environment.NORMAL; - - // Sections - Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); - Object c = getHandle.invoke(chunk); - Object w = this.methodGetWorld.of(c).call(); - Class clazz = c.getClass(); - Field sf = clazz.getDeclaredField("sections"); - sf.setAccessible(true); - Field tf = clazz.getDeclaredField("tileEntities"); - Field entitySlices = clazz.getDeclaredField("entitySlices"); - Object[] sections = (Object[]) sf.get(c); - Map tiles = (Map) tf.get(c); - Collection[] entities = (Collection[]) entitySlices.get(c); - - Method xm = null; - Method ym = null; - Method zm = null; - // Trim tiles - Collection tickList = ((Collection) this.tileEntityListTick.of(w).get()); - Set> entrySet = (Set>) (Set) tiles.entrySet(); - Iterator> iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Map.Entry tile = iterator.next(); - Object pos = tile.getKey(); - if (xm == null) { - Class clazz2 = pos.getClass().getSuperclass(); - xm = clazz2.getDeclaredMethod("getX"); - ym = clazz2.getDeclaredMethod("getY"); - zm = clazz2.getDeclaredMethod("getZ"); - } - int lx = (int) xm.invoke(pos) & 15; - int ly = (int) ym.invoke(pos); - int lz = (int) zm.invoke(pos) & 15; - int j = MainUtil.CACHE_I[ly][lx][lz]; - int k = MainUtil.CACHE_J[ly][lx][lz]; - char[] array = fs.getIdArray(j); - if (array == null) { - continue; - } - if (array[k] != 0) { - tickList.remove(tile.getValue()); - iterator.remove(); - } - } - - // Trim entities - for (int i = 0; i < 16; i++) { - if (entities[i] != null && fs.getCount(i) >= 4096) { - entities[i].clear(); - } - } - - // Efficiently merge sections - for (int j = 0; j < sections.length; j++) { - if (fs.getCount(j) == 0) { - continue; - } - char[] newArray = fs.getIdArray(j); - if (newArray == null) { - continue; - } - Object section = sections[j]; - if (section == null || fs.getCount(j) >= 4096) { - section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j)); - continue; - } - Object currentArray = getBlocks(section); - ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section); - boolean fill = true; - for (int k = 0; k < newArray.length; k++) { - char n = newArray[k]; - switch (n) { - case 0: - fill = false; - continue; - case 1: { - fill = false; - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - setType.call(x, y & 15, z, this.air); - continue; - } - default: - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - int id = n >> 4; - int data = n & 15; - Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12)); - setType.call(x, y & 15, z, iBlock); - } - } - if (fill) { - fs.setCount(j, Short.MAX_VALUE); - } - } - // Clear - } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) { - e.printStackTrace(); - } - fixLighting(chunk, fs, true); - refreshChunk(fs.getX(), fs.getZ()); - } - - public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException { - return this.classChunkSectionConstructor.create(i, flag, ids); - } - - public Object getBlocks(Object obj) { - return this.methodGetBlocks.of(obj).call(); - } - - @Override - public void fixChunkLighting(int x, int z) { - Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); - this.methodInitLighting.of(c).call(); - } - - public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) { - try { - if (!chunk.isLoaded()) { - chunk.load(false); - } else { - chunk.unload(true, false); - chunk.load(false); - } - - // Initialize lighting - Object c = this.methodGetHandleChunk.of(chunk).call(); - - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ()); - Object[] result = disableLighting(chunk); - enableLighting(result); - - this.methodInitLighting.of(c).call(); - - if (bc.getTotalRelight() != 0 || fixAll) { - Object[] sections = (Object[]) this.fieldSections.of(c).get(); - Object w = this.fieldWorld.of(c).get(); - - int X = chunk.getX() << 4; - int Z = chunk.getZ() << 4; - ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w); - for (int j = 0; j < sections.length; j++) { - Object section = sections[j]; - if (section == null) { - continue; - } - if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) { - continue; - } - char[] array = bc.getIdArray(j); - if (array != null) { - int l = PseudoRandom.random.random(2); - for (int k = 0; k < array.length; k++) { - int i = array[k]; - if (i < 16) { - continue; - } - short id = (short) (i >> 4); - switch (id) { // Lighting - default: - if (!fixAll) { - continue; - } - if ((k & 1) == l) { - l = 1 - l; - continue; - } - case 10: - case 11: - case 39: - case 40: - case 50: - case 51: - case 62: - case 74: - case 76: - case 89: - case 122: - case 124: - case 130: - case 138: - case 169: - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - if (isSurrounded(bc.blocks, x, y, z)) { - continue; - } - Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); - relight.call(pos); - } - } - } - } - } - resetLighting(result); - return true; - } catch (Throwable e) { - e.printStackTrace(); - } - return false; - } - - @Override - public void refreshChunk(int x, int z) { - getBukkitWorld().refreshChunk(x, z); - } - - public boolean isSurrounded(char[][] sections, int x, int y, int z) { - return isSolid(getId(sections, x, y + 1, z)) - && isSolid(getId(sections, x + 1, y - 1, z)) - && isSolid(getId(sections, x - 1, y, z)) - && isSolid(getId(sections, x, y, z + 1)) - && isSolid(getId(sections, x, y, z - 1)); - } - - public boolean isSolid(int i) { - if (i != 0) { - Material material = Material.getMaterial(i); - return material != null && Material.getMaterial(i).isOccluding(); - } - return false; - } - - public int getId(char[] section, int x, int y, int z) { - if (section == null) { - return 0; - } - int j = MainUtil.CACHE_J[y][x][z]; - return section[j] >> 4; - } - - public int getId(char[][] sections, int x, int y, int z) { - if (x < 0 || x > 15 || z < 0 || z > 15) { - return 1; - } - if (y < 0 || y > 255) { - return 1; - } - int i = MainUtil.CACHE_I[y][x][z]; - char[] section = sections[i]; - if (section == null) { - return 0; - } - return getId(section, x, y, z); - } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java index 13d4394ce..9bc3a713d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java @@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue; import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.Arrays; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; @@ -15,6 +14,8 @@ import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; import org.bukkit.material.MaterialData; +import java.util.Arrays; + public class GenChunk extends ScopedLocalBlockQueue { public final Biome[] biomes; @@ -37,13 +38,6 @@ public class GenChunk extends ScopedLocalBlockQueue { this.chunk = chunk; } - public void setChunk(ChunkWrapper wrap) { - chunk = null; - world = wrap.world; - cx = wrap.x; - cz = wrap.z; - } - public Chunk getChunk() { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); @@ -54,6 +48,13 @@ public class GenChunk extends ScopedLocalBlockQueue { return chunk; } + public void setChunk(ChunkWrapper wrap) { + chunk = null; + world = wrap.world; + cx = wrap.x; + cz = wrap.z; + } + public ChunkWrapper getChunkWrapper() { if (chunk == null) { return new ChunkWrapper(world, cx, cz); @@ -61,8 +62,7 @@ public class GenChunk extends ScopedLocalBlockQueue { return new ChunkWrapper(chunk.getWorld().getName(), chunk.getX(), chunk.getZ()); } - @Override - public void fillBiome(String biomeName) { + @Override public void fillBiome(String biomeName) { if (grid == null) { return; } @@ -74,9 +74,9 @@ public class GenChunk extends ScopedLocalBlockQueue { } } - @Override - public void setCuboid(Location pos1, Location pos2, PlotBlock block) { - if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) { + @Override public void setCuboid(Location pos1, Location pos2, PlotBlock block) { + if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0 + && pos2.getX() == 15 && pos2.getZ() == 15) { for (int y = pos1.getY(); y <= pos2.getY(); y++) { int layer = y >> 4; short[] data = result[layer]; @@ -92,8 +92,7 @@ public class GenChunk extends ScopedLocalBlockQueue { } } - @Override - public boolean setBiome(int x, int z, String biome) { + @Override public boolean setBiome(int x, int z, String biome) { return setBiome(x, z, Biome.valueOf(biome.toUpperCase())); } @@ -113,8 +112,7 @@ public class GenChunk extends ScopedLocalBlockQueue { return false; } - @Override - public boolean setBlock(int x, int y, int z, int id, int data) { + @Override public boolean setBlock(int x, int y, int z, int id, int data) { if (this.result == null) { this.cd.setBlock(x, y, z, new MaterialData(Material.getMaterial(id), (byte) data)); return true; @@ -136,8 +134,7 @@ public class GenChunk extends ScopedLocalBlockQueue { return true; } - @Override - public PlotBlock getBlock(int x, int y, int z) { + @Override public PlotBlock getBlock(int x, int y, int z) { int i = MainUtil.CACHE_I[y][x][z]; if (result == null) { MaterialData md = cd.getTypeAndData(x, y, z); @@ -167,23 +164,21 @@ public class GenChunk extends ScopedLocalBlockQueue { return chunk == null ? cz : chunk.getZ(); } - @Override - public String getWorld() { + @Override public String getWorld() { return chunk == null ? world : chunk.getWorld().getName(); } - @Override - public Location getMax() { + @Override public Location getMax() { return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4)); } - @Override - public Location getMin() { + @Override public Location getMin() { return new Location(getWorld(), getX() << 4, 0, getZ() << 4); } public GenChunk clone() { - GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ())); + GenChunk toReturn = + new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ())); if (this.result != null) { for (int i = 0; i < this.result.length; i++) { short[] matrix = this.result[i]; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DatFileFilter.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DatFileFilter.java index 2cd509051..8fc0398dd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DatFileFilter.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DatFileFilter.java @@ -5,8 +5,7 @@ import java.io.FilenameFilter; public class DatFileFilter implements FilenameFilter { - @Override - public boolean accept(File dir, String name) { + @Override public boolean accept(File dir, String name) { return name.endsWith(".dat"); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java index e066b29f8..ba24a34e5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java @@ -12,28 +12,23 @@ import java.util.UUID; public class DefaultUUIDWrapper extends UUIDWrapper { - @Override - public UUID getUUID(PlotPlayer player) { + @Override public UUID getUUID(PlotPlayer player) { return ((BukkitPlayer) player).player.getUniqueId(); } - @Override - public UUID getUUID(OfflinePlotPlayer player) { + @Override public UUID getUUID(OfflinePlotPlayer player) { return player.getUUID(); } - @Override - public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { + @Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); } - @Override - public UUID getUUID(String name) { + @Override public UUID getUUID(String name) { return Bukkit.getOfflinePlayer(name).getUniqueId(); } - @Override - public OfflinePlotPlayer[] getOfflinePlayers() { + @Override public OfflinePlotPlayer[] getOfflinePlayers() { OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; for (int i = 0; i < ops.length; i++) { @@ -42,8 +37,7 @@ public class DefaultUUIDWrapper extends UUIDWrapper { return toReturn; } - @Override - public OfflinePlotPlayer getOfflinePlayer(String name) { + @Override public OfflinePlotPlayer getOfflinePlayer(String name) { return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java index 15cf9b6ad..b36aafeb9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -15,6 +15,9 @@ import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; import com.intellectualcrafters.plot.util.expiry.ExpireManager; import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.plotsquared.bukkit.util.NbtFactory; +import org.bukkit.Bukkit; +import org.bukkit.World; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -24,9 +27,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; public class FileUUIDHandler extends UUIDHandlerImplementation { @@ -34,8 +34,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { super(wrapper); } - @Override - public boolean startCaching(Runnable whenDone) { + @Override public boolean startCaching(Runnable whenDone) { return super.startCaching(whenDone) && cache(whenDone); } @@ -49,13 +48,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { world = worlds.get(0).getName(); } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { PS.debug(C.PREFIX + "&6Starting player data caching for: " + world); File uuidFile = new File(PS.get().IMP.getDirectory(), "uuids.txt"); if (uuidFile.exists()) { try { - List lines = Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8); + List lines = + Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8); for (String line : lines) { try { line = line.trim(); @@ -65,7 +64,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); String[] split = line.split("\\|"); String name = split[0]; - if (name.isEmpty() || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) { + if (name.isEmpty() || (name.length() > 16) || !StringMan + .isAlphanumericUnd(name)) { continue; } UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); @@ -81,11 +81,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { e.printStackTrace(); } } - HashBiMap toAdd = HashBiMap.create(new HashMap()); + HashBiMap toAdd = + HashBiMap.create(new HashMap()); if (Settings.UUID.NATIVE_UUID_PROVIDER) { HashSet all = UUIDHandler.getAllUUIDS(); PS.debug("&aFast mode UUID caching enabled!"); - File playerDataFolder = new File(container, world + File.separator + "playerdata"); + File playerDataFolder = + new File(container, world + File.separator + "playerdata"); String[] dat = playerDataFolder.list(new DatFileFilter()); boolean check = all.isEmpty(); if (dat != null) { @@ -95,11 +97,15 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { UUID uuid = UUID.fromString(s); if (check || all.remove(uuid)) { File file = new File(playerDataFolder, current); - NbtFactory.NbtCompound compound = NbtFactory.fromStream(new FileInputStream(file), NbtFactory.StreamOptions.GZIP_COMPRESSION); + NbtFactory.NbtCompound compound = NbtFactory + .fromStream(new FileInputStream(file), + NbtFactory.StreamOptions.GZIP_COMPRESSION); if (!compound.containsKey("bukkit")) { - PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\""); + PS.debug("ERROR: Player data (" + uuid.toString() + + ".dat) does not contain the the key \"bukkit\""); } else { - NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); + NbtFactory.NbtCompound bukkit = + (NbtFactory.NbtCompound) compound.get("bukkit"); String name = (String) bukkit.get("lastKnownName"); long last = (long) bukkit.get("lastPlayed"); long first = (long) bukkit.get("firstPlayed"); @@ -123,7 +129,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } return; } else { - PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files"); + PS.debug("Failed to cache: " + all.size() + + " uuids - slowly processing all files"); } } HashSet worlds = Sets.newHashSet(world, "world"); @@ -132,7 +139,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { File playerDataFolder = null; for (String worldName : worlds) { // Getting UUIDs - playerDataFolder = new File(container, worldName + File.separator + "playerdata"); + playerDataFolder = + new File(container, worldName + File.separator + "playerdata"); String[] dat = playerDataFolder.list(new DatFileFilter()); if ((dat != null) && (dat.length != 0)) { for (String current : dat) { @@ -158,22 +166,28 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } for (UUID uuid : uuids) { try { - File file = new File(playerDataFolder + File.separator + uuid.toString() + ".dat"); + File file = + new File(playerDataFolder + File.separator + uuid.toString() + ".dat"); if (!file.exists()) { continue; } - NbtFactory.NbtCompound compound = NbtFactory.fromStream(new FileInputStream(file), NbtFactory.StreamOptions.GZIP_COMPRESSION); + NbtFactory.NbtCompound compound = NbtFactory + .fromStream(new FileInputStream(file), + NbtFactory.StreamOptions.GZIP_COMPRESSION); if (!compound.containsKey("bukkit")) { - PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\""); + PS.debug("ERROR: Player data (" + uuid.toString() + + ".dat) does not contain the the key \"bukkit\""); } else { - NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); + NbtFactory.NbtCompound bukkit = + (NbtFactory.NbtCompound) compound.get("bukkit"); String name = (String) bukkit.get("lastKnownName"); StringWrapper wrap = new StringWrapper(name); if (!toAdd.containsKey(wrap)) { long last = (long) bukkit.get("lastPlayed"); long first = (long) bukkit.get("firstPlayed"); if (Settings.UUID.OFFLINE) { - if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase().equals(name)) { + if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase() + .equals(name)) { uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); } else { long most = (long) compound.get("UUIDMost"); @@ -199,7 +213,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } if (getUUIDMap().isEmpty()) { - for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { + for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper + .getOfflinePlayers()) { long last = op.getLastPlayed(); if (last != 0) { String name = op.getName(); @@ -223,11 +238,9 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { return true; } - @Override - public void fetchUUID(final String name, final RunnableVal ifFetch) { + @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); TaskManager.runTask(ifFetch); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java index e2afa50e9..90d871165 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java @@ -9,24 +9,24 @@ import java.util.UUID; public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { - @Override - public UUID getUUID(PlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(PlotPlayer player) { + return UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } - @Override - public UUID getUUID(OfflinePlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(OfflinePlotPlayer player) { + return UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } - @Override - public UUID getUUID(OfflinePlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(OfflinePlayer player) { + return UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } - @Override - public UUID getUUID(String name) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(String name) { + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java index 273ff8fc1..63899deb7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java @@ -32,22 +32,22 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } } - @Override - public UUID getUUID(PlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(PlotPlayer player) { + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } - @Override - public UUID getUUID(OfflinePlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(OfflinePlotPlayer player) { + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } public UUID getUUID(OfflinePlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } - @Override - public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { + @Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { BiMap map = UUIDHandler.getUuidMap().inverse(); String name = null; if (map.containsKey(uuid)) { @@ -77,7 +77,8 @@ public class OfflineUUIDWrapper extends UUIDWrapper { if (players instanceof Player[]) { return (Player[]) players; } else { - @SuppressWarnings("unchecked") Collection p = (Collection) players; + @SuppressWarnings("unchecked") Collection p = + (Collection) players; return p.toArray(new Player[p.size()]); } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { @@ -88,13 +89,11 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } } - @Override - public UUID getUUID(String name) { + @Override public UUID getUUID(String name) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); } - @Override - public OfflinePlotPlayer[] getOfflinePlayers() { + @Override public OfflinePlotPlayer[] getOfflinePlayers() { OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; for (int i = 0; i < ops.length; i++) { @@ -103,8 +102,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper { return toReturn; } - @Override - public OfflinePlotPlayer getOfflinePlayer(String name) { + @Override public OfflinePlotPlayer getOfflinePlayer(String name) { return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java index d5d61d030..3e46a8746 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -12,6 +12,11 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; import com.intellectualcrafters.plot.uuid.UUIDWrapper; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -26,15 +31,12 @@ import java.util.ArrayDeque; import java.util.Collections; import java.util.HashMap; import java.util.UUID; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; public class SQLUUIDHandler extends UUIDHandlerImplementation { final int MAX_REQUESTS = 500; - private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; + private final String PROFILE_URL = + "https://sessionserver.mojang.com/session/minecraft/profile/"; private final int INTERVAL = 12000; private final JSONParser jsonParser = new JSONParser(); private final SQLite sqlite; @@ -49,8 +51,8 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } try (PreparedStatement stmt = getConnection().prepareStatement( - "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)" - + ')')) { + "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)" + + ')')) { stmt.execute(); } catch (SQLException e) { e.printStackTrace(); @@ -64,20 +66,21 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } } - @Override - public boolean startCaching(final Runnable whenDone) { + @Override public boolean startCaching(final Runnable whenDone) { if (!super.startCaching(whenDone)) { return false; } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { - HashBiMap toAdd = HashBiMap.create(new HashMap()); - try (PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); - ResultSet resultSet = statement.executeQuery()) { + HashBiMap toAdd = + HashBiMap.create(new HashMap()); + try (PreparedStatement statement = getConnection() + .prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); + ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { - StringWrapper username = new StringWrapper(resultSet.getString("username")); + StringWrapper username = + new StringWrapper(resultSet.getString("username")); UUID uuid = UUID.fromString(resultSet.getString("uuid")); toAdd.put(new StringWrapper(username.value), uuid); } @@ -96,10 +99,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } return; } - FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); + FileUUIDHandler fileHandler = + new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); fileHandler.startCaching(new Runnable() { - @Override - public void run() { + @Override public void run() { // If the file based UUID handler didn't cache it, then we can't cache offline mode // Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does if (Settings.UUID.OFFLINE) { @@ -110,18 +113,24 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { while (!toFetch.isEmpty()) { try { - for (int i = 0; i < Math.min(500, toFetch.size()); i++) { + for (int i = 0; + i < Math.min(500, toFetch.size()); i++) { UUID uuid = toFetch.pop(); HttpURLConnection connection = - (HttpURLConnection) new URL(SQLUUIDHandler.this.PROFILE_URL + uuid.toString().replace("-", "")) - .openConnection(); - try (InputStream con = connection.getInputStream()) { - InputStreamReader reader = new InputStreamReader(con); - JSONObject response = (JSONObject) SQLUUIDHandler.this.jsonParser.parse(reader); + (HttpURLConnection) new URL( + SQLUUIDHandler.this.PROFILE_URL + uuid + .toString().replace("-", "")) + .openConnection(); + try (InputStream con = connection + .getInputStream()) { + InputStreamReader reader = + new InputStreamReader(con); + JSONObject response = + (JSONObject) SQLUUIDHandler.this.jsonParser + .parse(reader); String name = (String) response.get("name"); if (name != null) { add(new StringWrapper(name), uuid); @@ -129,8 +138,9 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } connection.disconnect(); } - }catch(IOException | ParseException e){ - PS.debug("Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); + } catch (IOException | ParseException e) { + PS.debug( + "Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); } try { Thread.sleep(INTERVAL * 50); @@ -155,15 +165,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { return true; } - @Override - public void fetchUUID(final String name, final RunnableVal ifFetch) { - PS.debug(C.PREFIX + "UUID for '" + name + "' was null. We'll cache this from the Mojang servers!"); + @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { + PS.debug(C.PREFIX + "UUID for '" + name + + "' was null. We'll cache this from the Mojang servers!"); if (ifFetch == null) { return; } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -177,13 +186,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { stream.write(body.getBytes()); stream.flush(); stream.close(); - JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); + JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser + .parse(new InputStreamReader(connection.getInputStream())); JSONObject jsonProfile = (JSONObject) array.get(0); String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); ifFetch.value = UUID.fromString( - id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + '-' + id.substring(16, 20) + '-' + id - .substring(20, 32)); + id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + + '-' + id.substring(16, 20) + '-' + id.substring(20, 32)); } catch (IOException | ParseException e) { e.printStackTrace(); } @@ -192,8 +202,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { }); } - @Override - public void handleShutdown() { + @Override public void handleShutdown() { super.handleShutdown(); try { getConnection().close(); @@ -202,14 +211,13 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } } - @Override - public boolean add(final StringWrapper name, final UUID uuid) { + @Override public boolean add(final StringWrapper name, final UUID uuid) { // Ignoring duplicates if (super.add(name, uuid)) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - try (PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { + @Override public void run() { + try (PreparedStatement statement = getConnection().prepareStatement( + "REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { statement.setString(1, uuid.toString()); statement.setString(2, name.toString()); statement.execute(); @@ -227,13 +235,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { /** * This is useful for name changes */ - @Override - public void rename(final UUID uuid, final StringWrapper name) { + @Override public void rename(final UUID uuid, final StringWrapper name) { super.rename(uuid, name); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - try (PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { + @Override public void run() { + try (PreparedStatement statement = getConnection() + .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { statement.setString(1, name.value); statement.setString(2, uuid.toString()); statement.execute(); diff --git a/Core/build.gradle b/Core/build.gradle index 0b787c2f0..9ee8d429e 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -18,7 +18,7 @@ processResources { } } -jar.archiveName="plotsquared-api-${project.parent.version}.jar" +jar.archiveName = "plotsquared-api-${project.parent.version}.jar" jar.destinationDir = file '../mvn/com/plotsquared/plotsquared-api/' + project.parent.version task createPom << { pom { @@ -43,10 +43,10 @@ task copyFiles { from "../mvn/com/plotsquared/plotsquared-api/${project.parent.version}/" into '../mvn/com/plotsquared/plotsquared-api/latest/' include('*.jar') - rename ("plotsquared-api-${project.parent.version}.jar", 'plotsquared-api-latest.jar') + rename("plotsquared-api-${project.parent.version}.jar", 'plotsquared-api-latest.jar') } } } build.finalizedBy(copyFiles) -copyFiles.dependsOn(createPom) \ No newline at end of file +copyFiles.dependsOn(createPom) diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java b/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java index 71ad38983..2c26399b0 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java @@ -8,23 +8,23 @@ import java.util.Map; 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 path Path of the value to set. * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ @Override 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.

@@ -33,14 +33,14 @@ public interface Configuration extends ConfigurationSection { * @throws IllegalArgumentException Thrown if defaults is null. */ 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 check this, you should set the default source with {@link @@ -50,10 +50,10 @@ public interface Configuration extends ConfigurationSection { * @throws IllegalArgumentException Thrown if defaults is null or this. */ void addDefaults(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 @@ -62,10 +62,10 @@ public interface Configuration extends ConfigurationSection { * @return Configuration source for default values, or null if none exist. */ Configuration getDefaults(); - + /** * 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.

@@ -77,7 +77,7 @@ public interface Configuration extends ConfigurationSection { /** * Gets the {@link ConfigurationOptions} for this {@link Configuration}. - * + *

*

All setters through this method are chainable.

* * @return Options for this configuration diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java index 445d1e938..b5f2478bb 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java @@ -8,11 +8,11 @@ class ConfigurationOptions { private final Configuration configuration; private char pathSeparator = '.'; private boolean copyDefaults = false; - + protected ConfigurationOptions(Configuration configuration) { this.configuration = configuration; } - + /** * Returns the {@link Configuration} that this object is responsible for. * @@ -21,11 +21,11 @@ class ConfigurationOptions { 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 '.'. * @@ -34,11 +34,11 @@ class ConfigurationOptions { 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 '.'. * @@ -49,11 +49,11 @@ class ConfigurationOptions { 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, @@ -67,11 +67,11 @@ class ConfigurationOptions { 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, diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java index 496a2775a..b188093c0 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java @@ -11,45 +11,45 @@ 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. + * list. * @return Set of keys contained within this ConfigurationSection. */ 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. + * list. * @return Map of keys and values of this section. */ 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. + * default or being set. * @throws IllegalArgumentException Thrown when path is {@code null}. */ boolean contains(String path); @@ -57,13 +57,13 @@ public interface ConfigurationSection { /** * 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. + * having a default. * @throws IllegalArgumentException Thrown when path is {@code null}. */ boolean isSet(String path); @@ -71,14 +71,14 @@ public interface ConfigurationSection { /** * 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 {@code 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()}. * @@ -89,7 +89,7 @@ public interface ConfigurationSection { /** * 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. * @@ -100,10 +100,10 @@ public interface ConfigurationSection { /** * 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 {@code null}. @@ -115,10 +115,10 @@ public interface ConfigurationSection { /** * Gets the parent {@link ConfigurationSection} that directly contains * this {@link ConfigurationSection}. - * + *

*

For any {@link Configuration} themselves, this will return * {@code 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 {@code null}. @@ -129,7 +129,7 @@ public interface ConfigurationSection { /** * 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 {@code null}. @@ -142,12 +142,12 @@ public interface ConfigurationSection { /** * 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 path Path of the Object to get. * @param defaultValue The default value to return if the path is not found. * @return Requested Object. */ @@ -155,23 +155,23 @@ public interface ConfigurationSection { /** * Sets the specified path to the given value. - * + *

*

If value is {@code 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 javadoc for details. No implementations should allow * you to store {@link Configuration}s or {@link ConfigurationSection}s, * please use {@link #createSection(String)} for that. * - * @param path Path of the object to set. + * @param path Path of the object to set. * @param value New value to set the path to. */ 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. @@ -184,13 +184,13 @@ public interface ConfigurationSection { /** * 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. + * @param map The values to used. * @return Newly created section */ ConfigurationSection createSection(String path, Map map); @@ -199,7 +199,7 @@ public interface ConfigurationSection { /** * 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 {@code null}. @@ -212,21 +212,21 @@ public interface ConfigurationSection { /** * 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. + * @param def The default value to return if the path is not found or is + * not a String. * @return Requested String. */ 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 @@ -239,7 +239,7 @@ public interface ConfigurationSection { /** * 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. @@ -251,21 +251,21 @@ public interface ConfigurationSection { /** * 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. + * @param def The default value to return if the path is not found or is + * not an int. * @return Requested int. */ 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 @@ -278,7 +278,7 @@ public interface ConfigurationSection { /** * 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. @@ -291,21 +291,21 @@ public interface ConfigurationSection { /** * 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 path Path of the boolean to get. * @param defaultValue The default value to return if the path is not found or is - * not a boolean. + * not a boolean. * @return Requested boolean. */ boolean getBoolean(String path, boolean defaultValue); /** * 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 @@ -318,7 +318,7 @@ public interface ConfigurationSection { /** * 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. @@ -331,21 +331,21 @@ public interface ConfigurationSection { /** * 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 path Path of the double to get. * @param defaultValue The default value to return if the path is not found or is - * not a double. + * not a double. * @return Requested double. */ double getDouble(String path, double defaultValue); /** * 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 @@ -358,7 +358,7 @@ public interface ConfigurationSection { /** * 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. @@ -371,21 +371,21 @@ public interface ConfigurationSection { /** * 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. + * @param def The default value to return if the path is not found or is + * not a long. * @return Requested long. */ 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 @@ -400,7 +400,7 @@ public interface ConfigurationSection { /** * 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. @@ -413,21 +413,21 @@ public interface ConfigurationSection { /** * 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. + * @param def The default value to return if the path is not found or is + * not a List. * @return Requested List. */ 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 @@ -440,11 +440,11 @@ public interface ConfigurationSection { /** * 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. * @@ -455,11 +455,11 @@ public interface ConfigurationSection { /** * 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. * @@ -470,11 +470,11 @@ public interface ConfigurationSection { /** * 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. * @@ -485,11 +485,11 @@ public interface ConfigurationSection { /** * 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. * @@ -500,11 +500,11 @@ public interface ConfigurationSection { /** * 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. * @@ -515,11 +515,11 @@ public interface ConfigurationSection { /** * 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. * @@ -530,11 +530,11 @@ public interface ConfigurationSection { /** * 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. * @@ -545,11 +545,11 @@ public interface ConfigurationSection { /** * 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. * @@ -560,11 +560,11 @@ public interface ConfigurationSection { /** * 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. * @@ -575,7 +575,7 @@ public interface ConfigurationSection { /** * 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. @@ -589,7 +589,7 @@ public interface ConfigurationSection { /** * 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, @@ -602,7 +602,7 @@ public interface ConfigurationSection { /** * 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 @@ -617,7 +617,7 @@ public interface ConfigurationSection { /** * 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 {@code null}. @@ -628,19 +628,19 @@ public interface ConfigurationSection { /** * 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 {@code null}, the value will be removed from the * default Configuration source. - * + *

*

If the value as returned by {@link #getDefaultSection()} is * {@code 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 path Path of the value to set * @param value Value to set the default to * @throws IllegalArgumentException Thrown if path is {@code null} */ diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java b/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java index f98b241af..23765e20f 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java @@ -3,15 +3,15 @@ package com.intellectualcrafters.configuration; /** * Exception thrown when attempting to load an invalid {@link Configuration}. */ -@SuppressWarnings("serial") -public class InvalidConfigurationException extends Exception { - +@SuppressWarnings("serial") public class InvalidConfigurationException extends Exception { + /** * Creates a new instance of InvalidConfigurationException without a * message or cause. */ - public InvalidConfigurationException() {} - + public InvalidConfigurationException() { + } + /** * Constructs an instance of InvalidConfigurationException with the * specified message. @@ -21,7 +21,7 @@ public class InvalidConfigurationException extends Exception { public InvalidConfigurationException(String msg) { super(msg); } - + /** * Constructs an instance of InvalidConfigurationException with the * specified cause. @@ -31,13 +31,13 @@ public class InvalidConfigurationException extends 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. + * @param msg The details of the exception. */ public InvalidConfigurationException(String msg, Throwable cause) { super(msg, cause); diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java index 7d1a5721a..0b4c73a30 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java @@ -10,12 +10,13 @@ import java.util.Map; public class MemoryConfiguration extends MemorySection implements Configuration { protected Configuration defaults; protected MemoryConfigurationOptions options; - + /** * Creates an empty {@link MemoryConfiguration} with no default values. */ - public MemoryConfiguration() {} - + public MemoryConfiguration() { + } + /** * Creates an empty {@link MemoryConfiguration} using the specified {@link * Configuration} as a source for all default values. @@ -26,49 +27,42 @@ public class MemoryConfiguration extends MemorySection implements Configuration public MemoryConfiguration(Configuration defaults) { this.defaults = defaults; } - - @Override - public void addDefault(String path, Object value) { + + @Override public void addDefault(String path, Object value) { if (this.defaults == null) { this.defaults = new MemoryConfiguration(); } this.defaults.set(path, value); } - - @Override - public void addDefaults(Map defaults) { + + @Override public void addDefaults(Map defaults) { for (Map.Entry entry : defaults.entrySet()) { addDefault(entry.getKey(), entry.getValue()); } } - - @Override - public void addDefaults(Configuration defaults) { + + @Override public void addDefaults(Configuration defaults) { addDefaults(defaults.getValues(true)); } - - @Override - public Configuration getDefaults() { + + @Override public Configuration getDefaults() { return this.defaults; } - @Override - public void setDefaults(Configuration defaults) { + @Override public void setDefaults(Configuration defaults) { if (defaults == null) { throw new NullPointerException("Defaults may not be null"); } this.defaults = defaults; } - - @Override - public ConfigurationSection getParent() { + + @Override public ConfigurationSection getParent() { return null; } - - @Override - public MemoryConfigurationOptions options() { + + @Override public MemoryConfigurationOptions options() { if (this.options == null) { this.options = new MemoryConfigurationOptions(this); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java index b2df5e134..13f5f4076 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java @@ -8,20 +8,17 @@ public class MemoryConfigurationOptions extends ConfigurationOptions { protected MemoryConfigurationOptions(MemoryConfiguration configuration) { super(configuration); } - - @Override - public MemoryConfiguration configuration() { + + @Override public MemoryConfiguration configuration() { return (MemoryConfiguration) super.configuration(); } - - @Override - public MemoryConfigurationOptions copyDefaults(boolean value) { + + @Override public MemoryConfigurationOptions copyDefaults(boolean value) { super.copyDefaults(value); return this; } - - @Override - public MemoryConfigurationOptions pathSeparator(char value) { + + @Override public MemoryConfigurationOptions pathSeparator(char value) { super.pathSeparator(value); return this; } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java index 86fd77acd..5cca55a37 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java @@ -1,11 +1,6 @@ package com.intellectualcrafters.configuration; -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 java.util.*; /** * A type of {@link ConfigurationSection} that is stored in memory. @@ -21,16 +16,17 @@ public class MemorySection implements ConfigurationSection { /** * 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. + * Configuration} root. */ protected MemorySection() { if (!(this instanceof Configuration)) { - throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); + throw new IllegalStateException( + "Cannot construct a root MemorySection when not a Configuration"); } this.path = ""; @@ -43,10 +39,10 @@ public class MemorySection implements ConfigurationSection { * 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}. + * @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. + * if parent contains no root Configuration. */ protected MemorySection(ConfigurationSection parent, String path) { this.path = path; @@ -117,12 +113,12 @@ public class MemorySection implements ConfigurationSection { /** * 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. + * @param key Name of the specified section. * @return Full path of the section from its root. */ public static String createPath(ConfigurationSection section, String key) { @@ -132,16 +128,17 @@ public class MemorySection implements ConfigurationSection { /** * 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 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) { + public static String createPath(ConfigurationSection section, String key, + ConfigurationSection relativeTo) { Configuration root = section.getRoot(); if (root == null) { throw new IllegalStateException("Cannot create path without a root"); @@ -149,7 +146,8 @@ public class MemorySection implements ConfigurationSection { char separator = root.options().pathSeparator(); StringBuilder builder = new StringBuilder(); - for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) { + for (ConfigurationSection parent = section; + (parent != null) && (parent != relativeTo); parent = parent.getParent()) { if (builder.length() > 0) { builder.insert(0, separator); } @@ -168,8 +166,7 @@ public class MemorySection implements ConfigurationSection { return builder.toString(); } - @Override - public Set getKeys(boolean deep) { + @Override public Set getKeys(boolean deep) { Set result = new LinkedHashSet<>(); Configuration root = getRoot(); @@ -186,8 +183,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public Map getValues(boolean deep) { + @Override public Map getValues(boolean deep) { Map result = new LinkedHashMap<>(); Configuration root = getRoot(); @@ -204,13 +200,11 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public boolean contains(String path) { + @Override public boolean contains(String path) { return get(path) != null; } - @Override - public boolean isSet(String path) { + @Override public boolean isSet(String path) { Configuration root = getRoot(); if (root == null) { return false; @@ -221,40 +215,35 @@ public class MemorySection implements ConfigurationSection { return get(path, null) != null; } - @Override - public String getCurrentPath() { + @Override public String getCurrentPath() { return this.fullPath; } - @Override - public String getName() { + @Override public String getName() { return this.path; } - @Override - public Configuration getRoot() { + @Override public Configuration getRoot() { return this.root; } - @Override - public ConfigurationSection getParent() { + @Override public ConfigurationSection getParent() { return this.parent; } - @Override - public void addDefault(String path, Object value) { + @Override public void addDefault(String path, Object value) { 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"); + throw new UnsupportedOperationException( + "Unsupported addDefault(String, Object) implementation"); } root.addDefault(createPath(this, path), value); } - @Override - public ConfigurationSection getDefaultSection() { + @Override public ConfigurationSection getDefaultSection() { Configuration root = getRoot(); Configuration defaults = root == null ? null : root.getDefaults(); @@ -267,8 +256,7 @@ public class MemorySection implements ConfigurationSection { return null; } - @Override - public void set(String path, Object value) { + @Override public void set(String path, Object value) { Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot use section without a root"); @@ -302,13 +290,11 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public Object get(String path) { + @Override public Object get(String path) { return get(path, getDefault(path)); } - @Override - public Object get(String path, Object defaultValue) { + @Override public Object get(String path, Object defaultValue) { if (path == null) { throw new NullPointerException("Path cannot be null"); } @@ -347,8 +333,7 @@ public class MemorySection implements ConfigurationSection { return section.get(key, defaultValue); } - @Override - public ConfigurationSection createSection(String path) { + @Override public ConfigurationSection createSection(String path) { Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot create section without a root"); @@ -379,8 +364,7 @@ public class MemorySection implements ConfigurationSection { return section.createSection(key); } - @Override - public ConfigurationSection createSection(String path, Map map) { + @Override public ConfigurationSection createSection(String path, Map map) { ConfigurationSection section = createSection(path); for (Map.Entry entry : map.entrySet()) { @@ -395,14 +379,12 @@ public class MemorySection implements ConfigurationSection { } // Primitives - @Override - public String getString(String path) { + @Override public String getString(String path) { Object def = getDefault(path); return getString(path, def != null ? def.toString() : null); } - @Override - public String getString(String path, String def) { + @Override public String getString(String path, String def) { Object val = get(path, def); if (val != null) { return val.toString(); @@ -411,32 +393,27 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public boolean isString(String path) { + @Override public boolean isString(String path) { Object val = get(path); return val instanceof String; } - @Override - public int getInt(String path) { + @Override public int getInt(String path) { Object def = getDefault(path); return getInt(path, toInt(def, 0)); } - @Override - public int getInt(String path, int def) { + @Override public int getInt(String path, int def) { Object val = get(path, def); return toInt(val, def); } - @Override - public boolean isInt(String path) { + @Override public boolean isInt(String path) { Object val = get(path); return val instanceof Integer; } - @Override - public boolean getBoolean(String path) { + @Override public boolean getBoolean(String path) { Object def = getDefault(path); if (def instanceof Boolean) { return getBoolean(path, (Boolean) def); @@ -445,8 +422,7 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public boolean getBoolean(String path, boolean defaultValue) { + @Override public boolean getBoolean(String path, boolean defaultValue) { Object val = get(path, defaultValue); if (val instanceof Boolean) { return (Boolean) val; @@ -455,69 +431,58 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public boolean isBoolean(String path) { + @Override public boolean isBoolean(String path) { Object val = get(path); return val instanceof Boolean; } - @Override - public double getDouble(String path) { + @Override public double getDouble(String path) { Object def = getDefault(path); return getDouble(path, toDouble(def, 0)); } - @Override - public double getDouble(String path, double defaultValue) { + @Override public double getDouble(String path, double defaultValue) { Object val = get(path, defaultValue); return toDouble(val, defaultValue); } - @Override - public boolean isDouble(String path) { + @Override public boolean isDouble(String path) { Object val = get(path); return val instanceof Double; } - @Override - public long getLong(String path) { + @Override public long getLong(String path) { Object def = getDefault(path); return getLong(path, toLong(def, 0)); } - @Override - public long getLong(String path, long def) { + @Override public long getLong(String path, long def) { Object val = get(path, def); return toLong(val, def); } - @Override - public boolean isLong(String path) { + @Override public boolean isLong(String path) { Object val = get(path); return val instanceof Long; } // Java - @Override - public List getList(String path) { + @Override public List getList(String path) { Object def = getDefault(path); return getList(path, def instanceof List ? (List) def : null); } - @Override - public List getList(String path, List def) { + @Override public List getList(String path, List def) { Object val = get(path, def); return (List) ((val instanceof List) ? val : def); } - @Override - public boolean isList(String path) { + @Override public boolean isList(String path) { Object val = get(path); return val instanceof List; } - @Override - public List getStringList(String path) { + @Override public List getStringList(String path) { List list = getList(path); if (list == null) { @@ -535,8 +500,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getIntegerList(String path) { + @Override public List getIntegerList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -559,8 +523,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getBooleanList(String path) { + @Override public List getBooleanList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -580,8 +543,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getDoubleList(String path) { + @Override public List getDoubleList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -604,8 +566,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getFloatList(String path) { + @Override public List getFloatList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -628,8 +589,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getLongList(String path) { + @Override public List getLongList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -652,8 +612,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getByteList(String path) { + @Override public List getByteList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -676,8 +635,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getCharacterList(String path) { + @Override public List getCharacterList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -699,8 +657,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getShortList(String path) { + @Override public List getShortList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -723,8 +680,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List> getMapList(String path) { + @Override public List> getMapList(String path) { List list = getList(path); List> result = new ArrayList<>(); @@ -737,8 +693,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public ConfigurationSection getConfigurationSection(String path) { + @Override public ConfigurationSection getConfigurationSection(String path) { Object val = get(path, null); if (val != null) { return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; @@ -748,21 +703,15 @@ public class MemorySection implements ConfigurationSection { return (val instanceof ConfigurationSection) ? createSection(path) : null; } - @Override - public boolean isConfigurationSection(String path) { + @Override 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); + 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) { @@ -792,7 +741,8 @@ public class MemorySection implements ConfigurationSection { } } - protected void mapChildrenValues(Map output, ConfigurationSection section, boolean deep) { + protected void mapChildrenValues(Map output, ConfigurationSection section, + boolean deep) { if (section instanceof MemorySection) { MemorySection sec = (MemorySection) section; @@ -814,13 +764,14 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public String toString() { + @Override public String toString() { Configuration root = getRoot(); if (root == null) { - return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null + "']"; + return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null + + "']"; } else { - return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root.getClass().getSimpleName() + "']"; + return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root + .getClass().getSimpleName() + "']"; } } } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java index 2c4f61991..85e4987da 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java @@ -4,16 +4,7 @@ import com.intellectualcrafters.configuration.Configuration; import com.intellectualcrafters.configuration.InvalidConfigurationException; import com.intellectualcrafters.configuration.MemoryConfiguration; -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.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; +import java.io.*; import java.nio.charset.StandardCharsets; /** @@ -25,8 +16,9 @@ public abstract class FileConfiguration extends MemoryConfiguration { /** * Creates an empty {@link FileConfiguration} with no default values. */ - FileConfiguration() {} - + FileConfiguration() { + } + /** * Creates an empty {@link FileConfiguration} using the specified {@link * Configuration} as a source for all default values. @@ -36,20 +28,20 @@ public abstract class FileConfiguration extends MemoryConfiguration { 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. + * any reason. */ public void save(File file) throws IOException { File parent = file.getParentFile(); @@ -59,7 +51,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { String data = saveToString(); - try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { + try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), + StandardCharsets.UTF_8)) { writer.write(data); } } @@ -70,49 +63,51 @@ public abstract class FileConfiguration extends MemoryConfiguration { * @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. * * @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 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. + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. */ public void load(File file) throws IOException, InvalidConfigurationException { FileInputStream stream = new FileInputStream(file); - + load(new InputStreamReader(stream, StandardCharsets.UTF_8)); } /** * 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 IOException thrown when underlying reader throws an IOException * @throws InvalidConfigurationException thrown when the reader does not - * represent a valid Configuration + * represent a valid Configuration */ public void load(Reader reader) throws IOException, InvalidConfigurationException { StringBuilder builder = new StringBuilder(); - try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) { + try (BufferedReader input = reader instanceof BufferedReader ? + (BufferedReader) reader : + new BufferedReader(reader)) { String line; while ((line = input.readLine()) != null) { @@ -120,30 +115,30 @@ public abstract class FileConfiguration extends MemoryConfiguration { builder.append('\n'); } } - + loadFromString(builder.toString()); } /** * 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. + * invalid. */ 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. @@ -151,9 +146,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { * @return Compiled header */ protected abstract String buildHeader(); - - @Override - public FileConfigurationOptions options() { + + @Override public FileConfigurationOptions options() { if (this.options == null) { this.options = new FileConfigurationOptions(this); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java index a2c1c19e6..2f5d27ef1 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java @@ -11,37 +11,34 @@ import com.intellectualcrafters.configuration.MemoryConfigurationOptions; public class FileConfigurationOptions extends MemoryConfigurationOptions { private String header = null; private boolean copyHeader = true; - + protected FileConfigurationOptions(MemoryConfiguration configuration) { super(configuration); } - - @Override - public FileConfiguration configuration() { + + @Override public FileConfiguration configuration() { return (FileConfiguration) super.configuration(); } - - @Override - public FileConfigurationOptions copyDefaults(boolean value) { + + @Override public FileConfigurationOptions copyDefaults(boolean value) { super.copyDefaults(value); return this; } - - @Override - public FileConfigurationOptions pathSeparator(char value) { + + @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. - * + *

*

{@code null} is a valid value which will indicate that no header] * is to be applied. The default value is {@code null}. * @@ -50,16 +47,16 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { 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. - * + *

*

{@code null} is a valid value which will indicate that no header * is to be applied. * @@ -70,20 +67,20 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { 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(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 @@ -91,20 +88,20 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { 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(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 @@ -112,7 +109,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { */ public FileConfigurationOptions copyHeader(boolean value) { copyHeader = value; - + return this; } } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java index ae158f938..a686c7be1 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java @@ -28,11 +28,11 @@ public class YamlConfiguration extends FileConfiguration { /** * 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 @@ -64,8 +64,7 @@ public class YamlConfiguration extends FileConfiguration { return config; } - @Override - public String saveToString() { + @Override public String saveToString() { yamlOptions.setIndent(options().indent()); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); @@ -79,9 +78,8 @@ public class YamlConfiguration extends FileConfiguration { return header + dump; } - - @Override - public void loadFromString(String contents) throws InvalidConfigurationException { + + @Override public void loadFromString(String contents) throws InvalidConfigurationException { Map input; try { @@ -101,7 +99,7 @@ public class YamlConfiguration extends FileConfiguration { convertMapsToSections(input, this); } } - + protected void convertMapsToSections(Map input, ConfigurationSection section) { for (Map.Entry entry : input.entrySet()) { String key = entry.getKey().toString(); @@ -114,7 +112,7 @@ public class YamlConfiguration extends FileConfiguration { } } } - + protected String parseHeader(String input) { String[] lines = input.split("\r?\n", -1); StringBuilder result = new StringBuilder(); @@ -143,9 +141,8 @@ public class YamlConfiguration extends FileConfiguration { return result.toString(); } - - @Override - protected String buildHeader() { + + @Override protected String buildHeader() { String header = options().header(); if (options().copyHeader()) { @@ -182,8 +179,7 @@ public class YamlConfiguration extends FileConfiguration { return builder.toString(); } - @Override - public YamlConfigurationOptions options() { + @Override public YamlConfigurationOptions options() { if (options == null) { options = new YamlConfigurationOptions(this); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java index 242b40640..c502e682c 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java @@ -6,43 +6,38 @@ package com.intellectualcrafters.configuration.file; */ public class YamlConfigurationOptions extends FileConfigurationOptions { private int indent = 2; - + YamlConfigurationOptions(YamlConfiguration configuration) { super(configuration); } - - @Override - public YamlConfiguration configuration() { + + @Override public YamlConfiguration configuration() { return (YamlConfiguration) super.configuration(); } - - @Override - public YamlConfigurationOptions copyDefaults(boolean value) { + + @Override public YamlConfigurationOptions copyDefaults(boolean value) { super.copyDefaults(value); return this; } - - @Override - public YamlConfigurationOptions pathSeparator(char value) { + + @Override public YamlConfigurationOptions pathSeparator(char value) { super.pathSeparator(value); return this; } - - @Override - public YamlConfigurationOptions header(String value) { + + @Override public YamlConfigurationOptions header(String value) { super.header(value); return this; } - - @Override - public YamlConfigurationOptions copyHeader(boolean value) { + + @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 @@ -50,10 +45,10 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { 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 @@ -66,7 +61,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { if (value > 9) { throw new IllegalArgumentException("Indent cannot be greater than 9 characters"); } - + indent = value; return this; } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java index c70ea67b7..2c46805a6 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java @@ -10,38 +10,36 @@ import java.util.LinkedHashMap; import java.util.Map; public class YamlConstructor extends SafeConstructor { - + YamlConstructor() { yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); } - + private class ConstructCustomObject extends ConstructYamlMap { - @Override - public Object construct(final Node node) { + @Override public Object construct(final Node node) { if (node.isTwoStepsConstruction()) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } - + final Map raw = (Map) super.construct(node); - + if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { final Map typed = new LinkedHashMap<>(raw.size()); for (final Map.Entry entry : raw.entrySet()) { typed.put(entry.getKey().toString(), entry.getValue()); } - + try { return ConfigurationSerialization.deserializeObject(typed); } catch (final IllegalArgumentException ex) { throw new YAMLException("Could not deserialize object", ex); } } - + return raw; } - - @Override - public void construct2ndStep(final Node node, final Object object) { + + @Override public void construct2ndStep(final Node node, final Object object) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java index e130e5d94..239bda7ba 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java @@ -13,24 +13,25 @@ class YamlRepresenter extends Representer { YamlRepresenter() { this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); - this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); + this.multiRepresenters + .put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); } private class RepresentConfigurationSection extends RepresentMap { - @Override - public Node representData(Object data) { + @Override public Node representData(Object data) { return super.representData(((ConfigurationSection) data).getValues(false)); } } + private class RepresentConfigurationSerializable extends RepresentMap { - @Override - public Node representData(Object data) { + @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.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, + ConfigurationSerialization.getAlias(serializable.getClass())); values.putAll(serializable.serialize()); return super.representData(values); diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java index fed1b35b9..2df347043 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java @@ -21,10 +21,10 @@ import java.util.Map; * @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 javadoc. * diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java index 92b7edfba..58f22d14c 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java @@ -17,7 +17,8 @@ import java.util.logging.Logger; public class ConfigurationSerialization { public static final String SERIALIZED_TYPE_KEY = "=="; - private static final Map> aliases = new HashMap<>(); + private static final Map> aliases = + new HashMap<>(); private final Class clazz; protected ConfigurationSerialization(Class clazz) { @@ -27,31 +28,32 @@ public class ConfigurationSerialization { /** * 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 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) { + 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.

@@ -71,14 +73,16 @@ public class ConfigurationSerialization { } clazz = getClassByAlias(alias); if (clazz == null) { - throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); + 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 + "')"); + throw new IllegalArgumentException( + "Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); } return new ConfigurationSerialization(clazz).deserialize(args); @@ -107,7 +111,8 @@ public class ConfigurationSerialization { * @param alias Alias to register as * @see SerializableAs */ - public static void registerClass(Class clazz, String alias) { + public static void registerClass(Class clazz, + String alias) { aliases.put(alias, clazz); } @@ -127,7 +132,8 @@ public class ConfigurationSerialization { * @param clazz Class to unregister */ public static void unregisterClass(Class clazz) { - while (aliases.values().remove(clazz)) {} + while (aliases.values().remove(clazz)) { + } } /** @@ -195,32 +201,35 @@ public class ConfigurationSerialization { protected ConfigurationSerializable deserializeViaMethod(Method method, Map args) { try { - ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); + 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 " + this.clazz + " for deserialization: method returned null"); + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization: method returned null"); } else { return result; } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) { - Logger.getLogger(ConfigurationSerialization.class.getName()) - .log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + this.clazz - + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); } return null; } - protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map args) { + protected ConfigurationSerializable deserializeViaCtor( + Constructor ctor, Map args) { try { return ctor.newInstance(args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) { - Logger.getLogger(ConfigurationSerialization.class.getName()) - .log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + this.clazz - + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); } return null; diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java index b6676c747..090877f25 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java @@ -9,8 +9,7 @@ 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) +@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DelegateDeserialization { /** * Which class should be used as a delegate for this classes diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java index 54287571e..95c6c7af6 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java +++ b/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java @@ -19,9 +19,7 @@ import java.lang.annotation.Target; * * @see ConfigurationSerialization#registerClass(Class, String) */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface SerializableAs { +@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SerializableAs { /** * This is the name your class will be stored and retrieved as. *

diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java index 420a6ad69..b2c020eb6 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java @@ -27,13 +27,11 @@ public final class ByteArrayTag extends Tag { this.value = value; } - @Override - public byte[] getValue() { + @Override public byte[] getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { StringBuilder hex = new StringBuilder(); for (byte b : this.value) { String hexDigits = Integer.toHexString(b).toUpperCase(); diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java index 7e8c2b7e4..5174301ea 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java @@ -27,13 +27,11 @@ public final class ByteTag extends Tag { this.value = value; } - @Override - public Byte getValue() { + @Override public Byte getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java index 4bbbd62b5..2974944d1 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java @@ -36,15 +36,13 @@ public final class CompoundTag extends Tag { * Returns whether this compound tag contains the given key. * * @param key the given key - * * @return true if the tag contains the given key */ public boolean containsKey(String key) { return this.value.containsKey(key); } - @Override - public Map getValue() { + @Override public Map getValue() { return this.value; } @@ -52,7 +50,6 @@ public final class CompoundTag extends Tag { * Return a new compound tag with the given values. * * @param value the value - * * @return the new compound tag */ public CompoundTag setValue(Map value) { @@ -75,12 +72,11 @@ public final class CompoundTag extends Tag { /** * Get a byte array named with the given key. - * + *

*

If the key does not exist or its value is not a byte array * tag, then an empty byte array will be returned.

* * @param key the key - * * @return a byte array */ public byte[] getByteArray(String key) { @@ -97,7 +93,6 @@ public final class CompoundTag extends Tag { * {@code 0} will be returned.

* * @param key the key - * * @return a byte */ public byte getByte(String key) { @@ -114,7 +109,6 @@ public final class CompoundTag extends Tag { * {@code 0} will be returned.

* * @param key the key - * * @return a double */ public double getDouble(String key) { @@ -131,7 +125,6 @@ public final class CompoundTag extends Tag { * its value is not a number, then {@code 0} will be returned.

* * @param key the key - * * @return a double */ public double asDouble(String key) { @@ -158,7 +151,6 @@ public final class CompoundTag extends Tag { * {@code 0} will be returned.

* * @param key the key - * * @return a float */ public float getFloat(String key) { @@ -175,7 +167,6 @@ public final class CompoundTag extends Tag { * tag, then an empty array will be returned.

* * @param key the key - * * @return an int array */ public int[] getIntArray(String key) { @@ -192,7 +183,6 @@ public final class CompoundTag extends Tag { * {@code 0} will be returned.

* * @param key the key - * * @return an int */ public int getInt(String key) { @@ -209,7 +199,6 @@ public final class CompoundTag extends Tag { * its value is not a number, then {@code 0} will be returned.

* * @param key the key - * * @return an int */ public int asInt(String key) { @@ -236,7 +225,6 @@ public final class CompoundTag extends Tag { * then an empty list will be returned.

* * @param key the key - * * @return a list of tags */ public List getList(String key) { @@ -253,7 +241,6 @@ public final class CompoundTag extends Tag { * tag, then an empty tag list will be returned.

* * @param key the key - * * @return a tag list instance */ public ListTag getListTag(String key) { @@ -273,11 +260,10 @@ public final class CompoundTag extends Tag { * @param key the key * @param listType the class of the contained type * @param the type of list - * * @return a list of tags */ - @SuppressWarnings("unchecked") - public List getList(String key, Class listType) { + @SuppressWarnings("unchecked") public List getList(String key, + Class listType) { Tag tag = this.value.get(key); if (tag instanceof ListTag) { ListTag listTag = (ListTag) tag; @@ -296,7 +282,6 @@ public final class CompoundTag extends Tag { * {@code 0} will be returned.

* * @param key the key - * * @return a long */ public long getLong(String key) { @@ -313,7 +298,6 @@ public final class CompoundTag extends Tag { * its value is not a number, then {@code 0} will be returned.

* * @param key the key - * * @return a long */ public long asLong(String key) { @@ -340,7 +324,6 @@ public final class CompoundTag extends Tag { * {@code 0} will be returned.

* * @param key the key - * * @return a short */ public short getShort(String key) { @@ -357,7 +340,6 @@ public final class CompoundTag extends Tag { * {@code ""} will be returned.

* * @param key the key - * * @return a string */ public String getString(String key) { @@ -369,17 +351,18 @@ public final class CompoundTag extends Tag { } } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { append = "(\"" + getName() + "\")"; } StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n"); + bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()) + .append(" entries\r\n{\r\n"); for (Map.Entry entry : this.value.entrySet()) { - bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); + bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")) + .append("\r\n"); } bldr.append("}"); return bldr.toString(); diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java index 54e33db01..1d650a613 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java @@ -1,10 +1,10 @@ package com.intellectualcrafters.jnbt; -import static com.google.common.base.Preconditions.checkNotNull; - import java.util.HashMap; import java.util.Map; +import static com.google.common.base.Preconditions.checkNotNull; + /** * Helps create compound tags. */ @@ -43,7 +43,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder put(String key, Tag value) { @@ -58,7 +57,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putByteArray(String key, byte[] value) { @@ -70,7 +68,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putByte(String key, byte value) { @@ -82,7 +79,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putDouble(String key, double value) { @@ -94,7 +90,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putFloat(String key, float value) { @@ -106,7 +101,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putIntArray(String key, int[] value) { @@ -118,7 +112,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putInt(String key, int value) { @@ -130,7 +123,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putLong(String key, long value) { @@ -142,7 +134,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putShort(String key, short value) { @@ -154,7 +145,6 @@ public class CompoundTagBuilder { * * @param key they key * @param value the value - * * @return this object */ public CompoundTagBuilder putString(String key, String value) { @@ -165,7 +155,6 @@ public class CompoundTagBuilder { * Put all the entries from the given map into this map. * * @param value the map of tags - * * @return this object */ public CompoundTagBuilder putAll(Map value) { @@ -189,7 +178,6 @@ public class CompoundTagBuilder { * Build a new compound tag with this builder's entries. * * @param name the name of the tag - * * @return the created compound tag */ public CompoundTag build(String name) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java index c5954abd0..e05039ac6 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java @@ -27,13 +27,11 @@ public final class DoubleTag extends Tag { this.value = value; } - @Override - public Double getValue() { + @Override public Double getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/EndTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/EndTag.java index 8c7eba1e1..d226ec8e9 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/EndTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/EndTag.java @@ -8,15 +8,14 @@ public final class EndTag extends Tag { /** * Creates the tag. */ - public EndTag() {} + public EndTag() { + } - @Override - public Object getValue() { + @Override public Object getValue() { return null; } - @Override - public String toString() { + @Override public String toString() { return "TAG_End"; } } diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java index 21ab3734b..63207f127 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java @@ -27,13 +27,11 @@ public final class FloatTag extends Tag { this.value = value; } - @Override - public Float getValue() { + @Override public Float getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java index a33fa6952..d0f7ccb00 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java @@ -31,13 +31,11 @@ public final class IntArrayTag extends Tag { this.value = value; } - @Override - public int[] getValue() { + @Override public int[] getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { StringBuilder hex = new StringBuilder(); for (int b : this.value) { String hexDigits = Integer.toHexString(b).toUpperCase(); diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/IntTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/IntTag.java index da15b74f8..98dae4c51 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/IntTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/IntTag.java @@ -27,13 +27,11 @@ public final class IntTag extends Tag { this.value = value; } - @Override - public Integer getValue() { + @Override public Integer getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/ListTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ListTag.java index a68144346..c00923bc0 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/ListTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/ListTag.java @@ -1,11 +1,11 @@ package com.intellectualcrafters.jnbt; -import static com.google.common.base.Preconditions.checkNotNull; - import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; +import static com.google.common.base.Preconditions.checkNotNull; + /** * The {@code TAG_List} tag. */ @@ -49,8 +49,7 @@ public final class ListTag extends Tag { return this.type; } - @Override - public List getValue() { + @Override public List getValue() { return this.value; } @@ -58,7 +57,6 @@ public final class ListTag extends Tag { * Create a new list tag with this tag's name and type. * * @param list the new list - * * @return a new list tag */ public ListTag setValue(List list) { @@ -69,7 +67,6 @@ public final class ListTag extends Tag { * Get the tag if it exists at the given index. * * @param index the index - * * @return the tag or null */ public Tag getIfExists(int index) { @@ -85,7 +82,6 @@ public final class ListTag extends Tag { * array tag, then an empty byte array will be returned.

* * @param index the index - * * @return a byte array */ public byte[] getByteArray(int index) { @@ -102,7 +98,6 @@ public final class ListTag extends Tag { * {@code 0} will be returned.

* * @param index the index - * * @return a byte */ public byte getByte(int index) { @@ -119,7 +114,6 @@ public final class ListTag extends Tag { * then {@code 0} will be returned.

* * @param index the index - * * @return a double */ public double getDouble(int index) { @@ -136,7 +130,6 @@ public final class ListTag extends Tag { * exist or its value is not a number, then {@code 0} will be returned.

* * @param index the index - * * @return a double */ public double asDouble(int index) { @@ -163,7 +156,6 @@ public final class ListTag extends Tag { * then {@code 0} will be returned.

* * @param index the index - * * @return a float */ public float getFloat(int index) { @@ -180,7 +172,6 @@ public final class ListTag extends Tag { * array tag, then an empty array will be returned.

* * @param index the index - * * @return an int array */ public int[] getIntArray(int index) { @@ -197,7 +188,6 @@ public final class ListTag extends Tag { * {@code 0} will be returned.

* * @param index the index - * * @return an int */ public int getInt(int index) { @@ -214,7 +204,6 @@ public final class ListTag extends Tag { * or its value is not a number, then {@code 0} will be returned.

* * @param index the index - * * @return an int */ public int asInt(int index) { @@ -241,7 +230,6 @@ public final class ListTag extends Tag { * tag, then an empty list will be returned.

* * @param index the index - * * @return a list of tags */ public List getList(int index) { @@ -258,7 +246,6 @@ public final class ListTag extends Tag { * tag, then an empty tag list will be returned.

* * @param index the index - * * @return a tag list instance */ public ListTag getListTag(int index) { @@ -278,11 +265,10 @@ public final class ListTag extends Tag { * @param index the index * @param listType the class of the contained type * @param the NBT type - * * @return a list of tags */ - @SuppressWarnings("unchecked") - public List getList(int index, Class listType) { + @SuppressWarnings("unchecked") public List getList(int index, + Class listType) { Tag tag = getIfExists(index); if (tag instanceof ListTag) { ListTag listTag = (ListTag) tag; @@ -301,7 +287,6 @@ public final class ListTag extends Tag { * {@code 0} will be returned.

* * @param index the index - * * @return a long */ public long getLong(int index) { @@ -318,7 +303,6 @@ public final class ListTag extends Tag { * or its value is not a number, then {@code 0} will be returned.

* * @param index the index - * * @return a long */ public long asLong(int index) { @@ -345,7 +329,6 @@ public final class ListTag extends Tag { * then {@code 0} will be returned.

* * @param index the index - * * @return a short */ public short getShort(int index) { @@ -362,7 +345,6 @@ public final class ListTag extends Tag { * then {@code ""} will be returned.

* * @param index the index - * * @return a string */ public String getString(int index) { @@ -374,17 +356,16 @@ public final class ListTag extends Tag { } } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { append = "(\"" + getName() + "\")"; } StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_List").append(append).append(": ").append(this.value.size()).append(" entries of type ") - .append(NBTUtils.getTypeName(this.type)) - .append("\r\n{\r\n"); + bldr.append("TAG_List").append(append).append(": ").append(this.value.size()) + .append(" entries of type ").append(NBTUtils.getTypeName(this.type)) + .append("\r\n{\r\n"); for (Tag t : this.value) { bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); } diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java index 0a0d2531a..0dd0450b4 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java @@ -1,12 +1,12 @@ package com.intellectualcrafters.jnbt; -import static com.google.common.base.Preconditions.checkNotNull; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; +import static com.google.common.base.Preconditions.checkNotNull; + /** * Helps create list tags. */ @@ -30,7 +30,6 @@ public class ListTagBuilder { * Create a new builder instance. * * @param type - * * @return a new builder */ public static ListTagBuilder create(Class type) { @@ -42,11 +41,9 @@ public class ListTagBuilder { * * @param entries * @param - * * @return a new builder */ - @SafeVarargs - public static ListTagBuilder createWith(T... entries) { + @SafeVarargs public static ListTagBuilder createWith(T... entries) { checkNotNull(entries); if (entries.length == 0) { throw new IllegalArgumentException("This method needs an array of at least one entry"); @@ -66,13 +63,14 @@ public class ListTagBuilder { * Add the given tag. * * @param value the tag - * * @return this object */ public ListTagBuilder add(Tag value) { checkNotNull(value); if (!this.type.isInstance(value)) { - throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + this.type.getCanonicalName()); + throw new IllegalArgumentException( + value.getClass().getCanonicalName() + " is not of expected type " + this.type + .getCanonicalName()); } this.entries.add(value); return this; @@ -82,7 +80,6 @@ public class ListTagBuilder { * Add all the tags in the given list. * * @param value a list of tags - * * @return this object */ public ListTagBuilder addAll(Collection value) { @@ -106,7 +103,6 @@ public class ListTagBuilder { * Build a new list tag with this builder's entries. * * @param name the name of the tag - * * @return the created list tag */ public ListTag build(String name) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/LongTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/LongTag.java index 422a4a9de..02b2b3079 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/LongTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/LongTag.java @@ -27,13 +27,11 @@ public final class LongTag extends Tag { this.value = value; } - @Override - public Long getValue() { + @Override public Long getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java index 43282b5ad..cab80688d 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java @@ -9,22 +9,21 @@ import java.nio.charset.StandardCharsets; public final class NBTConstants { public static final Charset CHARSET = StandardCharsets.UTF_8; - public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, - TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, - TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11; + public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = + 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, + TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11; /** * Default private constructor. */ - private NBTConstants() {} + private NBTConstants() { + } /** * Convert a type ID to its corresponding {@link Tag} class. * * @param id type ID - * * @return tag class - * * @throws IllegalArgumentException thrown if the tag ID is not valid */ public static Class getClassFromType(int id) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java index 622a1c5fd..0d7a2d656 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java @@ -24,7 +24,6 @@ public final class NBTInputStream implements Closeable { * Creates a new {@code NBTInputStream}, which will source its data from the specified input stream. * * @param is the input stream - * * @throws IOException if an I/O error occurs */ public NBTInputStream(InputStream is) { @@ -35,7 +34,6 @@ public final class NBTInputStream implements Closeable { * Reads an NBT tag from the stream. * * @return The tag that was read. - * * @throws IOException if an I/O error occurs. */ public Tag readTag() throws IOException { @@ -46,7 +44,6 @@ public final class NBTInputStream implements Closeable { * Reads an NBT tag from the stream. * * @return The tag that was read. - * * @throws IOException if an I/O error occurs. */ public Tag readTag(int maxDepth) throws IOException { @@ -57,9 +54,7 @@ public final class NBTInputStream implements Closeable { * Reads an NBT from the stream. * * @param depth the depth of this tag - * * @return The tag that was read. - * * @throws IOException if an I/O error occurs. */ private Tag readTag(int depth, int maxDepth) throws IOException { @@ -85,9 +80,7 @@ public final class NBTInputStream implements Closeable { * @param type the type * @param name the name * @param depth the depth - * * @return the tag - * * @throws IOException if an I/O error occurs. */ private Tag readTagPayload(int type, String name, int depth, int maxDepth) throws IOException { @@ -98,7 +91,8 @@ public final class NBTInputStream implements Closeable { switch (type) { case NBTConstants.TYPE_END: if (depth == 0) { - throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it."); + throw new IOException( + "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); } else { return new EndTag(); } @@ -185,8 +179,7 @@ public final class NBTInputStream implements Closeable { } } - @Override - public void close() throws IOException { + @Override public void close() throws IOException { this.is.close(); } } diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java index 0ec56f364..0ed66927d 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java @@ -9,7 +9,7 @@ import java.util.List; /** * This class writes NBT, or Named Binary Tag * {@code Tag} objects to an underlying {@code OutputStream}. - * + *

*

The NBT format was created by Markus Persson, and the specification may * be found at @linktourl http://www.minecraft.net/docs/NBT.txt *

@@ -28,7 +28,6 @@ public final class NBTOutputStream implements Closeable { * specified underlying output stream. * * @param os The output stream. - * * @throws IOException if an I/O error occurs. */ public NBTOutputStream(OutputStream os) { @@ -39,7 +38,6 @@ public final class NBTOutputStream implements Closeable { * Writes a tag. * * @param tag The tag to write. - * * @throws IOException if an I/O error occurs. */ public void writeTag(Tag tag) throws IOException { @@ -59,7 +57,6 @@ public final class NBTOutputStream implements Closeable { * Writes tag payload. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeTagPayload(Tag tag) throws IOException { @@ -110,7 +107,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Byte} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeByteTagPayload(ByteTag tag) throws IOException { @@ -121,7 +117,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Byte_Array} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeByteArrayTagPayload(ByteArrayTag tag) throws IOException { @@ -134,7 +129,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Compound} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeCompoundTagPayload(CompoundTag tag) throws IOException { @@ -148,7 +142,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_List} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeListTagPayload(ListTag tag) throws IOException { @@ -166,7 +159,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_String} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeStringTagPayload(StringTag tag) throws IOException { @@ -179,7 +171,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Double} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeDoubleTagPayload(DoubleTag tag) throws IOException { @@ -190,7 +181,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Float} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeFloatTagPayload(FloatTag tag) throws IOException { @@ -201,7 +191,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Long} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeLongTagPayload(LongTag tag) throws IOException { @@ -212,7 +201,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Int} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeIntTagPayload(IntTag tag) throws IOException { @@ -223,7 +211,6 @@ public final class NBTOutputStream implements Closeable { * Writes a {@code TAG_Short} tag. * * @param tag The tag. - * * @throws IOException if an I/O error occurs. */ private void writeShortTagPayload(ShortTag tag) throws IOException { @@ -247,13 +234,13 @@ public final class NBTOutputStream implements Closeable { } } - @Override - public void close() throws IOException { + @Override public void close() throws IOException { this.os.close(); } /** * Flush output. + * * @throws IOException */ public void flush() throws IOException { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java index a0f2cabd7..e663367bf 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java @@ -10,13 +10,13 @@ public final class NBTUtils { /** * Default private constructor. */ - private NBTUtils() {} + private NBTUtils() { + } /** * Gets the type name of a tag. * * @param clazz the tag class - * * @return The type name. */ public static String getTypeName(Class clazz) { @@ -53,9 +53,7 @@ public final class NBTUtils { * Gets the type code of a tag class. * * @param clazz the tag class - * * @return The type code. - * * @throws IllegalArgumentException if the tag class is invalid. */ public static int getTypeCode(Class clazz) { @@ -92,9 +90,7 @@ public final class NBTUtils { * Gets the class of a type of tag. * * @param type the type - * * @return The class. - * * @throws IllegalArgumentException if the tag type is invalid. */ public static Class getTypeClass(int type) { @@ -135,17 +131,17 @@ public final class NBTUtils { * @param key the key to look for * @param expected the expected NBT class type * @param - * * @return child tag */ - public static T getChildTag(Map items, String key, Class expected) - throws IllegalArgumentException { + public static T getChildTag(Map items, String key, + Class expected) throws IllegalArgumentException { if (!items.containsKey(key)) { throw new IllegalArgumentException("Missing a \"" + key + "\" tag"); } Tag tag = items.get(key); if (!expected.isInstance(tag)) { - throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName()); + throw new IllegalArgumentException( + key + " tag is not of tag type " + expected.getName()); } return expected.cast(tag); } diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java index df96b425e..f74a99700 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java @@ -27,13 +27,11 @@ public final class ShortTag extends Tag { this.value = value; } - @Override - public Short getValue() { + @Override public Short getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/jnbt/StringTag.java b/Core/src/main/java/com/intellectualcrafters/jnbt/StringTag.java index 0360715c0..6724fcc46 100644 --- a/Core/src/main/java/com/intellectualcrafters/jnbt/StringTag.java +++ b/Core/src/main/java/com/intellectualcrafters/jnbt/StringTag.java @@ -31,13 +31,11 @@ public final class StringTag extends Tag { this.value = value; } - @Override - public String getValue() { + @Override public String getValue() { return this.value; } - @Override - public String toString() { + @Override public String toString() { String name = getName(); String append = ""; if (name != null && !name.isEmpty()) { diff --git a/Core/src/main/java/com/intellectualcrafters/json/CDL.java b/Core/src/main/java/com/intellectualcrafters/json/CDL.java index e09a05478..a06e5d1bc 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/CDL.java +++ b/Core/src/main/java/com/intellectualcrafters/json/CDL.java @@ -4,13 +4,13 @@ package com.intellectualcrafters.json; * This provides static methods to convert comma delimited text into a JSONArray, and to covert a JSONArray into comma * delimited text. Comma delimited text is a very popular format for data interchange. It is understood by most * database, spreadsheet, and organizer programs. - * + *

* Each row of text represents a row in a table or a data record. Each row ends with a NEWLINE character. Each row * contains one or more values. Values are separated by commas. A value can contain any character except for comma, * unless is is wrapped in single quotes or double quotes. - * + *

* The first row usually contains the names of the columns. - * + *

* A comma delimited list can be converted into a JSONArray of JSONObjects. The names for the elements in the * JSONObjects can be taken from the names in the first row. * @@ -23,9 +23,7 @@ public class CDL { * Get the next value. The value can be wrapped in quotes. The value can be empty. * * @param x A JSONTokener of the source text. - * * @return The value string, or null if empty. - * * @throws JSONException if the quoted string is badly formed. */ private static String getValue(JSONTokener x) throws JSONException { @@ -66,9 +64,7 @@ public class CDL { * Produce a JSONArray of strings from a row of comma delimited values. * * @param x A JSONTokener of the source text. - * * @return A JSONArray of strings. - * * @throws JSONException */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { @@ -102,9 +98,7 @@ public class CDL { * @param names A JSONArray of names. This is commonly obtained from the first row of a comma delimited text file * using the rowToJSONArray method. * @param x A JSONTokener of the source text. - * * @return A JSONObject combining the names and values. - * * @throws JSONException */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { @@ -117,7 +111,6 @@ public class CDL { * Troublesome characters may be removed. * * @param ja A JSONArray of strings. - * * @return A string ending in NEWLINE. */ public static String rowToString(JSONArray ja) { @@ -129,8 +122,9 @@ public class CDL { Object object = ja.opt(i); if (object != null) { String string = object.toString(); - if (!string.isEmpty() && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || ( - string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) { + if (!string.isEmpty() && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) + || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) + == '"'))) { sb.append('"'); int length = string.length(); for (int j = 0; j < length; j += 1) { @@ -153,9 +147,7 @@ public class CDL { * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * * @param string The comma delimited text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { @@ -166,9 +158,7 @@ public class CDL { * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * * @param x The JSONTokener containing the comma delimited text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(JSONTokener x) throws JSONException { @@ -181,9 +171,7 @@ public class CDL { * * @param names A JSONArray of strings. * @param string The comma delimited text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException { @@ -196,9 +184,7 @@ public class CDL { * * @param names A JSONArray of strings. * @param x A JSONTokener of the source text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { @@ -224,9 +210,7 @@ public class CDL { * inspecting the first JSONObject. * * @param ja A JSONArray of JSONObjects. - * * @return A comma delimited text. - * * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { @@ -246,9 +230,7 @@ public class CDL { * * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. - * * @return A comma delimited text. - * * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/Cookie.java b/Core/src/main/java/com/intellectualcrafters/json/Cookie.java index ef58c8e8a..827799d2f 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/Cookie.java +++ b/Core/src/main/java/com/intellectualcrafters/json/Cookie.java @@ -16,7 +16,6 @@ public class Cookie { * encode '=' and ';' because we must. We encode '%' and '+' because they are meta characters in URL encoding. * * @param string The source string. - * * @return The escaped result. */ public static String escape(final String string) { @@ -36,7 +35,7 @@ public class Cookie { } return sb.toString(); } - + /** * Convert a cookie specification string into a JSONObject. The string will contain a name value pair separated by * '='. The name and the value will be unescaped, possibly converting '+' and '%' sequences. The cookie properties @@ -46,9 +45,7 @@ public class Cookie { * JSONObject. * * @param string The cookie specification string. - * * @return A JSONObject containing "name", "value", and possibly other members. - * * @throws JSONException */ public static JSONObject toJSONObject(final String string) throws JSONException { @@ -76,16 +73,14 @@ public class Cookie { } return jo; } - + /** * Convert a JSONObject into a cookie specification string. The JSONObject must contain "name" and "value" members. * If the JSONObject contains "expires", "domain", "path", or "secure" members, they will be appended to the cookie * specification string. All other members are ignored. * * @param jo A JSONObject - * * @return A cookie specification string - * * @throws JSONException */ public static String toString(final JSONObject jo) throws JSONException { @@ -105,13 +100,12 @@ public class Cookie { } return sb.toString(); } - + /** * Convert {@code %}hh sequences to single characters, and convert plus to space. * * @param string A string that may contain {@code +}  (plus) and %hh * sequences. - * * @return The unescaped string. */ public static String unescape(final String string) { diff --git a/Core/src/main/java/com/intellectualcrafters/json/CookieList.java b/Core/src/main/java/com/intellectualcrafters/json/CookieList.java index c0bf0f994..522e4e886 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/CookieList.java +++ b/Core/src/main/java/com/intellectualcrafters/json/CookieList.java @@ -13,14 +13,12 @@ public class CookieList { * Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated * from the values by '='. The pairs are separated by ';'. The names and the values will be unescaped, possibly * converting '+' and '%' sequences. - * + *

* To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * * @param string A cookie list string - * * @return A JSONObject - * * @throws JSONException */ public static JSONObject toJSONObject(final String string) throws JSONException { @@ -34,16 +32,14 @@ public class CookieList { } return jo; } - + /** * Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The names are separated * from the values by '='. The pairs are separated by ';'. The characters '%', '+', '=', and ';' in the names and * values are replaced by "%hh". * * @param jo A JSONObject - * * @return A cookie list string - * * @throws JSONException */ public static String toString(final JSONObject jo) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/HTTP.java b/Core/src/main/java/com/intellectualcrafters/json/HTTP.java index d95995b29..43abfc45d 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/HTTP.java +++ b/Core/src/main/java/com/intellectualcrafters/json/HTTP.java @@ -13,7 +13,7 @@ public class HTTP { * Carriage return/line feed. */ public static final String CRLF = "\r\n"; - + public static JSONObject toJSONObject(final String string) throws JSONException { final JSONObject jo = new JSONObject(); final HTTPTokener x = new HTTPTokener(string); @@ -40,11 +40,11 @@ public class HTTP { } return jo; } - + /** * Convert a JSONObject into an HTTP header. A request header must contain - * - * + *

+ *

*

      * {
      *    Method: "POST" (for example),
@@ -52,10 +52,10 @@ public class HTTP {
      *    "HTTP-Version": "HTTP/1.1" (for example)
      * }
      * 
- * + *

* A response header must contain - * - * + *

+ *

*

      * {
      *    "HTTP-Version": "HTTP/1.1" (for example),
@@ -63,13 +63,11 @@ public class HTTP {
      *    "Reason-Phrase": "OK" (for example)
      * }
      * 
- * + *

* Any other members of the JSONObject will be output as HTTP fields. The result will end with two CRLF pairs. * * @param jo A JSONObject - * * @return An HTTP header string. - * * @throws JSONException if the object does not contain enough information. */ public static String toString(final JSONObject jo) throws JSONException { @@ -96,7 +94,9 @@ public class HTTP { sb.append(CRLF); while (keys.hasNext()) { string = keys.next(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase" + .equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo + .isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); diff --git a/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java b/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java index 5a3fb1e56..2459c6e33 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java +++ b/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java @@ -15,12 +15,11 @@ public class HTTPTokener extends JSONTokener { public HTTPTokener(final String string) { super(string); } - + /** * Get the next token or string. This is used in parsing HTTP headers. * * @return A String. - * * @throws JSONException */ public String nextToken() throws JSONException { @@ -32,7 +31,7 @@ public class HTTPTokener extends JSONTokener { } while (Character.isWhitespace(c)); if ((c == '"') || (c == '\'')) { q = c; - for (;;) { + for (; ; ) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); @@ -43,7 +42,7 @@ public class HTTPTokener extends JSONTokener { sb.append(c); } } - for (;;) { + for (; ; ) { if ((c == 0) || Character.isWhitespace(c)) { return sb.toString(); } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java b/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java index 32b75bd01..33a53acb1 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java @@ -14,16 +14,16 @@ import java.util.Map; * accessing the values by index, and {@code put} methods for adding or replacing values. The values can be any of * these types: {@code Boolean}, {@code JSONArray}, {@code JSONObject}, {@code Number}, * {@code String}, or the {@code JSONObject.NULL object}. - * + *

*

The constructor can convert a JSON text into a Java object. The {@code toString} method converts to JSON text. - * + *

*

A {@code get} method returns a value if one can be found, and throws an exception if one cannot be found. An * {@code opt} method returns a default value instead of throwing an exception, and so is useful for obtaining * optional values. - * + *

*

The generic {@code get()} and {@code opt()} methods return an object which you can cast or query for type. * There are also typed {@code get} and {@code opt} methods that do type checking and type coercion for you. - * + *

*

The texts produced by the {@code toString} methods strictly conform to JSON syntax rules. The constructors are * more forgiving in the texts they will accept:

  • An extra {@code ,} (comma) may appear * just before the closing bracket.
  • The {@code null} value will be inserted when there is {@code ,} @@ -41,19 +41,18 @@ public class JSONArray { * The arrayList where the JSONArray's properties are kept. */ private final ArrayList myArrayList; - + /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList(); } - + /** * Construct a JSONArray from a JSONTokener. * * @param x A JSONTokener - * * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { @@ -63,7 +62,7 @@ public class JSONArray { } if (x.nextClean() != ']') { x.back(); - for (;;) { + for (; ; ) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); @@ -86,19 +85,18 @@ public class JSONArray { } } } - + /** * Construct a JSONArray from a source JSON text. * * @param source A string that begins with {@code [} (left bracket) and ends with * {@code ]}  (right bracket). - * * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } - + /** * Construct a JSONArray from a Collection. * @@ -112,7 +110,7 @@ public class JSONArray { } } } - + /** * Construct a JSONArray from an array * @@ -126,17 +124,16 @@ public class JSONArray { this.put(JSONObject.wrap(Array.get(array, i))); } } else { - throw new JSONException("JSONArray initial value should be a string or collection or array."); + throw new JSONException( + "JSONArray initial value should be a string or collection or array."); } } - + /** * Get the object value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return An object value. - * * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { @@ -146,69 +143,67 @@ public class JSONArray { } return object; } - + /** * Get the boolean value associated with an index. The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. - * * @return The truth. - * * @throws JSONException If there is no value for the index or if the value is not convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = get(index); - if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("false"))) { return false; - } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { + } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } - + /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return The value. - * * @throws JSONException If the key is not found or if the value cannot be converted to a number. */ public double getDouble(int index) throws JSONException { Object object = get(index); try { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } - + /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return The value. - * * @throws JSONException If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { Object object = get(index); try { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } - + /** * Get the JSONArray associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return A JSONArray value. - * * @throws JSONException If there is no value for the index. or if the value is not a JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { @@ -218,14 +213,12 @@ public class JSONArray { } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } - + /** * Get the JSONObject associated with an index. * * @param index subscript - * * @return A JSONObject value. - * * @throws JSONException If there is no value for the index or if the value is not a JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { @@ -235,32 +228,30 @@ public class JSONArray { } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } - + /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return The value. - * * @throws JSONException If the key is not found or if the value cannot be converted to a number. */ public long getLong(int index) throws JSONException { Object object = get(index); try { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } - + /** * Get the string associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return A string value. - * * @throws JSONException If there is no string value for the index. */ public String getString(int index) throws JSONException { @@ -270,26 +261,23 @@ public class JSONArray { } throw new JSONException("JSONArray[" + index + "] not a string."); } - + /** * Determine if the value is null. * * @param index The index must be between 0 and length() - 1. - * * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(opt(index)); } - + /** * Make a string from the contents of this JSONArray. The {@code separator} string is inserted between each * element. Warning: This method assumes that the data structure is acyclical. * * @param separator A string that will be inserted between the elements. - * * @return a string. - * * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { @@ -303,7 +291,7 @@ public class JSONArray { } return sb.toString(); } - + /** * Get the number of elements in the JSONArray, included nulls. * @@ -312,37 +300,34 @@ public class JSONArray { public int length() { return this.myArrayList.size(); } - + /** * Get the optional object value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { return ((index < 0) || (index >= length())) ? null : this.myArrayList.get(index); } - + /** * Get the optional boolean value associated with an index. It returns false if there is no value at that index, or * if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. - * * @return The truth. */ public boolean optBoolean(int index) { return this.optBoolean(index, false); } - + /** * Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that * index or if it is not a Boolean or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and length() - 1. * @param defaultValue A boolean default. - * * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { @@ -352,26 +337,24 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if * the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * * @return The value. */ public double optDouble(int index) { return this.optDouble(index, Double.NaN); } - + /** * Get the optional double value associated with an index. The defaultValue is returned if there is no value for the * index, or if the value is not a number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. - * * @return The value. */ public double optDouble(int index, double defaultValue) { @@ -381,26 +364,24 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional int value associated with an index. Zero is returned if there is no value for the index, or if * the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * * @return The value. */ public int optInt(int index) { return this.optInt(index, 0); } - + /** * Get the optional int value associated with an index. The defaultValue is returned if there is no value for the * index, or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. - * * @return The value. */ public int optInt(int index, int defaultValue) { @@ -410,52 +391,48 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional JSONArray associated with an index. * * @param index subscript - * * @return A JSONArray value, or null if the index has no value, or if the value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = opt(index); return o instanceof JSONArray ? (JSONArray) o : null; } - + /** * Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the * index has no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. - * * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = opt(index); return o instanceof JSONObject ? (JSONObject) o : null; } - + /** * Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if * the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * * @return The value. */ public long optLong(int index) { return this.optLong(index, 0); } - + /** * Get the optional long value associated with an index. The defaultValue * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. - * * @return The value. */ public long optLong(int index, long defaultValue) { @@ -465,66 +442,60 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value is not a * string and is not null, then it is converted to a string. * * @param index The index must be between 0 and length() - 1. - * * @return A String value. */ public String optString(int index) { return this.optString(index, ""); } - + /** * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. - * * @return A String value. */ public String optString(int index, String defaultValue) { Object object = opt(index); return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); } - + /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. - * * @return this. */ public JSONArray put(boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param value A Collection value. - * * @return this. */ public JSONArray put(Collection value) { this.put(new JSONArray(value)); return this; } - + /** * Append a double value. This increases the array's length by one. * * @param value A double value. - * * @return this. - * * @throws JSONException if the value is not finite. */ public JSONArray put(double value) throws JSONException { @@ -533,90 +504,82 @@ public class JSONArray { this.put(d); return this; } - + /** * Append an int value. This increases the array's length by one. * * @param value An int value. - * * @return this. */ public JSONArray put(int value) { this.put(Integer.valueOf(value)); return this; } - + /** * Append an long value. This increases the array's length by one. * * @param value A long value. - * * @return this. */ public JSONArray put(long value) { this.put(Long.valueOf(value)); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param value A Map value. - * * @return this. */ public JSONArray put(Map value) { this.put(new JSONObject(value)); return this; } - + /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * + * Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } - + /** * Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then * null elements will be added as necessary to pad it out. * * @param index The subscript. * @param value A boolean value. - * * @return this. - * * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param index The subscript. * @param value A Collection value. - * * @return this. - * * @throws JSONException If the index is negative or if the value is not - * finite. + * finite. */ public JSONArray put(int index, Collection value) throws JSONException { this.put(index, new JSONArray(value)); return this; } - + /** * Put or replace a double value. If the index is greater than the length * of the JSONArray, then null elements will be added as necessary to pad @@ -624,66 +587,58 @@ public class JSONArray { * * @param index The subscript. * @param value A double value. - * * @return this. - * * @throws JSONException If the index is negative or if the value is not - * finite. + * finite. */ public JSONArray put(int index, double value) throws JSONException { this.put(index, new Double(value)); return this; } - + /** * Put or replace an int value. If the index is greater than the length of the JSONArray, then null elements will be * added as necessary to pad it out. * * @param index The subscript. * @param value An int value. - * * @return this. - * * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { this.put(index, Integer.valueOf(value)); return this; } - + /** * Put or replace a long value. If the index is greater than the length of the JSONArray, then null elements will be * added as necessary to pad it out. * * @param index The subscript. * @param value A long value. - * * @return this. - * * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { this.put(index, Long.valueOf(value)); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONObject that * is produced from a Map. * * @param index The subscript. * @param value The Map value. - * * @return this. - * * @throws JSONException If the index is negative or if the the value is an - * invalid number. + * invalid number. */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); return this; } - + /** * Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then * null elements will be added as necessary to pad it out. @@ -691,9 +646,7 @@ public class JSONArray { * @param index The subscript. * @param value The value to put into the array. The value should be a Boolean, Double, Integer, JSONArray, * JSONObject, Long, or String, or the JSONObject.NULL object. - * * @return this. - * * @throws JSONException If the index is negative or if the the value is an invalid number. */ public JSONArray put(int index, Object value) throws JSONException { @@ -711,23 +664,21 @@ public class JSONArray { } return this; } - + /** * Remove an index and close the hole. * * @param index The index of the element to be removed. - * * @return The value that was associated with the index, or null if there was no value. */ public Object remove(int index) { return (index >= 0) && (index < length()) ? this.myArrayList.remove(index) : null; } - + /** * Determine if two JSONArrays are similar. They must contain similar sequences. * * @param other The other JSONArray - * * @return true if they are equal */ public boolean similar(Object other) { @@ -755,14 +706,12 @@ public class JSONArray { } return true; } - + /** * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray. * * @param names A JSONArray containing a list of key strings. These will be paired with the values. - * * @return A JSONObject, or null if there are no names or if this JSONArray has no values. - * * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { @@ -775,35 +724,32 @@ public class JSONArray { } return jo; } - + /** * Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to * produce a syntactically correct JSON text then null will be returned instead. This could occur if the array * contains an invalid number. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the array. */ - @Override - public String toString() { + @Override public String toString() { try { return this.toString(0); } catch (JSONException ignored) { return null; } } - + /** * Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is * acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. - * * @return a printable, displayable, transmittable representation of the object, beginning with * {@code [} (left bracket) and ending with {@code ]}  (right * bracket). - * * @throws JSONException */ public String toString(int indentFactor) throws JSONException { @@ -812,30 +758,27 @@ public class JSONArray { return this.write(sw, indentFactor, 0).toString(); } } - + /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } - + /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. * @param indent The indention of the top level. - * * @return The writer. - * * @throws JSONException */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONException.java b/Core/src/main/java/com/intellectualcrafters/json/JSONException.java index 0d2acb352..8fd9f88da 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONException.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONException.java @@ -9,7 +9,7 @@ package com.intellectualcrafters.json; public class JSONException extends RuntimeException { private static final long serialVersionUID = 0; private Throwable cause; - + /** * Constructs a JSONException with an explanatory message. * @@ -18,7 +18,7 @@ public class JSONException extends RuntimeException { public JSONException(final String message) { super(message); } - + /** * Constructs a new JSONException with the specified cause. * @@ -28,14 +28,13 @@ public class JSONException extends RuntimeException { super(cause.getMessage()); this.cause = cause; } - + /** * Returns the cause of this exception or null if the cause is nonexistent or unknown. * * @return the cause of this exception or null if the cause is nonexistent or unknown. */ - @Override - public Throwable getCause() { + @Override public Throwable getCause() { return cause; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONML.java b/Core/src/main/java/com/intellectualcrafters/json/JSONML.java index 0b1f9ece4..5153a38a5 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONML.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONML.java @@ -16,12 +16,11 @@ public class JSONML { * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null if we are at the outermost level. - * * @return A JSONArray if the value is the outermost tag, otherwise null. - * * @throws JSONException */ - private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { + private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) + throws JSONException { String attribute; char c; String closeTag = null; @@ -47,7 +46,8 @@ public class JSONML { // Close tag 0)) { @@ -180,22 +182,20 @@ public class JSONML { } } } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each * XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then * the second element will be JSONObject containing the name/value pairs. If the tag contains children, then strings * * @param string The source string. - * * @return A JSONArray containing the structured data from the XML string. - * * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each * XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then @@ -204,58 +204,50 @@ public class JSONML { * are ignored. * * @param x An XMLTokener. - * * @return A JSONArray containing the structured data from the XML string. - * * @throws JSONException */ public static JSONArray toJSONArray(XMLTokener x) throws JSONException { return (JSONArray) parse(x, true, null); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * property which will be an array of strings and JsonML JSONObjects. - * + *

    * Comments, prologs, DTDs, and <[ [ ]]> are ignored. * * @param x An XMLTokener of the XML source text. - * * @return A JSONObject containing the structured data from the XML string. - * * @throws JSONException */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { return (JSONObject) parse(x, false, null); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * property which will be an array of strings and JsonML JSONObjects. - * + *

    * Comments, prologs, DTDs, and <[ [ ]]> are ignored. * * @param string The XML source text. - * * @return A JSONObject containing the structured data from the XML string. - * * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } - + /** * Reverse the JSONML transformation, making an XML text from a JSONArray. * * @param ja A JSONArray. - * * @return An XML string. - * * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { @@ -323,16 +315,14 @@ public class JSONML { } return sb.toString(); } - + /** * Reverse the JSONML transformation, making an XML text from a JSONObject. The JSONObject must contain a "tagName" * property. If it has children, then it must have a "childNodes" property containing an array of objects. The other * properties are attributes with string values. * * @param jo A JSONObject. - * * @return An XML string. - * * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java b/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java index 685e15fd8..4e7d06e84 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java @@ -7,15 +7,8 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.ResourceBundle; -import java.util.Set; /** * A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces @@ -28,21 +21,21 @@ import java.util.Set; * values into a JSON text using the put and toString methods. A get method * returns a value if one can be found, and throws an exception if one cannot be found. An opt method * returns a default value instead of throwing an exception, and so is useful for obtaining optional values. - * + *

    * The generic get() and opt() methods return an object, which you can cast or query for type. * There are also typed get and opt methods that do type checking and type coercion for you. * The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such * as null. - * + *

    * The put methods add or replace values in an object. For example, - * - * + *

    + *

    *

      * myString = new JSONObject().put("JSON", "Hello, World!").toString();
      * 
    - * + *

    * produces the string {"JSON": "Hello, World"}. - * + *

    * The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors * are more forgiving in the texts they will accept:

    • An extra , (comma) may * appear just before the closing brace.
    • Strings may be quoted with ' (single @@ -65,21 +58,20 @@ public class JSONObject { * The map where the JSONObject's properties are kept. */ private final Map map; - + /** * Construct an empty JSONObject. */ public JSONObject() { this.map = new HashMap(); } - + /** * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to identify the keys that * should be copied. Missing keys are ignored. * * @param jo A JSONObject. * @param names An array of strings. - * * @throws JSONException * @throws JSONException If a value is a non-finite number or if a name is duplicated. */ @@ -88,15 +80,15 @@ public class JSONObject { for (String name : names) { try { putOnce(name, jo.opt(name)); - } catch (JSONException ignore) {} + } catch (JSONException ignore) { + } } } - + /** * Construct a JSONObject from a JSONTokener. * * @param x A JSONTokener object containing the source string. - * * @throws JSONException If there is a syntax error in the source string or a duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { @@ -106,7 +98,7 @@ public class JSONObject { if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } - for (;;) { + for (; ; ) { c = x.nextClean(); switch (c) { case 0: @@ -139,12 +131,11 @@ public class JSONObject { } } } - + /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of the JSONObject. - * * @throws JSONException */ public JSONObject(Map map) { @@ -158,16 +149,16 @@ public class JSONObject { } } } - + /** * Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting with "get" or "is" * followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. - * + *

      * The key is formed by removing the "get" or "is" prefix. If the second remaining * character is not upper case, then the first character is converted to lower case. - * + *

      * For example, if an object has a method named "getPluginName", and if the result of calling * object.getPluginName() is "Larry Fine", then the JSONObject will contain "name": "Larry * Fine". @@ -178,7 +169,7 @@ public class JSONObject { this(); populateMap(bean); } - + /** * Construct a JSONObject from an Object, using reflection to find the public members. The resulting JSONObject's * keys will be the strings from the names array, and the values will be the field values associated with those keys @@ -193,33 +184,33 @@ public class JSONObject { for (String name : names) { try { putOpt(name, c.getField(name).get(object)); - } catch (JSONException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) {} + } catch (JSONException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) { + } } } - + /** * Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor. * * @param source A string beginning with { (left brace) and ending with * }  (right brace). - * * @throws JSONException If there is a syntax error in the source string or a duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } - + /** * Construct a JSONObject from a ResourceBundle. * * @param baseName The ResourceBundle base name. * @param locale The Locale to load the ResourceBundle for. - * * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); + ResourceBundle bundle = ResourceBundle + .getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { @@ -246,12 +237,11 @@ public class JSONObject { } } } - + /** * Produce a string from a double. The string "null" will be returned if the number is not finite. * * @param d A double. - * * @return A String. */ public static String doubleToString(double d) { @@ -270,7 +260,7 @@ public class JSONObject { } return string; } - + /** * Get an array of field names from a JSONObject. * @@ -290,7 +280,7 @@ public class JSONObject { } return names; } - + /** * Get an array of field names from an Object. * @@ -312,14 +302,12 @@ public class JSONObject { } return names; } - + /** * Produce a string from a Number. * * @param number A Number - * * @return A String. - * * @throws JSONException If n is a non-finite number. */ public static String numberToString(Number number) throws JSONException { @@ -339,13 +327,12 @@ public class JSONObject { } return string; } - + /** * Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted * control character or an unescaped quote or backslash. * * @param string A String - * * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { @@ -402,7 +389,8 @@ public class JSONObject { w.write("\\r"); break; default: - if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) { + if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c + < '\u2100'))) { w.write("\\u"); hhhh = Integer.toHexString(c); w.write("0000", 0, 4 - hhhh.length()); @@ -415,12 +403,11 @@ public class JSONObject { w.write('"'); return w; } - + /** * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. * * @param string A String. - * * @return A simple JSON value. */ public static Object stringToValue(String string) { @@ -444,7 +431,8 @@ public class JSONObject { char b = string.charAt(0); if (((b >= '0') && (b <= '9')) || (b == '-')) { try { - if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1)) { + if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') + > -1)) { d = Double.valueOf(string); if (!d.isInfinite() && !d.isNaN()) { return d; @@ -459,16 +447,16 @@ public class JSONObject { } } } - } catch (NumberFormatException ignore) {} + } catch (NumberFormatException ignore) { + } } return string; } - + /** * Throw an exception if the object is a NaN or infinite number. * * @param o The object to test. - * * @throws JSONException If o is a non-finite number. */ public static void testValidity(Object o) throws JSONException { @@ -484,7 +472,7 @@ public class JSONObject { } } } - + /** * Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be * used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does @@ -492,16 +480,14 @@ public class JSONObject { * If the value is an array or Collection, then a JSONArray will be made from it and its toJSONString method will be * called. If the value is a MAP, then a JSONObject will be made from it and its toJSONString method will be called. * Otherwise, the value's toString method will be called, and the result will be quoted. - * - * + *

      + *

      * Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. - * * @return a printable, displayable, transmittable representation of the object, beginning with * { (left brace) and ending with } (right * brace). - * * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { @@ -523,7 +509,8 @@ public class JSONObject { if (value instanceof Number) { return numberToString((Number) value); } - if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { + if ((value instanceof Boolean) || (value instanceof JSONObject) + || (value instanceof JSONArray)) { return value.toString(); } if (value instanceof Map) { @@ -537,7 +524,7 @@ public class JSONObject { } return quote(value.toString()); } - + /** * Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection, * wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et @@ -545,7 +532,6 @@ public class JSONObject { * if it doesn't, try to wrap it in a JSONObject. If the wrapping fails, then null is returned. * * @param object The object to wrap - * * @return The wrapped value */ public static Object wrap(Object object) { @@ -553,19 +539,12 @@ public class JSONObject { if (object == null) { return NULL; } - if ((object instanceof JSONObject) - || (object instanceof JSONArray) - || NULL.equals(object) - || (object instanceof JSONString) - || (object instanceof Byte) - || (object instanceof Character) - || (object instanceof Short) - || (object instanceof Integer) - || (object instanceof Long) - || (object instanceof Boolean) - || (object instanceof Float) - || (object instanceof Double) - || (object instanceof String)) { + if ((object instanceof JSONObject) || (object instanceof JSONArray) || NULL + .equals(object) || (object instanceof JSONString) || (object instanceof Byte) + || (object instanceof Character) || (object instanceof Short) + || (object instanceof Integer) || (object instanceof Long) + || (object instanceof Boolean) || (object instanceof Float) + || (object instanceof Double) || (object instanceof String)) { return object; } if (object instanceof Collection) { @@ -579,7 +558,8 @@ public class JSONObject { } Package objectPackage = object.getClass().getPackage(); String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; - if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) { + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || ( + object.getClass().getClassLoader() == null)) { return object.toString(); } return new JSONObject(object); @@ -588,7 +568,8 @@ public class JSONObject { } } - static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { + static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) + throws JSONException, IOException { if ((value == null) || value.equals(null)) { writer.write("null"); } else if (value instanceof JSONObject) { @@ -624,20 +605,18 @@ public class JSONObject { writer.write(' '); } } - + /** * Accumulate values under a key. It is similar to the put method except that if there is already an object stored * under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already * a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. - * + *

      * If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if * multiple values are accumulated, then the result will be like append. * * @param key A key string. * @param value An object to be accumulated under the key. - * * @return this. - * * @throws JSONException If the value is an invalid number or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { @@ -652,7 +631,7 @@ public class JSONObject { } return this; } - + /** * Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the * JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated @@ -660,9 +639,7 @@ public class JSONObject { * * @param key A key string. * @param value An object to be accumulated under the key. - * * @return this. - * * @throws JSONException If the key is null or if the current value associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { @@ -677,14 +654,12 @@ public class JSONObject { } return this; } - + /** * Get the value object associated with a key. * * @param key A key string. - * * @return The object associated with the key. - * * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { @@ -697,70 +672,68 @@ public class JSONObject { } return object; } - + /** * Get the boolean value associated with a key. * * @param key A key string. - * * @return The truth. - * * @throws JSONException if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object object = get(key); - if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("false"))) { return false; - } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { + } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } - + /** * Get the double value associated with a key. * * @param key A key string. - * * @return The numeric value. - * * @throws JSONException if the key is not found or if the value is not a Number object and cannot be converted to a * number. */ public double getDouble(String key) throws JSONException { Object object = get(key); try { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } - + /** * Get the int value associated with a key. * * @param key A key string. - * * @return The integer value. - * * @throws JSONException if the key is not found or if the value cannot be converted to an integer. */ public int getInt(String key) throws JSONException { Object object = get(key); try { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } } - + /** * Get the JSONArray value associated with a key. * * @param key A key string. - * * @return A JSONArray which is the value. - * * @throws JSONException if the key is not found or if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { @@ -770,14 +743,12 @@ public class JSONObject { } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } - + /** * Get the JSONObject value associated with a key. * * @param key A key string. - * * @return A JSONObject which is the value. - * * @throws JSONException if the key is not found or if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { @@ -787,32 +758,30 @@ public class JSONObject { } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } - + /** * Get the long value associated with a key. * * @param key A key string. - * * @return The long value. - * * @throws JSONException if the key is not found or if the value cannot be converted to a long. */ public long getLong(String key) throws JSONException { Object object = get(key); try { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } } - + /** * Get the string associated with a key. * * @param key A key string. - * * @return A string which is the value. - * * @throws JSONException if there is no string value for the key. */ public String getString(String key) throws JSONException { @@ -822,26 +791,23 @@ public class JSONObject { } throw new JSONException("JSONObject[" + quote(key) + "] not a string."); } - + /** * Determine if the JSONObject contains a specific key. * * @param key A key string. - * * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.map.containsKey(key); } - + /** * Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is * such a property, and if it is an Integer, Long, Double, or Float, then add one to it. * * @param key A key string. - * * @return this. - * * @throws JSONException If there is already a property with this name that is not an Integer, Long, Double, or * Float. */ @@ -862,18 +828,17 @@ public class JSONObject { } return this; } - + /** * Determine if the value associated with the key is null or if there is no value. * * @param key A key string. - * * @return true if there is no value associated with the key or if the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(opt(key)); } - + /** * Get an enumeration of the keys of the JSONObject. * @@ -882,7 +847,7 @@ public class JSONObject { public Iterator keys() { return keySet().iterator(); } - + /** * Get a set of keys of the JSONObject. * @@ -891,7 +856,7 @@ public class JSONObject { public Set keySet() { return this.map.keySet(); } - + /** * Get the number of keys stored in the JSONObject. * @@ -900,7 +865,7 @@ public class JSONObject { public int length() { return this.map.size(); } - + /** * Produce a JSONArray containing the names of the elements of this JSONObject. * @@ -914,37 +879,34 @@ public class JSONObject { } return ja.length() == 0 ? null : ja; } - + /** * Get an optional value associated with a key. * * @param key A key string. - * * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.map.get(key); } - + /** * Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. - * * @return The truth. */ public boolean optBoolean(String key) { return this.optBoolean(key, false); } - + /** * Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is * not a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. - * * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { @@ -954,26 +916,24 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If * the value is a string, an attempt will be made to evaluate it as a number. * * @param key A string which is the key. - * * @return An object which is the value. */ public double optDouble(String key) { return this.optDouble(key, Double.NaN); } - + /** * Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not * a number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. - * * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { @@ -983,26 +943,24 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. - * * @return An object which is the value. */ public int optInt(String key) { return this.optInt(key, 0); } - + /** * Get an optional int value associated with a key, or the default if there is no such key or if the value is not a * number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. - * * @return An object which is the value. */ public int optInt(String key, int defaultValue) { @@ -1012,52 +970,48 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not * a JSONArray. * * @param key A key string. - * * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray) o : null; } - + /** * Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not * a JSONObject. * * @param key A key string. - * * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object object = opt(key); return object instanceof JSONObject ? (JSONObject) object : null; } - + /** * Get an optional long value associated with a key, or zero if there is no such key or if the value is not a * number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. - * * @return An object which is the value. */ public long optLong(String key) { return this.optLong(key, 0); } - + /** * Get an optional long value associated with a key, or the default if there is no such key or if the value is not a * number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. - * * @return An object which is the value. */ public long optLong(String key, long defaultValue) { @@ -1067,25 +1021,23 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is * not a string and is not null, then it is converted to a string. * * @param key A key string. - * * @return A string which is the value. */ public String optString(String key) { return this.optString(key, ""); } - + /** * Get an optional string associated with a key. It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. - * * @return A string which is the value. */ public String optString(String key, String defaultValue) { @@ -1112,7 +1064,8 @@ public class JSONObject { } else if (name.startsWith("is")) { key = name.substring(2); } - if (!key.isEmpty() && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) { + if (!key.isEmpty() && Character.isUpperCase(key.charAt(0)) && ( + method.getParameterTypes().length == 0)) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { @@ -1124,100 +1077,89 @@ public class JSONObject { } } } - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignore) {} + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignore) { + } } } - + /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. - * * @return this. - * * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { this.put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } - + /** * Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection. * * @param key A key string. * @param value A Collection value. - * * @return this. - * * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { this.put(key, new JSONArray(value)); return this; } - + /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. - * * @return this. - * * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { this.put(key, new Double(value)); return this; } - + /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. - * * @return this. - * * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { this.put(key, Integer.valueOf(value)); return this; } - + /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. - * * @return this. - * * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { this.put(key, Long.valueOf(value)); return this; } - + /** * Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map. * * @param key A key string. * @param value A Map value. - * * @return this. - * * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { this.put(key, new JSONObject(value)); return this; } - + /** * Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if * it is present. @@ -1225,9 +1167,7 @@ public class JSONObject { * @param key A key string. * @param value An object which is the value. It should be of one of these types: Boolean, Double, Integer, * JSONArray, JSONObject, Long, String, or the JSONObject.NULL object. - * * @return this. - * * @throws JSONException If the value is non-finite number or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { @@ -1242,16 +1182,14 @@ public class JSONObject { } return this; } - + /** * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and only if there is * not already a member with that name. * * @param key string * @param value object - * * @return this. - * * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { @@ -1263,16 +1201,14 @@ public class JSONObject { } return this; } - + /** * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null. * * @param key A key string. * @param value An object which is the value. It should be of one of these types: Boolean, Double, Integer, * JSONArray, JSONObject, Long, String, or the JSONObject.NULL object. - * * @return this. - * * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { @@ -1281,24 +1217,22 @@ public class JSONObject { } return this; } - + /** * Remove a name and its value, if present. * * @param key The name to be removed. - * * @return The value that was associated with the name, or null if there was no value. */ public Object remove(String key) { return this.map.remove(key); } - + /** * Determine if two JSONObjects are similar. They must contain the same set of names which must be associated with * similar values. * * @param other The other JSONObject - * * @return true if they are equal */ public boolean similar(Object other) { @@ -1330,15 +1264,13 @@ public class JSONObject { return false; } } - + /** * Produce a JSONArray containing the values of the members of this JSONObject. * * @param names A JSONArray containing a list of key strings. This determines the sequence of the values in the * result. - * * @return A JSONArray of values. - * * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { @@ -1351,37 +1283,34 @@ public class JSONObject { } return ja; } - + /** * Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a * syntactically correct JSON text, then null will be returned instead. - * + *

      * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable representation of the object, beginning with * { (left brace) and ending with } (right * brace). */ - @Override - public String toString() { + @Override public String toString() { try { return this.toString(0); } catch (JSONException ignored) { return null; } } - + /** * Make a prettyprinted JSON text of this JSONObject. - * + *

      * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. - * * @return a printable, displayable, portable, transmittable representation of the object, beginning with * { (left brace) and ending with } (right * brace). - * * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { @@ -1390,27 +1319,25 @@ public class JSONObject { return this.write(w, indentFactor, 0).toString(); } } - + /** * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. - * + *

      * Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } - + /** * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. - * + *

      * Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * * @throws JSONException */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { @@ -1457,7 +1384,7 @@ public class JSONObject { throw new JSONException(exception); } } - + /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the * value that JavaScript calls undefined. @@ -1468,34 +1395,30 @@ public class JSONObject { * * @return NULL. */ - @Override - protected final Object clone() { + @Override protected final Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ignored) { return this; } } - + /** * A Null object is equal to the null value and to itself. * * @param object An object to test for nullness. - * * @return true if the object parameter is the JSONObject.NULL object or null. */ - @Override - public boolean equals(Object object) { + @Override public boolean equals(Object object) { return (object == null) || (object == this); } - + /** * Get the "null" string value. * * @return The string "null". */ - @Override - public String toString() { + @Override public String toString() { return "null"; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java b/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java index ecacb861e..d668bcb5e 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java @@ -6,28 +6,28 @@ import java.io.StringWriter; * JSONStringer provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. - * + *

      * A JSONStringer instance provides a value method for appending values to the text, and a key * method for adding keys before values in objects. There are array and endArray methods that * make and bound array values, and object and endObject methods which make and bound object * values. All of these methods return the JSONWriter instance, permitting cascade style. For example, - * - * + *

      + *

      *

        * myString = new JSONStringer().object().key("JSON").value("Hello,
        * World!").endObject().toString();
        * 
      - * + *

      * which produces the string - * - * + *

      + *

      *

        * {"JSON":"Hello, World!"}
        * 
      - * + *

      * The first method called must be array or object. There are no methods for adding commas or * colons. JSONStringer adds them for you. Objects and arrays can be nested up to 20 levels deep. - * + *

      * This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org @@ -40,7 +40,7 @@ public class JSONStringer extends JSONWriter { public JSONStringer() { super(new StringWriter()); } - + /** * Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return * null if there was a problem in the construction of the JSON text (such as the calls to @@ -48,8 +48,7 @@ public class JSONStringer extends JSONWriter { * * @return The JSON text. */ - @Override - public String toString() { + @Override public String toString() { return mode == 'd' ? writer.toString() : null; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java b/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java index fa23fb91d..e6e3fef0c 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java @@ -1,11 +1,6 @@ package com.intellectualcrafters.json; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; /** * A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and @@ -22,7 +17,7 @@ public class JSONTokener { private long line; private char previous; private boolean usePrevious; - + /** * Construct a JSONTokener from a Reader. * @@ -37,7 +32,7 @@ public class JSONTokener { character = 1; line = 1; } - + /** * Construct a JSONTokener from an InputStream. * @@ -46,7 +41,7 @@ public class JSONTokener { public JSONTokener(final InputStream inputStream) throws JSONException { this(new InputStreamReader(inputStream)); } - + /** * Construct a JSONTokener from a string. * @@ -55,12 +50,11 @@ public class JSONTokener { public JSONTokener(final String s) { this(new StringReader(s)); } - + /** * Get the hex value of a character (base16). * * @param c A character between '0' and '9' or between 'A' and 'F' or between 'a' and 'f'. - * * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(final char c) { @@ -75,7 +69,7 @@ public class JSONTokener { } return -1; } - + /** * Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter * before attempting to parse the next number or identifier. @@ -89,11 +83,11 @@ public class JSONTokener { usePrevious = true; eof = false; } - + public boolean end() { return eof && !usePrevious; } - + /** * Determine if the source string still contains characters that next() can consume. * @@ -107,7 +101,7 @@ public class JSONTokener { back(); return true; } - + /** * Get the next character in the source string. * @@ -142,14 +136,12 @@ public class JSONTokener { previous = (char) c; return previous; } - + /** * Consume the next character, and check that it matches a specified character. * * @param c The character to match. - * * @return The character. - * * @throws JSONException if the character does not match. */ public char next(final char c) throws JSONException { @@ -159,14 +151,12 @@ public class JSONTokener { } return n; } - + /** * Get the next n characters. * * @param n The number of characters to take. - * * @return A string of n characters. - * * @throws JSONException Substring bounds error if there are not n characters remaining in the source string. */ public String next(final int n) throws JSONException { @@ -184,38 +174,35 @@ public class JSONTokener { } return new String(chars); } - + /** * Get the next char in the string, skipping whitespace. * * @return A character, or 0 if there are no more characters. - * * @throws JSONException */ public char nextClean() throws JSONException { - for (;;) { + for (; ; ) { final char c = this.next(); if ((c == 0) || (c > ' ')) { return c; } } } - + /** * Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format * does not allow strings in single quotes, but an implementation is allowed to accept them. * * @param quote The quoting character, either "  (double quote) or ' *  (single quote). - * * @return A String. - * * @throws JSONException Unterminated string. */ public String nextString(final char quote) throws JSONException { char c; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); switch (c) { case 0: @@ -261,17 +248,16 @@ public class JSONTokener { } } } - + /** * Get the text up but not including the specified character or the end of line, whichever comes first. * * @param delimiter A delimiter character. - * * @return A string. */ public String nextTo(final char delimiter) throws JSONException { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { final char c = this.next(); if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) { if (c != 0) { @@ -282,19 +268,18 @@ public class JSONTokener { sb.append(c); } } - + /** * Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes * first. * * @param delimiters A set of delimiter characters. - * * @return A string, trimmed. */ public String nextTo(final String delimiters) throws JSONException { char c; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) { if (c != 0) { @@ -305,13 +290,12 @@ public class JSONTokener { sb.append(c); } } - + /** * Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * * @return An object. - * * @throws JSONException If syntax error. */ public Object nextValue() throws JSONException { @@ -347,13 +331,12 @@ public class JSONTokener { } return JSONObject.stringToValue(string); } - + /** * Skip characters until the next character is the requested character. If the requested character is not found, no * characters are skipped. * * @param to A character to skip to. - * * @return The requested character, or zero if the requested character is not found. */ public char skipTo(final char to) throws JSONException { @@ -379,25 +362,23 @@ public class JSONTokener { back(); return c; } - + /** * Make a JSONException to signal a syntax error. * * @param message The error message. - * * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(final String message) { return new JSONException(message + toString()); } - + /** * Make a printable string of this JSONTokener. * * @return " at {index} [character {character} line {line}]" */ - @Override - public String toString() { + @Override public String toString() { return " at " + index + " [character " + character + " line " + line + "]"; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java b/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java index 44f893ce6..a70c0f9d9 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java +++ b/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java @@ -7,27 +7,27 @@ import java.io.Writer; * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. - * + *

      * A JSONWriter instance provides a value method for appending values to the text, and a key * method for adding keys before values in objects. There are array and endArray methods that * make and bound array values, and object and endObject methods which make and bound object * values. All of these methods return the JSONWriter instance, permitting a cascade style. For example, - * - * + *

      + *

      *

        * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
        * 
      - * + *

      * which writes - * - * + *

      + *

      *

        * {"JSON":"Hello, World!"}
        * 
      - * + *

      * The first method called must be array or object. There are no methods for adding commas or * colons. JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep. - * + *

      * This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org @@ -55,7 +55,7 @@ public class JSONWriter { * The stack top index. A value of 0 indicates that the stack is empty. */ private int top; - + /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ @@ -66,14 +66,12 @@ public class JSONWriter { top = 0; writer = w; } - + /** * Append a value. * * @param string A string value. - * * @return this - * * @throws JSONException If the value is out of sequence. */ private JSONWriter append(final String string) throws JSONException { @@ -97,13 +95,12 @@ public class JSONWriter { } throw new JSONException("Value out of sequence."); } - + /** * Begin appending a new array. All values until the balancing endArray will be appended to this array. * The endArray method must be called to mark the array's end. * * @return this - * * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as * a key or after the end of the outermost array or object). */ @@ -116,15 +113,13 @@ public class JSONWriter { } throw new JSONException("Misplaced array."); } - + /** * End something. * * @param mode Mode * @param c Closing character - * * @return this - * * @throws JSONException If unbalanced. */ private JSONWriter end(final char mode, final char c) throws JSONException { @@ -140,37 +135,33 @@ public class JSONWriter { comma = true; return this; } - + /** * End an array. This method most be called to balance calls to array. * * @return this - * * @throws JSONException If incorrectly nested. */ public JSONWriter endArray() throws JSONException { return end('a', ']'); } - + /** * End an object. This method most be called to balance calls to object. * * @return this - * * @throws JSONException If incorrectly nested. */ public JSONWriter endObject() throws JSONException { return end('k', '}'); } - + /** * Append a key. The key will be associated with the next value. In an object, every value must be preceded by a * key. * * @param string A key string. - * * @return this - * * @throws JSONException If the key is out of place. For example, keys do not belong in arrays or if the key is * null. */ @@ -195,13 +186,12 @@ public class JSONWriter { } throw new JSONException("Misplaced key."); } - + /** * Begin appending a new object. All keys and values until the balancing endObject will be appended to * this object. The endObject method must be called to mark the object's end. * * @return this - * * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as * a key or after the end of the outermost array or object). */ @@ -217,12 +207,11 @@ public class JSONWriter { } throw new JSONException("Misplaced object."); } - + /** * Pop an array or object scope. * * @param c The scope to close. - * * @throws JSONException If nesting is wrong. */ private void pop(final char c) throws JSONException { @@ -236,12 +225,11 @@ public class JSONWriter { top -= 1; mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k'; } - + /** * Push an array or object scope. * * @param jo The scope to open. - * * @throws JSONException If nesting is too deep. */ private void push(final JSONObject jo) throws JSONException { @@ -252,54 +240,46 @@ public class JSONWriter { mode = jo == null ? 'a' : 'k'; top += 1; } - + /** * Append either the value true or the value false . * * @param b A boolean. - * * @return this - * * @throws JSONException */ public JSONWriter value(final boolean b) throws JSONException { return append(b ? "true" : "false"); } - + /** * Append a double value. * * @param d A double. - * * @return this - * * @throws JSONException If the number is not finite. */ public JSONWriter value(final double d) throws JSONException { return this.value(new Double(d)); } - + /** * Append a long value. * * @param l A long. - * * @return this - * * @throws JSONException */ public JSONWriter value(final long l) throws JSONException { return append(Long.toString(l)); } - + /** * Append an object value. * * @param object The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an * object that implements JSONString. - * * @return this - * * @throws JSONException If the value is out of sequence. */ public JSONWriter value(final Object object) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/Kim.java b/Core/src/main/java/com/intellectualcrafters/json/Kim.java index 7209e26c3..7ad4e98e0 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/Kim.java +++ b/Core/src/main/java/com/intellectualcrafters/json/Kim.java @@ -5,22 +5,22 @@ package com.intellectualcrafters.json; * byte. The last byte of a character never has the MSB reset. Every byte that is not the last byte has the MSB set. Kim * stands for "Keep it minimal". A Unicode character is never longer than 3 bytes. Every byte contributes 7 bits to the * character. ASCII is unmodified. - * + *

      * Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF U+FFFF four bytes U+10FFFF - * + *

      * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one byte smaller when encoded in Kim compared * to UTF-8. - * + *

      * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, Avestan, Balinese, Batak, Bopomofo, * Buginese, Buhid, Carian, Cherokee, Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, Glagolitic, * Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, * Lycian, Lydian, Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old Turkic, Oriya, * Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. - * + *

      * A kim object can be constructed from an ordinary UTF-16 string, or from a byte array. A kim object can produce a * UTF-16 string. - * + *

      * As with UTF-8, it is possible to detect character boundaries within a byte sequence. UTF-8 is one of the world's * great inventions. While Kim is more efficient, it is not clear that it is worth the expense of transition. * @@ -43,7 +43,7 @@ public class Kim { * The memoization of toString(). */ private String string = null; - + /** * Make a kim from a portion of a byte array. * @@ -70,7 +70,7 @@ public class Kim { hashcode += sum << 16; } } - + /** * Make a kim from a byte array. * @@ -80,7 +80,7 @@ public class Kim { public Kim(final byte[] bytes, final int length) { this(bytes, 0, length); } - + /** * Make a new kim from a substring of an existing kim. The coordinates are in byte units, not character units. * @@ -91,12 +91,11 @@ public class Kim { public Kim(final Kim kim, final int from, final int thru) { this(kim.bytes, from, thru); } - + /** * Make a kim from a string. * * @param string The string. - * * @throws JSONException if surrogate pair mismatch. */ public Kim(final String string) throws JSONException { @@ -151,7 +150,8 @@ public class Kim { } else { if ((character >= 0xD800) && (character <= 0xDBFF)) { i += 1; - character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; + character = + (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; } b = 0x80 | (character >>> 14); bytes[at] = (byte) b; @@ -173,14 +173,12 @@ public class Kim { hashcode += sum << 16; } } - + /** * Returns the number of bytes needed to contain the character in Kim format. * * @param character a Unicode character between 0 and 0x10FFFF. - * * @return 1, 2, or 3 - * * @throws JSONException if the character is not representable in a kim. */ public static int characterSize(final int character) throws JSONException { @@ -189,15 +187,14 @@ public class Kim { } return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; } - + /** * Returns the character at the specified index. The index refers to byte values and ranges from 0 to length - 1. * The index of the next character is at index + Kim.characterSize(kim.characterAt(index)). * * @param at the index of the char value. The first character is at 0. - * - * @throws JSONException if at does not point to a valid character. * @return a Unicode character between 0 and 0x10FFFF. + * @throws JSONException if at does not point to a valid character. */ public int characterAt(final int at) throws JSONException { final int c = get(at); @@ -214,35 +211,33 @@ public class Kim { } else { final int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; - if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) { + if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ( + (character < 0xD800) || (character > 0xDFFF))) { return character; } } throw new JSONException("Bad character at " + at); } - + /** * Copy the contents of this kim to a byte array. * * @param bytes A byte array of sufficient size. * @param at The position within the byte array to take the byes. - * * @return The position immediately after the copy. */ public int copy(final byte[] bytes, final int at) { System.arraycopy(this.bytes, 0, bytes, at, length); return at + length; } - + /** * Two kim objects containing exactly the same bytes in the same order are equal to each other. * * @param obj the other kim with which to compare. - * * @return true if this and obj are both kim objects containing identical byte sequences. */ - @Override - public boolean equals(final Object obj) { + @Override public boolean equals(final Object obj) { if (!(obj instanceof Kim)) { return false; } @@ -255,14 +250,12 @@ public class Kim { } return java.util.Arrays.equals(bytes, that.bytes); } - + /** * Get a byte from a kim. * * @param at The position of the byte. The first byte is at 0. - * * @return The byte. - * * @throws JSONException if there is no byte at that position. */ public int get(final int at) throws JSONException { @@ -271,25 +264,22 @@ public class Kim { } return (bytes[at]) & 0xFF; } - + /** * Returns a hash code value for the kim. */ - @Override - public int hashCode() { + @Override public int hashCode() { return hashcode; } - + /** * Produce a UTF-16 String from this kim. The number of codepoints in the string will not be greater than the number * of bytes in the kim, although it could be less. * * @return The string. A kim memoizes its string representation. - * * @throws JSONException if the kim is not valid. */ - @Override - public String toString() throws JSONException { + @Override public String toString() throws JSONException { if (string == null) { int c; int length = 0; diff --git a/Core/src/main/java/com/intellectualcrafters/json/Property.java b/Core/src/main/java/com/intellectualcrafters/json/Property.java index cef76fc83..f248e98ee 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/Property.java +++ b/Core/src/main/java/com/intellectualcrafters/json/Property.java @@ -15,12 +15,11 @@ public class Property { * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. * * @param properties java.util.Properties - * * @return JSONObject - * * @throws JSONException */ - public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException { + public static JSONObject toJSONObject(final java.util.Properties properties) + throws JSONException { final JSONObject jo = new JSONObject(); if ((properties != null) && !properties.isEmpty()) { final Enumeration enumProperties = properties.propertyNames(); @@ -31,14 +30,12 @@ public class Property { } return jo; } - + /** * Converts the JSONObject into a property file object. * * @param jo JSONObject - * * @return java.util.Properties - * * @throws JSONException */ public static Properties toProperties(final JSONObject jo) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/XML.java b/Core/src/main/java/com/intellectualcrafters/json/XML.java index 58ecb4407..5ec8e81ed 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/XML.java +++ b/Core/src/main/java/com/intellectualcrafters/json/XML.java @@ -46,12 +46,11 @@ class XML { } return sb.toString(); } - + /** * Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes. * * @param string A string. - * * @throws JSONException */ static void noSpace(String string) throws JSONException { @@ -65,19 +64,18 @@ class XML { } } } - + /** * Scan the content following the named tag, attaching it to the context. * * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. - * * @return true if the close tag is processed. - * * @throws JSONException */ - private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { + private static boolean parse(XMLTokener x, JSONObject context, String name) + throws JSONException { // Test for and skip past these forms: // // @@ -147,7 +145,7 @@ class XML { String tagName = (String) token; token = null; JSONObject jsonobject = new JSONObject(); - for (;;) { + for (; ; ) { if (token == null) { token = x.nextToken(); } @@ -178,7 +176,7 @@ class XML { return false; // Content, between <...> and } else if (token == GT) { - for (;;) { + for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { @@ -195,7 +193,8 @@ class XML { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); - } else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) { + } else if ((jsonobject.length() == 1) && (jsonobject.opt("content") + != null)) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); @@ -210,14 +209,13 @@ class XML { } } } - + /** * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. * This is much less ambitious than JSONObject.stringToValue, especially because it does not attempt to convert plus * forms, octal forms, hex forms, or E forms lacking decimal points. * * @param string A String. - * * @return A simple JSON value. */ static Object stringToValue(String string) { @@ -245,7 +243,8 @@ class XML { if (value.toString().equals(string)) { return value; } - } catch (NumberFormatException ignored) {} + } catch (NumberFormatException ignored) { + } } return string; } @@ -258,28 +257,24 @@ class XML { } return jo; } - + /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. - * * @return A string. - * * @throws JSONException */ public static String toString(Object object) throws JSONException { return toString(object, null); } - + /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. * @param tagName The optional name of the enclosing tag. - * * @return A string. - * * @throws JSONException */ public static String toString(Object object, String tagName) throws JSONException { @@ -369,8 +364,11 @@ class XML { return sb.toString(); } else { string = escape(object.toString()); - return (tagName == null) ? '"' + string + '"' : - string.isEmpty() ? '<' + tagName + "/>" : '<' + tagName + '>' + string + "'; + return (tagName == null) ? + '"' + string + '"' : + string.isEmpty() ? + '<' + tagName + "/>" : + '<' + tagName + '>' + string + "'; } } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java b/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java index 51f7ff639..ea36c3a06 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java +++ b/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java @@ -13,6 +13,7 @@ public class XMLTokener extends JSONTokener { * The table of entity values. It initially contains Character values for amp, apos, gt, lt, quot. */ public static final HashMap entity; + static { entity = new HashMap<>(8); entity.put("amp", XML.AMP); @@ -21,7 +22,7 @@ public class XMLTokener extends JSONTokener { entity.put("lt", XML.LT); entity.put("quot", XML.QUOT); } - + /** * Construct an XMLTokener from a string. * @@ -30,36 +31,35 @@ public class XMLTokener extends JSONTokener { public XMLTokener(final String s) { super(s); } - + /** * Get the text in the CDATA block. * * @return The string up to the ]]>. - * * @throws JSONException If the ]]> is not found. */ public String nextCDATA() throws JSONException { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { char c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); int i = sb.length() - 3; - if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) { + if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) + == '>')) { sb.setLength(i); return sb.toString(); } } } - + /** * Get the next XML outer token, trimming whitespace. There are two kinds of tokens: the '<' character which begins * a markup tag, and the content text between markup tags. * * @return A string, or a '<' Character, or null if there is no more source text. - * * @throws JSONException */ public Object nextContent() throws JSONException { @@ -74,7 +74,7 @@ public class XMLTokener extends JSONTokener { return XML.LT; } StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { if ((c == '<') || (c == 0)) { back(); return sb.toString().trim(); @@ -87,20 +87,18 @@ public class XMLTokener extends JSONTokener { c = next(); } } - + /** * Return the next entity. These entities are translated to Characters: & " > < * ". * * @param ampersand An ampersand character. - * * @return A Character or an entity String if the entity is not recognized. - * * @throws JSONException If missing ';' in XML entity. */ public Object nextEntity(final char ampersand) throws JSONException { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { final char c = next(); if (Character.isLetterOrDigit(c) || (c == '#')) { sb.append(Character.toLowerCase(c)); @@ -114,13 +112,12 @@ public class XMLTokener extends JSONTokener { final Object object = entity.get(string); return object != null ? object : ampersand + string + ';'; } - + /** * Returns the next XML meta token. This is used for skipping over and structures. * * @return Syntax characters (< > / = ! ?) are returned as Character, and strings and names are * returned as Boolean. We don't care what the values actually are. - * * @throws JSONException If a string is not properly closed or if the XML is badly structured. */ public Object nextMeta() throws JSONException { @@ -147,7 +144,7 @@ public class XMLTokener extends JSONTokener { case '"': case '\'': q = c; - for (;;) { + for (; ; ) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); @@ -157,7 +154,7 @@ public class XMLTokener extends JSONTokener { } } default: - for (;;) { + for (; ; ) { c = next(); if (Character.isWhitespace(c)) { return Boolean.TRUE; @@ -178,13 +175,12 @@ public class XMLTokener extends JSONTokener { } } } - + /** * Get the next XML Token. These tokens are found inside of angle brackets. It may be one of these characters: * / >= ! ? or it may be a string wrapped in single quotes or double quotes, or it may be a name. * * @return a String or a Character. - * * @throws JSONException If the XML is not well formed. */ public Object nextToken() throws JSONException { @@ -209,12 +205,12 @@ public class XMLTokener extends JSONTokener { return XML.BANG; case '?': return XML.QUEST; - // Quoted string + // Quoted string case '"': case '\'': q = c; sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); @@ -231,7 +227,7 @@ public class XMLTokener extends JSONTokener { default: // Name sb = new StringBuilder(); - for (;;) { + for (; ; ) { sb.append(c); c = next(); if (Character.isWhitespace(c)) { @@ -257,13 +253,12 @@ public class XMLTokener extends JSONTokener { } } } - + /** * Skip characters until past the requested string. If it is not found, we are left at the end of the source with a * result of false. * * @param to A string to skip past. - * * @throws JSONException */ public boolean skipPast(final String to) throws JSONException { @@ -283,7 +278,7 @@ public class XMLTokener extends JSONTokener { circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ - for (int offset = 0; ;) { + for (int offset = 0; ; ) { int j = offset; boolean b = true; /* Compare the circle buffer with the to string. */ diff --git a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java index 5ce7beb64..c59a6c04c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java @@ -5,17 +5,7 @@ import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; import com.intellectualcrafters.plot.logger.ILogger; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChatManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.block.QueueProvider; import java.io.File; @@ -25,24 +15,28 @@ public interface IPlotMain extends ILogger { /** * Log a message to console. + * * @param message The message to log */ void log(String message); /** * Get the `PlotSquared` directory. + * * @return The plugin directory */ File getDirectory(); /** * Get the directory containing all the worlds. + * * @return The directory containing the worlds */ File getWorldContainer(); /** * Wrap a player into a PlotPlayer object. + * * @param player The player to convert to a PlotPlayer * @return A PlotPlayer */ @@ -50,57 +44,65 @@ public interface IPlotMain extends ILogger { /** * Disable the implementation. - * + *

      *

        - *
      • If a full disable isn't feasibly, just disable what it can. + *
      • If a full disable isn't feasibly, just disable what it can. *
      */ void disable(); /** * Get the version of the PlotSquared being used. + * * @return the plugin version */ int[] getPluginVersion(); /** * Get the version of the PlotSquared being used as a string. + * * @return the plugin version as a string */ String getPluginVersionString(); /** * Usually PlotSquared + * * @return */ String getPluginName(); /** * Get the version of Minecraft that is running. + * * @return */ int[] getServerVersion(); /** * Get the NMS package prefix. + * * @return The NMS package prefix */ String getNMSPackage(); /** * Get the schematic handler. + * * @return The {@link SchematicHandler} */ SchematicHandler initSchematicHandler(); /** * Get the Chat Manager. + * * @return The {@link ChatManager} */ ChatManager initChatManager(); /** * The task manager will run and manage Minecraft tasks. + * * @return */ TaskManager getTaskManager(); @@ -142,42 +144,49 @@ public interface IPlotMain extends ILogger { /** * Get the economy provider. + * * @return */ EconHandler getEconomyHandler(); /** * Get the {@link com.intellectualcrafters.plot.util.block.QueueProvider} class. + * * @return */ QueueProvider initBlockQueue(); /** * Get the {@link WorldUtil} class. + * * @return */ WorldUtil initWorldUtil(); /** * Get the EventUtil class. + * * @return */ EventUtil initEventUtil(); /** * Get the chunk manager. + * * @return */ ChunkManager initChunkManager(); /** * Get the {@link SetupUtils} class. + * * @return */ SetupUtils initSetupUtils(); /** * Get {@link HybridUtils} class. + * * @return */ HybridUtils initHybridUtils(); @@ -189,6 +198,7 @@ public interface IPlotMain extends ILogger { /** * If a world is already loaded, set the generator (use NMS if required). + * * @param world The world to set the generator */ void setGenerator(String world); @@ -196,6 +206,7 @@ public interface IPlotMain extends ILogger { /** * Get the {@link UUIDHandlerImplementation} which will cache and * provide UUIDs. + * * @return */ UUIDHandlerImplementation initUUIDHandler(); @@ -203,6 +214,7 @@ public interface IPlotMain extends ILogger { /** * Get the {@link InventoryUtil} class (used for implementation specific * inventory guis). + * * @return */ InventoryUtil initInventoryUtil(); @@ -210,18 +222,21 @@ public interface IPlotMain extends ILogger { /** * Run the converter for the implementation (not necessarily PlotMe, just * any plugin that we can convert from). + * * @return */ boolean initPlotMeConverter(); /** * Unregister a PlotPlayer from cache e.g. if they have logged off. + * * @param player */ void unregister(PlotPlayer player); /** * Get the generator wrapper for a world (world) and generator (name). + * * @param world * @param name * @return @@ -244,12 +259,14 @@ public interface IPlotMain extends ILogger { /** * Usually HybridGen + * * @return Default implementation generator */ IndependentPlotGenerator getDefaultGenerator(); /** * Get the class that will manage player titles. + * * @return */ AbstractTitle initTitleManager(); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PS.java b/Core/src/main/java/com/intellectualcrafters/plot/PS.java index a2f842f94..f9ad6d889 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/PS.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/PS.java @@ -17,69 +17,27 @@ import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; import com.intellectualcrafters.plot.logger.DelegateLogger; import com.intellectualcrafters.plot.logger.ILogger; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotFilter; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.object.worlds.DefaultPlotAreaManager; import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChatManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.CommentManager; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.intellectualcrafters.plot.util.expiry.ExpireManager; import com.intellectualcrafters.plot.util.expiry.ExpiryTask; import com.plotsquared.listener.WESubscriber; import com.sk89q.worldedit.WorldEdit; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; + +import java.io.*; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.sql.SQLException; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -87,42 +45,42 @@ import java.util.zip.ZipInputStream; /** * An implementation of the core, with a static getter for easy access. */ -public class PS{ +public class PS { private static PS instance; // Implementation public final IPlotMain IMP; - // Implementation logger - private ILogger logger; // Current thread private final Thread thread; - // Platform / Version / Update URL - private Updater updater; - private PlotVersion version; // WorldEdit instance public WorldEdit worldedit; - // Files and configuration - private File jarFile = null; // This file public File styleFile; public File configFile; public File worldsFile; public File commandsFile; public File translationFile; - private File storageFile; public YamlConfiguration style; public YamlConfiguration config; public YamlConfiguration worlds; public YamlConfiguration storage; public YamlConfiguration commands; - // Temporary hold the plots/clusters before the worlds load + // Temporary hold the plots/clusters before the worlds load public HashMap> clusters_tmp; public HashMap> plots_tmp; - + // Implementation logger + private ILogger logger; + // Platform / Version / Update URL + private Updater updater; + private PlotVersion version; + // Files and configuration + private File jarFile = null; // This file + private File storageFile; private PlotAreaManager manager; /** * Initialize PlotSquared with the desired Implementation class. + * * @param iPlotMain Implementation of {@link IPlotMain} used - * @param platform The platform being used + * @param platform The platform being used */ public PS(IPlotMain iPlotMain, String platform) { PS.instance = this; @@ -134,12 +92,15 @@ public class PS{ new ReflectionUtils(this.IMP.getNMSPackage()); try { URL url = PS.class.getProtectionDomain().getCodeSource().getLocation(); - this.jarFile = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); + this.jarFile = new File( + new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")) + .toURI().getPath()); } catch (MalformedURLException | URISyntaxException | SecurityException e) { e.printStackTrace(); this.jarFile = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared.jar"); if (!this.jarFile.exists()) { - this.jarFile = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar"); + this.jarFile = new File(this.IMP.getDirectory().getParentFile(), + "PlotSquared-" + platform + ".jar"); } } if (getJavaVersion() < 1.8) { @@ -147,8 +108,9 @@ public class PS{ } TaskManager.IMP = this.IMP.getTaskManager(); setupConfigs(); - this.translationFile = - MainUtil.getFile(this.IMP.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + IMP.getPluginName() + ".use_THIS.yml"); + this.translationFile = MainUtil.getFile(this.IMP.getDirectory(), + Settings.Paths.TRANSLATIONS + File.separator + IMP.getPluginName() + + ".use_THIS.yml"); C.load(this.translationFile); // Setup manager @@ -165,7 +127,8 @@ public class PS{ // Comments CommentManager.registerDefaultInboxes(); // Kill entities - if (Settings.Enabled_Components.KILL_ROAD_MOBS || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + if (Settings.Enabled_Components.KILL_ROAD_MOBS + || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { this.IMP.runEntityTask(); } if (Settings.Enabled_Components.EVENTS) { @@ -231,14 +194,14 @@ public class PS{ } } catch (Throwable e) { - PS.debug("Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); + PS.debug( + "Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); } } // Economy if (Settings.Enabled_Components.ECONOMY) { TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { EconHandler.manager = PS.this.IMP.getEconomyHandler(); } }); @@ -248,14 +211,12 @@ public class PS{ if (Settings.Enabled_Components.UPDATER) { updater = new Updater(); TaskManager.IMP.taskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { updater.update(getPlatform(), getVersion()); } }); TaskManager.IMP.taskRepeatAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { updater.update(getPlatform(), getVersion()); } }, 36000); @@ -273,16 +234,18 @@ public class PS{ } } TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { + @Override public void run() { for (String world : section.getKeys(false)) { if (world.equals("CheckingPlotSquaredGenerator")) { continue; } if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { - debug("&c`" + world + "` was not properly loaded - " + IMP.getPluginName() + " will now try to load it properly: "); - debug("&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); - debug("&8 - &7Your world management plugin may be faulty (or non existent)"); + debug("&c`" + world + "` was not properly loaded - " + IMP + .getPluginName() + " will now try to load it properly: "); + debug( + "&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); + debug( + "&8 - &7Your world management plugin may be faulty (or non existent)"); PS.this.IMP.setGenerator(world); } } @@ -355,8 +318,20 @@ public class PS{ return logger; } + /** + * Set the Logger. + * + * @param logger the logger the plugin should use + * @see DelegateLogger + * @see #getLogger() + */ + public void setLogger(ILogger logger) { + this.logger = logger; + } + /** * The plugin updater + * * @return */ public Updater getUpdater() { @@ -367,28 +342,15 @@ public class PS{ return manager; } - /** - * Set the Logger. - * @see DelegateLogger - * @see #getLogger() - * @param logger the logger the plugin should use - */ - public void setLogger(ILogger logger) { - this.logger = logger; - } - private void startUuidCatching() { TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { + @Override public void run() { debug("Starting UUID caching"); UUIDHandler.startCaching(new Runnable() { - @Override - public void run() { + @Override public void run() { UUIDHandler.add(new StringWrapper("*"), DBFunc.everyone); foreachPlotRaw(new RunnableVal() { - @Override - public void run(Plot plot) { + @Override public void run(Plot plot) { if (plot.hasOwner() && plot.temp != -1) { if (UUIDHandler.getName(plot.owner) == null) { UUIDHandler.implementation.unknown.add(plot.owner); @@ -418,14 +380,16 @@ public class PS{ private void startPlotMeConversion() { if (Settings.Enabled_Components.PLOTME_CONVERTER || Settings.PlotMe.CACHE_UUDS) { TaskManager.IMP.taskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { if (PS.this.IMP.initPlotMeConverter()) { PS.log("&c=== IMPORTANT ==="); - PS.log("&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); + PS.log( + "&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); PS.log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); - PS.log("&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); - PS.log("&c - After the conversion is finished, please set 'plotme-converter' to false in the " + PS.log( + "&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); + PS.log( + "&c - After the conversion is finished, please set 'plotme-converter' to false in the " + "'settings.yml'"); } Settings.Enabled_Components.PLOTME_CONVERTER = false; @@ -440,17 +404,19 @@ public class PS{ /** * Check if `version` is >= `version2`. + * * @param version * @param version2 * @return true if `version` is >= `version2` */ public boolean checkVersion(int[] version, int... version2) { - return version[0] > version2[0] || version[0] == version2[0] && version[1] > version2[1] || version[0] == version2[0] - && version[1] == version2[1] && version[2] >= version2[2]; + return version[0] > version2[0] || version[0] == version2[0] && version[1] > version2[1] + || version[0] == version2[0] && version[1] == version2[1] && version[2] >= version2[2]; } /** * Get the current PlotSquared version. + * * @return current version in config or null */ public PlotVersion getVersion() { @@ -459,8 +425,9 @@ public class PS{ /** * Get the server platform this plugin is running on this is running on. - * + *

      *

      This will be either Bukkit or Sponge

      + * * @return the server implementation */ public String getPlatform() { @@ -507,7 +474,8 @@ public class PS{ Set clusters; if (clusters_tmp == null || (clusters = clusters_tmp.remove(plotArea.toString())) == null) { if (plotArea.TYPE == 2) { - clusters = this.clusters_tmp != null ? this.clusters_tmp.get(plotArea.worldname) : null; + clusters = + this.clusters_tmp != null ? this.clusters_tmp.get(plotArea.worldname) : null; if (clusters != null) { Iterator iterator = clusters.iterator(); while (iterator.hasNext()) { @@ -576,14 +544,14 @@ public class PS{ /** * Get all the base plots in a single set (for merged plots it just returns * the bottom plot). + * * @return Set of base Plots */ public Set getBasePlots() { int size = getPlotCount(); final Set result = new HashSet<>(size); foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { for (Plot plot : value.getPlots()) { if (!plot.isBasePlot()) { continue; @@ -623,8 +591,7 @@ public class PS{ } } Collections.sort(overflow, new Comparator() { - @Override - public int compare(Plot a, Plot b) { + @Override public int compare(Plot a, Plot b) { return a.hashCode() - b.hashCode(); } }); @@ -634,14 +601,14 @@ public class PS{ /** * Sort plots by hashcode. + * * @param plots the collection of plots to sort * @return the sorted collection * @deprecated Unchecked, please use - * {@link #sortPlots(Collection, SortType, PlotArea)} which has - * additional checks before calling this + * {@link #sortPlots(Collection, SortType, PlotArea)} which has + * additional checks before calling this */ - @Deprecated - public ArrayList sortPlotsByHash(Collection plots) { + @Deprecated public ArrayList sortPlotsByHash(Collection plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; @@ -690,10 +657,10 @@ public class PS{ /** * Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will in turn call this. + * * @param input an array of plots to sort */ - @Deprecated - public void sortPlotsByHash(Plot[] input) { + @Deprecated public void sortPlotsByHash(Plot[] input) { List[] bucket = new ArrayList[32]; for (int i = 0; i < bucket.length; i++) { bucket[i] = new ArrayList<>(); @@ -720,8 +687,7 @@ public class PS{ } } - @Deprecated - public ArrayList sortPlotsByTimestamp(Collection plots) { + @Deprecated public ArrayList sortPlotsByTimestamp(Collection plots) { int hardMax = 256000; int max = 0; int overflowSize = 0; @@ -770,12 +736,12 @@ public class PS{ /** * Sort plots by creation timestamp. + * * @param input - * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks * @return + * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks */ - @Deprecated - public List sortPlotsByModified(Collection input) { + @Deprecated public List sortPlotsByModified(Collection input) { List list; if (input instanceof List) { list = (List) input; @@ -783,9 +749,9 @@ public class PS{ list = new ArrayList<>(input); } Collections.sort(list, new Comparator() { - @Override - public int compare(Plot a, Plot b) { - return Long.compare(ExpireManager.IMP.getTimestamp(a.owner), ExpireManager.IMP.getTimestamp(b.owner)); + @Override public int compare(Plot a, Plot b) { + return Long.compare(ExpireManager.IMP.getTimestamp(a.owner), + ExpireManager.IMP.getTimestamp(b.owner)); } }); return list; @@ -794,13 +760,15 @@ public class PS{ /** * Sort a collection of plots by world (with a priority world), then * by hashcode. - * @param plots the plots to sort - * @param type The sorting method to use for each world (timestamp, or hash) + * + * @param plots the plots to sort + * @param type The sorting method to use for each world (timestamp, or hash) * @param priorityArea Use null, "world", or "gibberish" if you - * want default world order + * want default world order * @return ArrayList of plot */ - public ArrayList sortPlots(Collection plots, SortType type, final PlotArea priorityArea) { + public ArrayList sortPlots(Collection plots, SortType type, + final PlotArea priorityArea) { // group by world // sort each HashMap> map = new HashMap<>(); @@ -827,8 +795,7 @@ public class PS{ } List areas = Arrays.asList(manager.getAllPlotAreas()); Collections.sort(areas, new Comparator() { - @Override - public int compare(PlotArea a, PlotArea b) { + @Override public int compare(PlotArea a, PlotArea b) { if (priorityArea != null && StringMan.isEqual(a.toString(), b.toString())) { return -1; } @@ -860,14 +827,14 @@ public class PS{ /** * A more generic way to filter plots - make your own method * if you need complex filters. + * * @param filters the filter * @return a filtered set of plots */ public Set getPlots(final PlotFilter... filters) { final HashSet set = new HashSet<>(); foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { for (PlotFilter filter : filters) { if (!filter.allowsArea(value)) { return; @@ -890,14 +857,14 @@ public class PS{ /** * Get all the plots in a single set. + * * @return Set of Plots */ public Set getPlots() { int size = getPlotCount(); final Set result = new HashSet<>(size); foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { result.addAll(value.getPlots()); } }); @@ -929,7 +896,8 @@ public class PS{ /** * Get all the plots owned by a player name. - * @param world the world + * + * @param world the world * @param player the plot owner * @return Set of Plot */ @@ -940,7 +908,8 @@ public class PS{ /** * Get all the plots owned by a player name. - * @param area the PlotArea + * + * @param area the PlotArea * @param player the plot owner * @return Set of Plot */ @@ -951,7 +920,8 @@ public class PS{ /** * Get all plots by a PlotPlayer. - * @param world the world + * + * @param world the world * @param player the plot owner * @return Set of plot */ @@ -961,7 +931,8 @@ public class PS{ /** * Get all plots by a PlotPlayer. - * @param area the PlotArea + * + * @param area the PlotArea * @param player the plot owner * @return Set of plot */ @@ -971,8 +942,9 @@ public class PS{ /** * Get all plots by a UUID in a world. + * * @param world the world - * @param uuid the plot owner + * @param uuid the plot owner * @return Set of plot */ public Set getPlots(String world, UUID uuid) { @@ -989,6 +961,7 @@ public class PS{ /** * Get all plots by a UUID in an area. + * * @param area the {@code PlotArea} * @param uuid the plot owner * @return Set of plot @@ -1008,20 +981,21 @@ public class PS{ /** * Use {@link #hasPlotArea(String)}. * Note: Worlds may have more than one plot area - * @deprecated + * * @param world the world * @return if the world is a plotworld + * @deprecated */ - @Deprecated - public boolean isPlotWorld(String world) { + @Deprecated public boolean isPlotWorld(String world) { return hasPlotArea(world); } /** * Check if a plot world. + * * @param world the world - * @see #getPlotAreaByString(String) to get the PlotArea object * @return if a plot world is registered + * @see #getPlotAreaByString(String) to get the PlotArea object */ public boolean hasPlotArea(String world) { return manager.getPlotAreas(world, null).length != 0; @@ -1030,8 +1004,7 @@ public class PS{ public Collection getPlots(String world) { final HashSet set = new HashSet<>(); foreachPlotArea(world, new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { set.addAll(value.getPlots()); } }); @@ -1040,6 +1013,7 @@ public class PS{ /** * Get the plots for a PlotPlayer. + * * @param player the player to retrieve the plots for * @return Set of Plot */ @@ -1061,14 +1035,14 @@ public class PS{ /** * Get the plots for a UUID. + * * @param uuid the plot owner * @return Set of Plot's owned by the player */ public Set getPlots(final UUID uuid) { final ArrayList myPlots = new ArrayList<>(); foreachPlot(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { if (value.isOwnerAbs(uuid)) { myPlots.add(value); } @@ -1079,7 +1053,8 @@ public class PS{ public boolean hasPlot(final UUID uuid) { for (PlotArea area : manager.getAllPlotAreas()) { - if (area.hasPlot(uuid)) return true; + if (area.hasPlot(uuid)) + return true; } return false; } @@ -1087,8 +1062,7 @@ public class PS{ public Set getBasePlots(final UUID uuid) { final ArrayList myplots = new ArrayList<>(); foreachBasePlot(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { if (value.isOwner(uuid)) { myplots.add(value); } @@ -1099,14 +1073,14 @@ public class PS{ /** * Get the plots for a UUID. + * * @param uuid the UUID of the owner * @return Set of Plot */ public Set getPlotsAbs(final UUID uuid) { final ArrayList myPlots = new ArrayList<>(); foreachPlot(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { if (value.isOwnerAbs(uuid)) { myPlots.add(value); } @@ -1117,7 +1091,8 @@ public class PS{ /** * Unregister a plot from local memory (does not call DB). - * @param plot the plot to remove + * + * @param plot the plot to remove * @param callEvent If to call an event about the plot being removed * @return true if plot existed | false if it didn't */ @@ -1143,18 +1118,19 @@ public class PS{ /** * This method is called by the PlotGenerator class normally. *
        - *
      • Initializes the PlotArea and PlotManager classes - *
      • Registers the PlotArea and PlotManager classes - *
      • Loads (and/or generates) the PlotArea configuration - *
      • Sets up the world border if configured + *
      • Initializes the PlotArea and PlotManager classes + *
      • Registers the PlotArea and PlotManager classes + *
      • Loads (and/or generates) the PlotArea configuration + *
      • Sets up the world border if configured *
      - * + *

      *

      If loading an augmented plot world: *

        - *
      • Creates the AugmentedPopulator classes - *
      • Injects the AugmentedPopulator classes if required + *
      • Creates the AugmentedPopulator classes + *
      • Injects the AugmentedPopulator classes if required *
      - * @param world the world to load + * + * @param world the world to load * @param baseGenerator The generator for that world, or null */ public void loadWorld(String world, GeneratorWrapper baseGenerator) { @@ -1186,12 +1162,14 @@ public class PS{ plotGenerator = baseGenerator.getPlotGenerator(); } else if (worldSection != null) { String secondaryGeneratorName = worldSection.getString("generator.plugin"); - GeneratorWrapper secondaryGenerator = this.IMP.getGenerator(world, secondaryGeneratorName); + GeneratorWrapper secondaryGenerator = + this.IMP.getGenerator(world, secondaryGeneratorName); if (secondaryGenerator != null && secondaryGenerator.isFull()) { plotGenerator = secondaryGenerator.getPlotGenerator(); } else { String primaryGeneratorName = worldSection.getString("generator.init"); - GeneratorWrapper primaryGenerator = this.IMP.getGenerator(world, primaryGeneratorName); + GeneratorWrapper primaryGenerator = + this.IMP.getGenerator(world, primaryGeneratorName); if (primaryGenerator != null && primaryGenerator.isFull()) { plotGenerator = primaryGenerator.getPlotGenerator(); } else { @@ -1235,7 +1213,9 @@ public class PS{ PS.log(C.PREFIX + "&aDetected world load for '" + world + "'"); String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName()); if (type == 2) { - Set clusters = this.clusters_tmp != null ? this.clusters_tmp.get(world) : new HashSet(); + Set clusters = this.clusters_tmp != null ? + this.clusters_tmp.get(world) : + new HashSet(); if (clusters == null) { throw new IllegalArgumentException("No cluster exists for world: " + world); } @@ -1253,7 +1233,8 @@ public class PS{ if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } - PlotArea pa = areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); + PlotArea pa = + areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { @@ -1264,7 +1245,8 @@ public class PS{ PS.log(C.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); PS.log(C.PREFIX + "&c | &9plotworld: &7" + pa); PS.log(C.PREFIX + "&c | &9manager: &7" + pa); - PS.log(C.PREFIX + "&cNote: &7Area created for cluster:" + name + " (invalid or old configuration?)"); + PS.log(C.PREFIX + "&cNote: &7Area created for cluster:" + name + + " (invalid or old configuration?)"); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); toLoad.add(pa); @@ -1295,19 +1277,22 @@ public class PS{ return; } if (type == 1) { - throw new IllegalArgumentException("Invalid type for multi-area world. Expected `2`, got `" + 1 + "`"); + throw new IllegalArgumentException( + "Invalid type for multi-area world. Expected `2`, got `" + 1 + "`"); } for (String areaId : areasSection.getKeys(false)) { PS.log(C.PREFIX + "&3 - " + areaId); String[] split = areaId.split("(?<=[^;-])-"); if (split.length != 3) { - throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); + throw new IllegalArgumentException("Invalid Area identifier: " + areaId + + ". Expected form `--`"); } String name = split[0]; PlotId pos1 = PlotId.fromString(split[1]); PlotId pos2 = PlotId.fromString(split[2]); if (pos1 == null || pos2 == null || name.isEmpty()) { - throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); + throw new IllegalArgumentException("Invalid Area identifier: " + areaId + + ". Expected form `--`"); } PlotArea existing = getPlotArea(world, name); if (existing != null && name.equals(existing.id)) { @@ -1371,12 +1356,12 @@ public class PS{ /** * Setup the configuration for a plot world based on world arguments. - * + *

      *

      * e.g. /mv create <world> normal -g PlotSquared:<args> * - * @param world The name of the world - * @param args The arguments + * @param world The name of the world + * @param args The arguments * @param generator the plot generator * @return boolean | if valid arguments were provided */ @@ -1398,35 +1383,44 @@ public class PS{ switch (key) { case "s": case "size": - this.worlds.set(base + "plot.size", Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "plot.size", + Configuration.INTEGER.parseString(value).shortValue()); break; case "g": case "gap": - this.worlds.set(base + "road.width", Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "road.width", + Configuration.INTEGER.parseString(value).shortValue()); break; case "h": case "height": - this.worlds.set(base + "road.height", Configuration.INTEGER.parseString(value).shortValue()); - this.worlds.set(base + "plot.height", Configuration.INTEGER.parseString(value).shortValue()); - this.worlds.set(base + "wall.height", Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "road.height", + Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "plot.height", + Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "wall.height", + Configuration.INTEGER.parseString(value).shortValue()); break; case "f": case "floor": - this.worlds.set(base + "plot.floor", - new ArrayList<>(Arrays.asList(StringMan.join(Configuration.BLOCKLIST.parseString(value), ",").split(",")))); + this.worlds.set(base + "plot.floor", new ArrayList<>(Arrays.asList( + StringMan.join(Configuration.BLOCKLIST.parseString(value), ",") + .split(",")))); break; case "m": case "main": - this.worlds.set(base + "plot.filling", - new ArrayList<>(Arrays.asList(StringMan.join(Configuration.BLOCKLIST.parseString(value), ",").split(",")))); + this.worlds.set(base + "plot.filling", new ArrayList<>(Arrays.asList( + StringMan.join(Configuration.BLOCKLIST.parseString(value), ",") + .split(",")))); break; case "w": case "wall": - this.worlds.set(base + "wall.filling", Configuration.BLOCK.parseString(value).toString()); + this.worlds.set(base + "wall.filling", + Configuration.BLOCK.parseString(value).toString()); break; case "b": case "border": - this.worlds.set(base + "wall.block", Configuration.BLOCK.parseString(value).toString()); + this.worlds.set(base + "wall.block", + Configuration.BLOCK.parseString(value).toString()); break; default: PS.log("&cKey not found: &7" + element); @@ -1439,7 +1433,8 @@ public class PS{ } } try { - ConfigurationSection section = this.worlds.getConfigurationSection("worlds." + world); + ConfigurationSection section = + this.worlds.getConfigurationSection("worlds." + world); plotworld.saveConfiguration(section); plotworld.loadConfiguration(section); this.worlds.save(this.worldsFile); @@ -1489,7 +1484,8 @@ public class PS{ } Files.copy(stream, newJar.toPath()); } - MainUtil.sendMessage(sender, "$1The update will take effect when the server is restarted next"); + MainUtil.sendMessage(sender, + "$1The update will take effect when the server is restarted next"); return true; } catch (IOException e) { MainUtil.sendMessage(sender, "Failed to update " + IMP.getPluginName() + ""); @@ -1503,7 +1499,8 @@ public class PS{ /** * Copy a file from inside the jar to a location - * @param file Name of the file inside PlotSquared.jar + * + * @param file Name of the file inside PlotSquared.jar * @param folder The output location relative to /plugins/PlotSquared/ */ public void copyFile(String file, String folder) { @@ -1519,7 +1516,8 @@ public class PS{ try (InputStream stream = this.IMP.getClass().getResourceAsStream(file)) { byte[] buffer = new byte[2048]; if (stream == null) { - try (ZipInputStream zis = new ZipInputStream(new FileInputStream(this.jarFile))) { + try (ZipInputStream zis = new ZipInputStream( + new FileInputStream(this.jarFile))) { ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); @@ -1575,8 +1573,7 @@ public class PS{ // Validate that all data in the db is correct final HashSet plots = new HashSet<>(); foreachPlotRaw(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { plots.add(value); } }); @@ -1601,8 +1598,9 @@ public class PS{ } Database database; if (Storage.MySQL.USE) { - database = new com.intellectualcrafters.plot.database.MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE, - Storage.MySQL.USER, Storage.MySQL.PASSWORD); + database = new com.intellectualcrafters.plot.database.MySQL(Storage.MySQL.HOST, + Storage.MySQL.PORT, Storage.MySQL.DATABASE, Storage.MySQL.USER, + Storage.MySQL.PASSWORD); } else if (Storage.SQLite.USE) { File file = MainUtil.getFile(IMP.getDirectory(), Storage.SQLite.DB + ".db"); database = new com.intellectualcrafters.plot.database.SQLite(file); @@ -1625,7 +1623,8 @@ public class PS{ } this.clusters_tmp = DBFunc.getClusters(); } catch (ClassNotFoundException | SQLException e) { - PS.log(C.PREFIX + "&cFailed to open DATABASE connection. The plugin will disable itself."); + PS.log( + C.PREFIX + "&cFailed to open DATABASE connection. The plugin will disable itself."); if (Storage.MySQL.USE) { PS.log("$4MYSQL"); } else if (Storage.SQLite.USE) { @@ -1634,21 +1633,24 @@ public class PS{ PS.log("&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); PS.log("&d==== End of stacktrace ===="); - PS.log("&6Please go to the " + IMP.getPluginName() + " 'storage.yml' and configure the database correctly."); + PS.log("&6Please go to the " + IMP.getPluginName() + + " 'storage.yml' and configure the database correctly."); this.IMP.disable(); } } /** * Setup the default configuration. + * * @throws IOException if the config failed to save */ public void setupConfig() throws IOException { String lastVersionString = this.config.getString("version"); if (lastVersionString != null) { String[] split = lastVersionString.split("\\."); - int[] lastVersion = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; - if (checkVersion(new int[]{3, 4, 0}, lastVersion)) { + int[] lastVersion = new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]), + Integer.parseInt(split[2])}; + if (checkVersion(new int[] {3, 4, 0}, lastVersion)) { Settings.convertLegacy(configFile); if (config.contains("worlds")) { ConfigurationSection worldSection = config.getConfigurationSection("worlds"); @@ -1672,7 +1674,8 @@ public class PS{ this.version = PlotVersion.tryParse(versionString); Settings.DATE = new Date(100 + version.year, version.month, version.day).toGMTString(); Settings.BUILD = "https://ci.athion.net/job/PlotSquared/" + version.build; - Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer.toHexString(version.hash); + Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer + .toHexString(version.hash); System.out.println("Version is " + this.version); } catch (Throwable ignore) { ignore.printStackTrace(); @@ -1683,14 +1686,15 @@ public class PS{ /** * Setup all configuration files
      - * - Config: settings.yml
      - * - Storage: storage.yml
      - * - Translation: PlotSquared.use_THIS.yml, style.yml
      + * - Config: settings.yml
      + * - Storage: storage.yml
      + * - Translation: PlotSquared.use_THIS.yml, style.yml
      */ public void setupConfigs() { File folder = new File(this.IMP.getDirectory(), "config"); if (!folder.exists() && !folder.mkdirs()) { - PS.log(C.PREFIX + "&cFailed to create the /plugins/config folder. Please create it manually."); + PS.log(C.PREFIX + + "&cFailed to create the /plugins/config folder. Please create it manually."); } try { this.worldsFile = new File(folder, "worlds.yml"); @@ -1704,7 +1708,8 @@ public class PS{ try { this.configFile = new File(folder, "settings.yml"); if (!this.configFile.exists() && !this.configFile.createNewFile()) { - PS.log("Could not create the settings file, please create \"settings.yml\" manually."); + PS.log( + "Could not create the settings file, please create \"settings.yml\" manually."); } this.config = YamlConfiguration.loadConfiguration(this.configFile); setupConfig(); @@ -1712,13 +1717,15 @@ public class PS{ PS.log("Failed to save settings.yml"); } try { - this.styleFile = MainUtil.getFile(IMP.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + "style.yml"); + this.styleFile = MainUtil.getFile(IMP.getDirectory(), + Settings.Paths.TRANSLATIONS + File.separator + "style.yml"); if (!this.styleFile.exists()) { if (!this.styleFile.getParentFile().exists()) { this.styleFile.getParentFile().mkdirs(); } if (!this.styleFile.createNewFile()) { - PS.log("Could not create the style file, please create \"translations/style.yml\" manually"); + PS.log( + "Could not create the style file, please create \"translations/style.yml\" manually"); } } this.style = YamlConfiguration.loadConfiguration(this.styleFile); @@ -1730,7 +1737,8 @@ public class PS{ try { this.storageFile = new File(folder, "storage.yml"); if (!this.storageFile.exists() && !this.storageFile.createNewFile()) { - PS.log("Could not the storage settings file, please create \"storage.yml\" manually."); + PS.log( + "Could not the storage settings file, please create \"storage.yml\" manually."); } this.storage = YamlConfiguration.loadConfiguration(this.storageFile); setupStorage(); @@ -1740,7 +1748,8 @@ public class PS{ try { this.commandsFile = new File(folder, "commands.yml"); if (!this.commandsFile.exists() && !this.commandsFile.createNewFile()) { - PS.log("Could not the storage settings file, please create \"commands.yml\" manually."); + PS.log( + "Could not the storage settings file, please create \"commands.yml\" manually."); } this.commands = YamlConfiguration.loadConfiguration(this.commandsFile); } catch (IOException ignored) { @@ -1771,7 +1780,8 @@ public class PS{ if (Settings.DEBUG) { Map components = Settings.getFields(Settings.Enabled_Components.class); for (Entry component : components.entrySet()) { - PS.log(C.PREFIX + String.format("&cKey: &6%s&c, Value: &6%s", component.getKey(), component.getValue())); + PS.log(C.PREFIX + String.format("&cKey: &6%s&c, Value: &6%s", component.getKey(), + component.getValue())); } } } @@ -1797,6 +1807,7 @@ public class PS{ /** * Get the Java version. + * * @return the java version */ public double getJavaVersion() { @@ -1873,10 +1884,10 @@ public class PS{ /** * Not recommended for use since worlds can have multiple PlotAreas. + * * @return Set of world names */ - @Deprecated - public Set getPlotWorldStrings() { + @Deprecated public Set getPlotWorldStrings() { HashSet set = new HashSet<>(manager.getAllPlotAreas().length); for (String world : manager.getAllWorlds()) { if (manager.getPlotAreas(world, null).length != 0) { @@ -1899,6 +1910,7 @@ public class PS{ /** * Get a list of PlotArea objects. + * * @param world the world * @return Collection of PlotArea objects */ @@ -1911,12 +1923,13 @@ public class PS{ /** * Get the relevant plot area for a specified location. *

        - *
      • If there is only one plot area globally that will be returned. - *
      • If there is only one plot area in the world, it will return that. - *
      • If the plot area for a location cannot be unambiguously - * resolved, null will be returned. + *
      • If there is only one plot area globally that will be returned. + *
      • If there is only one plot area in the world, it will return that. + *
      • If the plot area for a location cannot be unambiguously + * resolved, null will be returned. *
      * Note: An applicable plot area may not include the location i.e. clusters + * * @param location the location * @return */ @@ -1931,8 +1944,8 @@ public class PS{ /** * Get the {@code PlotArea} which contains a location. *
        - *
      • If the plot area does not contain a location, null - * will be returned. + *
      • If the plot area does not contain a location, null + * will be returned. *
      * * @param location the location @@ -1948,7 +1961,8 @@ public class PS{ if (areas == null) { for (PlotArea area : manager.getAllPlotAreas()) { if (area.worldname.equalsIgnoreCase(split[0])) { - if (area.id == null || split.length == 2 && area.id.equalsIgnoreCase(split[1])) { + if (area.id == null || split.length == 2 && area.id + .equalsIgnoreCase(split[1])) { return area; } } @@ -1968,27 +1982,27 @@ public class PS{ return null; } } - + /** * Get Plots based on alias * - * @param alias to search plots + * @param alias to search plots * @param worldname to filter alias to a specific world [optional] null means all worlds - * * @return Set<{@link Plot}> empty if nothing found */ public Set getPlotsByAlias(String alias, String worldname) { - Set result = new HashSet<>(); - - if (alias != null) { - for (Plot plot : getPlots()) { - if (alias.equals(plot.getAlias()) && (worldname == null || worldname.equals(plot.getWorldName()))) { - result.add(plot); - } - } - } - - return result; + Set result = new HashSet<>(); + + if (alias != null) { + for (Plot plot : getPlots()) { + if (alias.equals(plot.getAlias()) && (worldname == null || worldname + .equals(plot.getWorldName()))) { + result.add(plot); + } + } + } + + return result; } public Set getPlotAreas(String world, RegionWrapper region) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/Platform.java b/Core/src/main/java/com/intellectualcrafters/plot/Platform.java index d9b461377..0a6775ccb 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/Platform.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/Platform.java @@ -1,9 +1,6 @@ package com.intellectualcrafters.plot; public enum Platform { - Bukkit, - Sponge, - Spigot, - Cauldron + Bukkit, Sponge, Spigot, Cauldron } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java b/Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java index 937d0af73..946ced65e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java @@ -11,15 +11,6 @@ public class PlotVersion { this.build = build; } - public static PlotVersion tryParse(String version) { - try { - return new PlotVersion(version); - } catch (Exception ignore) { - ignore.printStackTrace(); - return new PlotVersion(0, 0, 0, 0, 0); - } - } - public PlotVersion(String version) { String[] split = version.substring(version.indexOf('=') + 1).split("-"); if (split[0].equals("unknown")) { @@ -30,7 +21,7 @@ public class PlotVersion { this.year = Integer.parseInt(date[0]); this.month = Integer.parseInt(date[1]); this.day = Integer.parseInt(date[2]); - if(split[1].equals("SNAPSHOT")) { // fallback when compiling with Maven + if (split[1].equals("SNAPSHOT")) { // fallback when compiling with Maven this.hash = 0; this.build = 0; } else { @@ -39,12 +30,21 @@ public class PlotVersion { } } - @Override - public String toString() { - if(hash == 0 && build == 0) { + public static PlotVersion tryParse(String version) { + try { + return new PlotVersion(version); + } catch (Exception ignore) { + ignore.printStackTrace(); + return new PlotVersion(0, 0, 0, 0, 0); + } + } + + @Override public String toString() { + if (hash == 0 && build == 0) { return "PlotSquared-" + year + "." + month + "." + day + "-SNAPSHOT"; } else { - return "PlotSquared-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash) + "-" + build; + return "PlotSquared-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash) + + "-" + build; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/Updater.java b/Core/src/main/java/com/intellectualcrafters/plot/Updater.java index dd7f15cd0..2024a543d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/Updater.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/Updater.java @@ -1,6 +1,7 @@ package com.intellectualcrafters.plot; import com.intellectualcrafters.plot.util.MainUtil; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -16,7 +17,9 @@ public class Updater { public String getChanges() { if (changes == null) { - try (Scanner scanner = new Scanner(new URL("http://empcraft.com/plots/cl?" + Integer.toHexString(PS.get().getVersion().hash)).openStream(), "UTF-8")) { + try (Scanner scanner = new Scanner(new URL( + "http://empcraft.com/plots/cl?" + Integer.toHexString(PS.get().getVersion().hash)) + .openStream(), "UTF-8")) { changes = scanner.useDelimiter("\\A").next(); } catch (IOException e) { e.printStackTrace(); @@ -35,7 +38,8 @@ public class Updater { return; } try { - String downloadUrl = "https://ci.athion.net/job/PlotSquared/lastSuccessfulBuild/artifact/target/PlotSquared-%platform%-%version%.jar"; + String downloadUrl = + "https://ci.athion.net/job/PlotSquared/lastSuccessfulBuild/artifact/target/PlotSquared-%platform%-%version%.jar"; String versionUrl = "http://empcraft.com/plots/version.php?%platform%"; URL url = new URL(versionUrl.replace("%platform%", platform)); try (Scanner reader = new Scanner(url.openStream())) { @@ -43,12 +47,15 @@ public class Updater { PlotVersion version = new PlotVersion(versionString); if (version.isNewer(newVersion != null ? newVersion : currentVersion)) { newVersion = version; - URL download = new URL(downloadUrl.replaceAll("%platform%", platform).replaceAll("%version%", versionString)); + URL download = new URL(downloadUrl.replaceAll("%platform%", platform) + .replaceAll("%version%", versionString)); try (ReadableByteChannel rbc = Channels.newChannel(download.openStream())) { File jarFile = PS.get().getJarFile(); - File finalFile = new File(jarFile.getParent(), "update" + File.separator + jarFile.getName()); - File outFile = new File(jarFile.getParent(), "update" + File.separator + jarFile.getName().replace(".jar", ".part")); + File finalFile = new File(jarFile.getParent(), + "update" + File.separator + jarFile.getName()); + File outFile = new File(jarFile.getParent(), + "update" + File.separator + jarFile.getName().replace(".jar", ".part")); boolean exists = outFile.exists(); if (exists) { outFile.delete(); @@ -63,11 +70,14 @@ public class Updater { } outFile.renameTo(finalFile); PS.debug("Updated PlotSquared to " + versionString); - MainUtil.sendAdmin("&7Restart to update PlotSquared with these changes: &c/plot changelog &7or&c " + "http://empcraft.com/plots/cl?" + Integer.toHexString(currentVersion.hash)); + MainUtil.sendAdmin( + "&7Restart to update PlotSquared with these changes: &c/plot changelog &7or&c " + + "http://empcraft.com/plots/cl?" + Integer + .toHexString(currentVersion.hash)); } } } } catch (Throwable ignore) { } } -} \ No newline at end of file +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java index 956bd0f01..40e98429a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java @@ -16,24 +16,20 @@ import java.util.Iterator; import java.util.Set; import java.util.UUID; -@CommandDeclaration( - command = "add", - description = "Allow a user to build while you are online", - usage = "/plot add ", - category = CommandCategory.SETTINGS, - permission = "plots.add", - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "add", description = "Allow a user to build while you are online", usage = "/plot add ", category = CommandCategory.SETTINGS, permission = "plots.add", requiredType = RequiredType.NONE) public class Add extends Command { public Add() { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); - checkTrue(plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.NO_PLOT_PERMS); + checkTrue(plot.isOwner(player.getUUID()) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.NO_PLOT_PERMS); checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage()); final Set uuids = MainUtil.getUUIDsFromString(args[0]); checkTrue(!uuids.isEmpty(), C.INVALID_PLAYER, args[0]); @@ -41,7 +37,9 @@ public class Add extends Command { int size = plot.getTrusted().size() + plot.getMembers().size(); while (iter.hasNext()) { UUID uuid = iter.next(); - if (uuid == DBFunc.everyone && !(Permissions.hasPermission(player, C.PERMISSION_TRUST_EVERYONE) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST))) { + if (uuid == DBFunc.everyone && !( + Permissions.hasPermission(player, C.PERMISSION_TRUST_EVERYONE) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST))) { MainUtil.sendMessage(player, C.INVALID_PLAYER, MainUtil.getName(uuid)); iter.remove(); continue; @@ -59,7 +57,8 @@ public class Add extends Command { size += plot.getTrusted().contains(uuid) ? 0 : 1; } checkTrue(!uuids.isEmpty(), null); - checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS); + checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS); confirm.run(this, new Runnable() { @Override // Success public void run() { @@ -78,4 +77,4 @@ public class Add extends Command { } }, null); } -} \ No newline at end of file +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java index d22dbfe91..81647fa33 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Alias.java @@ -12,70 +12,65 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "setalias", - permission = "plots.alias", - description = "Set the plot name", - usage = "/plot alias ", - aliases = {"alias", "sa", "name", "rename", "setname", "seta", "nameplot"}, - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "setalias", permission = "plots.alias", description = "Set the plot name", usage = "/plot alias ", aliases = { + "alias", "sa", "name", "rename", "setname", "seta", + "nameplot"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Alias extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { - - if (args.length == 0) { - C.COMMAND_SYNTAX.send(player, "/plot alias "); + @Override public boolean onCommand(PlotPlayer player, String[] args) { + + if (args.length == 0) { + C.COMMAND_SYNTAX.send(player, "/plot alias "); return false; } - - Location loc = player.getLocation(); + + Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } - + if (!plot.hasOwner()) { sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } - + if (!plot.isOwner(player.getUUID())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } - + boolean result = false; - - switch (args[0].toLowerCase()) { - case "set": - if (args.length != 2) { - C.COMMAND_SYNTAX.send(player, "/plot alias "); - return false; - } - - if(canExecuteCommand(player, C.PERMISSION_ALIAS_SET, false) || canExecuteCommand(player, C.PERMISSION_ALIAS_SET_OBSOLETE, false)) { - result = setAlias(player, plot, args[1]); - } else { - MainUtil.sendMessage(player, C.NO_PERMISSION); - } - - break; - case "remove": - if(canExecuteCommand(player, C.PERMISSION_ALIAS_REMOVE, true)) { - result = removeAlias(player, plot); - } - break; - default: - C.COMMAND_SYNTAX.send(player, "/plot alias "); - result = false; - } - - return result; - } - - + + switch (args[0].toLowerCase()) { + case "set": + if (args.length != 2) { + C.COMMAND_SYNTAX.send(player, "/plot alias "); + return false; + } + + if (canExecuteCommand(player, C.PERMISSION_ALIAS_SET, false) || canExecuteCommand( + player, C.PERMISSION_ALIAS_SET_OBSOLETE, false)) { + result = setAlias(player, plot, args[1]); + } else { + MainUtil.sendMessage(player, C.NO_PERMISSION); + } + + break; + case "remove": + if (canExecuteCommand(player, C.PERMISSION_ALIAS_REMOVE, true)) { + result = removeAlias(player, plot); + } + break; + default: + C.COMMAND_SYNTAX.send(player, "/plot alias "); + result = false; + } + + return result; + } + + private boolean setAlias(PlotPlayer player, Plot plot, String alias) { if (alias.isEmpty()) { C.COMMAND_SYNTAX.send(player, "/plot alias "); @@ -107,20 +102,20 @@ public class Alias extends SubCommand { MainUtil.sendMessage(player, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); return true; } - + private boolean removeAlias(PlotPlayer player, Plot plot) { - plot.setAlias(null); - MainUtil.sendMessage(player, C.ALIAS_REMOVED.s()); - return true; + plot.setAlias(null); + MainUtil.sendMessage(player, C.ALIAS_REMOVED.s()); + return true; } - + private boolean canExecuteCommand(PlotPlayer player, C caption, boolean sendMessage) { - if (!Permissions.hasPermission(player, caption)) { - if(sendMessage) { - MainUtil.sendMessage(player, C.NO_PERMISSION); - } - return false; - } - return true; + if (!Permissions.hasPermission(player, caption)) { + if (sendMessage) { + MainUtil.sendMessage(player, C.NO_PERMISSION); + } + return false; + } + return true; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java index cfab9a55e..64738ba14 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java @@ -6,42 +6,19 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Configuration; import com.intellectualcrafters.plot.generator.AugmentedUtils; import com.intellectualcrafters.plot.generator.HybridPlotWorld; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.IOException; import java.util.ArrayList; import java.util.Objects; import java.util.Set; -@CommandDeclaration(command = "area", - permission = "plots.area", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.NONE, - description = "Create a new PlotArea", - aliases = "world", - usage = "/plot area ", - confirmation = true) +@CommandDeclaration(command = "area", permission = "plots.area", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.NONE, description = "Create a new PlotArea", aliases = "world", usage = "/plot area ", confirmation = true) public class Area extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 0) { C.COMMAND_SYNTAX.send(player, getUsage()); return false; @@ -56,48 +33,58 @@ public class Area extends SubCommand { } switch (args.length) { case 1: - C.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX + .send(player, "/plot area create [world[:id]] [=]..."); return false; case 2: switch (args[1].toLowerCase()) { case "pos1": { // Set position 1 HybridPlotWorld area = player.getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, + "/plot area create [world[:id]] [=]..."); return false; } Location location = player.getLocation(); player.setMeta("area_pos1", location); - C.SET_ATTRIBUTE.send(player, "area_pos1", location.getX() + "," + location.getZ()); - MainUtil.sendMessage(player, "You will now set pos2: /plot area create pos2" + C.SET_ATTRIBUTE.send(player, "area_pos1", + location.getX() + "," + location.getZ()); + MainUtil.sendMessage(player, + "You will now set pos2: /plot area create pos2" + "\nNote: The chosen plot size may result in the created area not exactly matching your second position."); return true; } case "pos2": // Set position 2 and finish creation for type=2 (partial) final HybridPlotWorld area = player.getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, + "/plot area create [world[:id]] [=]..."); return false; } Location pos1 = player.getLocation(); Location pos2 = player.getMeta("area_pos1"); int dx = Math.abs(pos1.getX() - pos2.getX()); int dz = Math.abs(pos1.getZ() - pos2.getZ()); - int numX = Math.max(1, (dx + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); - int numZ = Math.max(1, (dz + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); + int numX = Math.max(1, + (dx + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); + int numZ = Math.max(1, + (dz + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); int ddx = dx - (numX * area.SIZE - area.ROAD_WIDTH); int ddz = dz - (numZ * area.SIZE - area.ROAD_WIDTH); int bx = Math.min(pos1.getX(), pos2.getX()) + ddx; int bz = Math.min(pos1.getZ(), pos2.getZ()) + ddz; int tx = Math.max(pos1.getX(), pos2.getX()) - ddx; int tz = Math.max(pos1.getZ(), pos2.getZ()) - ddz; - int lower = (area.ROAD_WIDTH & 1) == 0 ? area.ROAD_WIDTH / 2 - 1 : area.ROAD_WIDTH / 2; + int lower = (area.ROAD_WIDTH & 1) == 0 ? + area.ROAD_WIDTH / 2 - 1 : + area.ROAD_WIDTH / 2; final int offsetX = bx - (area.ROAD_WIDTH == 0 ? 0 : lower); final int offsetZ = bz - (area.ROAD_WIDTH == 0 ? 0 : lower); final RegionWrapper region = new RegionWrapper(bx, tx, bz, tz); Set areas = PS.get().getPlotAreas(area.worldname, region); if (!areas.isEmpty()) { - C.CLUSTER_INTERSECTION.send(player, areas.iterator().next().toString()); + C.CLUSTER_INTERSECTION + .send(player, areas.iterator().next().toString()); return false; } final SetupObject object = new SetupObject(); @@ -110,10 +97,11 @@ public class Area extends SubCommand { object.plotManager = PS.imp().getPluginName(); object.setupGenerator = PS.imp().getPluginName(); object.step = area.getSettingNodes(); - final String path = "worlds." + area.worldname + ".areas." + area.id + '-' + object.min + '-' + object.max; + final String path = + "worlds." + area.worldname + ".areas." + area.id + '-' + + object.min + '-' + object.max; Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (offsetX != 0) { PS.get().worlds.set(path + ".road.offset.x", offsetX); } @@ -126,20 +114,25 @@ public class Area extends SubCommand { C.SETUP_FINISHED.send(player); player.teleport(WorldUtil.IMP.getSpawn(world)); if (area.TERRAIN != 3) { - ChunkManager.largeRegionTask(world, region, new RunnableVal() { - @Override - public void run(ChunkLoc value) { - AugmentedUtils.generate(world, value.x, value.z, null); - } - }, null); + ChunkManager.largeRegionTask(world, region, + new RunnableVal() { + @Override public void run(ChunkLoc value) { + AugmentedUtils + .generate(world, value.x, value.z, + null); + } + }, null); } } else { - MainUtil.sendMessage(player, "An error occurred while creating the world: " + area.worldname); + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + area.worldname); } } }; if (hasConfirmation(player)) { - CmdConfirm.addPending(player, getCommandString() + " create pos2 (Creates world)", run); + CmdConfirm.addPending(player, + getCommandString() + " create pos2 (Creates world)", run); } else { run.run(); } @@ -155,7 +148,8 @@ public class Area extends SubCommand { id = null; } object.world = split[0]; - final HybridPlotWorld pa = new HybridPlotWorld(object.world, id, PS.get().IMP.getDefaultGenerator(), null, null); + final HybridPlotWorld pa = new HybridPlotWorld(object.world, id, + PS.get().IMP.getDefaultGenerator(), null, null); PlotArea other = PS.get().getPlotArea(pa.worldname, id); if (other != null && Objects.equals(pa.id, other.id)) { C.SETUP_WORLD_TAKEN.send(player, pa.toString()); @@ -170,7 +164,8 @@ public class Area extends SubCommand { for (int i = 2; i < args.length; i++) { String[] pair = args[i].split("="); if (pair.length != 2) { - C.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, getCommandString() + + " create [world[:id]] [=]..."); return false; } switch (pair[0].toLowerCase()) { @@ -216,7 +211,8 @@ public class Area extends SubCommand { object.type = pa.TYPE; break; default: - C.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, getCommandString() + + " create [world[:id]] [=]..."); return false; } } @@ -226,13 +222,13 @@ public class Area extends SubCommand { return false; } Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { String path = "worlds." + pa.worldname; if (!PS.get().worlds.contains(path)) { PS.get().worlds.createSection(path); } - ConfigurationSection section = PS.get().worlds.getConfigurationSection(path); + ConfigurationSection section = + PS.get().worlds.getConfigurationSection(path); pa.saveConfiguration(section); pa.loadConfiguration(section); object.plotManager = PS.imp().getPluginName(); @@ -242,7 +238,9 @@ public class Area extends SubCommand { C.SETUP_FINISHED.send(player); player.teleport(WorldUtil.IMP.getSpawn(world)); } else { - MainUtil.sendMessage(player, "An error occurred while creating the world: " + pa.worldname); + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + pa.worldname); } try { PS.get().worlds.save(PS.get().worldsFile); @@ -252,14 +250,16 @@ public class Area extends SubCommand { } }; if (hasConfirmation(player)) { - CmdConfirm.addPending(player, getCommandString() + ' ' + StringMan.join(args, " "), run); + CmdConfirm.addPending(player, + getCommandString() + ' ' + StringMan.join(args, " "), run); } else { run.run(); } return true; } if (pa.id == null) { - C.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, getCommandString() + + " create [world[:id]] [=]..."); return false; } if (WorldUtil.IMP.isWorld(pa.worldname)) { @@ -273,7 +273,9 @@ public class Area extends SubCommand { player.teleport(WorldUtil.IMP.getSpawn(pa.worldname)); } player.setMeta("area_create_area", pa); - MainUtil.sendMessage(player, "$1Go to the first corner and use: $2 " + getCommandString() + " create pos1"); + MainUtil.sendMessage(player, + "$1Go to the first corner and use: $2 " + getCommandString() + + " create pos1"); break; } return true; @@ -321,15 +323,12 @@ public class Area extends SubCommand { percent = claimed == 0 ? 0 : 100d * claimed / Integer.MAX_VALUE; region = "N/A"; } - String value = "&r$1NAME: " + name - + "\n$1Type: $2" + area.TYPE - + "\n$1Terrain: $2" + area.TERRAIN - + "\n$1Usage: $2" + String.format("%.2f", percent) + '%' - + "\n$1Claimed: $2" + claimed - + "\n$1Clusters: $2" + clusters - + "\n$1Region: $2" + region - + "\n$1Generator: $2" + generator; - MainUtil.sendMessage(player, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); + String value = "&r$1NAME: " + name + "\n$1Type: $2" + area.TYPE + "\n$1Terrain: $2" + + area.TERRAIN + "\n$1Usage: $2" + String.format("%.2f", percent) + '%' + + "\n$1Claimed: $2" + claimed + "\n$1Clusters: $2" + clusters + "\n$1Region: $2" + + region + "\n$1Generator: $2" + generator; + MainUtil.sendMessage(player, + C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); return true; } case "l": @@ -353,44 +352,45 @@ public class Area extends SubCommand { return false; } ArrayList areas = new ArrayList<>(PS.get().getPlotAreas()); - paginate(player, areas, 8, page, new RunnableVal3() { - @Override - public void run(Integer i, PlotArea area, PlotMessage message) { - String name; - double percent; - int claimed = area.getPlotCount(); - int clusters = area.getClusters().size(); - String region; - String generator = String.valueOf(area.getGenerator()); - if (area.TYPE == 2) { - PlotId min = area.getMin(); - PlotId max = area.getMax(); - name = area.worldname + ';' + area.id + ';' + min + ';' + max; - int size = (max.x - min.x + 1) * (max.y - min.y + 1); - percent = claimed == 0 ? 0 : size / (double) claimed; - region = area.getRegion().toString(); - } else { - name = area.worldname; - percent = claimed == 0 ? 0 : Short.MAX_VALUE * Short.MAX_VALUE / (double) claimed; - region = "N/A"; - } - PlotMessage tooltip = new PlotMessage() - .text("Claimed=").color("$1").text(String.valueOf(claimed)).color("$2") - .text("\nUsage=").color("$1").text(String.format("%.2f", percent) + '%').color("$2") - .text("\nClusters=").color("$1").text(String.valueOf(clusters)).color("$2") - .text("\nRegion=").color("$1").text(region).color("$2") + paginate(player, areas, 8, page, + new RunnableVal3() { + @Override public void run(Integer i, PlotArea area, PlotMessage message) { + String name; + double percent; + int claimed = area.getPlotCount(); + int clusters = area.getClusters().size(); + String region; + String generator = String.valueOf(area.getGenerator()); + if (area.TYPE == 2) { + PlotId min = area.getMin(); + PlotId max = area.getMax(); + name = area.worldname + ';' + area.id + ';' + min + ';' + max; + int size = (max.x - min.x + 1) * (max.y - min.y + 1); + percent = claimed == 0 ? 0 : size / (double) claimed; + region = area.getRegion().toString(); + } else { + name = area.worldname; + percent = claimed == 0 ? + 0 : + Short.MAX_VALUE * Short.MAX_VALUE / (double) claimed; + region = "N/A"; + } + PlotMessage tooltip = new PlotMessage().text("Claimed=").color("$1") + .text(String.valueOf(claimed)).color("$2").text("\nUsage=") + .color("$1").text(String.format("%.2f", percent) + '%').color("$2") + .text("\nClusters=").color("$1").text(String.valueOf(clusters)) + .color("$2").text("\nRegion=").color("$1").text(region).color("$2") .text("\nGenerator=").color("$1").text(generator).color("$2"); - // type / terrain - String visit = "/plot area tp " + area.toString(); - message.text("[").color("$3") - .text(String.valueOf(i)).command(visit).tooltip(visit).color("$1") - .text("]").color("$3") - .text(' ' + name).tooltip(tooltip).command(getCommandString() + " info " + area).color("$1").text(" - ") - .color("$2") + // type / terrain + String visit = "/plot area tp " + area.toString(); + message.text("[").color("$3").text(String.valueOf(i)).command(visit) + .tooltip(visit).color("$1").text("]").color("$3").text(' ' + name) + .tooltip(tooltip).command(getCommandString() + " info " + area) + .color("$1").text(" - ").color("$2") .text(area.TYPE + ":" + area.TERRAIN).color("$3"); - } - }, "/plot area list", C.AREA_LIST_HEADER_PAGED.s()); + } + }, "/plot area list", C.AREA_LIST_HEADER_PAGED.s()); return true; case "regen": case "clear": @@ -406,20 +406,20 @@ public class Area extends SubCommand { return false; } if (area.TYPE != 2) { - MainUtil.sendMessage(player, "$4Stop the server and delete: " + area.worldname + "/region"); + MainUtil.sendMessage(player, + "$4Stop the server and delete: " + area.worldname + "/region"); return false; } - ChunkManager.largeRegionTask(area.worldname, area.getRegion(), new RunnableVal() { - @Override - public void run(ChunkLoc value) { - AugmentedUtils.generate(area.worldname, value.x, value.z, null); - } - }, new Runnable() { - @Override - public void run() { - player.sendMessage("Regen complete"); - } - }); + ChunkManager + .largeRegionTask(area.worldname, area.getRegion(), new RunnableVal() { + @Override public void run(ChunkLoc value) { + AugmentedUtils.generate(area.worldname, value.x, value.z, null); + } + }, new Runnable() { + @Override public void run() { + player.sendMessage("Regen complete"); + } + }); return true; } case "goto": @@ -445,17 +445,20 @@ public class Area extends SubCommand { center = WorldUtil.IMP.getSpawn(area.worldname); } else { RegionWrapper region = area.getRegion(); - center = new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, 0, - region.minZ + (region.maxZ - region.minZ) / 2); - center.setY(1 + WorldUtil.IMP.getHighestBlock(area.worldname, center.getX(), center.getZ())); + center = + new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, + 0, region.minZ + (region.maxZ - region.minZ) / 2); + center.setY(1 + WorldUtil.IMP + .getHighestBlock(area.worldname, center.getX(), center.getZ())); } player.teleport(center); return true; case "delete": case "remove": - MainUtil.sendMessage(player, "$1World creation settings may be stored in multiple locations:" - + "\n$3 - $2Bukkit bukkit.yml" - + "\n$3 - $2" + PS.imp().getPluginName() + " settings.yml" + MainUtil.sendMessage(player, + "$1World creation settings may be stored in multiple locations:" + + "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PS.imp().getPluginName() + + " settings.yml" + "\n$3 - $2Multiverse worlds.yml (or any world management plugin)" + "\n$1Stop the server and delete it from these locations."); return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java index cc50723d4..9f44155d6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java @@ -4,43 +4,167 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.ByteArrayUtilities; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.CommandDeclaration; import javax.annotation.Nullable; import java.util.Set; -@CommandDeclaration(command = "auto", - permission = "plots.auto", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - description = "Claim the nearest plot", - aliases = "a", - usage = "/plot auto [length,width]") +@CommandDeclaration(command = "auto", permission = "plots.auto", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, description = "Claim the nearest plot", aliases = "a", usage = "/plot auto [length,width]") public class Auto extends SubCommand { - @Deprecated - public static PlotId getNextPlotId(PlotId id, int step) { + @Deprecated public static PlotId getNextPlotId(PlotId id, int step) { return id.getNextId(step); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, + @Nullable Integer allowed_plots, int size_x, int size_z) { + if (allowed_plots == null) + allowed_plots = player.getAllowedPlots(); + int currentPlots = + Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname); + int diff = currentPlots - allowed_plots; + if (diff + size_x * size_z > 0) { + if (diff < 0) { + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); + return false; + } else if (player.hasPersistentMeta("grantedPlots")) { + int grantedPlots = + ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); + if (grantedPlots - diff < size_x * size_z) { + player.removePersistentMeta("grantedPlots"); + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + return false; + } else { + int left = grantedPlots - diff - size_x * size_z; + if (left == 0) { + player.removePersistentMeta("grantedPlots"); + } else { + player.setPersistentMeta("grantedPlots", + ByteArrayUtilities.integerToBytes(left)); + } + MainUtil.sendMessage(player, C.REMOVED_GRANTED_PLOT, "" + left, + "" + (grantedPlots - left)); + } + } else { + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + return false; + } + } + return true; + } + + /** + * Get the next plot id (spiral out from 0,0) + * + * @param start + * @return + */ + @Deprecated public static PlotId getNextPlot(PlotId start) { + int plots; + PlotId center; + center = new PlotId(0, 0); + plots = Integer.MAX_VALUE; + PlotId currentId; + for (int i = 0; i < plots; i++) { + if (start == null) { + start = new PlotId(0, 0); + } else { + start = start.getNextId(1); + } + currentId = new PlotId(center.x + start.x, center.y + start.y); + return currentId; + } + return null; + } + + /** + * Teleport the player home, or claim a new plot + * + * @param player + * @param area + * @param start + * @param schem + */ + public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start, + final String schem) { + Set plots = player.getPlots(); + if (!plots.isEmpty()) { + plots.iterator().next().teleportPlayer(player); + } else { + autoClaimSafe(player, area, start, schem); + } + } + + /** + * Claim a new plot for a player + * + * @param player + * @param area + * @param start + * @param schem + */ + public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, + final String schem) { + autoClaimSafe(player, area, start, schem, null); + } + + /** + * Claim a new plot for a player + * + * @param player + * @param area + * @param start + * @param schem + */ + public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, + final String schem, @Nullable Integer allowed_plots) { + player.setMeta(Auto.class.getName(), true); + autoClaimFromDatabase(player, area, start, new RunnableVal() { + @Override public void run(final Plot plot) { + TaskManager.IMP.sync(new RunnableVal() { + @Override public void run(Object ignore) { + player.deleteMeta(Auto.class.getName()); + if (plot == null) { + MainUtil.sendMessage(player, C.NO_FREE_PLOTS); + } else if (checkAllowedPlots(player, area, allowed_plots, 1, 1)) { + plot.claim(player, true, schem, false); + if (area.AUTO_MERGE) { + plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); + } + } else { + DBFunc.delete(plot); + } + } + }); + } + }); + } + + public static void autoClaimFromDatabase(final PlotPlayer player, final PlotArea area, + PlotId start, final RunnableVal whenDone) { + final Plot plot = area.getNextFreePlot(player, start); + if (plot == null) { + whenDone.run(null); + return; + } + whenDone.value = plot; + plot.owner = player.getUUID(); + DBFunc.createPlotSafe(plot, whenDone, new Runnable() { + @Override public void run() { + autoClaimFromDatabase(player, area, plot.getId(), whenDone); + } + }); + } + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { PlotArea plotarea = player.getApplicablePlotArea(); if (plotarea == null) { if (EconHandler.manager != null) { for (PlotArea area : PS.get().getPlotAreaManager().getAllPlotAreas()) { - if (EconHandler.manager.hasPermission(area.worldname, player.getName(), "plots.auto")) { + if (EconHandler.manager + .hasPermission(area.worldname, player.getName(), "plots.auto")) { if (plotarea != null) { plotarea = null; break; @@ -84,25 +208,32 @@ public class Auto extends SubCommand { } } if (size_x * size_z > Settings.Claim.MAX_AUTO_AREA) { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, Settings.Claim.MAX_AUTO_AREA + ""); + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, + Settings.Claim.MAX_AUTO_AREA + ""); return false; } final int allowed_plots = player.getAllowedPlots(); - if (player.getMeta(Auto.class.getName(), false) || !checkAllowedPlots(player, plotarea, allowed_plots, size_x, size_z)) return false; + if (player.getMeta(Auto.class.getName(), false) || !checkAllowedPlots(player, plotarea, + allowed_plots, size_x, size_z)) + return false; if (schematic != null && !schematic.isEmpty()) { if (!plotarea.SCHEMATICS.contains(schematic.toLowerCase())) { sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic); return true; } - if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)); + if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)); return true; } } if (EconHandler.manager != null && plotarea.USE_ECONOMY) { Expression costExp = plotarea.PRICES.get("claim"); - double cost = costExp.evaluate((double) (Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname))); + double cost = costExp.evaluate((double) (Settings.Limit.GLOBAL ? + player.getPlotCount() : + player.getPlotCount(plotarea.worldname))); cost = (size_x * size_z) * cost; if (cost > 0d) { if (EconHandler.manager.getMoney(player) < cost) { @@ -134,7 +265,8 @@ public class Auto extends SubCommand { plot.claim(player, teleport, null); } } - if (!plotarea.mergePlots(MainUtil.getPlotSelectionIds(start, end), true, true)) { + if (!plotarea + .mergePlots(MainUtil.getPlotSelectionIds(start, end), true, true)) { return false; } break; @@ -144,135 +276,4 @@ public class Auto extends SubCommand { return true; } } - - private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, @Nullable Integer allowed_plots, int size_x, int size_z) { - if (allowed_plots == null) - allowed_plots = player.getAllowedPlots(); - int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname); - int diff = currentPlots - allowed_plots; - if (diff + size_x * size_z > 0) { - if (diff < 0) { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); - return false; - } else if (player.hasPersistentMeta("grantedPlots")) { - int grantedPlots = ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); - if (grantedPlots - diff < size_x * size_z) { - player.removePersistentMeta("grantedPlots"); - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); - return false; - } else { - int left = grantedPlots - diff - size_x * size_z; - if (left == 0) { - player.removePersistentMeta("grantedPlots"); - } else { - player.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(left)); - } - MainUtil.sendMessage(player, C.REMOVED_GRANTED_PLOT, "" + left, "" + (grantedPlots - left)); - } - } else { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); - return false; - } - } - return true; - } - - /** - * Get the next plot id (spiral out from 0,0) - * @param start - * @return - */ - @Deprecated - public static PlotId getNextPlot(PlotId start) { - int plots; - PlotId center; - center = new PlotId(0, 0); - plots = Integer.MAX_VALUE; - PlotId currentId; - for (int i = 0; i < plots; i++) { - if (start == null) { - start = new PlotId(0, 0); - } else { - start = start.getNextId(1); - } - currentId = new PlotId(center.x + start.x, center.y + start.y); - return currentId; - } - return null; - } - - /** - * Teleport the player home, or claim a new plot - * @param player - * @param area - * @param start - * @param schem - */ - public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start, final String schem) { - Set plots = player.getPlots(); - if (!plots.isEmpty()) { - plots.iterator().next().teleportPlayer(player); - } else { - autoClaimSafe(player, area, start, schem); - } - } - - /** - * Claim a new plot for a player - * @param player - * @param area - * @param start - * @param schem - */ - public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, final String schem) { - autoClaimSafe(player, area, start, schem, null); - } - - /** - * Claim a new plot for a player - * @param player - * @param area - * @param start - * @param schem - */ - public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, final String schem, @Nullable Integer allowed_plots) { - player.setMeta(Auto.class.getName(), true); - autoClaimFromDatabase(player, area, start, new RunnableVal() { - @Override - public void run(final Plot plot) { - TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object ignore) { - player.deleteMeta(Auto.class.getName()); - if (plot == null) { - MainUtil.sendMessage(player, C.NO_FREE_PLOTS); - } else if (checkAllowedPlots(player, area, allowed_plots, 1, 1)) { - plot.claim(player, true, schem, false); - if (area.AUTO_MERGE) { - plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); - } - } else { - DBFunc.delete(plot); - } - } - }); - } - }); - } - - public static void autoClaimFromDatabase(final PlotPlayer player, final PlotArea area, PlotId start, final RunnableVal whenDone) { - final Plot plot = area.getNextFreePlot(player, start); - if (plot == null) { - whenDone.run(null); - return; - } - whenDone.value = plot; - plot.owner = player.getUUID(); - DBFunc.createPlotSafe(plot, whenDone, new Runnable() { - @Override - public void run() { - autoClaimFromDatabase(player, area, plot.getId(), whenDone); - } - }); - } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java index e9ec94e91..a25a7679f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/BO3.java @@ -9,12 +9,8 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "bo3", - aliases = {"bo2"}, - description = "Mark a plot as done", - permission = "plots.bo3", - category = CommandCategory.SCHEMATIC, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "bo3", aliases = { + "bo2"}, description = "Mark a plot as done", permission = "plots.bo3", category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE) public class BO3 extends SubCommand { public void noArgs(PlotPlayer player) { @@ -22,14 +18,14 @@ public class BO3 extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot bo3 import "); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null || !plot.hasOwner()) { return !sendMessage(player, C.NOT_IN_PLOT); } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_BO3)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_BO3)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java index b43ad37ec..3c187173c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Biome.java @@ -8,21 +8,16 @@ import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "setbiome", - permission = "plots.set.biome", - description = "Set the plot biome", - usage = "/plot biome [biome]", - aliases = {"biome", "sb", "setb", "b"}, - category = CommandCategory.APPEARANCE, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "setbiome", permission = "plots.set.biome", description = "Set the plot biome", usage = "/plot biome [biome]", aliases = { + "biome", "sb", "setb", + "b"}, category = CommandCategory.APPEARANCE, requiredType = RequiredType.NONE) public class Biome extends SetCommand { - @Override - public boolean set(final PlotPlayer player, final Plot plot, final String value) { + @Override public boolean set(final PlotPlayer player, final Plot plot, final String value) { int biome = WorldUtil.IMP.getBiomeFromString(value); if (biome == -1) { - String biomes = StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s()); + String biomes = + StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s()); C.NEED_BIOME.send(player); MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes); return false; @@ -33,8 +28,7 @@ public class Biome extends SetCommand { } plot.addRunning(); plot.setBiome(value.toUpperCase(), new Runnable() { - @Override - public void run() { + @Override public void run() { plot.removeRunning(); MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase()); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java index 38d260ebf..10f2040a6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java @@ -15,21 +15,16 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.Set; -@CommandDeclaration( - command = "buy", - description = "Buy the plot you are standing on", - usage = "/plot buy", - permission = "plots.buy", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "buy", description = "Buy the plot you are standing on", usage = "/plot buy", permission = "plots.buy", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Buy extends Command { public Buy() { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, final RunnableVal2 whenDone) { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + final RunnableVal2 whenDone) { check(EconHandler.manager, C.ECON_DISABLED); final Plot plot; if (args.length != 0) { @@ -41,7 +36,8 @@ public class Buy extends Command { checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); checkTrue(!plot.isOwner(player.getUUID()), C.CANNOT_BUY_OWN); Set plots = plot.getConnectedPlots(); - checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(), C.CANT_CLAIM_MORE_PLOTS); + checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(), + C.CANT_CLAIM_MORE_PLOTS); Optional flag = plot.getFlag(Flags.PRICE); if (!flag.isPresent()) { throw new CommandException(C.NOT_FOR_SALE); @@ -53,7 +49,8 @@ public class Buy extends Command { @Override // Success public void run() { C.REMOVED_BALANCE.send(player, price); - EconHandler.manager.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price); + EconHandler.manager + .depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price); PlotPlayer owner = UUIDHandler.getPlayer(plot.owner); if (owner != null) { C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Changelog.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Changelog.java index ab665b841..85d9ac5e1 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Changelog.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Changelog.java @@ -5,31 +5,26 @@ import com.intellectualcrafters.plot.Updater; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.IOException; import java.net.URL; import java.util.Scanner; -@CommandDeclaration( - command = "changelog", - permission = "plots.admin.command.changelog", - description = "View the changelog", - usage = "/plot changelog", - requiredType = RequiredType.NONE, - aliases = {"cl"}, - category = CommandCategory.ADMINISTRATION) -public class Changelog extends SubCommand { +@CommandDeclaration(command = "changelog", permission = "plots.admin.command.changelog", description = "View the changelog", usage = "/plot changelog", requiredType = RequiredType.NONE, aliases = { + "cl"}, category = CommandCategory.ADMINISTRATION) public class Changelog extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { try { Updater updater = PS.get().getUpdater(); String changes = updater != null ? updater.getChanges() : null; if (changes == null) { - try (Scanner scanner = new Scanner(new URL("http://empcraft.com/plots/cl?" + Integer.toHexString(PS.get().getVersion().hash)).openStream(), "UTF-8")) { + try (Scanner scanner = new Scanner(new URL("http://empcraft.com/plots/cl?" + Integer + .toHexString(PS.get().getVersion().hash)).openStream(), "UTF-8")) { changes = scanner.useDelimiter("\\A").next(); } } - changes = changes.replaceAll("#([0-9]+)", "github.com/IntellectualSites/PlotSquared/pulls/$1"); + changes = changes + .replaceAll("#([0-9]+)", "github.com/IntellectualSites/PlotSquared/pulls/$1"); MainUtil.sendMessage(player, changes); } catch (IOException e) { throw new RuntimeException(e); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java index d99a54ebd..679812e84 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Chat.java @@ -3,17 +3,10 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "chat", - description = "Toggle plot chat on or off", - usage = "/plot chat [on|off]", - permission = "plots.chat", - category = CommandCategory.CHAT, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "chat", description = "Toggle plot chat on or off", usage = "/plot chat [on|off]", permission = "plots.chat", category = CommandCategory.CHAT, requiredType = RequiredType.NONE) public class Chat extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { MainCommand.getInstance().toggle.chat(this, player, new String[0], null, null); return true; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java index eedc900ae..0f13fb9a6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java @@ -3,28 +3,17 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.ByteArrayUtilities; import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "claim", - aliases = "c", - description = "Claim the current plot you're standing on", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - permission = "plots.claim", usage = "/plot claim") +@CommandDeclaration(command = "claim", aliases = "c", description = "Claim the current plot you're standing on", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, permission = "plots.claim", usage = "/plot claim") public class Claim extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String schematic = ""; if (args.length >= 1) { schematic = args[0]; @@ -34,11 +23,13 @@ public class Claim extends SubCommand { if (plot == null) { return sendMessage(player, C.NOT_IN_PLOT); } - int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); + int currentPlots = + Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); int grants = 0; if (currentPlots >= player.getAllowedPlots()) { if (player.hasPersistentMeta("grantedPlots")) { - grants = ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); + grants = + ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); if (grants <= 0) { player.removePersistentMeta("grantedPlots"); return sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); @@ -56,7 +47,8 @@ public class Claim extends SubCommand { if (!area.SCHEMATICS.contains(schematic.toLowerCase())) { return sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic); } - if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { + if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { return sendMessage(player, C.NO_SCHEMATIC_PERMISSION, schematic); } } @@ -80,7 +72,8 @@ public class Claim extends SubCommand { if (grants == 1) { player.removePersistentMeta("grantedPlots"); } else { - player.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(grants - 1)); + player.setPersistentMeta("grantedPlots", + ByteArrayUtilities.integerToBytes(grants - 1)); } sendMessage(player, C.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1)); } @@ -88,11 +81,9 @@ public class Claim extends SubCommand { plot.owner = player.getUUID(); final String finalSchematic = schematic; DBFunc.createPlotSafe(plot, new Runnable() { - @Override - public void run() { + @Override public void run() { TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { + @Override public void run(Object value) { plot.claim(player, true, finalSchematic, false); if (area.AUTO_MERGE) { plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); @@ -101,8 +92,7 @@ public class Claim extends SubCommand { }); } }, new Runnable() { - @Override - public void run() { + @Override public void run() { sendMessage(player, C.PLOT_NOT_CLAIMED); } }); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java index 375d408c6..ec845e57f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Clear.java @@ -14,13 +14,7 @@ import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "clear", - description = "Clear a plot", - permission = "plots.clear", - category = CommandCategory.APPEARANCE, - usage = "/plot clear", - aliases = "reset", - confirmation = true) +@CommandDeclaration(command = "clear", description = "Clear a plot", permission = "plots.clear", category = CommandCategory.APPEARANCE, usage = "/plot clear", aliases = "reset", confirmation = true) public class Clear extends Command { // Note: To clear a specific plot use /plot clear @@ -30,24 +24,24 @@ public class Clear extends Command { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { checkTrue(args.length == 0, C.COMMAND_SYNTAX, getUsage()); final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); - checkTrue(plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CLEAR), C.NO_PLOT_PERMS); + checkTrue(plot.isOwner(player.getUUID()) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CLEAR), C.NO_PLOT_PERMS); checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER); - checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions.hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE); + checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions + .hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE); confirm.run(this, new Runnable() { - @Override - public void run() { + @Override public void run() { final long start = System.currentTimeMillis(); boolean result = plot.clear(true, false, new Runnable() { - @Override - public void run() { + @Override public void run() { plot.unlink(); GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.removeRunning(); // If the state changes, then mark it as no longer done if (plot.getFlag(Flags.DONE).isPresent()) { @@ -56,7 +50,8 @@ public class Clear extends Command { if (plot.getFlag(Flags.ANALYSIS).isPresent()) { FlagManager.removePlotFlag(plot, Flags.ANALYSIS); } - MainUtil.sendMessage(player, C.CLEARING_DONE, "" + (System.currentTimeMillis() - start)); + MainUtil.sendMessage(player, C.CLEARING_DONE, + "" + (System.currentTimeMillis() - start)); } }); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java index 28572b8f5..1bc8c4a67 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java @@ -4,32 +4,21 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.BlockLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "cluster", - aliases = "clusters", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.NONE, - permission = "plots.cluster", - description = "Manage a plot cluster") +@CommandDeclaration(command = "cluster", aliases = "clusters", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.NONE, permission = "plots.cluster", description = "Manage a plot cluster") public class Cluster extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome if (args.length == 0) { @@ -83,10 +72,13 @@ public class Cluster extends SubCommand { return false; } if (args.length != 4) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster create "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster create "); return false; } - int currentClusters = Settings.Limit.GLOBAL ? player.getClusterCount() : player.getPlotCount(player.getLocation().getWorld()); + int currentClusters = Settings.Limit.GLOBAL ? + player.getClusterCount() : + player.getPlotCount(player.getLocation().getWorld()); if (currentClusters >= player.getAllowedPlots()) { return sendMessage(player, C.CANT_CLAIM_MORE_CLUSTERS); } @@ -125,7 +117,8 @@ public class Cluster extends SubCommand { UUID uuid = player.getUUID(); for (Plot plot : plots) { if (!plot.isOwner(uuid)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_CREATE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_CREATE_OTHER); return false; } } @@ -139,9 +132,11 @@ public class Cluster extends SubCommand { } else { current = player.getPlayerClusterCount(player.getLocation().getWorld()); } - int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER_SIZE, Settings.Limit.MAX_PLOTS); + int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER_SIZE, + Settings.Limit.MAX_PLOTS); if (current + cluster.getArea() > allowed) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea())); return false; } // create cluster @@ -192,7 +187,8 @@ public class Cluster extends SubCommand { } if (!cluster.owner.equals(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_DELETE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_DELETE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_DELETE_OTHER); return false; } } @@ -207,7 +203,8 @@ public class Cluster extends SubCommand { return false; } if (args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster resize "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster resize "); return false; } // check pos1 / pos2 @@ -234,7 +231,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_RESIZE_OTHER); return false; } } @@ -244,21 +242,24 @@ public class Cluster extends SubCommand { MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, intersect.getName()); return false; } - HashSet existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); + HashSet existing = + area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); HashSet newPlots = area.getPlotSelectionOwned(pos1, pos2); HashSet removed = (HashSet) existing.clone(); removed.removeAll(newPlots); // Check expand / shrink if (!removed.isEmpty()) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_SHRINK)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE_SHRINK); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_RESIZE_SHRINK); return false; } } newPlots.removeAll(existing); if (!newPlots.isEmpty()) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_EXPAND)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE_EXPAND); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_RESIZE_EXPAND); return false; } } @@ -270,9 +271,11 @@ public class Cluster extends SubCommand { current = player.getPlayerClusterCount(player.getLocation().getWorld()); } current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); - int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER, Settings.Limit.MAX_PLOTS); + int allowed = Permissions + .hasPermissionRange(player, C.PERMISSION_CLUSTER, Settings.Limit.MAX_PLOTS); if (current + cluster.getArea() > allowed) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea())); return false; } // resize cluster @@ -303,7 +306,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INVITE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_INVITE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_INVITE_OTHER); return false; } } @@ -347,7 +351,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_KICK_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK_OTHER); + MainUtil + .sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK_OTHER); return false; } } @@ -358,7 +363,8 @@ public class Cluster extends SubCommand { return false; } // Can't kick if the player is yourself, the owner, or not added to the cluster - if (uuid.equals(player.getUUID()) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) { + if (uuid.equals(player.getUUID()) || uuid.equals(cluster.owner) || !cluster + .isAdded(uuid)) { MainUtil.sendMessage(player, C.CANNOT_KICK_PLAYER, cluster.getName()); return false; } @@ -372,7 +378,8 @@ public class Cluster extends SubCommand { if (player2 != null) { MainUtil.sendMessage(player2, C.CLUSTER_REMOVED, cluster.getName()); } - for (Plot plot : new ArrayList<>(PS.get().getPlots(player2.getLocation().getWorld(), uuid))) { + for (Plot plot : new ArrayList<>( + PS.get().getPlots(player2.getLocation().getWorld(), uuid))) { PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { plot.unclaim(); @@ -425,7 +432,8 @@ public class Cluster extends SubCommand { cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); - for (Plot plot : new ArrayList<>(PS.get().getPlots(player.getLocation().getWorld(), uuid))) { + for (Plot plot : new ArrayList<>( + PS.get().getPlots(player.getLocation().getWorld(), uuid))) { PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { player.getLocation().getWorld(); @@ -443,7 +451,8 @@ public class Cluster extends SubCommand { return false; } if (args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster helpers "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster helpers "); return false; } PlotArea area = player.getApplicablePlotArea(); @@ -470,7 +479,8 @@ public class Cluster extends SubCommand { DBFunc.removeHelper(cluster, uuid); return MainUtil.sendMessage(player, C.CLUSTER_REMOVED_HELPER); } - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster helpers "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster helpers "); return false; } case "spawn": @@ -497,7 +507,8 @@ public class Cluster extends SubCommand { UUID uuid = player.getUUID(); if (!cluster.isAdded(uuid)) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_TP_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP_OTHER); + MainUtil + .sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP_OTHER); return false; } } @@ -540,7 +551,8 @@ public class Cluster extends SubCommand { owner = "unknown"; } String name = cluster.getName(); - String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + (cluster.getP2().y - cluster.getP1().y + 1); + String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + ( + cluster.getP2().y - cluster.getP1().y + 1); String rights = cluster.isAdded(player.getUUID()) + ""; String message = C.CLUSTER_INFO.s(); message = message.replaceAll("%id%", id); @@ -573,7 +585,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_SETHOME_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_SETHOME_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_SETHOME_OTHER); return false; } } @@ -581,7 +594,8 @@ public class Cluster extends SubCommand { Location relative = player.getLocation().subtract(base.getX(), 0, base.getZ()); BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ()); cluster.settings.setPosition(blockloc); - DBFunc.setPosition(cluster, relative.getX() + "," + relative.getY() + "," + relative.getZ()); + DBFunc.setPosition(cluster, + relative.getX() + "," + relative.getY() + "," + relative.getZ()); return MainUtil.sendMessage(player, C.POSITION_SET); } MainUtil.sendMessage(player, C.CLUSTER_AVAILABLE_ARGS); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java index f85efc302..e724986af 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java @@ -8,39 +8,31 @@ public enum CommandCategory { * Claiming CommandConfig. * Such as: /plot claim */ - CLAIMING("Claiming"), - /** + CLAIMING("Claiming"), /** * Teleportation CommandConfig. * Such as: /plot visit */ - TELEPORT("Teleport"), - /** + TELEPORT("Teleport"), /** * Protection. */ - SETTINGS("Protection"), - /** + SETTINGS("Protection"), /** * Chat. */ - CHAT("Chat"), - /** + CHAT("Chat"), /** * Web. */ - SCHEMATIC("Web"), - /** + SCHEMATIC("Web"), /** * Cosmetic. */ - APPEARANCE("Cosmetic"), - /** + APPEARANCE("Cosmetic"), /** * Information CommandConfig. * Such as: /plot info */ - INFO("Info"), - /** + INFO("Info"), /** * Debug CommandConfig. * Such as: /plot debug */ - DEBUG("Debug"), - /** + DEBUG("Debug"), /** * Administration commands. */ ADMINISTRATION("Admin"); @@ -48,6 +40,7 @@ public enum CommandCategory { * The category name (Readable). */ private final String name; + /** * Constructor. * @@ -57,8 +50,7 @@ public enum CommandCategory { this.name = name; } - @Override - public String toString() { + @Override public String toString() { return this.name; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java index 37341b447..222115561 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Comment.java @@ -16,23 +16,20 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.Arrays; import java.util.Map.Entry; -@CommandDeclaration(command = "comment", - aliases = {"msg"}, - description = "Comment on a plot", - category = CommandCategory.CHAT, - requiredType = RequiredType.NONE, - permission = "plots.comment") +@CommandDeclaration(command = "comment", aliases = { + "msg"}, description = "Comment on a plot", category = CommandCategory.CHAT, requiredType = RequiredType.NONE, permission = "plots.comment") public class Comment extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if (args.length < 2) { - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); if (inbox == null) { - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } Location loc = player.getLocation(); @@ -44,7 +41,8 @@ public class Comment extends SubCommand { plot = loc.getPlotAbs(); } else { if (args.length < 4) { - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } index = 2; @@ -54,11 +52,14 @@ public class Comment extends SubCommand { return false; } String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " "); - PlotComment comment = new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), System.currentTimeMillis()); + PlotComment comment = + new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), + System.currentTimeMillis()); boolean result = inbox.addComment(plot, comment); if (!result) { sendMessage(player, C.NO_PLOT_INBOX, ""); - sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } for (Entry entry : UUIDHandler.getPlayers().entrySet()) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java index 17586dc82..cd08ff970 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java @@ -11,25 +11,16 @@ import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; +import java.util.*; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -@CommandDeclaration(command = "condense", - permission = "plots.admin", - description = "Condense a plotworld", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.CONSOLE) +@CommandDeclaration(command = "condense", permission = "plots.admin", description = "Condense a plotworld", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE) public class Condense extends SubCommand { public static boolean TASK = false; - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length != 2 && args.length != 3) { MainUtil.sendMessage(player, "/plot condense [radius]"); return false; @@ -42,7 +33,8 @@ public class Condense extends SubCommand { switch (args[1].toLowerCase()) { case "start": { if (args.length == 2) { - MainUtil.sendMessage(player, "/plot condense " + area.toString() + " start "); + MainUtil.sendMessage(player, + "/plot condense " + area.toString() + " start "); return false; } if (Condense.TASK) { @@ -112,14 +104,14 @@ public class Condense extends SubCommand { } MainUtil.sendMessage(player, "TASK STARTED..."); Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (!Condense.TASK) { MainUtil.sendMessage(player, "TASK CANCELLED."); } if (allPlots.isEmpty()) { Condense.TASK = false; - MainUtil.sendMessage(player, "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); + MainUtil.sendMessage(player, + "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); return; } final Runnable task = this; @@ -134,10 +126,10 @@ public class Condense extends SubCommand { i++; final AtomicBoolean result = new AtomicBoolean(false); result.set(origin.move(possible, new Runnable() { - @Override - public void run() { + @Override public void run() { if (result.get()) { - MainUtil.sendMessage(player, "Moving: " + origin + " -> " + possible); + MainUtil.sendMessage(player, + "Moving: " + origin + " -> " + possible); TaskManager.runTaskLater(task, 1); } } @@ -170,7 +162,8 @@ public class Condense extends SubCommand { return true; case "info": if (args.length == 2) { - MainUtil.sendMessage(player, "/plot condense " + area.toString() + " info "); + MainUtil.sendMessage(player, + "/plot condense " + area.toString() + " info "); return false; } if (!MathMan.isInteger(args[2])) { @@ -193,18 +186,21 @@ public class Condense extends SubCommand { MainUtil.sendMessage(player, "=== INPUT EVAL ==="); MainUtil.sendMessage(player, "INPUT RADIUS: " + radius); MainUtil.sendMessage(player, "ESTIMATED MOVES: " + userMove); - MainUtil.sendMessage(player, "ESTIMATED TIME: No idea, times will drastically change based on the system performance and load"); + MainUtil.sendMessage(player, + "ESTIMATED TIME: No idea, times will drastically change based on the system performance and load"); MainUtil.sendMessage(player, "&e - Radius is measured in plot width"); return true; } - MainUtil.sendMessage(player, "/plot condense " + area.worldname + " [radius]"); + MainUtil.sendMessage(player, + "/plot condense " + area.worldname + " [radius]"); return false; } public Set getPlots(Collection plots, int radius) { HashSet outside = new HashSet<>(); for (Plot plot : plots) { - if (plot.getId().x > radius || plot.getId().x < -radius || plot.getId().y > radius || plot.getId().y < -radius) { + if (plot.getId().x > radius || plot.getId().x < -radius || plot.getId().y > radius + || plot.getId().y < -radius) { outside.add(plot.getId()); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java index e794397ec..9e28da7cb 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Confirm.java @@ -9,21 +9,18 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "confirm", - permission = "plots.use", - description = "Confirm an action", - category = CommandCategory.INFO) +@CommandDeclaration(command = "confirm", permission = "plots.use", description = "Confirm an action", category = CommandCategory.INFO) public class Confirm extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { CmdInstance command = CmdConfirm.getPending(player); if (command == null) { MainUtil.sendMessage(player, C.FAILED_CONFIRM); return false; } CmdConfirm.removePending(player); - if ((System.currentTimeMillis() - command.timestamp) > Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000) { + if ((System.currentTimeMillis() - command.timestamp) + > Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000) { MainUtil.sendMessage(player, C.EXPIRED_CONFIRM); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java index 60a5da47b..eb17b8614 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Continue.java @@ -9,21 +9,16 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "continue", - description = "Continue a plot that was previously marked as done", - permission = "plots.continue", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "continue", description = "Continue a plot that was previously marked as done", permission = "plots.continue", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Continue extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Plot plot = player.getCurrentPlot(); if ((plot == null) || !plot.hasOwner()) { return !sendMessage(player, C.NOT_IN_PLOT); } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CONTINUE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CONTINUE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -32,7 +27,8 @@ public class Continue extends SubCommand { return false; } int size = plot.getConnectedPlots().size(); - if (Settings.Done.COUNTS_TOWARDS_LIMIT && (player.getAllowedPlots() < player.getPlotCount() + size)) { + if (Settings.Done.COUNTS_TOWARDS_LIMIT && (player.getAllowedPlots() + < player.getPlotCount() + size)) { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND_CONTINUE); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java index 99849f926..bf34ae36b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java @@ -8,24 +8,18 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "copy", - permission = "plots.copy", - aliases = {"copypaste"}, - category = CommandCategory.CLAIMING, - description = "Copy a plot", - usage = "/plot copy ", - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "copy", permission = "plots.copy", aliases = { + "copypaste"}, category = CommandCategory.CLAIMING, description = "Copy a plot", usage = "/plot copy ", requiredType = RequiredType.NONE) public class Copy extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); } - if (!plot1.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if (!plot1.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -47,8 +41,7 @@ public class Copy extends SubCommand { return false; } if (plot1.copy(plot2, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, C.COPY_SUCCESS); } })) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java index 0ac6017d0..b901e7267 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/CreateRoadSchematic.java @@ -9,18 +9,11 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "createroadschematic", - aliases = {"crs"}, - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.NONE, - permission = "plots.createroadschematic", - description = "Add a road schematic to your world using the roads around your current plot", - usage = "/plot createroadschematic") +@CommandDeclaration(command = "createroadschematic", aliases = { + "crs"}, category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.NONE, permission = "plots.createroadschematic", description = "Add a road schematic to your world using the roads around your current plot", usage = "/plot createroadschematic") public class CreateRoadSchematic extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -30,7 +23,8 @@ public class CreateRoadSchematic extends SubCommand { return sendMessage(player, C.NOT_IN_PLOT_WORLD); } HybridUtils.manager.setupRoadSchematic(plot); - MainUtil.sendMessage(player, "$1Saved new road schematic. To test the road, fly to a few other plots and use /plot debugroadregen"); + MainUtil.sendMessage(player, + "$1Saved new road schematic. To test the road, fly to a few other plots and use /plot debugroadregen"); return true; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java index 5f9c14108..2e3b576ac 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java @@ -13,6 +13,7 @@ import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.sql.SQLException; import java.util.ArrayList; @@ -21,20 +22,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map.Entry; -@CommandDeclaration( - command = "database", - aliases = {"convert"}, - category = CommandCategory.ADMINISTRATION, - permission = "plots.database", - description = "Convert/Backup Storage", - requiredType = RequiredType.CONSOLE, - usage = "/plot database [area] ") +@CommandDeclaration(command = "database", aliases = { + "convert"}, category = CommandCategory.ADMINISTRATION, permission = "plots.database", description = "Convert/Backup Storage", requiredType = RequiredType.CONSOLE, usage = "/plot database [area] ") public class Database extends SubCommand { - public static void insertPlots(final SQLManager manager, final List plots, final PlotPlayer player) { + public static void insertPlots(final SQLManager manager, final List plots, + final PlotPlayer player) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { ArrayList ps = new ArrayList<>(); for (Plot p : plots) { @@ -42,22 +37,21 @@ public class Database extends SubCommand { } MainUtil.sendMessage(player, "&6Starting..."); manager.createPlotsAndData(ps, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database conversion finished!"); manager.close(); } }); } catch (Exception e) { - MainUtil.sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); + MainUtil.sendMessage(player, + "Failed to insert plot objects, see stacktrace for info"); e.printStackTrace(); } } }); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { MainUtil.sendMessage(player, "/plot database [area] "); return false; @@ -81,17 +75,20 @@ public class Database extends SubCommand { switch (args[0].toLowerCase()) { case "import": if (args.length < 2) { - MainUtil.sendMessage(player, "/plot database import [prefix]"); + MainUtil + .sendMessage(player, "/plot database import [prefix]"); return false; } - File file = MainUtil.getFile(PS.get().IMP.getDirectory(), args[1].endsWith(".db") ? args[1] : args[1] + ".db"); + File file = MainUtil.getFile(PS.get().IMP.getDirectory(), + args[1].endsWith(".db") ? args[1] : args[1] + ".db"); if (!file.exists()) { MainUtil.sendMessage(player, "&6Database does not exist: " + file); return false; } MainUtil.sendMessage(player, "&6Starting..."); implementation = new SQLite(file); - SQLManager manager = new SQLManager(implementation, args.length == 3 ? args[2] : "", true); + SQLManager manager = + new SQLManager(implementation, args.length == 3 ? args[2] : "", true); HashMap> map = manager.getPlots(); plots = new ArrayList<>(); for (Entry> entry : map.entrySet()) { @@ -106,9 +103,12 @@ public class Database extends SubCommand { if (newPlot != null) { PlotId newId = newPlot.getId(); PlotId id = plot.getId(); - File worldFile = new File(PS.imp().getWorldContainer(), id.toCommaSeparatedString()); + File worldFile = new File(PS.imp().getWorldContainer(), + id.toCommaSeparatedString()); if (worldFile.exists()) { - File newFile = new File(PS.imp().getWorldContainer(), newId.toCommaSeparatedString()); + File newFile = + new File(PS.imp().getWorldContainer(), + newId.toCommaSeparatedString()); worldFile.renameTo(newFile); } id.x = newId.x; @@ -119,7 +119,8 @@ public class Database extends SubCommand { continue; } } - MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp); + MainUtil.sendMessage(player, + "Skipping duplicate plot: " + plot + " | id=" + plot.temp); continue; } plot.setArea(pa); @@ -135,15 +136,15 @@ public class Database extends SubCommand { } } DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database conversion finished!"); } }); return true; case "mysql": if (args.length < 6) { - return MainUtil.sendMessage(player, "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); + return MainUtil.sendMessage(player, + "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); } String host = args[1]; String port = args[2]; @@ -159,7 +160,8 @@ public class Database extends SubCommand { if (args.length < 2) { return MainUtil.sendMessage(player, "/plot database sqlite [file]"); } - File sqliteFile = MainUtil.getFile(PS.get().IMP.getDirectory(), args[1] + ".db"); + File sqliteFile = + MainUtil.getFile(PS.get().IMP.getDirectory(), args[1] + ".db"); implementation = new SQLite(sqliteFile); break; default: @@ -171,15 +173,18 @@ public class Database extends SubCommand { return true; } catch (ClassNotFoundException | SQLException e) { MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info"); - MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); + MainUtil.sendMessage(player, + "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); MainUtil.sendMessage(player, "&d==== End of stacktrace ===="); - MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!"); + MainUtil + .sendMessage(player, "$1Please make sure you are using the correct arguments!"); return false; } } catch (ClassNotFoundException | SQLException e) { MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info"); - MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); + MainUtil.sendMessage(player, + "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); MainUtil.sendMessage(player, "&d==== End of stacktrace ===="); MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!"); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java index ccc4ad95b..e7866fd5f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java @@ -7,15 +7,10 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "debug", - category = CommandCategory.DEBUG, - description = "Show debug information", - usage = "/plot debug [msg]", - permission = "plots.admin") +@CommandDeclaration(command = "debug", category = CommandCategory.DEBUG, description = "Show debug information", usage = "/plot debug [msg]", permission = "plots.admin") public class Debug extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { StringBuilder msg = new StringBuilder(); for (C caption : C.values()) { @@ -30,7 +25,8 @@ public class Debug extends SubCommand { String section = C.DEBUG_SECTION.s(); information.append(header); information.append(getSection(section, "PlotArea")); - information.append(getLine(line, "Plot Worlds", StringMan.join(PS.get().getPlotAreas(), ", "))); + information + .append(getLine(line, "Plot Worlds", StringMan.join(PS.get().getPlotAreas(), ", "))); information.append(getLine(line, "Owned Plots", PS.get().getPlots().size())); information.append(getSection(section, "Messages")); information.append(getLine(line, "Total Messages", C.values().length)); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java index 9e0ee7653..31a7ab41a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugAllowUnsafe.java @@ -8,19 +8,12 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -@CommandDeclaration( - command = "debugallowunsafe", - description = "Allow unsafe actions until toggled off", - usage = "/plot debugallowunsafe", - category = CommandCategory.DEBUG, - requiredType = RequiredType.NONE, - permission = "plots.debugallowunsafe") +@CommandDeclaration(command = "debugallowunsafe", description = "Allow unsafe actions until toggled off", usage = "/plot debugallowunsafe", category = CommandCategory.DEBUG, requiredType = RequiredType.NONE, permission = "plots.debugallowunsafe") public class DebugAllowUnsafe extends SubCommand { public static final List unsafeAllowed = new ArrayList<>(); - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if (unsafeAllowed.contains(player.getUUID())) { unsafeAllowed.remove(player.getUUID()); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java index 3e00d0be5..febe462e8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java @@ -4,14 +4,7 @@ import com.google.common.collect.BiMap; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.StringWrapper; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.UUIDHandler; @@ -22,23 +15,16 @@ import java.util.ArrayList; import java.util.Map; import java.util.UUID; -@CommandDeclaration( - command = "debugclaimtest", - description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. " - + "Execution time may vary", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE, - permission = "plots.debugclaimtest") +@CommandDeclaration(command = "debugclaimtest", description = + "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. " + + "Execution time may vary", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE, permission = "plots.debugclaimtest") public class DebugClaimTest extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 3) { - return !MainUtil - .sendMessage( - null, - "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the " - + "plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); + return !MainUtil.sendMessage(null, + "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the " + + "plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); } PlotArea area = PS.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { @@ -53,11 +39,13 @@ public class DebugClaimTest extends SubCommand { max = PlotId.fromString(args[2]); } catch (Exception ignored) { return !MainUtil.sendMessage(player, - "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion " - + "will only check the plots in the selected area."); + "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion " + + "will only check the plots in the selected area."); } - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Beginning sign to plot conversion. This may take a while..."); - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: &7Beginning sign to plot conversion. This may take a while..."); + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); PlotManager manager = area.getPlotManager(); ArrayList plots = new ArrayList<>(); for (PlotId id : MainUtil.getPlotSelectionIds(min, max)) { @@ -80,8 +68,10 @@ public class DebugClaimTest extends SubCommand { BiMap map = UUIDHandler.getUuidMap(); UUID uuid = map.get(new StringWrapper(line)); if (uuid == null) { - for (Map.Entry stringWrapperUUIDEntry : map.entrySet()) { - if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) { + for (Map.Entry stringWrapperUUIDEntry : map + .entrySet()) { + if (stringWrapperUUIDEntry.getKey().value.toLowerCase() + .startsWith(line.toLowerCase())) { uuid = stringWrapperUUIDEntry.getValue(); break; } @@ -91,20 +81,22 @@ public class DebugClaimTest extends SubCommand { uuid = UUIDHandler.getUUID(line, null); } if (uuid != null) { - MainUtil.sendMessage(player, " - &aFound plot: " + plot.getId() + " : " + line); + MainUtil + .sendMessage(player, " - &aFound plot: " + plot.getId() + " : " + line); plot.setOwner(uuid); plots.add(plot); } else { - MainUtil.sendMessage(player, " - &cInvalid PlayerName: " + plot.getId() + " : " + line); + MainUtil.sendMessage(player, + " - &cInvalid PlayerName: " + plot.getId() + " : " + line); } } } } if (!plots.isEmpty()) { - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database update finished!"); } }); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java index 2219c08e4..354379058 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java @@ -8,71 +8,37 @@ import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.intellectualcrafters.plot.util.expiry.ExpireManager; import com.intellectualcrafters.plot.util.expiry.PlotAnalysis; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.listener.WEManager; + +import javax.script.*; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import javax.script.Bindings; -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import javax.script.SimpleScriptContext; +import java.util.*; -@CommandDeclaration(command = "debugexec", - permission = "plots.admin", - description = "Mutli-purpose debug command", - aliases = {"exec", "$"}, - category = CommandCategory.DEBUG) -public class DebugExec extends SubCommand { +@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = { + "exec", "$"}, category = CommandCategory.DEBUG) public class DebugExec extends SubCommand { private ScriptEngine engine; private Bindings scope; public DebugExec() { try { if (PS.get() != null) { - File file = new File(PS.get().IMP.getDirectory(), Settings.Paths.SCRIPTS + File.separator + "start.js"); + File file = new File(PS.get().IMP.getDirectory(), + Settings.Paths.SCRIPTS + File.separator + "start.js"); if (file.exists()) { init(); - String script = StringMan.join(Files - .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), "start.js"), - StandardCharsets.UTF_8), - System.getProperty("line.separator")); + String script = StringMan.join(Files.readLines(new File(new File( + PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), + "start.js"), StandardCharsets.UTF_8), System.getProperty("line.separator")); this.scope.put("THIS", this); this.scope.put("PlotPlayer", ConsolePlayer.getConsole()); this.engine.eval(script, this.scope); @@ -148,10 +114,11 @@ public class DebugExec extends SubCommand { } } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { - List allowed_params = - Arrays.asList("analyze", "calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "seen", "list-scripts", "start-rgar", "stop-rgar", "help", "addcmd", "runasync", "run", "allcmd", "all"); + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + List allowed_params = Arrays + .asList("analyze", "calibrate-analysis", "remove-flag", "stop-expire", "start-expire", + "seen", "list-scripts", "start-rgar", "stop-rgar", "help", "addcmd", "runasync", + "run", "allcmd", "all"); if (args.length > 0) { String arg = args[0].toLowerCase(); String script; @@ -170,19 +137,20 @@ public class DebugExec extends SubCommand { } MainUtil.sendMessage(player, "$1Starting task..."); HybridUtils.manager.analyzePlot(plot, new RunnableVal() { - @Override - public void run(PlotAnalysis value) { - MainUtil.sendMessage(player, "$1Done: $2Use $3/plot debugexec analyze$2 for more information"); + @Override public void run(PlotAnalysis value) { + MainUtil.sendMessage(player, + "$1Done: $2Use $3/plot debugexec analyze$2 for more information"); } }); return true; } case "calibrate-analysis": if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot debugexec analyze "); MainUtil.sendMessage(player, - "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating " - + "it)"); + "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating " + + "it)"); return false; } double threshold; @@ -190,12 +158,12 @@ public class DebugExec extends SubCommand { threshold = Integer.parseInt(args[1]) / 100d; } catch (NumberFormatException ignored) { MainUtil.sendMessage(player, "$2Invalid threshold: " + args[1]); - MainUtil.sendMessage(player, "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); + MainUtil.sendMessage(player, + "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); return false; } PlotAnalysis.calcOptimalModifiers(new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry"); } }, threshold); @@ -207,7 +175,8 @@ public class DebugExec extends SubCommand { return MainUtil.sendMessage(player, "Cancelled task."); case "remove-flag": if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot debugexec remove-flag "); return false; } String flag = args[1]; @@ -220,7 +189,8 @@ public class DebugExec extends SubCommand { return MainUtil.sendMessage(player, "Cleared flag: " + flag); case "start-rgar": { if (args.length != 2) { - MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar "); + MainUtil.sendMessage(player, + "&cInvalid syntax: /plot debugexec start-rgar "); return false; } PlotArea area = PS.get().getPlotAreaByString(args[1]); @@ -230,12 +200,14 @@ public class DebugExec extends SubCommand { } boolean result; if (HybridUtils.regions != null) { - result = HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0); + result = + HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0); } else { result = HybridUtils.manager.scheduleRoadUpdate(area, 0); } if (!result) { - MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)"); + MainUtil.sendMessage(player, + "&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } return true; @@ -267,7 +239,8 @@ public class DebugExec extends SubCommand { } OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); if (op == null || op.getLastPlayed() == 0) { - return MainUtil.sendMessage(player, "Player hasn't connected before: " + args[1]); + return MainUtil + .sendMessage(player, "Player hasn't connected before: " + args[1]); } Timestamp stamp = new Timestamp(op.getLastPlayed()); Date date = new Date(stamp.getTime()); @@ -281,18 +254,21 @@ public class DebugExec extends SubCommand { case "he": case "?": case "help": - MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">"); + MainUtil.sendMessage(player, + "Possible sub commands: /plot debugexec <" + StringMan + .join(allowed_params, "|") + ">"); return false; case "addcmd": try { - final String cmd = StringMan.join(Files - .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), - args[1]), - StandardCharsets.UTF_8), - System.getProperty("line.separator")); - new Command(MainCommand.getInstance(), true, args[1].split("\\.")[0], null, RequiredType.NONE, CommandCategory.DEBUG) { - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + final String cmd = StringMan.join(Files.readLines(MainUtil.getFile(new File( + PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), + args[1]), StandardCharsets.UTF_8), + System.getProperty("line.separator")); + new Command(MainCommand.getInstance(), true, args[1].split("\\.")[0], null, + RequiredType.NONE, CommandCategory.DEBUG) { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { try { DebugExec.this.scope.put("PlotPlayer", player); DebugExec.this.scope.put("args", args); @@ -306,18 +282,18 @@ public class DebugExec extends SubCommand { return true; } catch (IOException e) { e.printStackTrace(); - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); return false; } case "runasync": async = true; case "run": try { - script = StringMan.join(Files - .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), - args[1]), - StandardCharsets.UTF_8), - System.getProperty("line.separator")); + script = StringMan.join(Files.readLines(MainUtil.getFile(new File( + PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), + args[1]), StandardCharsets.UTF_8), + System.getProperty("line.separator")); if (args.length > 2) { HashMap replacements = new HashMap<>(); for (int i = 2; i < args.length; i++) { @@ -331,7 +307,8 @@ public class DebugExec extends SubCommand { } break; case "list-scripts": - String path = PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS; + String path = + PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS; File folder = new File(path); File[] filesArray = folder.listFiles(); @@ -351,18 +328,20 @@ public class DebugExec extends SubCommand { } List allFiles = Arrays.asList(filesArray); - paginate(player, allFiles, 8, page, new RunnableVal3() { + paginate(player, allFiles, 8, page, + new RunnableVal3() { - @Override - public void run(Integer i, File file, PlotMessage message) { - String name = file.getName(); - message.text("[").color("$3").text(String.valueOf(i)).color("$1").text("]").color("$3").text(' ' + name).color("$1"); - } - }, "/plot debugexec list-scripts", "List of scripts"); + @Override public void run(Integer i, File file, PlotMessage message) { + String name = file.getName(); + message.text("[").color("$3").text(String.valueOf(i)).color("$1") + .text("]").color("$3").text(' ' + name).color("$1"); + } + }, "/plot debugexec list-scripts", "List of scripts"); return true; case "allcmd": if (args.length < 3) { - C.COMMAND_SYNTAX.send(player, "/plot debugexec allcmd "); + C.COMMAND_SYNTAX + .send(player, "/plot debugexec allcmd "); return false; } long start = System.currentTimeMillis(); @@ -392,7 +371,9 @@ public class DebugExec extends SubCommand { init(); this.scope.put("_2", params); this.scope.put("_3", cmd); - script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + script = + "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + + args[1] + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand" + "(PlotPlayer,_2)}}"; @@ -402,9 +383,10 @@ public class DebugExec extends SubCommand { C.COMMAND_SYNTAX.send(player, "/plot debugexec all "); return false; } - script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan - .join(Arrays.copyOfRange(args, 2, args.length), " ") - + "}}"; + script = + "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + + args[1] + "){" + StringMan + .join(Arrays.copyOfRange(args, 2, args.length), " ") + "}}"; break; default: @@ -421,8 +403,7 @@ public class DebugExec extends SubCommand { if (async) { final String toExec = script; TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { long start = System.currentTimeMillis(); Object result = null; try { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java index b12c1cb40..9cfbffd66 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugFixFlags.java @@ -16,21 +16,14 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; -@CommandDeclaration( - command = "debugfixflags", - usage = "/plot debugfixflags ", - permission = "plots.debugfixflags", - description = "Attempt to fix all flags for a world", - requiredType = RequiredType.CONSOLE, - category = CommandCategory.DEBUG) +@CommandDeclaration(command = "debugfixflags", usage = "/plot debugfixflags ", permission = "plots.debugfixflags", description = "Attempt to fix all flags for a world", requiredType = RequiredType.CONSOLE, category = CommandCategory.DEBUG) public class DebugFixFlags extends SubCommand { public DebugFixFlags() { super(Argument.String); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { PlotArea area = PS.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[0]); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugImportWorlds.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugImportWorlds.java index 1fd648271..d1dd55b48 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugImportWorlds.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugImportWorlds.java @@ -13,22 +13,19 @@ import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.util.UUID; -@CommandDeclaration( - command = "debugimportworlds", - permission = "plots.admin", - description = "Import worlds by player name", - requiredType = RequiredType.CONSOLE, - category = CommandCategory.TELEPORT) +@CommandDeclaration(command = "debugimportworlds", permission = "plots.admin", description = "Import worlds by player name", requiredType = RequiredType.CONSOLE, category = CommandCategory.TELEPORT) public class DebugImportWorlds extends Command { public DebugImportWorlds() { super(MainCommand.getInstance(), true); } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { // UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)) PlotAreaManager pam = PS.get().getPlotAreaManager(); if (!(pam instanceof SinglePlotAreaManager)) { @@ -43,7 +40,8 @@ public class DebugImportWorlds extends Command { if (!WorldUtil.IMP.isWorld(name) && PlotId.fromString(name) == null) { UUID uuid = UUIDHandler.getUUID(name, null); if (uuid == null) { - uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); + uuid = + UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); } while (new File(container, id.toCommaSeparatedString()).exists()) { id = Auto.getNextPlotId(id, 1); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java index 00aa74d31..6d4407fd3 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugLoadTest.java @@ -5,17 +5,10 @@ import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.PlotPlayer; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "debugloadtest", - permission = "plots.debugloadtest", - description = "This debug command will force the reload of all plots in the DB", - usage = "/plot debugloadtest", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE) +@CommandDeclaration(command = "debugloadtest", permission = "plots.debugloadtest", description = "This debug command will force the reload of all plots in the DB", usage = "/plot debugloadtest", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE) public class DebugLoadTest extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { PS.get().plots_tmp = DBFunc.getPlots(); return true; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java index 083ae256b..56569e51e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugPaste.java @@ -13,41 +13,39 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.io.File; import java.io.IOException; -@CommandDeclaration(command = "debugpaste", - aliases = "dp", usage = "/plot debugpaste", - description = "Upload settings.yml, worlds.yml, commands.yml and latest.log to www.hastebin.com", - permission = "plots.debugpaste", - category = CommandCategory.DEBUG) +@CommandDeclaration(command = "debugpaste", aliases = "dp", usage = "/plot debugpaste", description = "Upload settings.yml, worlds.yml, commands.yml and latest.log to www.hastebin.com", permission = "plots.debugpaste", category = CommandCategory.DEBUG) public class DebugPaste extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { String settingsYML = HastebinUtility.upload(PS.get().configFile); String worldsYML = HastebinUtility.upload(PS.get().worldsFile); String commandsYML = HastebinUtility.upload(PS.get().commandsFile); String latestLOG; try { - latestLOG = HastebinUtility.upload(new File(PS.get().IMP.getDirectory(), "../../logs/latest.log")); + latestLOG = HastebinUtility + .upload(new File(PS.get().IMP.getDirectory(), "../../logs/latest.log")); } catch (IOException ignored) { - MainUtil.sendMessage(player, "&clatest.log is too big to be pasted, will ignore"); + MainUtil.sendMessage(player, + "&clatest.log is too big to be pasted, will ignore"); latestLOG = "too big :("; } StringBuilder b = new StringBuilder(); b.append( - "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " - + "problem\n\n# We will start with some informational files\n"); + "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " + + "problem\n\n# We will start with some informational files\n"); b.append("links.settings_yml: ").append(settingsYML).append('\n'); b.append("links.worlds_yml: ").append(worldsYML).append('\n'); b.append("links.commands_yml: ").append(commandsYML).append('\n'); b.append("links.latest_log: ").append(latestLOG).append('\n'); b.append("\n# Server Information\n"); int[] sVersion = PS.get().IMP.getServerVersion(); - b.append("version.server: ").append(sVersion[0]).append('.').append(sVersion[1]).append('.').append(sVersion[2]).append('\n'); - b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';').append(!Settings.UUID.OFFLINE).append('\n'); + b.append("version.server: ").append(sVersion[0]).append('.').append(sVersion[1]) + .append('.').append(sVersion[2]).append('\n'); + b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';') + .append(!Settings.UUID.OFFLINE).append('\n'); b.append("plugins:"); for (String id : PS.get().IMP.getPluginIds()) { String[] split = id.split(":"); @@ -55,21 +53,26 @@ public class DebugPaste extends SubCommand { String enabled = split.length == 2 ? split[1] : "unknown"; String name = split2[0]; String version = split2.length == 2 ? split2[1] : "unknown"; - b.append("\n ").append(name).append(":\n ").append("version: '").append(version).append('\'').append("\n enabled: ") - .append(enabled); + b.append("\n ").append(name).append(":\n ").append("version: '") + .append(version).append('\'').append("\n enabled: ").append(enabled); } b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); Runtime runtime = Runtime.getRuntime(); b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); - b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n"); - b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n"); - b.append("java.version: '").append(System.getProperty("java.version")).append("'\n"); + b.append("java.specification.version: '") + .append(System.getProperty("java.specification.version")).append("'\n"); + b.append("java.vendor: '").append(System.getProperty("java.vendor")) + .append("'\n"); + b.append("java.version: '").append(System.getProperty("java.version")) + .append("'\n"); b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); - b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); + b.append("os.version: '").append(System.getProperty("os.version")) + .append("'\n\n"); b.append("# Okay :D Great. You are now ready to create your bug report!"); - b.append("\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); + b.append( + "\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); String link = HastebinUtility.upload(b.toString()); player.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java index 914eab1d3..251b4b4b8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java @@ -4,26 +4,15 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.generator.HybridPlotManager; import com.intellectualcrafters.plot.generator.HybridPlotWorld; import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MathMan; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "debugroadregen", - usage = "/plot debugroadregen", - requiredType = RequiredType.NONE, - description = "Regenerate all roads based on the road schematic", - category = CommandCategory.DEBUG, - permission = "plots.debugroadregen") +@CommandDeclaration(command = "debugroadregen", usage = "/plot debugroadregen", requiredType = RequiredType.NONE, description = "Regenerate all roads based on the road schematic", category = CommandCategory.DEBUG, permission = "plots.debugroadregen") public class DebugRoadRegen extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); PlotArea plotArea = loc.getPlotArea(); if (!(plotArea instanceof HybridPlotWorld)) { @@ -45,14 +34,17 @@ public class DebugRoadRegen extends SubCommand { } boolean result = HybridUtils.manager.regenerateRoad(plotArea, chunk, extend); MainUtil.sendMessage(player, - "&6Regenerating chunk: " + chunk.x + ',' + chunk.z + "\n&6 - Result: " + (result ? "&aSuccess" : "&cFailed")); + "&6Regenerating chunk: " + chunk.x + ',' + chunk.z + "\n&6 - Result: " + (result ? + "&aSuccess" : + "&cFailed")); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } else { HybridPlotManager manager = (HybridPlotManager) plotArea.getPlotManager(); manager.createRoadEast(plotArea, plot); manager.createRoadSouth(plotArea, plot); manager.createRoadSouthEast(plotArea, plot); - MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + "\n&6 - Result: &aSuccess"); + MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + + "\n&6 - Result: &aSuccess"); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java index 4684cdd39..075234f70 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugSaveTest.java @@ -9,23 +9,15 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.ArrayList; -@CommandDeclaration( - command = "debugsavetest", - permission = "plots.debugsavetest", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE, - usage = "/plot debugsavetest", - description = "This command will force the recreation of all plots in the DB") +@CommandDeclaration(command = "debugsavetest", permission = "plots.debugsavetest", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE, usage = "/plot debugsavetest", description = "This command will force the recreation of all plots in the DB") public class DebugSaveTest extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { ArrayList plots = new ArrayList(); plots.addAll(PS.get().getPlots()); MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`"); DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database sync finished!"); } }); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java index 9ebc7a058..80eed8d6b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java @@ -2,31 +2,16 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "delete", - permission = "plots.delete", - description = "Delete a plot", - usage = "/plot delete", - aliases = {"dispose", "del", "reset"}, - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - confirmation = true) +@CommandDeclaration(command = "delete", permission = "plots.delete", description = "Delete a plot", usage = "/plot delete", aliases = { + "dispose", "del", + "reset"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, confirmation = true) public class Delete extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); @@ -36,23 +21,23 @@ public class Delete extends SubCommand { if (!plot.hasOwner()) { return !sendMessage(player, C.PLOT_UNOWNED); } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DELETE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DELETE)) { return !sendMessage(player, C.NO_PLOT_PERMS); } final PlotArea plotArea = plot.getArea(); final java.util.Set plots = plot.getConnectedPlots(); - final int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); + final int currentPlots = + Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.getRunning() > 0) { MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); return; } final long start = System.currentTimeMillis(); boolean result = plot.deletePlot(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.removeRunning(); if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) { Expression valueExr = plotArea.PRICES.get("sell"); @@ -62,7 +47,8 @@ public class Delete extends SubCommand { sendMessage(player, C.ADDED_BALANCE, String.valueOf(value)); } } - MainUtil.sendMessage(player, C.DELETING_DONE, System.currentTimeMillis() - start); + MainUtil.sendMessage(player, C.DELETING_DONE, + System.currentTimeMillis() - start); } }); if (result) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java index 4a88676dd..0c61dbf9d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java @@ -6,12 +6,7 @@ import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.PlotGameMode; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; @@ -19,20 +14,15 @@ import java.util.Iterator; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "deny", - aliases = {"d", "ban"}, - description = "Deny a user from a plot", - usage = "/plot deny ", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "deny", aliases = {"d", + "ban"}, description = "Deny a user from a plot", usage = "/plot deny ", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Deny extends SubCommand { public Deny() { super(Argument.PlayerName); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); Plot plot = location.getPlotAbs(); @@ -43,7 +33,8 @@ public class Deny extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return true; } @@ -55,7 +46,9 @@ public class Deny extends SubCommand { Iterator iter = uuids.iterator(); while (iter.hasNext()) { UUID uuid = iter.next(); - if (uuid == DBFunc.everyone && !(Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) { + if (uuid == DBFunc.everyone && !( + Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) { MainUtil.sendMessage(player, C.INVALID_PLAYER, MainUtil.getName(uuid)); continue; } @@ -105,7 +98,8 @@ public class Deny extends SubCommand { Location spawn = WorldUtil.IMP.getSpawn(loc.getWorld()); MainUtil.sendMessage(player, C.YOU_GOT_DENIED); if (plot.equals(spawn.getPlot())) { - Location newSpawn = WorldUtil.IMP.getSpawn(PS.get().getPlotAreaManager().getAllWorlds()[0]); + Location newSpawn = + WorldUtil.IMP.getSpawn(PS.get().getPlotAreaManager().getAllWorlds()[0]); if (plot.equals(newSpawn.getPlot())) { // Kick from server if you can't be teleported to spawn player.kick(C.YOU_GOT_DENIED.s()); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java index 550dfc397..88380071d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Desc.java @@ -8,18 +8,12 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "setdescription", - permission = "plots.set.desc", - description = "Set the plot description", - usage = "/plot desc ", - aliases = {"desc", "setdesc", "setd", "description"}, - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "setdescription", permission = "plots.set.desc", description = "Set the plot description", usage = "/plot desc ", aliases = { + "desc", "setdesc", "setd", + "description"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Desc extends SetCommand { - @Override - public boolean set(PlotPlayer player, Plot plot, String desc) { + @Override public boolean set(PlotPlayer player, Plot plot, String desc) { if (desc.isEmpty()) { plot.removeFlag(Flags.DESCRIPTION); MainUtil.sendMessage(player, C.DESC_UNSET); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java index 41294b4a4..ce95f555e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Done.java @@ -14,22 +14,18 @@ import com.intellectualcrafters.plot.util.expiry.ExpireManager; import com.intellectualcrafters.plot.util.expiry.PlotAnalysis; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "done", - aliases = {"submit"}, - description = "Mark a plot as done", - permission = "plots.done", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "done", aliases = { + "submit"}, description = "Mark a plot as done", permission = "plots.done", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Done extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if ((plot == null) || !plot.hasOwner()) { return !sendMessage(player, C.NOT_IN_PLOT); } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DONE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DONE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -49,10 +45,10 @@ public class Done extends SubCommand { plot.removeRunning(); } else { HybridUtils.manager.analyzePlot(plot, new RunnableVal() { - @Override - public void run(PlotAnalysis value) { + @Override public void run(PlotAnalysis value) { plot.removeRunning(); - boolean result = value.getComplexity(doneRequirements) <= doneRequirements.THRESHOLD; + boolean result = + value.getComplexity(doneRequirements) <= doneRequirements.THRESHOLD; finish(plot, player, result); } }); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java index 3f043e21f..d9091b654 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Download.java @@ -8,27 +8,16 @@ import com.intellectualcrafters.plot.flag.Flags; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.BO3Handler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.CommandDeclaration; import java.net.URL; -@CommandDeclaration(usage = "/plot download [schematic|bo3|world]", - command = "download", - aliases = {"dl"}, - category = CommandCategory.SCHEMATIC, - requiredType = RequiredType.NONE, - description = "Download your plot", - permission = "plots.download") +@CommandDeclaration(usage = "/plot download [schematic|bo3|world]", command = "download", aliases = { + "dl"}, category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Download your plot", permission = "plots.download") public class Download extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String world = player.getLocation().getWorld(); if (!PS.get().hasPlotArea(world)) { return !sendMessage(player, C.NOT_IN_PLOT_WORLD); @@ -41,12 +30,13 @@ public class Download extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if ((Settings.Done.REQUIRED_FOR_DOWNLOAD && (!plot.getFlag(Flags.DONE).isPresent())) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) { + if ((Settings.Done.REQUIRED_FOR_DOWNLOAD && (!plot.getFlag(Flags.DONE).isPresent())) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) { MainUtil.sendMessage(player, C.DONE_NOT_DONE); return false; } - if ((!plot.isOwner(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if ((!plot.isOwner(player.getUUID())) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -54,19 +44,18 @@ public class Download extends SubCommand { MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); return false; } - if (args.length == 0 || (args.length == 1 && StringMan.isEqualIgnoreCaseToAny(args[0], "sch", "schem", "schematic"))) { + if (args.length == 0 || (args.length == 1 && StringMan + .isEqualIgnoreCaseToAny(args[0], "sch", "schem", "schematic"))) { if (plot.getVolume() > Integer.MAX_VALUE) { C.SCHEMATIC_TOO_LARGE.send(player); return false; } plot.addRunning(); SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { - @Override - public void run(CompoundTag value) { + @Override public void run(CompoundTag value) { plot.removeRunning(); SchematicHandler.manager.upload(value, null, null, new RunnableVal() { - @Override - public void run(URL url) { + @Override public void run(URL url) { if (url == null) { MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); return; @@ -76,7 +65,8 @@ public class Download extends SubCommand { }); } }); - } else if (args.length == 1 && StringMan.isEqualIgnoreCaseToAny(args[0], "bo3", "bo2", "b03", "b02")) { + } else if (args.length == 1 && StringMan + .isEqualIgnoreCaseToAny(args[0], "bo3", "bo2", "b03", "b02")) { if (!Permissions.hasPermission(player, C.PERMISSION_DOWNLOAD_BO3)) { C.NO_PERMISSION.send(player, C.PERMISSION_DOWNLOAD_BO3); return false; @@ -87,8 +77,7 @@ public class Download extends SubCommand { } plot.addRunning(); BO3Handler.upload(plot, null, null, new RunnableVal() { - @Override - public void run(URL url) { + @Override public void run(URL url) { plot.removeRunning(); if (url == null) { MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); @@ -97,7 +86,8 @@ public class Download extends SubCommand { MainUtil.sendMessage(player, url.toString()); } }); - } else if (args.length == 1 && StringMan.isEqualIgnoreCaseToAny(args[0], "mcr", "world", "mca")) { + } else if (args.length == 1 && StringMan + .isEqualIgnoreCaseToAny(args[0], "mcr", "world", "mca")) { if (!Permissions.hasPermission(player, C.PERMISSION_DOWNLOAD_WORLD)) { C.NO_PERMISSION.send(player, C.PERMISSION_DOWNLOAD_WORLD); return false; @@ -106,8 +96,7 @@ public class Download extends SubCommand { plot.addRunning(); WorldUtil.IMP.saveWorld(world); WorldUtil.IMP.upload(plot, null, null, new RunnableVal() { - @Override - public void run(URL url) { + @Override public void run(URL url) { plot.removeRunning(); if (url == null) { MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java index 7afd81474..cd2a7f5a3 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java @@ -14,14 +14,8 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.*; -@CommandDeclaration( - command = "setflag", - aliases = {"f", "flag", "setf", "setflag"}, - usage = "/plot flag ", - description = "Set plot flags", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE, - permission = "plots.flag") +@CommandDeclaration(command = "setflag", aliases = {"f", "flag", "setf", + "setflag"}, usage = "/plot flag ", description = "Set plot flags", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, permission = "plots.flag") public class FlagCmd extends SubCommand { private boolean checkPermValue(PlotPlayer player, Flag flag, String key, String value) { @@ -33,17 +27,19 @@ public class FlagCmd extends SubCommand { int numeric = Integer.parseInt(value); perm = perm.substring(0, perm.length() - value.length() - 1); if (numeric > 0) { - int checkRange = PS.get().getPlatform().equalsIgnoreCase("bukkit") ? numeric : Settings.Limit.MAX_PLOTS; + int checkRange = PS.get().getPlatform().equalsIgnoreCase("bukkit") ? + numeric : + Settings.Limit.MAX_PLOTS; return player.hasPermissionRange(perm, checkRange) >= numeric; } - } catch (NumberFormatException ignore) {} + } catch (NumberFormatException ignore) { + } } return Permissions.hasPermission(player, perm); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { /* * plot flag set fly true @@ -66,7 +62,8 @@ public class FlagCmd extends SubCommand { sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_SET_FLAG_OTHER)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_SET_FLAG_OTHER)) { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_OTHER); return false; } @@ -76,7 +73,8 @@ public class FlagCmd extends SubCommand { if (flag == null || flag.isReserved()) { boolean suggested = false; try { - StringComparison> stringComparison = new StringComparison<>(args[1], Flags.getFlags()); + StringComparison> stringComparison = + new StringComparison<>(args[1], Flags.getFlags()); String best = stringComparison.getBestMatch(); if (best != null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG_SUGGESTED, best); @@ -118,7 +116,8 @@ public class FlagCmd extends SubCommand { } String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); if (!checkPermValue(player, flag, args[1], value)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), value.toLowerCase())); + MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE + .f(args[1].toLowerCase(), value.toLowerCase())); return false; } Object parsed = flag.parseValue(value); @@ -140,24 +139,29 @@ public class FlagCmd extends SubCommand { return false; } if (args.length != 2 && args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); return false; } - if (!Permissions.hasPermission(player, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) { + if (!Permissions + .hasPermission(player, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) { if (args.length != 3) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase())); return false; } for (String entry : args[2].split(",")) { if (!checkPermValue(player, flag, args[1], entry)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); return false; } } } if (args.length == 3 && flag instanceof ListFlag) { String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); - Optional flag1 = plot.getFlag((Flag>) flag); + Optional flag1 = + plot.getFlag((Flag>) flag); if (flag1.isPresent()) { boolean o = flag1.get().removeAll((Collection) flag.parseValue(value)); if (o) { @@ -176,9 +180,9 @@ public class FlagCmd extends SubCommand { return false; } } - if(flag == Flags.TIME) { + if (flag == Flags.TIME) { player.setTime(Long.MAX_VALUE); - } else if(flag == Flags.WEATHER) { + } else if (flag == Flags.WEATHER) { player.setWeather(PlotWeather.RESET); } MainUtil.sendMessage(player, C.FLAG_REMOVED); @@ -190,12 +194,14 @@ public class FlagCmd extends SubCommand { return false; } if (args.length < 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); return false; } for (String entry : args[2].split(",")) { if (!checkPermValue(player, flag, args[1], entry)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); return false; } } @@ -207,7 +213,8 @@ public class FlagCmd extends SubCommand { } Object val = parsed; if (flag instanceof ListFlag) { - Optional flag1 = plot.getFlag((Flag>) flag); + Optional flag1 = + plot.getFlag((Flag>) flag); if (flag1.isPresent()) { boolean o = flag1.get().addAll((Collection) parsed); if (o) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java index 468e63252..5265df582 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java @@ -22,16 +22,17 @@ public class GenerateDocs { List commands = MainCommand.getInstance().getCommands(); GenerateDocs.log("### Want to document some commands?"); GenerateDocs.log(" - This page is automatically generated"); - GenerateDocs.log(" - Fork the project and add a javadoc comment to one of the command classes"); + GenerateDocs + .log(" - Fork the project and add a javadoc comment to one of the command classes"); GenerateDocs.log(" - Then do a pull request and it will be added to this page"); GenerateDocs.log(""); GenerateDocs.log("# Contents"); for (CommandCategory category : CommandCategory.values()) { GenerateDocs.log("###### " + category.name()); for (Command command : MainCommand.getInstance().getCommands(category, null)) { - GenerateDocs - .log(" - [/plot " + command.getId() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getId() - + ") "); + GenerateDocs.log(" - [/plot " + command.getId() + + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command + .getId() + ") "); } GenerateDocs.log(""); } @@ -48,11 +49,12 @@ public class GenerateDocs { // Header String source = - "https://github.com/IntellectualSites/PlotSquared/tree/master/Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz - + ".java"; + "https://github.com/IntellectualSites/PlotSquared/tree/master/Core/src/main/java/com/intellectualcrafters/plot/commands/" + + clazz + ".java"; GenerateDocs.log("## [" + name.toUpperCase() + "](" + source + ") "); - File file = new File("Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); + File file = new File( + "Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); List perms = GenerateDocs.getPerms(name, lines); List usages = GenerateDocs.getUsage(name, lines); @@ -123,7 +125,8 @@ public class GenerateDocs { prefix = " "; } if (usage.length() != 0) { - usages.add(usage.toString().trim().replaceAll(" ", " ").replaceAll("\\{label\\}", "plot")); + usages.add(usage.toString().trim().replaceAll(" ", " ") + .replaceAll("\\{label\\}", "plot")); } } } @@ -203,7 +206,9 @@ public class GenerateDocs { for (String line : lines) { line = line.trim(); if (line.startsWith("/** ") || line.startsWith("*/ ") || line.startsWith("* ")) { - line = line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "").trim(); + line = + line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "") + .trim(); result.append(line + '\n'); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java index 7917d6f14..b1bf5af2f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Grant.java @@ -12,22 +12,19 @@ import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.UUID; -@CommandDeclaration( - command = "grant", - category = CommandCategory.CLAIMING, - usage = "/plot grant [player]", - permission = "plots.grant", - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "grant", category = CommandCategory.CLAIMING, usage = "/plot grant [player]", permission = "plots.grant", requiredType = RequiredType.NONE) public class Grant extends Command { public Grant() { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { checkTrue(args.length >= 1 && args.length <= 2, C.COMMAND_SYNTAX, getUsage()); final String arg0 = args[0].toLowerCase(); switch (arg0) { @@ -40,19 +37,21 @@ public class Grant extends Command { if (args.length > 2) { break; } - final UUID uuid = args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : player.getUUID(); + final UUID uuid = + args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : player.getUUID(); if (uuid == null) { C.INVALID_PLAYER.send(player, args[1]); return; } MainUtil.getPersistentMeta(uuid, "grantedPlots", new RunnableVal() { - @Override - public void run(byte[] array) { + @Override public void run(byte[] array) { if (arg0.equals("check")) { // check - int granted = array == null ? 0 : ByteArrayUtilities.bytesToInteger(array); + int granted = + array == null ? 0 : ByteArrayUtilities.bytesToInteger(array); C.GRANTED_PLOTS.send(player, granted); } else { // add - int amount = 1 + (array == null ? 0 : ByteArrayUtilities.bytesToInteger(array)); + int amount = + 1 + (array == null ? 0 : ByteArrayUtilities.bytesToInteger(array)); boolean replace = array != null; String key = "grantedPlots"; byte[] rawData = ByteArrayUtilities.integerToBytes(amount); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java index de77178d7..5f7b791c4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java @@ -11,24 +11,20 @@ import com.intellectualcrafters.plot.util.helpmenu.HelpMenu; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "help", - description = "Get this help menu", - aliases = {"he", "?"}, - category = CommandCategory.INFO, - usage="help [category|#]", - permission="plots.use") +@CommandDeclaration(command = "help", description = "Get this help menu", aliases = {"he", + "?"}, category = CommandCategory.INFO, usage = "help [category|#]", permission = "plots.use") public class Help extends Command { public Help(Command parent) { super(parent, true); } - @Override - public boolean canExecute(PlotPlayer player, boolean message) { + @Override public boolean canExecute(PlotPlayer player, boolean message) { return true; } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { switch (args.length) { case 0: displayHelp(player, null, 0); @@ -80,15 +76,18 @@ public class Help extends Command { StringBuilder builder = new StringBuilder(); builder.append(C.HELP_HEADER.s()); for (CommandCategory c : CommandCategory.values()) { - builder.append( - "\n" + StringMan.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); + builder.append("\n" + StringMan + .replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), + "%category_desc%", c.toString())); } - builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all").replaceAll("%category_desc%", "Display all commands")); + builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all") + .replaceAll("%category_desc%", "Display all commands")); builder.append("\n" + C.HELP_FOOTER.s()); MainUtil.sendMessage(player, builder.toString(), false); return; } page--; - new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages().generatePage(page, getParent().toString()).render(); + new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages() + .generatePage(page, getParent().toString()).render(); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java index a23cb965c..7ef081339 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java @@ -15,13 +15,7 @@ import com.plotsquared.general.commands.CommandDeclaration; import java.util.ArrayList; import java.util.List; -@CommandDeclaration( - command = "inbox", - description = "Review the comments for a plot", - usage = "/plot inbox [inbox] [delete |clear|page]", - permission = "plots.inbox", - category = CommandCategory.CHAT, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "inbox", description = "Review the comments for a plot", usage = "/plot inbox [inbox] [delete |clear|page]", permission = "plots.inbox", category = CommandCategory.CHAT, requiredType = RequiredType.NONE) public class Inbox extends SubCommand { public void displayComments(PlotPlayer player, List oldComments, int page) { @@ -46,8 +40,8 @@ public class Inbox extends SubCommand { } StringBuilder string = new StringBuilder(); string.append(StringMan - .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", page + 1, "%max", totalPages + 1, "%word", "all") - + '\n'); + .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", + page + 1, "%max", totalPages + 1, "%word", "all") + '\n'); // This might work xD for (int x = page * 12; x < max; x++) { @@ -58,14 +52,14 @@ public class Inbox extends SubCommand { } else { color = "&7"; } - string.append("&8[&7#").append(x + 1).append("&8][&7").append(comment.world).append(';').append(comment.id).append("&8][&6") - .append(comment.senderName).append("&8]").append(color).append(comment.comment).append('\n'); + string.append("&8[&7#").append(x + 1).append("&8][&7").append(comment.world).append(';') + .append(comment.id).append("&8][&6").append(comment.senderName).append("&8]") + .append(color).append(comment.comment).append('\n'); } MainUtil.sendMessage(player, string.toString()); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { final Plot plot = player.getCurrentPlot(); if (plot == null) { sendMessage(player, C.NOT_IN_PLOT); @@ -76,18 +70,19 @@ public class Inbox extends SubCommand { return false; } if (args.length == 0) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox [inbox] [delete |clear|page]"); for (final CommentInbox inbox : CommentManager.inboxes.values()) { if (inbox.canRead(plot, player)) { if (!inbox.getComments(plot, new RunnableVal>() { - @Override - public void run(List value) { + @Override public void run(List value) { if (value != null) { int total = 0; int unread = 0; for (PlotComment comment : value) { total++; - if (comment.timestamp > CommentManager.getTimestamp(player, inbox.toString())) { + if (comment.timestamp > CommentManager + .getTimestamp(player, inbox.toString())) { unread++; } } @@ -98,7 +93,9 @@ public class Inbox extends SubCommand { } else { color = ""; } - sendMessage(player, C.INBOX_ITEM, color + inbox.toString() + " (" + total + '/' + unread + ')'); + sendMessage(player, C.INBOX_ITEM, + color + inbox.toString() + " (" + total + '/' + unread + + ')'); return; } } @@ -113,7 +110,8 @@ public class Inbox extends SubCommand { } final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); if (inbox == null) { - sendMessage(player, C.INVALID_INBOX, StringMan.join(CommentManager.inboxes.keySet(), ", ")); + sendMessage(player, C.INVALID_INBOX, + StringMan.join(CommentManager.inboxes.keySet(), ", ")); return false; } player.setMeta("inbox:" + inbox.toString(), System.currentTimeMillis()); @@ -126,7 +124,8 @@ public class Inbox extends SubCommand { return false; } if (args.length != 3) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox " + inbox.toString() + " delete "); } final int index; try { @@ -136,13 +135,13 @@ public class Inbox extends SubCommand { return false; } } catch (NumberFormatException ignored) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox " + inbox.toString() + " delete "); return false; } if (!inbox.getComments(plot, new RunnableVal>() { - @Override - public void run(List value) { + @Override public void run(List value) { if (index > value.size()) { sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); return; @@ -162,7 +161,8 @@ public class Inbox extends SubCommand { sendMessage(player, C.NO_PERM_INBOX_MODIFY); } inbox.clearInbox(plot); - Optional> comments = plot.getSettings().getComments(inbox.toString()); + Optional> comments = + plot.getSettings().getComments(inbox.toString()); if (comments.isPresent()) { plot.getSettings().removeComments(comments.get()); } @@ -172,7 +172,8 @@ public class Inbox extends SubCommand { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox [inbox] [delete |clear|page]"); return false; } } @@ -184,8 +185,7 @@ public class Inbox extends SubCommand { return false; } if (!inbox.getComments(plot, new RunnableVal>() { - @Override - public void run(List value) { + @Override public void run(List value) { displayComments(player, value, page); } })) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java index 2ab3ecbe1..1d25456b1 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java @@ -2,26 +2,17 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.expiry.ExpireManager; import com.plotsquared.general.commands.CommandDeclaration; import java.util.UUID; -@CommandDeclaration(command = "info", - aliases = "i", - description = "Display plot info", - usage = "/plot info ", - category = CommandCategory.INFO) +@CommandDeclaration(command = "info", aliases = "i", description = "Display plot info", usage = "/plot info ", category = CommandCategory.INFO) public class Info extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Plot plot; String arg; if (args.length > 0) { @@ -65,13 +56,12 @@ public class Info extends SubCommand { if (args.length == 1) { args = new String[0]; } else { - args = new String[]{args[1]}; + args = new String[] {args[1]}; } } if (args.length == 1 && args[0].equalsIgnoreCase("inv")) { PlotInventory inv = new PlotInventory(player) { - @Override - public boolean onClick(int index) { + @Override public boolean onClick(int index) { // TODO InfoInventory not implemented yet!!!!!!!! // See plot rating or musicsubcommand on examples return false; @@ -79,21 +69,24 @@ public class Info extends SubCommand { }; UUID uuid = player.getUUID(); String name = MainUtil.getName(plot.owner); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(), - "&cOwner: &6" + name, - "&cAlias: &6" + plot.getAlias(), - "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), - "&cCan Build: &6" + plot.isAdded(uuid), - "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), - "&cIs Denied: &6" + plot.isDenied(uuid))); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", "&cAmount: &6" + plot.getTrusted().size(), - "&8Click to view a list of the trusted users")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", "&cAmount: &6" + plot.getMembers().size(), - "&8Click to view a list of plot members")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied", "&cAmount: &6" + plot.getDenied().size(), - "&8Click to view a list of denied players")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags", "&cAmount: &6" + plot.getFlags().size(), - "&8Click to view a list of plot flags")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", + "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, + "&cAlias: &6" + plot.getAlias(), + "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), + "&cCan Build: &6" + plot.isAdded(uuid), + "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), + "&cIs Denied: &6" + plot.isDenied(uuid))); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", + "&cAmount: &6" + plot.getTrusted().size(), + "&8Click to view a list of the trusted users")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", + "&cAmount: &6" + plot.getMembers().size(), + "&8Click to view a list of plot members")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied", + "&cAmount: &6" + plot.getDenied().size(), + "&8Click to view a list of denied players")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags", + "&cAmount: &6" + plot.getFlags().size(), "&8Click to view a list of plot flags")); inv.openInventory(); return true; } @@ -103,7 +96,8 @@ public class Info extends SubCommand { boolean trustedEveryone = plot.getMembers().contains(DBFunc.everyone); // Unclaimed? if (!hasOwner && !containsEveryone && !trustedEveryone) { - MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.getId().x + ";" + plot.getId().y); + MainUtil + .sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.getId().x + ";" + plot.getId().y); return true; } String info = C.PLOT_INFO.s(); @@ -112,8 +106,8 @@ public class Info extends SubCommand { info = getCaption(arg); if (info == null) { MainUtil.sendMessage(player, - "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &aseen&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, " - + "&aowner&7, &arating"); + "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &aseen&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, " + + "&aowner&7, &arating"); return false; } full = true; @@ -121,9 +115,9 @@ public class Info extends SubCommand { full = false; } MainUtil.format(info, plot, player, full, new RunnableVal() { - @Override - public void run(String value) { - MainUtil.sendMessage(player, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); + @Override public void run(String value) { + MainUtil.sendMessage(player, + C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); } }); return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java index 18a7af200..4145d2355 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java @@ -17,27 +17,22 @@ import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "kick", - aliases = {"k"}, - description = "Kick a player from your plot", - permission = "plots.kick", - usage = "", - category = CommandCategory.TELEPORT, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "kick", aliases = { + "k"}, description = "Kick a player from your plot", permission = "plots.kick", usage = "", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) public class Kick extends SubCommand { public Kick() { super(Argument.PlayerName); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); Plot plot = location.getPlot(); if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } - if ((!plot.hasOwner() || !plot.isOwner(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_KICK)) { + if ((!plot.hasOwner() || !plot.isOwner(player.getUUID())) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_KICK)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -50,7 +45,8 @@ public class Kick extends SubCommand { for (UUID uuid : uuids) { if (uuid == DBFunc.everyone) { for (PlotPlayer pp : plot.getPlayersInPlot()) { - if (pp == player || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_ENTRY_DENIED)) { + if (pp == player || Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_ENTRY_DENIED)) { continue; } players.add(pp); @@ -79,7 +75,8 @@ public class Kick extends SubCommand { Location spawn = WorldUtil.IMP.getSpawn(location.getWorld()); C.YOU_GOT_KICKED.send(player2); if (plot.equals(spawn.getPlot())) { - Location newSpawn = WorldUtil.IMP.getSpawn(PS.get().getPlotAreaManager().getAllWorlds()[0]); + Location newSpawn = + WorldUtil.IMP.getSpawn(PS.get().getPlotAreaManager().getAllWorlds()[0]); if (plot.equals(newSpawn.getPlot())) { // Kick from server if you can't be teleported to spawn player2.kick(C.YOU_GOT_KICKED.s()); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java index 7df2372f7..a0f6e39aa 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java @@ -9,20 +9,18 @@ import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.UUID; -@CommandDeclaration(command = "leave", - description = "Leave a plot", - permission = "plots.leave", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "leave", description = "Leave a plot", permission = "plots.leave", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Leave extends Command { public Leave() { super(MainCommand.getInstance(), true); } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); checkTrue(plot.isAdded(player.getUUID()), C.NO_PLOT_PERMS); @@ -45,4 +43,4 @@ public class Leave extends Command { } } } -} \ No newline at end of file +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java index 1465476a9..33499dea2 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java @@ -5,43 +5,22 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS.SortType; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.EconHandler; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.expiry.ExpireManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -@CommandDeclaration( - command = "list", - aliases = {"l", "find", "search"}, - description = "List plots", - permission = "plots.list", - category = CommandCategory.INFO, - usage = "/plot list > [#]") +@CommandDeclaration(command = "list", aliases = {"l", "find", + "search"}, description = "List plots", permission = "plots.list", category = CommandCategory.INFO, usage = "/plot list > [#]") public class ListCmd extends SubCommand { private String[] getArgumentList(PlotPlayer player) { List args = new ArrayList<>(); - if (EconHandler.manager != null && Permissions.hasPermission(player, C.PERMISSION_LIST_FORSALE)) { + if (EconHandler.manager != null && Permissions + .hasPermission(player, C.PERMISSION_LIST_FORSALE)) { args.add("forsale"); } if (Permissions.hasPermission(player, C.PERMISSION_LIST_MINE)) { @@ -84,11 +63,11 @@ public class ListCmd extends SubCommand { } public void noArgs(PlotPlayer player) { - MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); + MainUtil.sendMessage(player, + C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if (args.length < 1) { noArgs(player); return false; @@ -128,7 +107,8 @@ public class ListCmd extends SubCommand { } plots = new ArrayList<>(); for (Plot plot : PS.get().getPlots()) { - if (plot.getTrusted().contains(player.getUUID()) || plot.getMembers().contains(player.getUUID())) { + if (plot.getTrusted().contains(player.getUUID()) || plot.getMembers() + .contains(player.getUUID())) { plots.add(plot); } } @@ -139,7 +119,8 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(world))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD_NAME.f(world)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } plots = new ArrayList<>(PS.get().getPlots(world)); @@ -149,7 +130,9 @@ public class ListCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_EXPIRED); return false; } - plots = ExpireManager.IMP == null ? new ArrayList() : new ArrayList<>(ExpireManager.IMP.getPendingExpired()); + plots = ExpireManager.IMP == null ? + new ArrayList() : + new ArrayList<>(ExpireManager.IMP.getPendingExpired()); break; case "area": if (!Permissions.hasPermission(player, C.PERMISSION_LIST_AREA)) { @@ -157,7 +140,8 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(world))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD_NAME.f(world)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } plots = area == null ? new ArrayList() : new ArrayList<>(area.getPlots()); @@ -183,8 +167,7 @@ public class ListCmd extends SubCommand { plots.add(plot); } Collections.sort(plots, new Comparator() { - @Override - public int compare(Plot a, Plot b) { + @Override public int compare(Plot a, Plot b) { String va = "" + a.getFlags().get(Flags.DONE); String vb = "" + b.getFlags().get(Flags.DONE); if (MathMan.isInteger(va)) { @@ -205,8 +188,7 @@ public class ListCmd extends SubCommand { } plots = new ArrayList<>(PS.get().getPlots()); Collections.sort(plots, new Comparator() { - @Override - public int compare(Plot p1, Plot p2) { + @Override public int compare(Plot p1, Plot p2) { double v1 = 0; int p1s = p1.getSettings().getRatings().size(); int p2s = p2.getRatings().size(); @@ -302,8 +284,10 @@ public class ListCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD); return false; } - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(args[0]))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD_NAME.f(args[0])); + if (!Permissions + .hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(args[0]))) { + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_LIST_WORLD_NAME.f(args[0])); return false; } plots = new ArrayList<>(PS.get().getPlots(args[0])); @@ -313,7 +297,8 @@ public class ListCmd extends SubCommand { if (uuid == null) { try { uuid = UUID.fromString(args[0]); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } if (uuid != null) { if (!Permissions.hasPermission(player, C.PERMISSION_LIST_PLAYER)) { @@ -327,7 +312,9 @@ public class ListCmd extends SubCommand { } if (plots == null) { - sendMessage(player, C.DID_YOU_MEAN, new StringComparison<>(args[0], new String[]{"mine", "shared", "world", "all"}).getBestMatch()); + sendMessage(player, C.DID_YOU_MEAN, + new StringComparison<>(args[0], new String[] {"mine", "shared", "world", "all"}) + .getBestMatch()); return false; } @@ -339,8 +326,8 @@ public class ListCmd extends SubCommand { return true; } - public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, PlotArea area, - String[] args, boolean sort) { + public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, + PlotArea area, String[] args, boolean sort) { // Header Iterator iterator = plots.iterator(); while (iterator.hasNext()) { @@ -351,54 +338,61 @@ public class ListCmd extends SubCommand { if (sort) { plots = PS.get().sortPlots(plots, SortType.CREATION_DATE, area); } - this.paginate(player, plots, pageSize, page, new RunnableVal3() { - @Override - public void run(Integer i, Plot plot, PlotMessage message) { - String color; - if (plot.owner == null) { - color = "$3"; - } else if (plot.isOwner(player.getUUID())) { - color = "$1"; - } else if (plot.isAdded(player.getUUID())) { - color = "$4"; - } else if (plot.isDenied(player.getUUID())) { - color = "$2"; - } else { - color = "$1"; - } - PlotMessage trusted = - new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s().replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) - .color("$1"); - PlotMessage members = - new PlotMessage().text(C.color(C.PLOT_INFO_MEMBERS.s().replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))) - .color("$1"); - String strFlags = StringMan.join(plot.getFlags().values(), ","); - if (strFlags.isEmpty()) { - strFlags = C.NONE.s(); - } - PlotMessage flags = new PlotMessage().text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))).color("$1"); - message.text("[").color("$3").text(i + "").command("/plot visit " + plot.getArea() + ";" + plot.getId()) - .tooltip("/plot visit " + plot.getArea() + ";" + plot.getId()).color("$1") - .text("]") - .color("$3").text(" " + plot.toString()).tooltip(trusted, members, flags) - .command("/plot info " + plot.getArea() + ";" + plot.getId()).color(color).text(" - ").color("$2"); - String prefix = ""; - for (UUID uuid : plot.getOwners()) { - String name = UUIDHandler.getName(uuid); - if (name == null) { - message = message.text(prefix).color("$4").text("unknown").color("$2").tooltip(uuid.toString()).suggest(uuid.toString()); + this.paginate(player, plots, pageSize, page, + new RunnableVal3() { + @Override public void run(Integer i, Plot plot, PlotMessage message) { + String color; + if (plot.owner == null) { + color = "$3"; + } else if (plot.isOwner(player.getUUID())) { + color = "$1"; + } else if (plot.isAdded(player.getUUID())) { + color = "$4"; + } else if (plot.isDenied(player.getUUID())) { + color = "$2"; } else { - PlotPlayer pp = UUIDHandler.getPlayer(uuid); - if (pp != null) { - message = message.text(prefix).color("$4").text(name).color("$1").tooltip(new PlotMessage("Online").color("$4")); - } else { - message = message.text(prefix).color("$4").text(name).color("$1").tooltip(new PlotMessage("Offline").color("$3")); - } + color = "$1"; + } + PlotMessage trusted = new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s() + .replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) + .color("$1"); + PlotMessage members = new PlotMessage().text(C.color(C.PLOT_INFO_MEMBERS.s() + .replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))) + .color("$1"); + String strFlags = StringMan.join(plot.getFlags().values(), ","); + if (strFlags.isEmpty()) { + strFlags = C.NONE.s(); + } + PlotMessage flags = new PlotMessage() + .text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))) + .color("$1"); + message.text("[").color("$3").text(i + "") + .command("/plot visit " + plot.getArea() + ";" + plot.getId()) + .tooltip("/plot visit " + plot.getArea() + ";" + plot.getId()).color("$1") + .text("]").color("$3").text(" " + plot.toString()) + .tooltip(trusted, members, flags) + .command("/plot info " + plot.getArea() + ";" + plot.getId()).color(color) + .text(" - ").color("$2"); + String prefix = ""; + for (UUID uuid : plot.getOwners()) { + String name = UUIDHandler.getName(uuid); + if (name == null) { + message = message.text(prefix).color("$4").text("unknown").color("$2") + .tooltip(uuid.toString()).suggest(uuid.toString()); + } else { + PlotPlayer pp = UUIDHandler.getPlayer(uuid); + if (pp != null) { + message = message.text(prefix).color("$4").text(name).color("$1") + .tooltip(new PlotMessage("Online").color("$4")); + } else { + message = message.text(prefix).color("$4").text(name).color("$1") + .tooltip(new PlotMessage("Offline").color("$3")); + } + } + prefix = ", "; } - prefix = ", "; } - } - }, "/plot list " + args[0], C.PLOT_LIST_HEADER_PAGED.s()); + }, "/plot list " + args[0], C.PLOT_LIST_HEADER_PAGED.s()); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java index c5309ba80..fa60527b8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java @@ -3,33 +3,23 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.net.MalformedURLException; import java.net.URL; import java.util.List; -@CommandDeclaration( - command = "load", - aliases = {"restore"}, - category = CommandCategory.SCHEMATIC, - requiredType = RequiredType.NONE, - description = "Load your plot", - permission = "plots.load", - usage = "/plot restore") +@CommandDeclaration(command = "load", aliases = { + "restore"}, category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Load your plot", permission = "plots.load", usage = "/plot restore") public class Load extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String world = player.getLocation().getWorld(); if (!PS.get().hasPlotArea(world)) { return !sendMessage(player, C.NOT_IN_PLOT_WORLD); @@ -42,7 +32,8 @@ public class Load extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_LOAD)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_LOAD)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -64,7 +55,8 @@ public class Load extends SubCommand { schematic = schematics.get(Integer.parseInt(args[0]) - 1); } catch (Exception ignored) { // use /plot load - MainUtil.sendMessage(player, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ')'); + MainUtil + .sendMessage(player, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ')'); return false; } final URL url; @@ -78,26 +70,27 @@ public class Load extends SubCommand { plot.addRunning(); MainUtil.sendMessage(player, C.GENERATING_COMPONENT); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { Schematic schematic = SchematicHandler.manager.getSchematic(url); if (schematic == null) { plot.removeRunning(); - sendMessage(player, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); + sendMessage(player, C.SCHEMATIC_INVALID, + "non-existent or not in gzip format"); return; } PlotArea area = plot.getArea(); - SchematicHandler.manager.paste(schematic, plot, 0, area.MIN_BUILD_HEIGHT, 0, false, new RunnableVal() { - @Override - public void run(Boolean value) { - plot.removeRunning(); - if (value) { - sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); - } else { - sendMessage(player, C.SCHEMATIC_PASTE_FAILED); - } - } - }); + SchematicHandler.manager + .paste(schematic, plot, 0, area.MIN_BUILD_HEIGHT, 0, false, + new RunnableVal() { + @Override public void run(Boolean value) { + plot.removeRunning(); + if (value) { + sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); + } else { + sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + } + } + }); } }); return true; @@ -113,8 +106,7 @@ public class Load extends SubCommand { if (schematics == null) { plot.addRunning(); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { List schematics = SchematicHandler.manager.getSaves(player.getUUID()); plot.removeRunning(); if ((schematics == null) || schematics.isEmpty()) { @@ -140,13 +132,15 @@ public class Load extends SubCommand { if (split.length < 5) { continue; } - String time = secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); + String time = + secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); String world = split[1]; PlotId id = PlotId.fromString(split[2] + ';' + split[3]); String size = split[4]; String color = "$4"; MainUtil.sendMessage(player, - "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id + "$3 | " + color + size + 'x' + size); + "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id + + "$3 | " + color + size + 'x' + size); } catch (Exception e) { e.printStackTrace(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java index b1c14dc51..264d40d32 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java @@ -2,14 +2,7 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.CmdConfirm; import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.Permissions; @@ -21,11 +14,9 @@ import java.util.Arrays; /** * PlotSquared command class. */ -@CommandDeclaration( - command = "plot", - aliases = {"plots", "p", "plotsquared", "plot2", "p2", "ps", "2", "plotme", "plotz", "ap"}) -public class MainCommand extends Command { - +@CommandDeclaration(command = "plot", aliases = {"plots", "p", "plotsquared", "plot2", "p2", "ps", + "2", "plotme", "plotz", "ap"}) public class MainCommand extends Command { + private static MainCommand instance; public Help help; public Toggle toggle; @@ -137,14 +128,16 @@ public class MainCommand extends Command { public void run(final Command cmd, final Runnable success, final Runnable failure) { if (cmd.hasConfirmation(player)) { CmdConfirm.addPending(player, cmd.getUsage(), new Runnable() { - @Override - public void run() { + @Override public void run() { if (EconHandler.manager != null) { PlotArea area = player.getApplicablePlotArea(); if (area != null) { - Expression priceEval = area.PRICES.get(cmd.getFullId()); - Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; - if (price != null && EconHandler.manager.getMoney(player) < price) { + Expression priceEval = + area.PRICES.get(cmd.getFullId()); + Double price = + priceEval != null ? priceEval.evaluate(0d) : 0d; + if (price != null + && EconHandler.manager.getMoney(player) < price) { if (failure != null) { failure.run(); } @@ -177,8 +170,7 @@ public class MainCommand extends Command { } } }, new RunnableVal2() { - @Override - public void run(Command cmd, CommandResult result) { + @Override public void run(Command cmd, CommandResult result) { // Post command stuff!? } }); @@ -192,13 +184,13 @@ public class MainCommand extends Command { @Deprecated /** * @Deprecated legacy - */ - public void addCommand(SubCommand command) { + */ public void addCommand(SubCommand command) { PS.debug("Command registration is now done during instantiation"); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { // Clear perm caching // player.deleteMeta("perm"); // Optional command scope // @@ -208,7 +200,9 @@ public class MainCommand extends Command { if (args.length >= 2) { PlotArea area = player.getApplicablePlotArea(); Plot newPlot = Plot.fromString(area, args[0]); - if (newPlot != null && (player instanceof ConsolePlayer || newPlot.getArea().equals(area) || Permissions.hasPermission(player, C.PERMISSION_ADMIN)) && !newPlot.isDenied(player.getUUID())) { + if (newPlot != null && (player instanceof ConsolePlayer || newPlot.getArea() + .equals(area) || Permissions.hasPermission(player, C.PERMISSION_ADMIN)) && !newPlot + .isDenied(player.getUUID())) { Location newLoc = newPlot.getCenter(); if (player.canTeleport(newLoc)) { // Save meta @@ -233,9 +227,12 @@ public class MainCommand extends Command { if (EconHandler.manager != null) { PlotArea area = player.getApplicablePlotArea(); if (area != null) { - Expression priceEval = area.PRICES.get(cmd.getFullId()); - Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; - if (price != 0d && EconHandler.manager.getMoney(player) < price) { + Expression priceEval = + area.PRICES.get(cmd.getFullId()); + Double price = + priceEval != null ? priceEval.evaluate(0d) : 0d; + if (price != 0d + && EconHandler.manager.getMoney(player) < price) { if (failure != null) { failure.run(); } @@ -284,8 +281,7 @@ public class MainCommand extends Command { } } - @Override - public boolean canExecute(PlotPlayer player, boolean message) { + @Override public boolean canExecute(PlotPlayer player, boolean message) { return true; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java index b620fe468..b65d2d125 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java @@ -2,32 +2,17 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.CommandDeclaration; import java.util.UUID; -@CommandDeclaration(command = "merge", - aliases = "m", - description = "Merge the plot you are standing on, with another plot", - permission = "plots.merge", usage = "/plot merge [removeroads]", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE, - confirmation = true) +@CommandDeclaration(command = "merge", aliases = "m", description = "Merge the plot you are standing on, with another plot", permission = "plots.merge", usage = "/plot merge [removeroads]", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, confirmation = true) public class Merge extends SubCommand { - public static final String[] values = new String[]{"north", "east", "south", "west", "auto"}; - public static final String[] aliases = new String[]{"n", "e", "s", "w", "all"}; + public static final String[] values = new String[] {"north", "east", "south", "west", "auto"}; + public static final String[] aliases = new String[] {"n", "e", "s", "w", "all"}; public static String direction(float yaw) { yaw = yaw / 90; @@ -51,8 +36,7 @@ public class Merge extends SubCommand { } } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocationFull(); final Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -72,14 +56,17 @@ public class Merge extends SubCommand { } } final PlotArea plotArea = plot.getArea(); - Expression priceExr = plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; + Expression priceExr = + plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; final int size = plot.getConnectedPlots().size(); final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); - if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d && EconHandler.manager.getMoney(player) < price) { + if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d + && EconHandler.manager.getMoney(player) < price) { sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); return false; } - final int maxSize = Permissions.hasPermissionRange(player, "plots.merge", Settings.Limit.MAX_PLOTS); + final int maxSize = + Permissions.hasPermissionRange(player, "plots.merge", Settings.Limit.MAX_PLOTS); if (size - 1 > maxSize) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.merge." + (size + 1)); return false; @@ -126,8 +113,10 @@ public class Merge extends SubCommand { } } if (direction == -1) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]"); - MainUtil.sendMessage(player, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]"); + MainUtil + .sendMessage(player, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); return false; } final boolean terrain; @@ -145,7 +134,8 @@ public class Merge extends SubCommand { return true; } Plot adjacent = plot.getRelative(direction); - if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) || adjacent.isOwner(uuid)) { + if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) + || adjacent.isOwner(uuid)) { MainUtil.sendMessage(player, C.NO_AVAILABLE_AUTOMERGE); return false; } @@ -163,8 +153,7 @@ public class Merge extends SubCommand { isOnline = true; final int dir = direction; Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); plot.autoMerge(dir, maxSize - size, owner, terrain); PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID()); @@ -184,7 +173,8 @@ public class Merge extends SubCommand { } }; if (hasConfirmation(player)) { - CmdConfirm.addPending(accepter, C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); + CmdConfirm.addPending(accepter, + C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); } else { run.run(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java index 4e06c734b..c742aaba5 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Middle.java @@ -9,17 +9,11 @@ import com.plotsquared.general.commands.CommandDeclaration; /** * @author manuelgu, altered by Citymonstret */ -@CommandDeclaration( - command = "middle", - aliases = {"center", "centre"}, - description = "Teleports you to the center of the plot", - usage = "/plot middle", - category = CommandCategory.TELEPORT, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "middle", aliases = {"center", + "centre"}, description = "Teleports you to the center of the plot", usage = "/plot middle", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) public class Middle extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] arguments) { + @Override public boolean onCommand(PlotPlayer player, String[] arguments) { Location location = player.getLocation(); Plot plot = location.getPlot(); if (plot == null) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java index 8a3a52180..85d69b9e3 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java @@ -10,30 +10,24 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - usage = "/plot move ", - command = "move", - description = "Move a plot", - aliases = {"debugmove"}, - permission = "plots.move", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(usage = "/plot move ", command = "move", description = "Move a plot", aliases = { + "debugmove"}, permission = "plots.move", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Move extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); } - if (!plot1.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if (!plot1.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } boolean override = false; if (args.length == 2 && args[1].equalsIgnoreCase("-f")) { - args = new String[]{ args[0] }; + args = new String[] {args[0]}; override = true; } if (args.length != 1) { @@ -55,13 +49,13 @@ public class Move extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot copy "); return false; } - if (!plot1.getArea().isCompatible(plot2.getArea()) && (!override || !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s()))) { + if (!plot1.getArea().isCompatible(plot2.getArea()) && (!override || !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s()))) { C.PLOTWORLD_INCOMPATIBLE.send(player); return false; } if (plot1.move(plot2, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, C.MOVE_SUCCESS); } }, false)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java index 5f3a12dc9..4b86583e9 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java @@ -2,26 +2,14 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.WorldUtil; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "music", - permission = "plots.music", - description = "Player music in a plot", - usage = "/plot music", - category = CommandCategory.APPEARANCE, - requiredType = RequiredType.PLAYER) +@CommandDeclaration(command = "music", permission = "plots.music", description = "Player music in a plot", usage = "/plot music", category = CommandCategory.APPEARANCE, requiredType = RequiredType.PLAYER) public class Music extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -32,8 +20,7 @@ public class Music extends SubCommand { return true; } PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { - @Override - public boolean onClick(int index) { + @Override public boolean onClick(int index) { PlotItemStack item = getItem(index); if (item == null) { return true; @@ -49,7 +36,8 @@ public class Music extends SubCommand { }; int index = 0; for (int i = 2256; i < 2268; i++) { - String name = "&r&6" + WorldUtil.IMP.getClosestMatchingName(PlotBlock.get((short) i, (byte) 0)); + String name = + "&r&6" + WorldUtil.IMP.getClosestMatchingName(PlotBlock.get((short) i, (byte) 0)); String[] lore = {"&r&aClick to play!"}; PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore); inv.setItem(index, item); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Near.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Near.java index c9a15294d..4cba97d36 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Near.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Near.java @@ -9,18 +9,15 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "near", - aliases = "n", - description = "Display nearby players", - usage = "/plot near", - category = CommandCategory.INFO) +@CommandDeclaration(command = "near", aliases = "n", description = "Display nearby players", usage = "/plot near", category = CommandCategory.INFO) public class Near extends Command { public Near() { super(MainCommand.getInstance(), true); } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); C.PLOT_NEAR.send(player, StringMan.join(plot.getPlayersInPlot(), ", ")); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java index f73cb5c61..ed63e6ffb 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java @@ -4,29 +4,18 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.CommandDeclaration; import java.util.Set; import java.util.UUID; -@CommandDeclaration( - command = "setowner", - permission = "plots.set.owner", - description = "Set the plot owner", - usage = "/plot setowner ", - aliases = {"owner", "so", "seto"}, - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - confirmation = true) +@CommandDeclaration(command = "setowner", permission = "plots.set.owner", description = "Set the plot owner", usage = "/plot setowner ", aliases = { + "owner", "so", + "seto"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, confirmation = true) public class Owner extends SetCommand { - @Override - public boolean set(final PlotPlayer player, final Plot plot, String value) { + @Override public boolean set(final PlotPlayer player, final Plot plot, String value) { Set plots = plot.getConnectedPlots(); UUID uuid = null; String name = null; @@ -34,15 +23,18 @@ public class Owner extends SetCommand { try { uuid = UUID.fromString(value); name = MainUtil.getName(uuid); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } else { uuid = UUIDHandler.getUUID(value, null); name = UUIDHandler.getName(uuid); name = name == null ? value : name; } if (uuid == null || value.equalsIgnoreCase("-")) { - if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("null") || value.equalsIgnoreCase("-")) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SETOWNER.s(), true)) { + if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("null") || value + .equalsIgnoreCase("-")) { + if (!Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SETOWNER.s(), true)) { return false; } Set connected = plot.getConnectedPlots(); @@ -68,7 +60,9 @@ public class Owner extends SetCommand { return false; } int size = plots.size(); - int currentPlots = (Settings.Limit.GLOBAL ? other.getPlotCount() : other.getPlotCount(plot.getWorldName())) + size; + int currentPlots = (Settings.Limit.GLOBAL ? + other.getPlotCount() : + other.getPlotCount(plot.getWorldName())) + size; if (currentPlots > other.getAllowedPlots()) { sendMessage(player, C.CANT_TRANSFER_MORE_PLOTS); return false; @@ -78,9 +72,9 @@ public class Owner extends SetCommand { final UUID finalUUID = uuid; final boolean removeDenied = plot.isDenied(finalUUID); Runnable run = new Runnable() { - @Override - public void run() { - if (removeDenied) plot.removeDenied(finalUUID); + @Override public void run() { + if (removeDenied) + plot.removeDenied(finalUUID); plot.setOwner(finalUUID); plot.setSign(finalName); MainUtil.sendMessage(player, C.SET_OWNER); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/PluginCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/PluginCmd.java index 0938c42f1..27bbeb221 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/PluginCmd.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/PluginCmd.java @@ -8,29 +8,29 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(command = "plugin", - permission = "plots.use", - description = "Show plugin information", - aliases = "version", - category = CommandCategory.INFO) +@CommandDeclaration(command = "plugin", permission = "plots.use", description = "Show plugin information", aliases = "version", category = CommandCategory.INFO) public class PluginCmd extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { TaskManager.IMP.taskAsync(new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, String.format("$2>> $1&l" + PS.imp().getPluginName() + " $2($1Version$2: $1%s$2)", PS.get().getVersion())); - MainUtil.sendMessage(player, "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev"); - MainUtil.sendMessage(player, "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); - MainUtil.sendMessage(player, "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); + @Override public void run() { + MainUtil.sendMessage(player, String + .format("$2>> $1&l" + PS.imp().getPluginName() + " $2($1Version$2: $1%s$2)", + PS.get().getVersion())); + MainUtil.sendMessage(player, + "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev"); + MainUtil.sendMessage(player, + "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); + MainUtil.sendMessage(player, + "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); } }); return true; } public String getNewestVersionString() { - String str = HttpUtil.readUrl("https://api.github.com/repos/IntellectualSites/PlotSquared/releases/latest"); + String str = HttpUtil + .readUrl("https://api.github.com/repos/IntellectualSites/PlotSquared/releases/latest"); JSONObject release = new JSONObject(str); return release.getString("name"); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java index 95eccb11c..f25f05770 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java @@ -18,18 +18,10 @@ import java.util.HashSet; import java.util.Map.Entry; import java.util.UUID; -@CommandDeclaration( - usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", - command = "purge", - permission = "plots.admin", - description = "Purge all plots for a world", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.CONSOLE, - confirmation = true) +@CommandDeclaration(usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", command = "purge", permission = "plots.admin", description = "Purge all plots for a world", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE, confirmation = true) public class Purge extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 0) { return false; } @@ -145,10 +137,10 @@ public class Purge extends SubCommand { C.FOUND_NO_PLOTS.send(player); return false; } - String cmd = "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; + String cmd = + "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { PS.debug("Calculating plots to purge, please wait..."); HashSet ids = new HashSet<>(); for (Plot plot : toDelete) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java index 3121f5c21..8d8ae6790 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java @@ -5,44 +5,24 @@ import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -@CommandDeclaration(command = "rate", - permission = "plots.rate", - description = "Rate the plot", - usage = "/plot rate [#|next|purge]", - aliases = "rt", - category = CommandCategory.INFO, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot", usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO, requiredType = RequiredType.NONE) public class Rate extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 1) { switch (args[0].toLowerCase()) { case "next": { ArrayList plots = new ArrayList<>(PS.get().getBasePlots()); Collections.sort(plots, new Comparator() { - @Override - public int compare(Plot p1, Plot p2) { + @Override public int compare(Plot p1, Plot p2) { double v1 = 0; if (!p1.getRatings().isEmpty()) { for (Entry entry : p1.getRatings().entrySet()) { @@ -63,8 +43,9 @@ public class Rate extends SubCommand { }); UUID uuid = player.getUUID(); for (Plot p : plots) { - if ((!Settings.Done.REQUIRED_FOR_RATINGS || p.hasFlag(Flags.DONE)) && p.isBasePlot() && (!p.getRatings() - .containsKey(uuid)) && !p.isAdded(uuid)) { + if ((!Settings.Done.REQUIRED_FOR_RATINGS || p.hasFlag(Flags.DONE)) && p + .isBasePlot() && (!p.getRatings().containsKey(uuid)) && !p + .isAdded(uuid)) { p.teleportPlayer(player); MainUtil.sendMessage(player, C.RATE_THIS); return true; @@ -105,8 +86,7 @@ public class Rate extends SubCommand { } if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { final Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.getRatings().containsKey(player.getUUID())) { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; @@ -115,19 +95,21 @@ public class Rate extends SubCommand { final MutableInt rating = new MutableInt(0); String title = Settings.Ratings.CATEGORIES.get(0); PlotInventory inventory = new PlotInventory(player, 1, title) { - @Override - public boolean onClick(int i) { + @Override public boolean onClick(int i) { rating.add((i + 1) * Math.pow(10, index.getValue())); index.increment(); if (index.getValue() >= Settings.Ratings.CATEGORIES.size()) { int rV = rating.getValue(); - Rating result = EventUtil.manager.callRating(this.player, plot, new Rating(rV)); + Rating result = + EventUtil.manager.callRating(this.player, plot, new Rating(rV)); plot.addRating(this.player.getUUID(), result); sendMessage(this.player, C.RATING_APPLIED, plot.getId().toString()); if (Permissions.hasPermission(this.player, C.PERMISSION_COMMENT)) { - Command command = MainCommand.getInstance().getCommand(Comment.class); + Command command = + MainCommand.getInstance().getCommand(Comment.class); if (command != null) { - MainUtil.sendMessage(this.player, C.COMMENT_THIS, command.getUsage()); + MainUtil.sendMessage(this.player, C.COMMENT_THIS, + command.getUsage()); } } return false; @@ -151,8 +133,7 @@ public class Rate extends SubCommand { if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } @@ -182,8 +163,7 @@ public class Rate extends SubCommand { } final UUID uuid = player.getUUID(); final Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.getRatings().containsKey(uuid)) { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; @@ -196,8 +176,7 @@ public class Rate extends SubCommand { if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java index 9f4ef1f61..c521d203b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/RegenAllRoads.java @@ -11,27 +11,22 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.Set; -@CommandDeclaration( - command = "regenallroads", - description = "Regenerate all roads in the map using the set road schematic", - aliases = {"rgar"}, - usage = "/plot regenallroads [height]", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.CONSOLE, - permission = "plots.regenallroads") +@CommandDeclaration(command = "regenallroads", description = "Regenerate all roads in the map using the set road schematic", aliases = { + "rgar"}, usage = "/plot regenallroads [height]", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE, permission = "plots.regenallroads") public class RegenAllRoads extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { int height = 0; if (args.length == 2) { try { height = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { MainUtil.sendMessage(player, C.NOT_VALID_NUMBER, "(0, 256)"); - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); return false; } } else if (args.length != 1) { @@ -50,13 +45,16 @@ public class RegenAllRoads extends SubCommand { return false; } Set chunks = ChunkManager.manager.getChunkChunks(name); - MainUtil.sendMessage(player, "&cIf no schematic is set, the following will not do anything"); - MainUtil.sendMessage(player, "&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); + MainUtil + .sendMessage(player, "&cIf no schematic is set, the following will not do anything"); + MainUtil.sendMessage(player, + "&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); MainUtil.sendMessage(player, "&6Potential chunks to update: &7" + (chunks.size() * 1024)); MainUtil.sendMessage(player, "&6Estimated time: &7" + chunks.size() + " seconds"); boolean result = HybridUtils.manager.scheduleRoadUpdate(area, height); if (!result) { - MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)"); + MainUtil.sendMessage(player, + "&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java index 4b20ca2c6..3fc6002c4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Relight.java @@ -1,16 +1,12 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.block.LocalBlockQueue; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; + import java.util.HashSet; @CommandDeclaration(command = "relight", description = "Relight your plot", category = CommandCategory.DEBUG) @@ -19,8 +15,9 @@ public class Relight extends Command { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { final Plot plot = player.getCurrentPlot(); if (plot == null) { C.NOT_IN_PLOT.send(player); @@ -29,13 +26,11 @@ public class Relight extends Command { HashSet regions = plot.getRegions(); final LocalBlockQueue queue = plot.getArea().getQueue(false); ChunkManager.chunkTask(plot, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { queue.fixChunkLighting(value[0], value[1]); } }, new Runnable() { - @Override - public void run() { + @Override public void run() { plot.refreshChunks(); C.SET_BLOCK_ACTION_FINISHED.send(player); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java index 37092ac9c..e06dc672b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java @@ -10,27 +10,23 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; + import java.io.IOException; import java.util.Objects; -@CommandDeclaration(command = "reload", - permission = "plots.admin.command.reload", - description = "Reload configurations", - usage = "/plot reload", - category = CommandCategory.ADMINISTRATION) +@CommandDeclaration(command = "reload", permission = "plots.admin.command.reload", description = "Reload configurations", usage = "/plot reload", category = CommandCategory.ADMINISTRATION) public class Reload extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { try { // The following won't affect world generation, as that has to be // loaded during startup unfortunately. PS.get().setupConfigs(); C.load(PS.get().translationFile); PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea area) { - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection("worlds." + area.worldname); + @Override public void run(PlotArea area) { + ConfigurationSection worldSection = + PS.get().worlds.getConfigurationSection("worlds." + area.worldname); if (worldSection == null) { return; } @@ -38,8 +34,8 @@ public class Reload extends SubCommand { area.saveConfiguration(worldSection); area.loadDefaultConfiguration(worldSection); } else { - ConfigurationSection areaSection = - worldSection.getConfigurationSection("areas." + area.id + "-" + area.getMin() + "-" + area.getMax()); + ConfigurationSection areaSection = worldSection.getConfigurationSection( + "areas." + area.id + "-" + area.getMin() + "-" + area.getMax()); YamlConfiguration clone = new YamlConfiguration(); for (String key : areaSection.getKeys(true)) { if (areaSection.get(key) instanceof MemorySection) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java index 207223384..4c62f19fa 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java @@ -17,22 +17,15 @@ import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration( - command = "remove", - aliases = {"r","untrust", "ut", "undeny", "unban", "ud"}, - description = "Remove a player from a plot", - usage = "/plot remove ", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE, - permission = "plots.remove") +@CommandDeclaration(command = "remove", aliases = {"r", "untrust", "ut", "undeny", "unban", + "ud"}, description = "Remove a player from a plot", usage = "/plot remove ", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, permission = "plots.remove") public class Remove extends SubCommand { public Remove() { super(Argument.PlayerName); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); Plot plot = location.getPlotAbs(); if (plot == null) { @@ -42,7 +35,8 @@ public class Remove extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_REMOVE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_REMOVE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return true; } @@ -72,18 +66,17 @@ public class Remove extends SubCommand { if (!uuids.isEmpty()) { for (UUID uuid : uuids) { if (uuid == DBFunc.everyone) { - if (plot.removeTrusted(uuid)){ + if (plot.removeTrusted(uuid)) { EventUtil.manager.callTrusted(player, plot, uuid, false); count++; - }else if (plot.removeMember(uuid)) { + } else if (plot.removeMember(uuid)) { EventUtil.manager.callMember(player, plot, uuid, false); count++; - }else if (plot.removeDenied(uuid)) { + } else if (plot.removeDenied(uuid)) { EventUtil.manager.callDenied(player, plot, uuid, false); count++; } - } - else if (plot.getTrusted().contains(uuid)) { + } else if (plot.getTrusted().contains(uuid)) { if (plot.removeTrusted(uuid)) { EventUtil.manager.callTrusted(player, plot, uuid, false); count++; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java index bdf706faa..ba34b2df1 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java @@ -3,30 +3,22 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.jnbt.CompoundTag; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.TaskManager; import com.plotsquared.general.commands.CommandDeclaration; + import java.net.URL; import java.util.List; import java.util.UUID; -@CommandDeclaration(command = "save", - aliases = {"backup"}, - description = "Save your plot", - category = CommandCategory.SCHEMATIC, - requiredType = RequiredType.NONE, - permission = "plots.save") +@CommandDeclaration(command = "save", aliases = { + "backup"}, description = "Save your plot", category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, permission = "plots.save") public class Save extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String world = player.getLocation().getWorld(); if (!PS.get().hasPlotArea(world)) { return !sendMessage(player, C.NOT_IN_PLOT_WORLD); @@ -39,7 +31,8 @@ public class Save extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SAVE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SAVE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -49,23 +42,22 @@ public class Save extends SubCommand { } plot.addRunning(); SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { - @Override - public void run(final CompoundTag value) { + @Override public void run(final CompoundTag value) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { String time = (System.currentTimeMillis() / 1000) + ""; Location[] corners = plot.getCorners(); corners[0].setY(0); corners[1].setY(255); int size = (corners[1].getX() - corners[0].getX()) + 1; PlotId id = plot.getId(); - String world = plot.getArea().toString().replaceAll(";", "-").replaceAll("[^A-Za-z0-9]", ""); - final String file = time + '_' + world + '_' + id.x + '_' + id.y + '_' + size; + String world = plot.getArea().toString().replaceAll(";", "-") + .replaceAll("[^A-Za-z0-9]", ""); + final String file = + time + '_' + world + '_' + id.x + '_' + id.y + '_' + size; UUID uuid = player.getUUID(); SchematicHandler.manager.upload(value, uuid, file, new RunnableVal() { - @Override - public void run(URL url) { + @Override public void run(URL url) { plot.removeRunning(); if (url == null) { MainUtil.sendMessage(player, C.SAVE_FAILED); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java index 644a040ae..87ca5fb89 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java @@ -3,12 +3,7 @@ package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.SchematicHandler; @@ -21,19 +16,13 @@ import java.util.ArrayList; import java.util.Collection; import java.util.UUID; -@CommandDeclaration( - command = "schematic", - permission = "plots.schematic", - description = "Schematic command", - aliases = {"sch"}, - category = CommandCategory.SCHEMATIC, - usage = "/plot schematic ") +@CommandDeclaration(command = "schematic", permission = "plots.schematic", description = "Schematic command", aliases = { + "sch"}, category = CommandCategory.SCHEMATIC, usage = "/plot schematic ") public class SchematicCmd extends SubCommand { private boolean running = false; - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { sendMessage(player, C.SCHEMATIC_MISSING_ARG); return true; @@ -58,7 +47,8 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_PASTE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_PASTE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -69,8 +59,7 @@ public class SchematicCmd extends SubCommand { final String location = args[1]; this.running = true; TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { Schematic schematic; if (location.startsWith("url:")) { try { @@ -80,7 +69,8 @@ public class SchematicCmd extends SubCommand { schematic = SchematicHandler.manager.getSchematic(url); } catch (Exception e) { e.printStackTrace(); - sendMessage(player, C.SCHEMATIC_INVALID, "non-existent url: " + location); + sendMessage(player, C.SCHEMATIC_INVALID, + "non-existent url: " + location); SchematicCmd.this.running = false; return; } @@ -89,20 +79,21 @@ public class SchematicCmd extends SubCommand { } if (schematic == null) { SchematicCmd.this.running = false; - sendMessage(player, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); + sendMessage(player, C.SCHEMATIC_INVALID, + "non-existent or not in gzip format"); return; } - SchematicHandler.manager.paste(schematic, plot, 0, 0, 0, true, new RunnableVal() { - @Override - public void run(Boolean value) { - SchematicCmd.this.running = false; - if (value) { - sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); - } else { - sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + SchematicHandler.manager + .paste(schematic, plot, 0, 0, 0, true, new RunnableVal() { + @Override public void run(Boolean value) { + SchematicCmd.this.running = false; + if (value) { + sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); + } else { + sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + } } - } - }); + }); } }); break; @@ -146,7 +137,8 @@ public class SchematicCmd extends SubCommand { return false; } if (args.length != 2) { - MainUtil.sendMessage(player, "&cNeed world argument. Use &7/plot sch exportall "); + MainUtil.sendMessage(player, + "&cNeed world argument. Use &7/plot sch exportall "); return false; } PlotArea area = PS.get().getPlotAreaByString(args[1]); @@ -156,21 +148,24 @@ public class SchematicCmd extends SubCommand { } Collection plots = area.getPlots(); if (plots.isEmpty()) { - MainUtil.sendMessage(player, "&cInvalid world. Use &7/plot sch exportall "); + MainUtil + .sendMessage(player, "&cInvalid world. Use &7/plot sch exportall "); return false; } - boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, "&aFinished mass export"); - } - }); + boolean result = + SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&aFinished mass export"); + } + }); if (!result) { MainUtil.sendMessage(player, "&cTask is already running."); return false; } else { - MainUtil.sendMessage(player, "&3Plot&8->&3Schematic&8: &7Mass export has started. This may take a while."); - MainUtil.sendMessage(player, "&3Plot&8->&3Schematic&8: &7Found &c" + plots.size() + "&7 plots..."); + MainUtil.sendMessage(player, + "&3Plot&8->&3Schematic&8: &7Mass export has started. This may take a while."); + MainUtil.sendMessage(player, + "&3Plot&8->&3Schematic&8: &7Found &c" + plots.size() + "&7 plots..."); } break; } @@ -193,20 +188,21 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_SAVE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_SAVE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } location.getWorld(); Collection plots = new ArrayList<>(); plots.add(plot); - boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, "&aFinished export"); - SchematicCmd.this.running = false; - } - }); + boolean result = + SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&aFinished export"); + SchematicCmd.this.running = false; + } + }); if (!result) { MainUtil.sendMessage(player, "&cTask is already running."); return false; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java index d36c31555..f8047d47a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Set.java @@ -5,16 +5,8 @@ import com.intellectualcrafters.plot.config.Configuration; import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.WorldUtil; +import com.intellectualcrafters.plot.object.*; +import com.intellectualcrafters.plot.util.*; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.CommandDeclaration; @@ -23,43 +15,38 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; -@CommandDeclaration( - command = "set", - description = "Set a plot value", - aliases = {"s"}, - usage = "/plot set ", - permission = "plots.set", - category = CommandCategory.APPEARANCE, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "set", description = "Set a plot value", aliases = { + "s"}, usage = "/plot set ", permission = "plots.set", category = CommandCategory.APPEARANCE, requiredType = RequiredType.NONE) public class Set extends SubCommand { - public static final String[] values = new String[]{"biome", "alias", "home", "flag"}; - public static final String[] aliases = new String[]{"b", "w", "wf", "f", "a", "h", "fl"}; + public static final String[] values = new String[] {"biome", "alias", "home", "flag"}; + public static final String[] aliases = new String[] {"b", "w", "wf", "f", "a", "h", "fl"}; private final SetCommand component; public Set() { this.component = new SetCommand() { - @Override - public String getId() { + @Override public String getId() { return "set.component"; } - @Override - public boolean set(PlotPlayer player, final Plot plot, String value) { + @Override public boolean set(PlotPlayer player, final Plot plot, String value) { PlotArea plotArea = player.getLocation().getPlotArea(); PlotManager manager = player.getLocation().getPlotManager(); String[] components = manager.getPlotComponents(plotArea, plot.getId()); boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(player.getUUID()); String[] args = value.split(" "); - String material = StringMan.join(Arrays.copyOfRange(args, 1, args.length), ",").trim(); + String material = + StringMan.join(Arrays.copyOfRange(args, 1, args.length), ",").trim(); for (String component : components) { if (component.equalsIgnoreCase(args[0])) { - if (!Permissions.hasPermission(player, C.PERMISSION_SET_COMPONENT.f(component))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_COMPONENT.f(component)); + if (!Permissions + .hasPermission(player, C.PERMISSION_SET_COMPONENT.f(component))) { + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_COMPONENT.f(component)); return false; } PlotBlock[] blocks; @@ -80,23 +67,28 @@ public class Set extends SubCommand { } else { name = split[i]; } - StringComparison.ComparisonResult match = WorldUtil.IMP.getClosestBlock(name); + StringComparison.ComparisonResult match = + WorldUtil.IMP.getClosestBlock(name); if (match != null) { name = WorldUtil.IMP.getClosestMatchingName(match.best); if (name != null) { - MainUtil.sendMessage(player, C.DID_YOU_MEAN, name.toLowerCase()); + MainUtil.sendMessage(player, C.DID_YOU_MEAN, + name.toLowerCase()); } } return false; - } else if (!allowUnsafe && (block.id != 0 && !WorldUtil.IMP.isBlockSolid(block))) { - MainUtil.sendMessage(player, C.NOT_ALLOWED_BLOCK, block.toString()); + } else if (!allowUnsafe && (block.id != 0 && !WorldUtil.IMP + .isBlockSolid(block))) { + MainUtil + .sendMessage(player, C.NOT_ALLOWED_BLOCK, block.toString()); return false; } } if (!allowUnsafe) { for (PlotBlock block : blocks) { if (block.id != 0 && !WorldUtil.IMP.isBlockSolid(block)) { - MainUtil.sendMessage(player, C.NOT_ALLOWED_BLOCK, block.toString()); + MainUtil.sendMessage(player, C.NOT_ALLOWED_BLOCK, + block.toString()); return false; } } @@ -115,8 +107,7 @@ public class Set extends SubCommand { } MainUtil.sendMessage(player, C.GENERATING_COMPONENT); GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.removeRunning(); } }); @@ -133,14 +124,15 @@ public class Set extends SubCommand { newValues.addAll(Arrays.asList("biome", "alias", "home", "flag")); Plot plot = player.getCurrentPlot(); if (plot != null) { - newValues.addAll(Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + newValues.addAll( + Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); } - MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan.join(newValues, C.BLOCK_LIST_SEPARATER.formatted())); + MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan + .join(newValues, C.BLOCK_LIST_SEPARATER.formatted())); return false; } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if (args.length == 0) { return noArgs(player); } @@ -159,7 +151,8 @@ public class Set extends SubCommand { return false; } // components - HashSet components = new HashSet<>(Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + HashSet components = new HashSet<>( + Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); if (components.contains(args[0].toLowerCase())) { return this.component.onCommand(player, Arrays.copyOfRange(args, 0, args.length)); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java index ced109a75..ca0386103 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java @@ -10,8 +10,7 @@ import com.intellectualcrafters.plot.util.StringMan; public abstract class SetCommand extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -19,14 +18,16 @@ public abstract class SetCommand extends SubCommand { } if (!plot.hasOwner()) { if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND.f(getFullId())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_ADMIN_COMMAND.f(getFullId())); MainUtil.sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } } if (!plot.isOwner(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND.f(getFullId())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_ADMIN_COMMAND.f(getFullId())); MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java index 5ae2647c3..c7fb60582 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SetHome.java @@ -8,18 +8,11 @@ import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.util.MainUtil; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "sethome", - permission = "plots.set.home", - description = "Set the plot home", - usage = "/plot sethome [none]", - aliases = {"sh", "seth"}, - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "sethome", permission = "plots.set.home", description = "Set the plot home", usage = "/plot sethome [none]", aliases = { + "sh", "seth"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class SetHome extends SetCommand { - @Override - public boolean set(PlotPlayer player, Plot plot, String value) { + @Override public boolean set(PlotPlayer player, Plot plot, String value) { switch (value.toLowerCase()) { case "unset": case "remove": @@ -32,7 +25,9 @@ public class SetHome extends SetCommand { Plot base = plot.getBasePlot(false); Location bot = base.getBottomAbs(); Location loc = player.getLocationFull(); - BlockLoc rel = new BlockLoc(loc.getX() - bot.getX(), loc.getY(), loc.getZ() - bot.getZ(), loc.getYaw(), loc.getPitch()); + BlockLoc rel = + new BlockLoc(loc.getX() - bot.getX(), loc.getY(), loc.getZ() - bot.getZ(), + loc.getYaw(), loc.getPitch()); base.setHome(rel); return MainUtil.sendMessage(player, C.POSITION_SET); default: diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java index 6e2019ff6..201d25267 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java @@ -19,14 +19,8 @@ import java.util.Arrays; import java.util.List; import java.util.Map.Entry; -@CommandDeclaration( - command = "setup", - permission = "plots.admin.command.setup", - description = "Setup wizard for plot worlds", - usage = "/plot setup", - aliases = {"create"}, - category = CommandCategory.ADMINISTRATION) -public class Setup extends SubCommand { +@CommandDeclaration(command = "setup", permission = "plots.admin.command.setup", description = "Setup wizard for plot worlds", usage = "/plot setup", aliases = { + "create"}, category = CommandCategory.ADMINISTRATION) public class Setup extends SubCommand { public void displayGenerators(PlotPlayer player) { StringBuilder message = new StringBuilder(); @@ -43,8 +37,7 @@ public class Setup extends SubCommand { MainUtil.sendMessage(player, message.toString()); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { // going through setup SetupObject object = player.getMeta("setup"); if (object == null) { @@ -65,8 +58,8 @@ public class Setup extends SubCommand { if (object.setup_index > 0) { object.setup_index--; ConfigurationNode node = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, node.getDescription(), node.getType().getType(), - String.valueOf(node.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, node.getDescription(), + node.getType().getType(), String.valueOf(node.getDefaultValue())); return false; } else if (object.current > 0) { object.current--; @@ -78,7 +71,9 @@ public class Setup extends SubCommand { case 0: // choose generator if (args.length != 1 || !SetupUtils.generators.containsKey(args[0])) { String prefix = "\n&8 - &7"; - MainUtil.sendMessage(player, "&cYou must choose a generator!" + prefix + StringMan.join(SetupUtils.generators.keySet(), prefix) + MainUtil.sendMessage(player, + "&cYou must choose a generator!" + prefix + StringMan + .join(SetupUtils.generators.keySet(), prefix) .replaceAll(PS.imp().getPluginName(), "&2" + PS.imp().getPluginName())); sendMessage(player, C.SETUP_INIT); return false; @@ -86,12 +81,14 @@ public class Setup extends SubCommand { object.setupGenerator = args[0]; object.current++; String partial = "\n&8 - &7PARTIAL&8 - &7Vanilla with clusters of plots"; - MainUtil.sendMessage(player, "&6What world type do you want?\n&8 - &2DEFAULT&8 - &7Standard plot generation" + MainUtil.sendMessage(player, + "&6What world type do you want?\n&8 - &2DEFAULT&8 - &7Standard plot generation" + "\n&8 - &7AUGMENTED&8 - &7Plot generation with terrain" + partial); break; case 1: // choose world type List allTypes = Arrays.asList("default", "augmented", "partial"); - List allDesc = Arrays.asList("Standard plot generation", "Plot generation with vanilla terrain", + List allDesc = Arrays + .asList("Standard plot generation", "Plot generation with vanilla terrain", "Vanilla with clusters of plots"); ArrayList types = new ArrayList<>(); if (SetupUtils.generators.get(object.setupGenerator).isFull()) { @@ -104,9 +101,11 @@ public class Setup extends SubCommand { for (String type : types) { int i = allTypes.indexOf(type); if (type.equals("default")) { - MainUtil.sendMessage(player, "&8 - &2" + type + " &8-&7 " + allDesc.get(i)); + MainUtil + .sendMessage(player, "&8 - &2" + type + " &8-&7 " + allDesc.get(i)); } else { - MainUtil.sendMessage(player, "&8 - &7" + type + " &8-&7 " + allDesc.get(i)); + MainUtil + .sendMessage(player, "&8 - &7" + type + " &8-&7 " + allDesc.get(i)); } } return false; @@ -117,9 +116,12 @@ public class Setup extends SubCommand { object.current = 6; if (object.step == null) { object.plotManager = object.setupGenerator; - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); - SetupUtils.generators.get(object.plotManager).getPlotGenerator().processSetup(object); + object.step = + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .processSetup(object); } if (object.step.length == 0) { MainUtil.sendMessage(player, "&6What do you want your world to be called?"); @@ -127,31 +129,38 @@ public class Setup extends SubCommand { return true; } ConfigurationNode step = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); } else { if (gen.isFull()) { object.plotManager = object.setupGenerator; object.setupGenerator = null; - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); - SetupUtils.generators.get(object.plotManager).getPlotGenerator().processSetup(object); + object.step = + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .processSetup(object); } else { object.plotManager = PS.imp().getPluginName(); - MainUtil.sendMessage(player, "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); - MainUtil.sendMessage(player, "&7 - You may need to manually configure the other plugin"); - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + MainUtil.sendMessage(player, + "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); + MainUtil.sendMessage(player, + "&7 - You may need to manually configure the other plugin"); + object.step = + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); } if (object.type == 2) { MainUtil.sendMessage(player, "What would you like this area called?"); object.current++; } else { MainUtil.sendMessage(player, "&6What terrain would you like in plots?" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); object.current = 5; } } @@ -163,7 +172,8 @@ public class Setup extends SubCommand { } for (PlotArea area : PS.get().getPlotAreas()) { if (area.id != null && area.id.equalsIgnoreCase(args[0])) { - MainUtil.sendMessage(player, "&cYou must choose an area id that is not in use!"); + MainUtil.sendMessage(player, + "&cYou must choose an area id that is not in use!"); return false; } } @@ -188,22 +198,23 @@ public class Setup extends SubCommand { return false; } if (id.x <= object.min.x || id.y <= object.min.y) { - MainUtil.sendMessage(player, "&cThe max PlotId must be greater than the minimum!"); + MainUtil + .sendMessage(player, "&cThe max PlotId must be greater than the minimum!"); return false; } object.max = id; object.current++; MainUtil.sendMessage(player, "&6What terrain would you like in plots?" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); break; case 5: { // Choose terrain List terrain = Arrays.asList("none", "ore", "road", "all"); if (args.length != 1 || !terrain.contains(args[0].toLowerCase())) { - MainUtil.sendMessage(player, "&cYou must choose the terrain!" - + "\n&8 - &2NONE&8 - &7No terrain at all" + MainUtil.sendMessage(player, + "&cYou must choose the terrain!" + "\n&8 - &2NONE&8 - &7No terrain at all" + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); @@ -213,11 +224,12 @@ public class Setup extends SubCommand { object.current++; if (object.step == null) { object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); } ConfigurationNode step = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); break; } case 6: // world setup @@ -229,8 +241,8 @@ public class Setup extends SubCommand { } ConfigurationNode step = object.step[object.setup_index]; if (args.length < 1) { - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); return false; } boolean valid = step.isValid(args[0]); @@ -243,13 +255,13 @@ public class Setup extends SubCommand { return false; } step = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); return false; } else { sendMessage(player, C.SETUP_INVALID_ARG, args[0], step.getConstant()); - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); return false; } case 7: @@ -263,8 +275,9 @@ public class Setup extends SubCommand { return false; } MainUtil.sendMessage(player, - "&cThe world you specified already exists. After restarting, new terrain will use " + PS.imp().getPluginName() + ", however you may need to " - + "reset the world for it to generate correctly!"); + "&cThe world you specified already exists. After restarting, new terrain will use " + + PS.imp().getPluginName() + ", however you may need to " + + "reset the world for it to generate correctly!"); } object.world = args[0]; player.deleteMeta("setup"); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java index b53869965..ca1df5732 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/SubCommand.java @@ -9,8 +9,9 @@ import com.plotsquared.general.commands.Command; /** * SubCommand class - * @see Command(Command, boolean) + * * @Deprecated In favor of normal Command class + * @see Command(Command, boolean) */ public abstract class SubCommand extends Command { public SubCommand() { @@ -22,8 +23,9 @@ public abstract class SubCommand extends Command { setRequiredArguments(arguments); } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { onCommand(player, args); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java index d1871f6b3..471f14bb0 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java @@ -8,22 +8,18 @@ import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration(usage = "/plot swap ", - command = "swap", - description = "Swap two plots", - aliases = {"switch"}, - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(usage = "/plot swap ", command = "swap", description = "Swap two plots", aliases = { + "switch"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Swap extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); } - if (!plot1.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if (!plot1.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -45,8 +41,7 @@ public class Swap extends SubCommand { return false; } if (plot1.move(plot2, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, C.SWAP_SUCCESS); } }, true)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java index 6cfae47cc..c69a1cbf6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java @@ -10,21 +10,14 @@ import com.intellectualcrafters.plot.util.StringMan; import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.CommandDeclaration; -@CommandDeclaration( - command = "target", - usage = "/plot target <|nearest>", - description = "Target a plot with your compass", - permission = "plots.target", - requiredType = RequiredType.PLAYER, - category = CommandCategory.INFO) +@CommandDeclaration(command = "target", usage = "/plot target <|nearest>", description = "Target a plot with your compass", permission = "plots.target", requiredType = RequiredType.PLAYER, category = CommandCategory.INFO) public class Target extends SubCommand { public Target() { super(Argument.PlotID); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); if (!location.isPlotArea()) { MainUtil.sendMessage(player, C.NOT_IN_PLOT_WORLD); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java index 86102a444..b948c75d6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java +++ b/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java @@ -7,33 +7,21 @@ import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.ConfigurationNode; import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.FileBytes; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.SetupObject; +import com.intellectualcrafters.plot.object.*; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; import com.plotsquared.general.commands.CommandDeclaration; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; + +import java.io.*; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -@CommandDeclaration( - command = "template", - permission = "plots.admin", - description = "Create or use a world template", - usage = "/plot template [import|export]