org.spongepowered.api.Sponge Java Examples

The following examples show how to use org.spongepowered.api.Sponge. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlacklistListener.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Listener
public void onChangeEquipment(ChangeInventoryEvent.Equipment event, @Root Player player)
{
	if (!player.hasPermission("essentialcmds.blacklist.bypass"))
	{
		for (SlotTransaction transaction : event.getTransactions())
		{
			if (Utils.getBlacklistItems().contains(transaction.getFinal().createStack().getItem().getId()))
			{
				if (Utils.areBlacklistMsgsEnabled())
					player.sendMessage(Text.of(TextColors.RED, "The item ", TextColors.GRAY, transaction.getFinal().createStack().getItem().getId(), TextColors.RED, " has been confiscated as it is blacklisted."));

				transaction.setCustom(Sponge.getRegistry().createBuilder(ItemStack.Builder.class).itemType(ItemTypes.DIRT).quantity(1).build());
			}
		}
	}
}
 
Example #2
Source File: Utils.java    From EssentialCmds with MIT License 6 votes vote down vote up
public static void teleportPlayerToJail(Player player, int number)
{
	UUID worldUuid = UUID.fromString(Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "world").getString());
	double x = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "X").getDouble();
	double y = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "Y").getDouble();
	double z = Configs.getConfig(jailsConfig).getNode("jails", String.valueOf(number), "Z").getDouble();
	World world = Sponge.getServer().getWorld(worldUuid).orElse(null);

	if (world != null)
	{
		Location<World> location = new Location<World>(world, x, y, z);

		if (player.getWorld().getUniqueId().equals(worldUuid))
		{
			player.setLocation(location);
		}
		else
		{
			player.transferToWorld(world.getUniqueId(), location.getPosition());
		}
	}
}
 
