Java Code Examples for org.bukkit.Bukkit#getWorld()

The following examples show how to use org.bukkit.Bukkit#getWorld() . 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: ProtectionsTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void blockPlaceShouldNotBeCancelledInUnprotected() {
    RegionsTests.loadRegionTypeDirt();

    Player player = mock(Player.class);
    UUID uuid = new UUID(1, 2);
    when(player.getUniqueId()).thenReturn(uuid);

    Player player2 = mock(Player.class);
    UUID uuid2 = new UUID(1, 3);
    when(player2.getUniqueId()).thenReturn(uuid2);

    HashMap<UUID, String> owners = new HashMap<>();
    owners.put(uuid2, Constants.OWNER);
    Location regionLocation = new Location(Bukkit.getWorld("world"), 0,0,0);
    RegionManager.getInstance().addRegion(new Region("dirt", owners, regionLocation, RegionsTests.getRadii(), new HashMap<String, String>(),0));

    ProtectionHandler protectionHandler = new ProtectionHandler();
    BlockBreakEvent event = new BlockBreakEvent(TestUtil.block3, player);
    protectionHandler.onBlockBreak(event);
    assertFalse(event.isCancelled());
}
 
Example 2
Source File: CitizensShop.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean check() {
	NPC npc = this.getNPC();
	if (npc != null) {
		String worldName = shopkeeper.getWorldName();
		World world = Bukkit.getWorld(worldName);
		int x = shopkeeper.getX();
		int y = shopkeeper.getY();
		int z = shopkeeper.getZ();

		Location currentLocation = npc.getStoredLocation();
		Location expectedLocation = new Location(world, x + 0.5D, y + 0.5D, z + 0.5D);
		if (currentLocation == null) {
			npc.teleport(expectedLocation, PlayerTeleportEvent.TeleportCause.PLUGIN);
			Log.debug("Shopkeeper NPC (" + worldName + "," + x + "," + y + "," + z + ") had no location, teleported");
		} else if (!currentLocation.getWorld().equals(expectedLocation.getWorld()) || currentLocation.distanceSquared(expectedLocation) > 1.0D) {
			shopkeeper.setLocation(currentLocation);
			Log.debug("Shopkeeper NPC (" + worldName + "," + x + "," + y + "," + z + ") out of place, re-indexing");
		}
	} else {
		// Not going to force Citizens creation, this seems like it could go really wrong.
	}

	return false;
}
 
Example 3
Source File: ImportManager.java    From Statz with GNU General Public License v3.0 6 votes vote down vote up
private Optional<JSONObject> getUserStatisticsFile(UUID uuid, String worldName)
        throws IOException, ParseException {
    Objects.requireNonNull(uuid);
    Objects.requireNonNull(worldName);

    World world = Bukkit.getWorld(worldName);

    if (world == null) return Optional.empty();

    File worldFolder = new File(world.getWorldFolder(), "stats");
    File playerStatistics = new File(worldFolder, uuid.toString() + ".json");

    if (!playerStatistics.exists()) {
        return Optional.empty();
    }

    JSONObject rootObject = (JSONObject) new JSONParser().parse(new FileReader(playerStatistics));

    if (rootObject == null) return Optional.empty();

    if (rootObject.containsKey("stats")) {
        return Optional.ofNullable((JSONObject) rootObject.get("stats"));
    }

    return Optional.empty();
}
 
Example 4
Source File: UtilTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void placeHookShouldReportHighestPop() {
    CivilianManager.getInstance().createDefaultCivilian(TestUtil.player);
    TownTests.loadTownTypeHamlet2();
    Location location = new Location(Bukkit.getWorld("world"), 0,0,0);
    HashMap<UUID, String> people = new HashMap<>();
    people.put(TestUtil.player.getUniqueId(), "member");
    Town town = new Town("mytown1", "hamlet2", location, people, 100, 100,
            3, 0, -1);
    TownManager.getInstance().addTown(town);
    Town town1 = new Town("mytown2", "hamlet2", location, people, 100, 100,
            8, 1, -1);
    TownManager.getInstance().addTown(town1);
    PlaceHook placeHook = new PlaceHook();
    assertEquals("mytown2", placeHook.onPlaceholderRequest(TestUtil.player, "townname"));
}
 
