下面列出了怎么用org.bukkit.permissions.Permission的API类实例代码及写法,或者点击链接到github查看源代码。
private static Permission getPermission(
ConfigurationSection config, String id, PermissionDefault def, String realm) {
final Map<String, Boolean> permissions = new HashMap<>();
for (String permission : config.getStringList(realm)) {
if (permission.startsWith("-")) {
permissions.put(permission.substring(1), false);
} else if (permission.startsWith("+")) {
permissions.put(permission.substring(1), true);
} else {
permissions.put(permission, true);
}
}
final String node =
Permissions.GROUP
+ "."
+ id
+ (realm.contains("-") ? "-" + realm.substring(0, realm.indexOf('-')) : "");
return Permissions.register(new Permission(node, def, permissions));
}
private LuckPermsDefaultsMap tryInject() throws Exception {
Objects.requireNonNull(DEFAULT_PERMISSIONS_FIELD, "DEFAULT_PERMISSIONS_FIELD");
PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager();
if (!(pluginManager instanceof SimplePluginManager)) {
this.plugin.getLogger().severe("PluginManager instance is not a 'SimplePluginManager', instead: " + pluginManager.getClass());
this.plugin.getLogger().severe("Unable to inject LuckPerms Default Permission map.");
return null;
}
Object map = DEFAULT_PERMISSIONS_FIELD.get(pluginManager);
if (map instanceof LuckPermsDefaultsMap && ((LuckPermsDefaultsMap) map).plugin == this.plugin) {
return null;
}
//noinspection unchecked
Map<Boolean, Set<Permission>> castedMap = (Map<Boolean, Set<Permission>>) map;
// make a new map & inject it
LuckPermsDefaultsMap newMap = new LuckPermsDefaultsMap(this.plugin, castedMap);
DEFAULT_PERMISSIONS_FIELD.set(pluginManager, newMap);
return newMap;
}
@Override
public boolean hasPermission(@NonNull Permission permission) {
if (permission == null) {
throw new NullPointerException("permission");
}
QueryOptions queryOptions = this.queryOptionsSupplier.getQueryOptions();
TristateResult result = this.user.getCachedData().getPermissionData(queryOptions).checkPermission(permission.getName(), PermissionCheckEvent.Origin.PLATFORM_PERMISSION_CHECK);
// override default op handling using the Permission class we have
if (result.processorClass() == OpProcessor.class && this.plugin.getConfiguration().get(ConfigKeys.APPLY_BUKKIT_DEFAULT_PERMISSIONS)) {
// 'op == true' is implied by the presence of the OpProcessor class
return permission.getDefault().getValue(true);
}
return result.result().asBoolean();
}
public static boolean hasPerm(CommandSender sender, boolean basic, Permission perm) {
if (sender == null) return false;
// Ops can do everything
if (sender.isOp()) return true;
// If permissions are disabled, the user will have this command if it's a "basic" command
if (claimChunk.chConfig().getBool("basic", "disablePermissions")) {
return basic;
}
// If `claimchunk.player` is used, then the player will be able to use this command if it's a "basic" command
if (basic && sender.hasPermission("claimchunk.player")) {
return true;
}
// Check permission
return sender.hasPermission(perm);
}
public static Permission registerPermission(Permission perm, boolean withLegacy) {
Permission result = perm;
try {
Bukkit.getPluginManager().addPermission(perm);
} catch (IllegalArgumentException ex) {
result = Bukkit.getPluginManager().getPermission(perm.getName());
}
if (withLegacy) {
Permission legacy = new Permission(LEGACY_PREFIX + result.getName(), result.getDescription(), PermissionDefault.FALSE);
legacy.getChildren().put(result.getName(), true);
registerPermission(perm, false);
}
return result;
}
public static Permission registerPermissions(Permission parent) {
Permission commands = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all vanilla minecraft commands", parent);
DefaultPermissions.registerPermission(PREFIX + "kill", "Allows the user to commit suicide", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "me", "Allows the user to perform a chat action", PermissionDefault.TRUE, commands);
DefaultPermissions.registerPermission(PREFIX + "tell", "Allows the user to privately message another player", PermissionDefault.TRUE, commands);
DefaultPermissions.registerPermission(PREFIX + "say", "Allows the user to talk as the console", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "give", "Allows the user to give items to players", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "teleport", "Allows the user to teleport players", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "kick", "Allows the user to kick players", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "stop", "Allows the user to stop the server", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "list", "Allows the user to list all online players", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "gamemode", "Allows the user to change the gamemode of another player", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "xp", "Allows the user to give themselves or others arbitrary values of experience", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "toggledownfall", "Allows the user to toggle rain on/off for a given world", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "defaultgamemode", "Allows the user to change the default gamemode of the server", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "seed", "Allows the user to view the seed of the world", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "effect", "Allows the user to add/remove effects on players", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "selector", "Allows the use of selectors", PermissionDefault.OP, commands);
DefaultPermissions.registerPermission(PREFIX + "trigger", "Allows the use of the trigger command", PermissionDefault.TRUE, commands);
commands.recalculatePermissibles();
return commands;
}
@EventHandler
public void onResourcestatusChange(PlayerResourcePackStatusEvent event) {
if (ResourcePackManager.getForceResourcePack()) {
Status status = event.getStatus();
switch (status) {
case DECLINED:
case FAILED_DOWNLOAD:
final Player player = event.getPlayer();
if (!player.hasPermission(new Permission("additionsapi.resourcepack.bypass", PermissionDefault.FALSE)))
Bukkit.getServer().getScheduler().runTask(AdditionsAPI.getInstance(),
() -> player.kickPlayer(LangFileUtils.get("resource_pack_kick")));
break;
case ACCEPTED:
case SUCCESSFULLY_LOADED:
default:
break;
}
}
}
/**
* Economy (soft-dependency on Vault)
* - If a Vault-based economy was not found, disable the bounty system
*/
private void setupEconomy() {
if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
}
if (economy == null) {
instance.getLogger().warning("Bounty-system [disabled], Vault economy not found");
for (Permission permission : Bukkit.getPluginManager().getDefaultPermissions(false)) {
if (permission.getName().startsWith("globalwarming.bounty")) {
Bukkit.getPluginManager().getPermission(permission.getName())
.setDefault(PermissionDefault.FALSE);
}
}
} else {
instance.getLogger().info("Bounty-system [enabled], Vault economy found");
}
}
@Override
public void onEnable() {
// Ensure parsing errors show in the console on Lobby servers,
// since PGM is not around to do that.
mapdevLogger.setUseParentHandlers(true);
this.getServer().getPluginManager().registerEvents(new EnvironmentControlListener(), this);
this.getServer().getPluginManager().registerEvents(new Gizmos(), this);
this.getServer().getMessenger().registerOutgoingPluginChannel(this, BUNGEE_CHANNEL);
this.setupScoreboard();
this.loadConfig();
for(Gizmo gizmo : Gizmos.gizmos) {
Bukkit.getPluginManager().addPermission(new Permission(gizmo.getPermissionNode(), PermissionDefault.FALSE));
}
Settings settings = new Settings(this);
settings.register();
navigatorInterface.setOpenButtonSlot(Slot.Hotbar.forPosition(0));
}
static Permission register(Permission permission) {
try {
PGM.get().getServer().getPluginManager().addPermission(permission);
} catch (Throwable t) {
// No-op, the permission was already registered
}
return permission;
}
@Override
public boolean isPermissionSet(@NonNull Permission permission) {
if (permission == null) {
throw new NullPointerException("permission");
}
final boolean result = this.delegate.isPermissionSet(permission);
logCheck(PermissionCheckEvent.Origin.PLATFORM_LOOKUP_CHECK, permission.getName(), result);
return result;
}
public void addPermission(Permission perm, boolean dirty) {
String name = perm.getName().toLowerCase(java.util.Locale.ENGLISH);
if (permissions.containsKey(name)) {
throw new IllegalArgumentException("The permission " + name + " is already defined!");
}
permissions.put(name, perm);
calculatePermissionDefault(perm, dirty);
}
public static boolean register(CustomItem customItem, Plugin plugin, String group) {
initialize();
if (_plugin == null) {
return false;
} else if (customItem._owner != null || _container.contains(customItem)) {
_plugin.getLogger().warning(plugin.getName() + " tried to register an already registered CustomItem, " + customItem.getSlug());
return false;
}
CustomItemConfig config = _configsByGroup.get(group);
if (config == null) {
config = new CustomItemConfig(group);
}
config.configureItem(customItem);
config.saveToFile();
_configsByGroup.put(group, config);
customItem._owner = plugin;
customItem._group = group;
(new Permission("nbteditor.customitems.use." + customItem.getSlug())).addParent(_usePermission, true);
(new Permission("nbteditor.customitems.world-override." + customItem.getSlug())).addParent(_worldOverridePermission, true);
_container.put(customItem, plugin, group);
return true;
}
private void calculatePermissionDefault(Permission perm, boolean dirty) {
if ((perm.getDefault() == PermissionDefault.OP) || (perm.getDefault() == PermissionDefault.TRUE)) {
defaultPerms.get(true).add(perm);
if (dirty) {
dirtyPermissibles(true);
}
}
if ((perm.getDefault() == PermissionDefault.NOT_OP) || (perm.getDefault() == PermissionDefault.TRUE)) {
defaultPerms.get(false).add(perm);
if (dirty) {
dirtyPermissibles(false);
}
}
}
public static void registerCorePermissions() {
Permission parent = registerPermission(ROOT, "Gives the user the ability to use all CraftBukkit utilities and commands");
CommandPermissions.registerPermissions(parent);
BroadcastPermissions.registerPermissions(parent);
parent.recalculatePermissibles();
}
private List<BPPermission> expandChildPermsWithOrigin(List<BPPermission> perms)
{
for (int i = 0; i < perms.size(); i++)
{
//get perm info
String perm = perms.get(i).getPermission();
boolean neg = perm.startsWith("-");
perm = neg ? perm.substring(1) : perm;
//check perm
Permission p = Bukkit.getPluginManager().getPermission(perm);
if (p == null || p.getChildren().isEmpty())
{
continue;
}
//add all children
List<BPPermission> l = new ArrayList();
for (Map.Entry<String, Boolean> e : p.getChildren().entrySet())
{
l.add(new BPPermission((e.getValue() ? "" : "-") + e.getKey().toLowerCase(), "SuperPerms child of " + perm, true, null, null, null, null));
}
perms.addAll(i + 1, l);
}
return perms;
}
private Predicate generatePermissions(String commandName, CommandPermission permission) {
// If we've already registered a permission, set it to the "parent" permission.
/*
* This permission generation setup ONLY works iff: - You register the parent
* permission node FIRST. - Example: /mycmd - permission node my.perm /mycmd
* <arg> - permission node my.perm.other
*
* the my.perm.other permission node is revoked for the COMMAND REGISTRATION,
* however: - The permission node IS REGISTERED. - The permission node, if used
* for an argument (as in this case), will be used for suggestions for said
* argument
*/
if (permissionsToFix.containsKey(commandName.toLowerCase())) {
if (!permissionsToFix.get(commandName.toLowerCase()).equals(permission)) {
permission = permissionsToFix.get(commandName.toLowerCase());
}
} else {
// Add permission to a list to fix conflicts with minecraft:permissions
permissionsToFix.put(commandName.toLowerCase(), permission);
}
final CommandPermission finalPermission = permission;
// Register it to the Bukkit permissions registry
if (finalPermission.getPermission() != null) {
try {
Bukkit.getPluginManager().addPermission(new Permission(finalPermission.getPermission()));
} catch (IllegalArgumentException e) {
}
}
return (Object clw) -> permissionCheck(nms.getCommandSenderForCLW(clw), finalPermission);
}
/**
* 向服务端注册 BaseMainCommand 类
*
* @param command 命令全称(需在 plugin.yml 内注册)
* @param baseMainCommand 命令对象
* @return {@link BaseMainCommand}
*/
public static BaseMainCommand registerCommand(BaseCommand tCommand, String command, BaseMainCommand baseMainCommand, Plugin plugin) {
if (Bukkit.getPluginCommand(command) == null) {
String permission = tCommand.permission();
if (tCommand.permissionDefault() == PermissionDefault.TRUE || tCommand.permissionDefault() == PermissionDefault.NOT_OP) {
if (permission == null || permission.isEmpty()) {
permission = plugin.getName().toLowerCase() + ".command.use";
}
if (Bukkit.getPluginManager().getPermission(permission) != null) {
try {
Permission p = new Permission(permission, tCommand.permissionDefault());
Bukkit.getPluginManager().addPermission(p);
Bukkit.getPluginManager().recalculatePermissionDefaults(p);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
registerPluginCommand(
plugin,
command,
ArrayUtil.skipEmpty(tCommand.description(), "Registered by TabooLib."),
ArrayUtil.skipEmpty(tCommand.usage(), "/" + command),
ArrayUtil.skipEmpty(ArrayUtil.asList(tCommand.aliases()), new ArrayList<>()),
ArrayUtil.skipEmpty(tCommand.permission()),
ArrayUtil.skipEmpty(tCommand.permissionMessage()),
baseMainCommand,
baseMainCommand);
}
return BaseMainCommand.createCommandExecutor(command, baseMainCommand);
}
private void registerPackPermission(ResourcePack pack) {
if (getServer().getPluginManager().getPermission(pack.getPermission()) == null) {
Permission perm = new Permission(pack.getPermission());
perm.setDefault(PermissionDefault.OP);
perm.setDescription("Permission for access to the resourcepack " + pack.getName() + " via the usepack command and automatic sending.");
try {
getServer().getPluginManager().addPermission(perm);
} catch (IllegalArgumentException ignored) {} // Permission already registered
}
for (ResourcePack variant : pack.getVariants()) {
registerPackPermission(variant);
}
}
@Inject ChannelMatchModule(Match match, Plugin plugin) {
this.matchListeningPermission = new Permission("pgm.chat.all." + match.getId() + ".receive", PermissionDefault.FALSE);
final OnlinePlayerMapAdapter<Boolean> map = new OnlinePlayerMapAdapter<>(plugin);
map.enable();
this.teamChatters = new DefaultMapAdapter<>(map, true, false);
}
public static void sendResourcePack(Player player, String hostAddress) {
Bukkit.getServer().getScheduler().runTaskLater(AdditionsAPI.getInstance(), () -> {
if (ResourcePackManager.hasResource()
&& ConfigFile.getInstance().getConfig().getBoolean("resource-pack.send-to-player")
&& !player.hasPermission(
new Permission("additionsapi.resourcepack.disable", PermissionDefault.FALSE))) {
String link;
if (!ConfigFile.getInstance().getConfig().getBoolean("resource-pack.use-minepack")) {
if (hostAddress != null && hostAddress.equals("127.0.0.1")) {
link = "http://" + ResourcePackServer.localhost + ":" + ResourcePackServer.port
+ ResourcePackServer.path;
} else {
link = "http://" + ResourcePackServer.host + ":" + ResourcePackServer.port
+ ResourcePackServer.path;
}
} else {
link = MinePackInitializationMethod.resourcePack;
}
if (player != null && player.isOnline())
if (ResourcePackManager.hasSendWithHash)
try {
player.setResourcePack(link, ResourcePackManager.resourcePackSha1Byte);
} catch (NoSuchMethodError e) {
ResourcePackManager.hasSendWithHash = false;
player.setResourcePack(link);
}
else
player.setResourcePack(link);
Debug.saySuper("Sending Resource Pack Link to Player: " + link);
}
}, 20L);
}
void setupPermissions(String name, Permission parent) {
String permName = parent.getName();
if (permName.endsWith(".*")) {
permName = permName.substring(0, permName.length() - 2);
}
_perm = new Permission(permName + "." + name);
_perm.addParent(parent, true);
for (Entry<String, MySubCommand> entry : _subCommands.entrySet()) {
entry.getValue().setupPermissions(entry.getKey(), _perm);
}
Bukkit.getPluginManager().addPermission(_perm);
parent.recalculatePermissibles();
}
@Override
public Permission put(@NonNull String key, @NonNull Permission value) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(value, "value");
this.plugin.getPermissionRegistry().insert(key);
Permission ret = super.put(key, inject(value));
update();
return ret;
}
public static void registerArgument(AnniArgument argument)
{
if(argument != null)
{
if(argument.getPermission() != null)
{
Permission perm = new Permission(argument.getPermission());
Bukkit.getPluginManager().addPermission(perm);
perm.recalculatePermissibles();
}
arguments.put(argument.getArgumentName().toLowerCase(), argument);
recalcItemMenu();
}
}
@Override
protected void configure() {
requestStaticInjection(RaindropUtil.class);
new PluginFacetBinder(binder())
.register(RaindropCommands.class);
final PermissionBinder permissions = new PermissionBinder(binder());
for(int i = RaindropConstants.MULTIPLIER_MAX; i > 0; i = i - RaindropConstants.MULTIPLIER_INCREMENT) {
permissions.bindPermission().toInstance(new Permission("raindrops.multiplier." + i, PermissionDefault.FALSE));
}
}
@Override
public TristateResult hasPermission(String permission) {
Tristate t = this.plugin.getDefaultPermissionMap().lookupDefaultPermission(permission, this.isOp);
if (t != Tristate.UNDEFINED) {
return DEFAULT_PERMISSION_MAP_RESULT_FACTORY.result(t);
}
Permission defPerm = this.plugin.getPermissionMap().get(permission);
if (defPerm == null) {
return TristateResult.UNDEFINED;
}
return PERMISSION_MAP_RESULT_FACTORY.result(Tristate.of(defPerm.getDefault().getValue(this.isOp)));
}
private boolean canBypass(Player player) {
if(player == null) return false;
FileConfiguration config = this.plugin.getConfig("config.yml");
String bypassPermission = config.getString("combat.bypass-permission");
if(bypassPermission == null || bypassPermission.isEmpty()) return false;
Permission permission = new Permission(bypassPermission, "Bypass permission for CombatLogX.", PermissionDefault.FALSE);
return player.hasPermission(permission);
}
public CommandScript(String name, List<String> commands, Permission permission) {
this.name = name;
file = new File(DungeonsXL.COMMANDS, name + ".yml");
setCommands(commands);
}
@Override
public boolean hasPermission(Permission perm) {
return false;
}
@Override
public boolean isPermissionSet(Permission perm) {
validateOnline();
return getBukkitPlayer().isPermissionSet(perm);
}