Example #3
Source File: VirtualChestPlugin.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Listener
public void onReload(GameReloadEvent event)
{
    try
    {
        MessageReceiver src = event.getCause().first(CommandSource.class).orElse(Sponge.getServer().getConsole());
        src.sendMessage(this.translation.take("virtualchest.reload.start"));
        this.loadConfig();
        this.saveConfig();
        src.sendMessage(this.translation.take("virtualchest.reload.finish"));
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: GlobalData.java    From UltimateCore with MIT License 6 votes vote down vote up
/**
 * Set the value of a key to the specified value.
 *
 * @param key   The key to set the value of
 * @param value The value to set the value to
 * @param <C>   The type of value the key holds
 * @return Whether the value was accepted
 */
public static <C> boolean offer(Key.Global<C> key, C value) {
    Cause cause = Cause.builder().append(UltimateCore.getContainer()).build(EventContext.builder().build());
    DataOfferEvent<C> event = new DataOfferEvent<>(key, (C) datas.get(key.getIdentifier()), value, cause);
    Sponge.getEventManager().post(event);
    if (event.isCancelled()) {
        return false;
    }
    value = event.getValue().orElse(null);
    //Save to config if needed
    if (key.getProvider().isPresent()) {
        key.getProvider().get().save(Sponge.getGame(), value);
    }
    //Save to map
    if (value == null) {
        datas.remove(key.getIdentifier());
    } else {
        datas.put(key.getIdentifier(), value);
    }
    return true;
}
 
Example #5
Source File: BloodEffects.java    From UltimateCore with MIT License 6 votes vote down vote up
public static void reload() {
    effects.clear();
    ModuleConfig config = Modules.BLOOD.get().getConfig().get();
    for (EntityType type : Sponge.getRegistry().getAllOf(CatalogTypes.ENTITY_TYPE)) {
        CommentedConfigurationNode node = config.get().getNode("types", type.getId());
        try {
            BloodEffect effect = node.getValue(TypeToken.of(BloodEffect.class));
            if (effect == null) {
                continue;
            }
            effects.put(type, effect);
        } catch (ObjectMappingException e) {
            ErrorLogger.log(e, "Failed to deserialize bloodeffect for " + type.getId() + " (" + e.getMessage() + ")");
        }
    }
}
 
Example #6
Source File: ChangeSkinSponge.java    From ChangeSkin with MIT License 6 votes vote down vote up
@Listener
public void onInit(GameInitializationEvent initEvent) {
    if (!initialized)
        return;

    CommandManager cmdManager = Sponge.getCommandManager();

    //command and event register
    cmdManager.register(this, injector.getInstance(SelectCommand.class).buildSpec(), "skin-select", "skinselect");
    cmdManager.register(this, injector.getInstance(InfoCommand.class).buildSpec(), "skin-info");
    cmdManager.register(this, injector.getInstance(UploadCommand.class).buildSpec(), "skin-upload");
    cmdManager.register(this, injector.getInstance(SetCommand.class).buildSpec(), "changeskin", "setskin", "skin");
    cmdManager.register(this, injector.getInstance(InvalidateCommand.class)
            .buildSpec(), "skininvalidate", "skin-invalidate");

    Sponge.getEventManager().registerListeners(this, injector.getInstance(LoginListener.class));

    //incoming channel
    ChannelRegistrar channelReg = Sponge.getChannelRegistrar();
    String updateChannelName = new NamespaceKey(ARTIFACT_ID, UPDATE_SKIN_CHANNEL).getCombinedName();
    String permissionChannelName = new NamespaceKey(ARTIFACT_ID, CHECK_PERM_CHANNEL).getCombinedName();
    RawDataChannel updateChannel = channelReg.getOrCreateRaw(this, updateChannelName);
    RawDataChannel permChannel = channelReg.getOrCreateRaw(this, permissionChannelName);
    updateChannel.addListener(Type.SERVER, injector.getInstance(UpdateSkinListener.class));
    permChannel.addListener(Type.SERVER, injector.getInstance(CheckPermissionListener.class));
}
 
Example #7
Source File: GPClaim.java    From GriefPrevention with MIT License 6 votes vote down vote up
@Override
public ClaimResult addGroupTrusts(List<String> groups, TrustType type) {
    GPGroupTrustClaimEvent.Add event = new GPGroupTrustClaimEvent.Add(this, groups, type);
    Sponge.getEventManager().post(event);
    if (event.isCancelled()) {
        return new GPClaimResult(ClaimResultType.CLAIM_EVENT_CANCELLED, event.getMessage().orElse(null));
    }

    for (String group : groups) {
        List<String> groupList = this.getGroupTrustList(type);
        if (!groupList.contains(group)) {
            groupList.add(group);
        }
    }

    this.claimData.setRequiresSave(true);
    this.claimData.save();
    return new GPClaimResult(this, ClaimResultType.SUCCESS);
}
 
Example #8
Source File: UserParser.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context)
{
	String peek;
	try
	{
		peek = args.peek();
	}
	catch (ArgumentParseException e)
	{
		return Sponge.getGame().getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
	}

	return Sponge.getGame().getServer().getOnlinePlayers().stream().filter(x -> x.getName().toLowerCase().startsWith(peek))
		.map(Player::getName).collect(Collectors.toList());
}
 
Example #9
Source File: UIRenderer.java    From SubServers-2 with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to send a Title Message
 *
 * @param str Message
 * @param fadein FadeIn Transition length (in ticks)
 * @param stay How long the message should stay (in ticks)
 * @param fadeout FadeOut Transition length (in ticks)
 * @return Success Status
 */
public boolean sendTitle(String str, int fadein, int stay, int fadeout) {
    if (Util.isNull(str, fadein, stay, fadeout)) throw new NullPointerException();
    if (plugin.config.get().getMap("Settings").getBoolean("Use-Title-Messages", true)) {
        String line1, line2;
        if (!str.startsWith("\n") && str.contains("\n")) {
            line1 = str.split("\\n")[0];
            line2 = str.split("\\n")[1];
        } else {
            line1 = str.replace("\n", "");
            line2 = ChatColor.RESET.toString();
        }
        try {
            if (ChatColor.stripColor(line1).length() == 0 && ChatColor.stripColor(line2).length() == 0) {
                Sponge.getServer().getPlayer(player).get().resetTitle();
            } else {
                Sponge.getServer().getPlayer(player).get().sendTitle(Title.builder().title(ChatColor.convertColor(line1)).subtitle(ChatColor.convertColor(line2)).fadeIn((fadein >= 0)?fadein:10).stay((stay >= 0)?stay:70).fadeOut((fadeout >= 0)?fadeout:20).build());
            }
            return true;
        } catch (Throwable e) {
            return false;
        }
    } else return false;
}
 
Example #10
Source File: AttackLogicImpl.java    From EagleFactions with MIT License 6 votes vote down vote up
@Override
public void runHomeUsageRestorer(final UUID playerUUID)
{
    Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();

    taskBuilder.interval(1, TimeUnit.SECONDS).execute(task ->
    {
        if (EagleFactionsPlugin.BLOCKED_HOME.containsKey(playerUUID))
        {
            int seconds = EagleFactionsPlugin.BLOCKED_HOME.get(playerUUID);

            if (seconds <= 0)
            {
                EagleFactionsPlugin.BLOCKED_HOME.remove(playerUUID);
                task.cancel();
            }
            else
            {
                EagleFactionsPlugin.BLOCKED_HOME.replace(playerUUID, seconds, seconds - 1);
            }
        }
    }).submit(EagleFactionsPlugin.getPlugin());
}
 
Example #11
Source File: BlacklistListener.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Listener
public void onPickupItem(ChangeInventoryEvent.Pickup event, @Root Player player)
{
	if (!player.hasPermission("essentialcmds.blacklist.bypass"))
	{
		for (SlotTransaction transaction : event.getTransactions())
		{
			if (Utils.getBlacklistItems().contains(transaction.getFinal().createStack().getItem().getId()))
			{
				if (Utils.areBlacklistMsgsEnabled())
					player.sendMessage(Text.of(TextColors.RED, "The item ", TextColors.GRAY, transaction.getFinal().createStack().getItem().getId(), TextColors.RED, " has been confiscated as it is blacklisted."));

				transaction.setCustom(Sponge.getRegistry().createBuilder(ItemStack.Builder.class).itemType(ItemTypes.DIRT).quantity(1).build());
			}
		}
	}
}
 
Example #12
Source File: CommandHelper.java    From GriefPrevention with MIT License 6 votes vote down vote up
public static String lookupPlayerName(UUID playerID) {
    // parameter validation
    if (playerID == null) {
        return "somebody";
    }

    // check the cache
    Optional<User> player = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(playerID);
    if (player.isPresent()) {
        return player.get().getName();
    } else {
        try {
            return Sponge.getServer().getGameProfileManager().get(playerID).get().getName().get();
        } catch (Exception e) {
            return "someone";
        }
    }
}
 
Example #13
Source File: WorldsBase.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	ArrayList<String> worlds = EssentialCmds.getEssentialCmds().getGame().getServer().getWorlds().stream().filter(world -> world.getProperties().isEnabled()).map(World::getName).collect(Collectors.toCollection(ArrayList::new));

	PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
	ArrayList<Text> worldText = Lists.newArrayList();

	for (String name : worlds)
	{
		Text item = Text.builder(name)
			.onClick(TextActions.runCommand("/tpworld " + name))
			.onHover(TextActions.showText(Text.of(TextColors.WHITE, "Teleport to world ", TextColors.GOLD, name)))
			.color(TextColors.DARK_AQUA)
			.style(TextStyles.UNDERLINE)
			.build();

		worldText.add(item);
	}

	PaginationList.Builder paginationBuilder = paginationService.builder().contents(worldText).title(Text.of(TextColors.GREEN, "Showing Worlds")).padding(Text.of("-"));
	paginationBuilder.sendTo(src);
}
 