Example 5
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void regionShouldBeDestroyedAndRebuilt() {
    loadRegionTypeCobble();
    HashMap<UUID, String> owners = new HashMap<>();
    UUID uuid = new UUID(1, 4);
    owners.put(uuid, Constants.OWNER);
    Location location1 = new Location(Bukkit.getWorld("world"), 4, 0, 0);
    RegionManager.getInstance().addRegion(new Region("cobble", owners, location1, getRadii(), new HashMap<>(),0));
    BlockBreakEvent event = new BlockBreakEvent(TestUtil.blockUnique, TestUtil.player);
    CivilianListener civilianListener = new CivilianListener();
    civilianListener.onCivilianBlockBreak(event);
    ProtectionHandler protectionHandler = new ProtectionHandler();
    protectionHandler.onBlockBreak(event);
    BlockPlaceEvent event1 = mock(BlockPlaceEvent.class);
    Block block2 = TestUtil.createUniqueBlock(Material.CHEST, "Civs cobble", location1, false);
    when(event1.getBlockPlaced()).thenReturn(block2);
    ItemStack itemStack = TestUtil.createUniqueItemStack(Material.CHEST, "Civs Cobble");
    when(event1.getItemInHand()).thenReturn(itemStack);
    when(event1.getPlayer()).thenReturn(TestUtil.player);
    RegionListener regionListener = new RegionListener();
    regionListener.onBlockPlace(event1);
    assertNotNull(RegionManager.getInstance().getRegionAt(location1));
}
 
Example 6
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void regionShouldBeCreatedWithAllReqs() {
    loadRegionTypeCobble();

    BlockPlaceEvent event3 = mock(BlockPlaceEvent.class);
    when(event3.getBlockPlaced()).thenReturn(TestUtil.block3);
    ItemStack cobbleStack = TestUtil.createItemStack(Material.COBBLESTONE);
    doReturn(cobbleStack).when(event3).getItemInHand();
    BlockPlaceEvent event2 = mock(BlockPlaceEvent.class);
    when(event2.getBlockPlaced()).thenReturn(TestUtil.block2);
    when(event2.getItemInHand()).thenReturn(cobbleStack);
    BlockPlaceEvent event1 = mock(BlockPlaceEvent.class);
    when(event1.getPlayer()).thenReturn(TestUtil.player);
    Location regionLocation = new Location(Bukkit.getWorld("world"), -1 , 0, 0);
    Block chestBlock = TestUtil.createUniqueBlock(Material.CHEST, "Civs cobble", regionLocation, false);
    when(event1.getBlockPlaced()).thenReturn(chestBlock);
    List<String> lore = new ArrayList<>();
    lore.add(TestUtil.player.getUniqueId().toString());
    lore.add("Civs Cobble");
    ItemStack itemStack = TestUtil.mockItemStack(Material.CHEST, 1, "Civs Cobble", lore);
    doReturn(itemStack).when(event1).getItemInHand();

    RegionListener regionListener = new RegionListener();
    regionListener.onBlockPlace(event2);
    regionListener.onBlockPlace(event3);
    regionListener.onBlockPlace(event1);
    Region region = RegionManager.getInstance().getRegionAt(regionLocation);
    assertEquals("cobble", region.getType());
    assertEquals(5, region.getRadiusXP());
    assertEquals(5, region.getRadiusXN());
    assertEquals(-0.5, region.getLocation().getX(), 0.1);
    assertEquals(0.5, region.getLocation().getZ(), 0.1);
}
 
Example 7
Source File: LocationSerializer.java    From HolographicDisplays with GNU General Public License v3.0 5 votes vote down vote up
public static Location locationFromString(String input) throws WorldNotFoundException, InvalidFormatException {
	if (input == null) {
		throw new InvalidFormatException();
	}
	
	String[] parts = input.split(",");
	
	if (parts.length != 4) {
		throw new InvalidFormatException();
	}
	
	try {
		double x = Double.parseDouble(parts[1].replace(" ", ""));
		double y = Double.parseDouble(parts[2].replace(" ", ""));
		double z = Double.parseDouble(parts[3].replace(" ", ""));
	
		World world = Bukkit.getWorld(parts[0].trim());
		if (world == null) {
			throw new WorldNotFoundException(parts[0].trim());
		}
		
		return new Location(world, x, y, z);
		
	} catch (NumberFormatException ex) {
		throw new InvalidFormatException();
	}
}
 
Example 8
Source File: TownTests.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void townShouldDestroyWhenCriticalRegionDestroyed2() {
    RegionsTests.loadRegionTypeCobbleGroup();
    HashMap<UUID, String> people = new HashMap<>();
    people.put(TestUtil.player.getUniqueId(), Constants.OWNER);
    HashMap<String, String> effects = new HashMap<>();
    Location regionLocation = new Location(Bukkit.getWorld("world2"), 0,0,0);
    Region region = new Region("town_hall", people,
            regionLocation,
            RegionsTests.getRadii(),
            effects,0);
    loadTownTypeTribe();
    Location townLocation = new Location(Bukkit.getWorld("world2"), 1,0,0);

    RegionManager regionManager = RegionManager.getInstance();
    regionManager.addRegion(region);
    loadTown("Sanmak-kol", "tribe", townLocation);
    if (TownManager.getInstance().getTowns().isEmpty()) {
        fail("No town found");
    }
    ProtectionHandler protectionHandler = new ProtectionHandler();
    Block block = mock(Block.class);
    when(block.getLocation()).thenReturn(regionLocation);
    BlockBreakEvent blockBreakEvent = new BlockBreakEvent(block, TestUtil.player);
    CivilianListener civilianListener = new CivilianListener();
    protectionHandler.onBlockBreak(blockBreakEvent);
    if (!blockBreakEvent.isCancelled()) {
        civilianListener.onCivilianBlockBreak(blockBreakEvent);
    }
    assertNull(regionManager.getRegionAt(regionLocation));
    assertTrue(TownManager.getInstance().getTowns().isEmpty());
}
 
Example 9
Source File: PortMenuTest.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
public static Region loadRegion(String type) {
    HashMap<UUID, String> peopleMap = new HashMap<>();
    peopleMap.put(TestUtil.player.getUniqueId(), Constants.OWNER);
    Location location = new Location(Bukkit.getWorld("world"), 0,0,0);
    int[] radii = new int[6];
    for (int i=0; i<6; i++) {
        radii[i] = 5;
    }
    RegionType regionType = (RegionType) ItemManager.getInstance().getItemType(type);
    Region region = new Region(type, peopleMap, location, radii, regionType.getEffects(),0);

    RegionManager.getInstance().addRegion(region);

    return region;
}
 
Example 10
Source File: ImprovedOfflinePlayer.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public Location getLocation() {
  NBTTagList position = this.compound.getList("Pos", NBTStaticHelper.TAG_DOUBLE);
  NBTTagList rotation = this.compound.getList("Rotation", NBTStaticHelper.TAG_FLOAT);
  
  return new Location(
  		Bukkit.getWorld(new UUID(this.compound.getLong("WorldUUIDMost"), this.compound.getLong("WorldUUIDLeast"))),
  		position.d(0), position.d(1), position.d(2), rotation.e(0), rotation.e(1));
}
 
Example 11
Source File: WorldBorderThread.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
private void startMoving(){
	GameManager.getGameManager().broadcastInfoMessage(Lang.GAME_BORDER_START_SHRINKING);
	
	World overworld = Bukkit.getWorld(GameManager.getGameManager().getConfiguration().getOverworldUuid());
	WorldBorder overworldBorder = overworld.getWorldBorder();
	overworldBorder.setSize(2*endSize, timeToShrink);
	
	World nether = Bukkit.getWorld(GameManager.getGameManager().getConfiguration().getNetherUuid());
	if (nether != null) {
		WorldBorder netherBorder = nether.getWorldBorder();
		netherBorder.setSize(endSize, timeToShrink);
	}
}
 
Example 12
Source File: SpawnLoader.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Build a {@link Location} object based on the CMI configuration.
 *
 * @param configuration The CMI file configuration to read from
 *
 * @return Location corresponding to the values in the path
 */
private static Location getLocationFromCmiConfiguration(FileConfiguration configuration) {
    final String pathPrefix = "Spawn.Main";
    if (isLocationCompleteInCmiConfig(configuration, pathPrefix)) {
        String prefix = pathPrefix + ".";
        String worldName = configuration.getString(prefix + "World");
        World world = Bukkit.getWorld(worldName);
        if (!StringUtils.isEmpty(worldName) && world != null) {
            return new Location(world, configuration.getDouble(prefix + "X"),
                configuration.getDouble(prefix + "Y"), configuration.getDouble(prefix + "Z"),
                getFloat(configuration, prefix + "Yaw"), getFloat(configuration, prefix + "Pitch"));
        }
    }
    return null;
}
 