Example #14
Source File: GCExecutor.java    From EssentialCmds with MIT License 6 votes vote down vote up
@Override
public void executeAsync(CommandSource src, CommandContext ctx)
{
	double tps = Sponge.getServer().getTicksPerSecond();
	src.sendMessage(Text.of(TextColors.GOLD, "Current TPS: ", TextColors.GRAY, tps));
	src.sendMessage(Text.of(TextColors.GOLD, "World Info:"));

	for (World world : Sponge.getServer().getWorlds())
	{
		int numOfEntities = world.getEntities().size();
		int loadedChunks = Iterables.size(world.getLoadedChunks());
		src.sendMessage(Text.of());
		src.sendMessage(Text.of(TextColors.GREEN, "World: ", world.getName()));
		src.sendMessage(Text.of(TextColors.GOLD, "Entities: ", TextColors.GRAY, numOfEntities));
		src.sendMessage(Text.of(TextColors.GOLD, "Loaded Chunks: ", TextColors.GRAY, loadedChunks));
	}
}
 
Example #15
Source File: MobFlagGui.java    From RedProtect with GNU General Public License v3.0 6 votes vote down vote up
public void open() {
    //Register Listener
    Sponge.getGame().getEventManager().registerListeners(RedProtect.get().container, this);

    Inventory inv = RedProtect.get().getVersionHelper().newInventory(54, "Item flag GUI");

    int i = 0;
    while (i < this.guiItems.length) {
        int line = 0;
        int slot = i;
        if (i > 8) {
            line = i / 9;
            slot = i - (line * 9);
        }
        RedProtect.get().getVersionHelper().query(inv, slot, line).set(this.guiItems[i]);
        i++;
    }

    RedProtect.get().getVersionHelper().openInventory(inv, this.player);
}
 
Example #16
Source File: ClaimsListCommand.java    From EagleFactions with MIT License 5 votes vote down vote up
private void showClaimsList(final CommandSource source, final Faction faction)
{
    final List<Text> resultList = new ArrayList<>();
    final Set<Claim> claims = faction.getClaims();

    for (final Claim claim : claims)
    {
        final Text.Builder claimHoverInfo = Text.builder();
        claimHoverInfo.append(Text.of(TextColors.GOLD, "Accessible by faction: ", TextColors.RESET, claim.isAccessibleByFaction(), "\n"));
        final List<String> ownersNames = claim.getOwners().stream()
                .map(owner -> super.getPlugin().getPlayerManager().getFactionPlayer(owner))
                .filter(Optional::isPresent)
                .map(factionPlayer -> factionPlayer.get().getName())
                .collect(Collectors.toList());
        claimHoverInfo.append(Text.of(TextColors.GOLD, "Owners: ", TextColors.RESET, String.join(", ", ownersNames)));

        final Text.Builder textBuilder = Text.builder();
        final Optional<World> world = Sponge.getServer().getWorld(claim.getWorldUUID());
        String worldName = "";
        if (world.isPresent())
            worldName = world.get().getName();
        textBuilder.append(Text.of("- ", TextColors.YELLOW, "World: " , TextColors.GREEN, worldName, TextColors.RESET, " | ", TextColors.YELLOW, "Chunk: ", TextColors.GREEN, claim.getChunkPosition()))
                .onHover(TextActions.showText(claimHoverInfo.build()));
        resultList.add(textBuilder.build());
    }

    final PaginationList paginationList = PaginationList.builder().padding(Text.of("=")).title(Text.of(TextColors.YELLOW, "Claims List")).contents(resultList).linesPerPage(10).build();
    paginationList.sendTo(source);
}
 
Example #17
Source File: CommandAdjustBonusClaimBlocks.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) {
    WorldProperties worldProperties = args.<WorldProperties> getOne("world").orElse(Sponge.getServer().getDefaultWorld().get());

    if (worldProperties == null) {
        if (src instanceof Player) {
            worldProperties = ((Player) src).getWorld().getProperties();
        } else {
            worldProperties = Sponge.getServer().getDefaultWorld().get();
        }
    }
    if (worldProperties == null || !GriefPreventionPlugin.instance.claimsEnabledForWorld(worldProperties)) {
        GriefPreventionPlugin.sendMessage(src, GriefPreventionPlugin.instance.messageData.claimDisabledWorld.toText());
        return CommandResult.success();
    }

    // parse the adjustment amount
    int adjustment = args.<Integer>getOne("amount").get();
    User user = args.<User>getOne("user").get();

    // give blocks to player
    GPPlayerData playerData = GriefPreventionPlugin.instance.dataStore.getOrCreatePlayerData(worldProperties, user.getUniqueId());
    playerData.setBonusClaimBlocks(playerData.getBonusClaimBlocks() + adjustment);
    playerData.getStorageData().save();
    final Text message = GriefPreventionPlugin.instance.messageData.adjustBlocksSuccess
            .apply(ImmutableMap.of(
            "player", Text.of(user.getName()),
            "adjustment", Text.of(adjustment),
            "total", Text.of(playerData.getBonusClaimBlocks()))).build();
    GriefPreventionPlugin
            .sendMessage(src, message);
    GriefPreventionPlugin.addLogEntry(
            src.getName() + " adjusted " + user.getName() + "'s bonus claim blocks by " + adjustment + ".",
            CustomLogEntryTypes.AdminActivity);

    return CommandResult.success();
}
 
Example #18
Source File: Visualization.java    From GriefPrevention with MIT License 5 votes vote down vote up
public Visualization(Location<World> lesserBoundaryCorner, Location<World> greaterBoundaryCorner, VisualizationType type) {
    initBlockVisualTypes(type);
    this.lesserBoundaryCorner = lesserBoundaryCorner;
    this.greaterBoundaryCorner = greaterBoundaryCorner;
    this.type = type;
    this.snapshotBuilder = Sponge.getGame().getRegistry().createBuilder(BlockSnapshot.Builder.class);
    this.elements = new ArrayList<Transaction<BlockSnapshot>>();
    this.newElements = new ArrayList<>();
    this.corners = new ArrayList<>();
}
 