Example 13
Source File: UndergroundNether.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public void build(){
	if(enable){
		MainConfiguration cfg = GameManager.getGameManager().getConfiguration();
		
		int occurrences = RandomUtils.randomInteger(minOccurrences, maxOccurrences);
		int worldSize = GameManager.getGameManager().getWorldBorder().getStartSize();
		World overworld = Bukkit.getWorld(cfg.getOverworldUuid());
		
		for(int i = 1; i <= occurrences ; i++){

			int randX = RandomUtils.randomInteger(-worldSize, worldSize);
			int randZ = RandomUtils.randomInteger(-worldSize, worldSize);
			Location randLoc = new Location(overworld,randX,cfg.getNetherPasteAtY(),randZ);
			
			try {
				// to do find loc
				SchematicHandler.pasteSchematic(randLoc, netherSchematic, 0);
			} catch (Exception e) {
				Bukkit.getLogger().severe("[UhcCore] Couldn't paste nether schematic at "+
						randLoc.getBlockX()+" "+randLoc.getBlockY()+" "+randLoc.getBlockZ());
				e.printStackTrace();
			}
		}
		
	}  
	
}
 
Example 14
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void regionShouldBeNotDestroyedSecondary() {
    loadRegionTypeCobble();
    HashMap<UUID, String> owners = new HashMap<>();
    owners.put(TestUtil.player.getUniqueId(), Constants.OWNER);
    Location location1 = new Location(Bukkit.getWorld("world"), 0, 0, 0);
    RegionType regionType = (RegionType) ItemManager.getInstance().getItemType("cobble");
    Region region = new Region("cobble", owners, location1, getRadii(), regionType.getEffects(),0);
    RegionManager.getInstance().addRegion(region);
    BlockBreakEvent event = new BlockBreakEvent(TestUtil.block10, TestUtil.player);
    ProtectionHandler protectionHandler = new ProtectionHandler();
    protectionHandler.onBlockBreak(event);
    assertNotNull(RegionManager.getInstance().getRegionAt(location1));
}
 
Example 15
Source File: NPCEntity.java    From EliteMobs with GNU General Public License v3.0 4 votes vote down vote up
private boolean setSpawnLocation(String spawnLocation) {
    int counter = 0;
    World world = null;
    double x = 0;
    double y = 0;
    double z = 0;
    float yaw = 0;
    float pitch = 0;
    for (String substring : spawnLocation.split(",")) {
        switch (counter) {
            case 0:
                /*
                World is contained here
                 */
                world = Bukkit.getWorld(substring);
                break;
            case 1:
                /*
                X value is contained here
                 */
                x = Double.valueOf(substring);
                break;
            case 2:
                /*
                Y value is contained here
                 */
                y = Double.valueOf(substring);
                break;
            case 3:
                /*
                Z value is contained here
                 */
                z = Double.valueOf(substring);
                break;
            case 4:
                yaw = Float.valueOf(substring);
                break;
            case 5:
                pitch = Float.valueOf(substring);
                break;
        }

        counter++;
    }

    if (world == null) return false;

    this.spawnLocation = new Location(world, x, y, z, yaw, pitch);

    return true;
}
 
Example 16
Source File: Worldguard.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
@Override
public RegionFilter getFilter(String world) {
    return new WorldGuardFilter(Bukkit.getWorld(world));
}
 