Example #19
Source File: ServerService.java    From Web-API with MIT License 5 votes vote down vote up
private void recordStats() {
    long total = 0;
    long free = 0;
    File[] roots = File.listRoots();
    for (File root : roots) {
        total += root.getTotalSpace();
        free += root.getFreeSpace();
    }

    long maxMem = Runtime.getRuntime().maxMemory();
    long usedMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());

    // Stuff accessing sponge needs to be run on the server main thread
    WebAPI.runOnMain(() -> {
        averageTps.add(new ServerStat<>(Sponge.getServer().getTicksPerSecond()));
        onlinePlayers.add(new ServerStat<>(Sponge.getServer().getOnlinePlayers().size()));
    });
    cpuLoad.add(new ServerStat<>(systemMXBean.getProcessCpuLoad()));
    memoryLoad.add(new ServerStat<>(usedMem / (double)maxMem));
    diskUsage.add(new ServerStat<>((total - free) / (double)total));

    while (averageTps.size() > MAX_STATS_ENTRIES)
        averageTps.poll();
    while (onlinePlayers.size() > MAX_STATS_ENTRIES)
        onlinePlayers.poll();
    while (cpuLoad.size() > MAX_STATS_ENTRIES)
        cpuLoad.poll();
    while (memoryLoad.size() > MAX_STATS_ENTRIES)
        memoryLoad.poll();
    while (diskUsage.size() > MAX_STATS_ENTRIES)
        diskUsage.poll();
}
 
Example #20
Source File: VirtualChestActions.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void playSound(String command, Player player, Location<World> location, double pitch)
{
    double volume;
    SoundType soundType;
    GameRegistry registry = Sponge.getRegistry();
    Optional<SoundType> soundTypeOptional = registry.getType(SoundType.class, command);
    if (soundTypeOptional.isPresent())
    {
        volume = 1;
        soundType = soundTypeOptional.get();
    }
    else
    {
        int index = command.lastIndexOf(':');
        String id = index > 0 ? command.substring(0, index).toLowerCase() : "";
        Supplier<RuntimeException> error = () -> new NoSuchElementException("No value available for " + id);
        soundType = registry.getType(SoundType.class, id).orElseThrow(error);
        volume = Double.parseDouble(command.substring(index + 1));
    }
    if (Double.isNaN(pitch))
    {
        player.playSound(soundType, soundCategory, location.getPosition(), volume);
    }
    else
    {
        player.playSound(soundType, soundCategory, location.getPosition(), volume, pitch);
    }
}
 
Example #21
Source File: CoreModule.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public void onInit(GameInitializationEvent event) {
    //Commands
    UltimateCore.get().getCommandService().register(new UltimatecoreCommand());
    //Listeners
    Sponge.getEventManager().registerListeners(UltimateCore.get(), new DefaultListener());
}
 
Example #22
Source File: CommandHelper.java    From GriefDefender with MIT License 5 votes vote down vote up
private static boolean validateItemTarget(String target) {
    Optional<ItemType> itemType = Sponge.getRegistry().getType(ItemType.class, target);
    if (itemType.isPresent()) {
        return true;
    }
    // target could be an item block, so validate blockstate
    Optional<BlockState> blockState = Sponge.getRegistry().getType(BlockState.class, target);
    if (blockState.isPresent()) {
        return true;
    }

    return false;
}
 
Example #23
Source File: CommandHelper.java    From GriefDefender with MIT License 5 votes vote down vote up
private static boolean validateCommandMapping(CommandSource src, String command, String pluginId) {
    if (command.equals("any")) {
        return true;
    }

    CommandMapping commandMapping = Sponge.getCommandManager().get(command).orElse(null);
    if (commandMapping == null) {
        TextAdapter.sendComponent(src, MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.PLUGIN_COMMAND_NOT_FOUND,
                ImmutableMap.of(
                    "command", command,
                    "id", pluginId)));
        return false;
    }
    return true;
}
 
Example #24
Source File: FaweSponge.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public UUID getUUID(String name) {
    try {
        GameProfileManager pm = Sponge.getServer().getGameProfileManager();
        GameProfile profile = pm.get(name).get();
        return profile != null ? profile.getUniqueId() : null;
    } catch (Exception e) {
        return null;
    }
}
 