Example 17
Source File: CommandClaimAbandonAll.java    From GriefDefender with MIT License 4 votes vote down vote up
@CommandCompletion("@gdworlds @gddummy")
@CommandAlias("abandonall|abandonallclaims")
@Description("Abandons ALL your claims")
@Subcommand("abandon all")
public void execute(Player player, @Optional String worldName) {
    final GDPermissionUser user = PermissionHolderCache.getInstance().getOrCreateUser(player);
    int originalClaimCount = user.getInternalPlayerData().getInternalClaims().size();
    World world = null;
    if (worldName != null) {
        world = Bukkit.getWorld(worldName);
        if (world == null) {
            TextAdapter.sendComponent(player, MessageStorage.MESSAGE_DATA.getMessage(MessageStorage.COMMAND_WORLD_NOT_FOUND,
                    ImmutableMap.of("world", worldName)));
            return;
        }
        final GDClaimManager claimManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(world.getUID());
        final Set<Claim> claims = claimManager.getPlayerClaims(player.getUniqueId());
        if (claims == null || claims.isEmpty()) {
            originalClaimCount = 0;
        }
    }

    if (originalClaimCount == 0) {
        try {
            throw new CommandException(MessageCache.getInstance().CLAIM_NO_CLAIMS);
        } catch (CommandException e) {
            TextAdapter.sendComponent(player, e.getText());
            return;
        }
    }

    final boolean autoSchematicRestore = GriefDefenderPlugin.getActiveConfig(player.getWorld().getUID()).getConfig().claim.claimAutoSchematicRestore;
    Component message = null;
    if (world != null) {
        if (autoSchematicRestore) {
            message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.SCHEMATIC_ABANDON_ALL_RESTORE_WARNING_WORLD, ImmutableMap.of(
                    "world", world.getName()));
        } else {
            message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.ABANDON_ALL_WARNING_WORLD, ImmutableMap.of(
                    "world", world.getName()));
        }
    } else {
        message = autoSchematicRestore ? MessageCache.getInstance().SCHEMATIC_ABANDON_ALL_RESTORE_WARNING : MessageCache.getInstance().ABANDON_ALL_WARNING;
    }
    final Component confirmationText = TextComponent.builder()
            .append(message)
            .append(TextComponent.builder()
                .append("\n[")
                .append(MessageCache.getInstance().LABEL_CONFIRM.color(TextColor.GREEN))
                .append("]\n")
                .clickEvent(ClickEvent.runCommand(GDCallbackHolder.getInstance().createCallbackRunCommand(player, createConfirmationConsumer(user, world), true)))
                .hoverEvent(HoverEvent.showText(MessageCache.getInstance().UI_CLICK_CONFIRM)).build())
            .build();
    TextAdapter.sendComponent(player, confirmationText);
}
 
Example 18
Source File: CommonCustomMob.java    From civcraft with GNU General Public License v2.0 4 votes vote down vote up
public Location getLocation(EntityLiving entity2) {
	World world = Bukkit.getWorld(entity2.world.getWorld().getName());
	Location loc = new Location(world, entity2.locX, entity2.locY, entity2.locZ);
	return loc;
}
 
Example 19
Source File: WorldFilter.java    From SlackMC with MIT License 4 votes vote down vote up
public Object getObject(JavaPlugin plugin, String data) {
    return Bukkit.getWorld(data);
}
 
Example 20
Source File: TeleportListener.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPortalEvent (PlayerPortalEvent event){
	GameManager gm = GameManager.getGameManager();
	Player player = event.getPlayer();

	// Disable nether/end in deathmatch
	if (gm.getGameState() == GameState.DEATHMATCH){
		event.setCancelled(true);
		return;
	}
	
	if (event.getCause() == TeleportCause.NETHER_PORTAL) {

		if (!gm.getConfiguration().getEnableNether()){
			player.sendMessage(Lang.PLAYERS_NETHER_OFF);
			event.setCancelled(true);
			return;
		}

		// No Going back!
		if (gm.getScenarioManager().isActivated(Scenario.NOGOINGBACK) && event.getFrom().getWorld().getEnvironment() == Environment.NETHER){
			player.sendMessage(Lang.SCENARIO_NOGOINGBACK_ERROR);
			event.setCancelled(true);
			return;
		}

		// Handle event using versions utils as on 1.14+ PortalTravelAgent got removed.
		VersionUtils.getVersionUtils().handleNetherPortalEvent(event);

	}else if (event.getCause() == TeleportCause.END_PORTAL){

		if (gm.getConfiguration().getEnableTheEnd() && event.getFrom().getWorld().getEnvironment() == Environment.NORMAL){
			// Teleport to end
			Location end = new Location(Bukkit.getWorld(gm.getConfiguration().getTheEndUuid()), -42, 48, -18);

			createEndSpawnAir(end);
			createEndSpawnObsidian(end);

			event.setTo(end);
		}
	}
}