Example #25
Source File: ExpandVertCommand.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public CommandSpec register() {
    return CommandSpec.builder()
            .description(Text.of("Command to expand a region from bedrock to sky."))
            .arguments(
                    GenericArguments.optional(GenericArguments.string(Text.of("regionName"))),
                    GenericArguments.optional(GenericArguments.world(Text.of("world")))
            )
            .permission("redprotect.command.expand-vert")
            .executor((src, args) -> {
                if (!(src instanceof Player)) {
                    HandleHelpPage(src, 1);
                } else {
                    Player player = (Player) src;
                    Region r = RedProtect.get().rm.getTopRegion(player.getLocation(), this.getClass().getName());

                    if (args.hasAny("regionName")) {
                        r = RedProtect.get().rm.getRegion(args.<String>getOne("regionName").get(), player.getWorld().getName());
                    }

                    if (args.hasAny("world")) {
                        r = RedProtect.get().rm.getRegion(args.<String>getOne("regionName").get(), args.<World>getOne("world").get().getName());
                    }

                    if (r == null) {
                        RedProtect.get().lang.sendMessage(player, "cmdmanager.region.todo.that");
                        return CommandResult.success();
                    }

                    if (!RedProtect.get().ph.hasRegionPermAdmin(player, "expand-vert", r)) {
                        RedProtect.get().lang.sendMessage(player, "no.permission");
                        return CommandResult.success();
                    }

                    r.setMaxY(Sponge.getServer().getWorld(r.getWorld()).get().getDimension().getHeight());
                    r.setMinY(0);
                }
                return CommandResult.success();
            }).build();
}
 
Example #26
Source File: EventRunner.java    From EagleFactions with MIT License 5 votes vote down vote up
/**
 * @return True if cancelled, false if not
 */
public static boolean runFactionUnclaimEvent(final Player player, final Faction faction, final World world, final Vector3i chunkPosition)
{
    final EventContext eventContext = EventContext.builder()
            .add(EventContextKeys.OWNER, player)
            .add(EventContextKeys.PLAYER, player)
            .add(EventContextKeys.CREATOR, player)
            .build();

    final Cause eventCause = Cause.of(eventContext, player, faction);
    final FactionClaimEvent.Unclaim event = new FactionUnclaimEventImpl(player, faction, world, chunkPosition, eventCause);
    return Sponge.getEventManager().post(event);
}
 
Example #27
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public void startFlagChanger(final String r, final String flag, final Player p) {
    RedProtect.get().changeWait.add(r + flag);
    Sponge.getScheduler().createSyncExecutor(RedProtect.get().container).schedule(() -> {
        /*if (p != null && p.isOnline()){
                RedProtect.get().lang.sendMessage(p, RedProtect.get().lang.get("gui.needwait.ready").replace("{flag}", flag));
            }*/
        RedProtect.get().changeWait.remove(r + flag);
    }, RedProtect.get().config.configRoot().flags_configuration.change_flag_delay.seconds, TimeUnit.SECONDS);
}
 
Example #28
Source File: CommandClaimInfo.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static Consumer<CommandSource> createSettingsConsumer(CommandSource src, Claim claim, List<Text> textList, ClaimType type) {
    return settings -> {
        String name = type == ClaimType.TOWN ? "Town Settings" : "Admin Settings";
        PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get();
        PaginationList.Builder paginationBuilder = paginationService.builder()
                .title(Text.of(TextColors.AQUA, name)).padding(Text.of(TextStyles.STRIKETHROUGH, "-")).contents(textList);
        paginationBuilder.sendTo(src);
    };
}
 
Example #29
Source File: DeafModule.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public void onInit(GameInitializationEvent event) {
    UltimateCore.get().getCommandService().register(new DeafCommand());
    UltimateCore.get().getCommandService().register(new UndeafCommand());
    Sponge.getEventManager().registerListeners(UltimateCore.get(), new DeafListener());
    UltimateCore.get().getTickService().addRunnable("deaf", new DeafTickRunnable());
    //Register permissions
    new DeafPermissions();
}
 
Example #30
Source File: SpongeTaskChainFactory.java    From TaskChain with MIT License 5 votes vote down vote up
private SpongeGameInterface(Object plugin, AsyncQueue asyncQueue) {
    this.asyncQueue = asyncQueue;
    if (plugin == null || !Sponge.getPluginManager().fromInstance(plugin).isPresent()) {
        throw new IllegalArgumentException("Not a valid Sponge Plugin");
    }
    this.plugin = plugin;
}