file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
LeavesDecayEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/LeavesDecayEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * author: MagicDroidX * Nukkit Project */ public class LeavesDecayEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } public LeavesDecayEvent(Block block) { super(block); } }
479
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockGrowEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockGrowEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * author: MagicDroidX * Nukkit Project */ public class BlockGrowEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block newState; public BlockGrowEvent(Block block, Block newState) { super(block); this.newState = newState; } public Block getNewState() { return newState; } }
625
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockIgniteEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockIgniteEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class BlockIgniteEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block source; private final Entity entity; private final BlockIgniteCause cause; public BlockIgniteEvent(Block block, Block source, Entity entity, BlockIgniteCause cause) { super(block); this.source = source; this.entity = entity; this.cause = cause; } public Block getSource() { return source; } public Entity getEntity() { return entity; } public BlockIgniteCause getCause() { return cause; } public enum BlockIgniteCause { EXPLOSION, FIREBALL, FLINT_AND_STEEL, LAVA, LIGHTNING, SPREAD } }
1,055
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockSpreadEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockSpreadEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * author: MagicDroidX * Nukkit Project */ public class BlockSpreadEvent extends BlockFormEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block source; public BlockSpreadEvent(Block block, Block source, Block newState) { super(block, newState); this.source = source; } public Block getSource() { return source; } }
646
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
DoorToggleEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/DoorToggleEvent.java
package cn.nukkit.event.block; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * Created by Snake1999 on 2016/1/22. * Package cn.nukkit.event.block in project nukkit. */ public class DoorToggleEvent extends BlockUpdateEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private Player player; public DoorToggleEvent(Block block, Player player) { super(block); this.player = player; } public void setPlayer(Player player) { this.player = player; } public Player getPlayer() { return player; } }
771
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Event; /** * author: MagicDroidX * Nukkit Project */ public abstract class BlockEvent extends Event { protected final Block block; public BlockEvent(Block block) { this.block = block; } public Block getBlock() { return block; } }
358
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
SignChangeEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/SignChangeEvent.java
package cn.nukkit.event.block; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * author: MagicDroidX * Nukkit Project */ public class SignChangeEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Player player; private String[] lines = new String[4]; public SignChangeEvent(Block block, Player player, String[] lines) { super(block); this.player = player; this.lines = lines; } public Player getPlayer() { return player; } public String[] getLines() { return lines; } public String getLine(int index) { return this.lines[index]; } public void setLine(int index, String line) { this.lines[index] = line; } }
963
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockFromToEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockFromToEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class BlockFromToEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block to; public BlockFromToEvent(Block block, Block to) { super(block); this.to = to; } public Block getTo() { return to; } }
542
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockFormEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockFormEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * author: MagicDroidX * Nukkit Project */ public class BlockFormEvent extends BlockGrowEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } public BlockFormEvent(Block block, Block newState) { super(block, newState); } }
505
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockBurnEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockBurnEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * author: MagicDroidX * Nukkit Project */ public class BlockBurnEvent extends BlockEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public BlockBurnEvent(Block block) { super(block); } public static HandlerList getHandlers() { return handlers; } }
475
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockRedstoneEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockRedstoneEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.HandlerList; /** * Created by CreeperFace on 12.5.2017. */ public class BlockRedstoneEvent extends BlockEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private int oldPower; private int newPower; public BlockRedstoneEvent(Block block, int oldPower, int newPower) { super(block); this.oldPower = oldPower; this.newPower = newPower; } public int getOldPower() { return oldPower; } public int getNewPower() { return newPower; } }
697
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
BlockPistonChangeEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/block/BlockPistonChangeEvent.java
package cn.nukkit.event.block; import cn.nukkit.block.Block; import cn.nukkit.event.HandlerList; /** * Created by CreeperFace on 2.8.2017. */ public class BlockPistonChangeEvent extends BlockEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private int oldPower; private int newPower; public BlockPistonChangeEvent(Block block, int oldPower, int newPower) { super(block); this.oldPower = oldPower; this.newPower = newPower; } public int getOldPower() { return oldPower; } public int getNewPower() { return newPower; } }
704
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerMessageEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerMessageEvent.java
package cn.nukkit.event.player; /** * Created on 2015/12/23 by xtypr. * Package cn.nukkit.event.player in project Nukkit . */ public abstract class PlayerMessageEvent extends PlayerEvent { protected String message; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } }
380
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerAchievementAwardedEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerAchievementAwardedEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerAchievementAwardedEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final String achievement; public PlayerAchievementAwardedEvent(Player player, String achievementId) { this.player = player; this.achievement = achievementId; } public String getAchievement() { return this.achievement; } }
643
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerFormRespondedEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerFormRespondedEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.HandlerList; import cn.nukkit.form.response.FormResponse; import cn.nukkit.form.window.FormWindow; public class PlayerFormRespondedEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected int formID; protected FormWindow window; protected boolean closed = false; public PlayerFormRespondedEvent(Player player, int formID, FormWindow window) { this.player = player; this.formID = formID; this.window = window; } public int getFormID() { return this.formID; } public FormWindow getWindow() { return window; } /** * Can be null if player closed the window instead of submitting it */ public FormResponse getResponse() { return window.getResponse(); } /** * Defines if player closed the window or submitted it */ public boolean wasClosed() { return window.wasClosed(); } }
1,122
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerInvalidMoveEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerInvalidMoveEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * call when a player moves wrongly * * @author WilliamGao */ public class PlayerInvalidMoveEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean revert; public static HandlerList getHandlers() { return handlers; } public PlayerInvalidMoveEvent(Player player, boolean revert) { this.player = player; this.revert = revert; } public boolean isRevert() { return this.revert; } /** * @deprecated If you just simply want to disable the movement check, please use {@link Player#setCheckMovement(boolean)} instead. */ @Deprecated public void setRevert(boolean revert) { this.revert = revert; } }
909
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerBucketEmptyEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerBucketEmptyEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; import cn.nukkit.math.BlockFace; public class PlayerBucketEmptyEvent extends PlayerBucketEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } public PlayerBucketEmptyEvent(Player who, Block blockClicked, BlockFace blockFace, Item bucket, Item itemInHand) { super(who, blockClicked, blockFace, bucket, itemInHand); } }
589
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerGlassBottleFillEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerGlassBottleFillEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.item.Item; public class PlayerGlassBottleFillEvent extends PlayerEvent implements Cancellable { protected final Item item; protected final Block target; public PlayerGlassBottleFillEvent(Player player, Block target, Item item) { this.player = player; this.target = target; this.item = item.clone(); } public Item getItem() { return item; } public Block getBlock() { return target; } }
603
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerAnimationEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerAnimationEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerAnimationEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } public static final int ARM_SWING = 1; private final int animationType; public PlayerAnimationEvent(Player player) { this(player, ARM_SWING); } public PlayerAnimationEvent(Player player, int animation) { this.player = player; this.animationType = animation; } public int getAnimationType() { return this.animationType; } }
747
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerBucketEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerBucketEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.item.Item; import cn.nukkit.math.BlockFace; abstract class PlayerBucketEvent extends PlayerEvent implements Cancellable { private final Block blockClicked; private final BlockFace blockFace; private final Item bucket; private Item item; public PlayerBucketEvent(Player who, Block blockClicked, BlockFace blockFace, Item bucket, Item itemInHand) { this.player = who; this.blockClicked = blockClicked; this.blockFace = blockFace; this.item = itemInHand; this.bucket = bucket; } /** * Returns the bucket used in this event */ public Item getBucket() { return this.bucket; } /** * Returns the item in hand after the event */ public Item getItem() { return this.item; } public void setItem(Item item) { this.item = item; } public Block getBlockClicked() { return this.blockClicked; } public BlockFace getBlockFace() { return this.blockFace; } }
1,165
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerChunkRequestEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerChunkRequestEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerChunkRequestEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final int chunkX; private final int chunkZ; public PlayerChunkRequestEvent(Player player, int chunkX, int chunkZ) { this.player = player; this.chunkX = chunkX; this.chunkZ = chunkZ; } public int getChunkX() { return chunkX; } public int getChunkZ() { return chunkZ; } }
712
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerDeathEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerDeathEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.event.entity.EntityDeathEvent; import cn.nukkit.item.Item; import cn.nukkit.lang.TextContainer; public class PlayerDeathEvent extends EntityDeathEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private TextContainer deathMessage; private boolean keepInventory = false; private boolean keepExperience = false; private int experience; public PlayerDeathEvent(Player player, Item[] drops, TextContainer deathMessage, int experience) { super(player, drops); this.deathMessage = deathMessage; this.experience = experience; } public PlayerDeathEvent(Player player, Item[] drops, String deathMessage, int experience) { this(player, drops, new TextContainer(deathMessage), experience); } @Override public Player getEntity() { return (Player) super.getEntity(); } public TextContainer getDeathMessage() { return deathMessage; } public void setDeathMessage(TextContainer deathMessage) { this.deathMessage = deathMessage; } public void setDeathMessage(String deathMessage) { this.deathMessage = new TextContainer(deathMessage); } public boolean getKeepInventory() { return keepInventory; } public void setKeepInventory(boolean keepInventory) { this.keepInventory = keepInventory; } public boolean getKeepExperience() { return keepExperience; } public void setKeepExperience(boolean keepExperience) { this.keepExperience = keepExperience; } public int getExperience() { return experience; } public void setExperience(int experience) { this.experience = experience; } }
1,973
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerBedLeaveEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerBedLeaveEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.HandlerList; public class PlayerBedLeaveEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block bed; public PlayerBedLeaveEvent(Player player, Block bed) { this.player = player; this.bed = bed; } public Block getBed() { return bed; } }
532
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Event; /** * author: MagicDroidX * Nukkit Project */ public abstract class PlayerEvent extends Event { protected Player player; public Player getPlayer() { return player; } }
281
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerInteractEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerInteractEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; import cn.nukkit.level.Position; import cn.nukkit.math.BlockFace; import cn.nukkit.math.Vector3; /** * author: MagicDroidX * Nukkit Project */ public class PlayerInteractEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final Block blockTouched; protected final Vector3 touchVector; protected final BlockFace blockFace; protected final Item item; protected final Action action; public PlayerInteractEvent(Player player, Item item, Vector3 block, BlockFace face) { this(player, item, block, face, Action.RIGHT_CLICK_BLOCK); } public PlayerInteractEvent(Player player, Item item, Vector3 block, BlockFace face, Action action) { if (block instanceof Block) { this.blockTouched = (Block) block; this.touchVector = new Vector3(0, 0, 0); } else { this.touchVector = block; this.blockTouched = Block.get(Block.AIR, 0, new Position(0, 0, 0, player.level)); } this.player = player; this.item = item; this.blockFace = face; this.action = action; } public Action getAction() { return action; } public Item getItem() { return item; } public Block getBlock() { return blockTouched; } public Vector3 getTouchVector() { return touchVector; } public BlockFace getFace() { return blockFace; } public enum Action { LEFT_CLICK_BLOCK, RIGHT_CLICK_BLOCK, LEFT_CLICK_AIR, RIGHT_CLICK_AIR, PHYSICAL } }
1,919
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerBedEnterEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerBedEnterEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerBedEnterEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block bed; public PlayerBedEnterEvent(Player player, Block bed) { this.player = player; this.bed = bed; } public Block getBed() { return bed; } }
591
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerBucketFillEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerBucketFillEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; import cn.nukkit.math.BlockFace; public class PlayerBucketFillEvent extends PlayerBucketEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } public PlayerBucketFillEvent(Player who, Block blockClicked, BlockFace blockFace, Item bucket, Item itemInHand) { super(who, blockClicked, blockFace, bucket, itemInHand); } }
587
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerSettingsRespondedEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerSettingsRespondedEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.form.response.FormResponse; import cn.nukkit.form.window.FormWindow; public class PlayerSettingsRespondedEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected int formID; protected FormWindow window; protected boolean closed = false; public PlayerSettingsRespondedEvent(Player player, int formID, FormWindow window) { this.player = player; this.formID = formID; this.window = window; } public int getFormID() { return this.formID; } public FormWindow getWindow() { return window; } /** * Can be null if player closed the window instead of submitting it */ public FormResponse getResponse() { return window.getResponse(); } /** * Defines if player closed the window or submitted it */ public boolean wasClosed() { return window.wasClosed(); } @Override public void setCancelled() { super.setCancelled(); } }
1,273
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerRespawnEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerRespawnEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Position; public class PlayerRespawnEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private Position position; public PlayerRespawnEvent(Player player, Position position) { this.player = player; this.position = position; } public Position getRespawnPosition() { return position; } public void setRespawnPosition(Position position) { this.position = position; } }
670
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerLoginEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerLoginEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerLoginEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected String kickMessage; public PlayerLoginEvent(Player player, String kickMessage) { this.player = player; this.kickMessage = kickMessage; } public String getKickMessage() { return kickMessage; } public void setKickMessage(String kickMessage) { this.kickMessage = kickMessage; } }
703
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerDropItemEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerDropItemEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; public class PlayerDropItemEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Item drop; public PlayerDropItemEvent(Player player, Item drop) { this.player = player; this.drop = drop; } public Item getItem() { return this.drop; } }
597
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerItemHeldEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerItemHeldEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; /** * author: MagicDroidX * Nukkit Project */ public class PlayerItemHeldEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Item item; private final int hotbarSlot; public PlayerItemHeldEvent(Player player, Item item, int hotbarSlot) { this.player = player; this.item = item; this.hotbarSlot = hotbarSlot; } public int getSlot() { return this.hotbarSlot; } @Deprecated public int getInventorySlot() { return hotbarSlot; } public Item getItem() { return item; } }
883
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerMapInfoRequestEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerMapInfoRequestEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; /** * Created by CreeperFace on 18.3.2017. */ public class PlayerMapInfoRequestEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private Item item; public PlayerMapInfoRequestEvent(Player p, Item item) { this.player = p; this.item = item; } public Item getMap() { return item; } public static HandlerList getHandlers() { return handlers; } }
636
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerToggleSneakEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerToggleSneakEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerToggleSneakEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final boolean isSneaking; public PlayerToggleSneakEvent(Player player, boolean isSneaking) { this.player = player; this.isSneaking = isSneaking; } public boolean isSneaking() { return this.isSneaking; } }
620
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerServerSettingsRequestEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerServerSettingsRequestEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.form.window.FormWindow; import java.util.Map; /** * @author CreeperFace */ public class PlayerServerSettingsRequestEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private Map<Integer, FormWindow> settings; public PlayerServerSettingsRequestEvent(Player player, Map<Integer, FormWindow> settings) { this.player = player; this.settings = settings; } public Map<Integer, FormWindow> getSettings() { return settings; } public void setSettings(Map<Integer, FormWindow> settings) { this.settings = settings; } public void setSettings(int id, FormWindow window) { this.settings.put(id, window); } }
973
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerToggleFlightEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerToggleFlightEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerToggleFlightEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final boolean isFlying; public PlayerToggleFlightEvent(Player player, boolean isFlying) { this.player = player; this.isFlying = isFlying; } public boolean isFlying() { return this.isFlying; } }
609
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerToggleGlideEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerToggleGlideEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerToggleGlideEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final boolean isGliding; public PlayerToggleGlideEvent(Player player, boolean isSneaking) { this.player = player; this.isGliding = isSneaking; } public boolean isGliding() { return this.isGliding; } }
616
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerGameModeChangeEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerGameModeChangeEvent.java
package cn.nukkit.event.player; import cn.nukkit.AdventureSettings; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerGameModeChangeEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final int gamemode; protected AdventureSettings newAdventureSettings; public PlayerGameModeChangeEvent(Player player, int newGameMode, AdventureSettings newAdventureSettings) { this.player = player; this.gamemode = newGameMode; this.newAdventureSettings = newAdventureSettings; } public int getNewGamemode() { return gamemode; } public AdventureSettings getNewAdventureSettings() { return newAdventureSettings; } public void setNewAdventureSettings(AdventureSettings newAdventureSettings) { this.newAdventureSettings = newAdventureSettings; } }
1,045
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerCommandPreprocessEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerCommandPreprocessEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerCommandPreprocessEvent extends PlayerMessageEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } public PlayerCommandPreprocessEvent(Player player, String message) { this.player = player; this.message = message; } public void setPlayer(Player player) { this.player = player; } }
594
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerCreationEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerCreationEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Event; import cn.nukkit.event.HandlerList; import cn.nukkit.network.SourceInterface; /** * author: MagicDroidX * Nukkit Project */ public class PlayerCreationEvent extends Event { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final SourceInterface interfaz; private final Long clientId; private final String address; private final int port; private Class<? extends Player> baseClass; private Class<? extends Player> playerClass; public PlayerCreationEvent(SourceInterface interfaz, Class<? extends Player> baseClass, Class<? extends Player> playerClass, Long clientId, String address, int port) { this.interfaz = interfaz; this.clientId = clientId; this.address = address; this.port = port; this.baseClass = baseClass; this.playerClass = playerClass; } public SourceInterface getInterface() { return interfaz; } public String getAddress() { return address; } public int getPort() { return port; } public Long getClientId() { return clientId; } public Class<? extends Player> getBaseClass() { return baseClass; } public void setBaseClass(Class<? extends Player> baseClass) { this.baseClass = baseClass; } public Class<? extends Player> getPlayerClass() { return playerClass; } public void setPlayerClass(Class<? extends Player> playerClass) { this.playerClass = playerClass; } }
1,695
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerInteractEntityEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerInteractEntityEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; /** * Created by CreeperFace on 1. 1. 2017. */ public class PlayerInteractEntityEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); protected final Entity entity; protected final Item item; public PlayerInteractEntityEvent(Player player, Entity entity, Item item) { this.player = player; this.entity = entity; this.item = item; } public Entity getEntity() { return this.entity; } public Item getItem() { return this.item; } public static HandlerList getHandlers() { return handlers; } }
841
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerBlockPickEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerBlockPickEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; /** * @author CreeperFace */ public class PlayerBlockPickEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Block blockClicked; private Item item; public PlayerBlockPickEvent(Player player, Block blockClicked, Item item) { this.blockClicked = blockClicked; this.item = item; this.player = player; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public Block getBlockClicked() { return blockClicked; } }
893
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerMouseOverEntityEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerMouseOverEntityEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.event.HandlerList; public class PlayerMouseOverEntityEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Entity entity; public PlayerMouseOverEntityEvent(Player player, Entity entity) { this.player = player; this.entity = entity; } public Entity getEntity() { return entity; } }
569
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerToggleSprintEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerToggleSprintEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerToggleSprintEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected final boolean isSprinting; public PlayerToggleSprintEvent(Player player, boolean isSprinting) { this.player = player; this.isSprinting = isSprinting; } public boolean isSprinting() { return this.isSprinting; } }
628
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerTeleportEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerTeleportEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Level; import cn.nukkit.level.Location; import cn.nukkit.level.Position; import cn.nukkit.math.Vector3; public class PlayerTeleportEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private TeleportCause cause; private Location from; private Location to; private PlayerTeleportEvent(Player player) { this.player = player; } public PlayerTeleportEvent(Player player, Location from, Location to, TeleportCause cause) { this(player); this.from = from; this.to = to; this.cause = cause; } public PlayerTeleportEvent(Player player, Vector3 from, Vector3 to, TeleportCause cause) { this(player); this.from = vectorToLocation(player.getLevel(), from); this.from = vectorToLocation(player.getLevel(), to); this.cause = cause; } public Location getFrom() { return from; } public Location getTo() { return to; } public TeleportCause getCause() { return cause; } private Location vectorToLocation(Level baseLevel, Vector3 vector) { if (vector instanceof Location) return (Location) vector; if (vector instanceof Position) return ((Position) vector).getLocation(); return new Location(vector.getX(), vector.getY(), vector.getZ(), 0, 0, baseLevel); } public enum TeleportCause { COMMAND, // For Nukkit tp command only PLUGIN, // Every plugin NETHER_PORTAL, // Teleport using Nether portal ENDER_PEARL, // Teleport by ender pearl UNKNOWN // Unknown cause } }
1,912
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerKickEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerKickEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.lang.TextContainer; public class PlayerKickEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public enum Reason { NEW_CONNECTION, KICKED_BY_ADMIN, NOT_WHITELISTED, IP_BANNED, NAME_BANNED, INVALID_PVE, LOGIN_TIMEOUT, SERVER_FULL, FLYING_DISABLED, UNKNOWN; @Override public String toString() { return this.name(); } } public static HandlerList getHandlers() { return handlers; } protected TextContainer quitMessage; protected final Reason reason; protected final String reasonString; @Deprecated public PlayerKickEvent(Player player, String reason, String quitMessage) { this(player, Reason.UNKNOWN, reason, new TextContainer(quitMessage)); } @Deprecated public PlayerKickEvent(Player player, String reason, TextContainer quitMessage) { this(player, Reason.UNKNOWN, reason, quitMessage); } public PlayerKickEvent(Player player, Reason reason, TextContainer quitMessage) { this(player, reason, reason.toString(), quitMessage); } public PlayerKickEvent(Player player, Reason reason, String quitMessage) { this(player, reason, new TextContainer(quitMessage)); } public PlayerKickEvent(Player player, Reason reason, String reasonString, TextContainer quitMessage) { this.player = player; this.quitMessage = quitMessage; this.reason = reason; this.reasonString = reason.name(); } public String getReason() { return reasonString; } public Reason getReasonEnum() { return this.reason; } public TextContainer getQuitMessage() { return quitMessage; } public void setQuitMessage(TextContainer quitMessage) { this.quitMessage = quitMessage; } public void setQuitMessage(String joinMessage) { this.setQuitMessage(new TextContainer(joinMessage)); } }
2,211
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerFoodLevelChangeEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerFoodLevelChangeEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; public class PlayerFoodLevelChangeEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected int foodLevel; protected float foodSaturationLevel; public PlayerFoodLevelChangeEvent(Player player, int foodLevel, float foodSaturationLevel) { this.player = player; this.foodLevel = foodLevel; this.foodSaturationLevel = foodSaturationLevel; } public int getFoodLevel() { return this.foodLevel; } public void setFoodLevel(int foodLevel) { this.foodLevel = foodLevel; } public float getFoodSaturationLevel() { return foodSaturationLevel; } public void setFoodSaturationLevel(float foodSaturationLevel) { this.foodSaturationLevel = foodSaturationLevel; } }
1,037
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerEatFoodEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerEatFoodEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.food.Food; /** * Created by Snake1999 on 2016/1/14. * Package cn.nukkit.event.player in project nukkit. */ public class PlayerEatFoodEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private Food food; public static HandlerList getHandlers() { return handlers; } public PlayerEatFoodEvent(Player player, Food food) { this.player = player; this.food = food; } public Food getFood() { return food; } public void setFood(Food food) { this.food = food; } }
758
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerQuitEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerQuitEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.HandlerList; import cn.nukkit.lang.TextContainer; public class PlayerQuitEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected TextContainer quitMessage; protected boolean autoSave = true; protected String reason; public PlayerQuitEvent(Player player, TextContainer quitMessage, String reason) { this(player, quitMessage, true, reason); } public PlayerQuitEvent(Player player, TextContainer quitMessage) { this(player, quitMessage, true); } public PlayerQuitEvent(Player player, String quitMessage, String reason) { this(player, quitMessage, true, reason); } public PlayerQuitEvent(Player player, String quitMessage) { this(player, quitMessage, true); } public PlayerQuitEvent(Player player, String quitMessage, boolean autoSave, String reason) { this(player, new TextContainer(quitMessage), autoSave, reason); } public PlayerQuitEvent(Player player, String quitMessage, boolean autoSave) { this(player, new TextContainer(quitMessage), autoSave); } public PlayerQuitEvent(Player player, TextContainer quitMessage, boolean autoSave) { this(player, quitMessage, autoSave, "No reason"); } public PlayerQuitEvent(Player player, TextContainer quitMessage, boolean autoSave, String reason) { this.player = player; this.quitMessage = quitMessage; this.autoSave = autoSave; this.reason = reason; } public TextContainer getQuitMessage() { return quitMessage; } public void setQuitMessage(TextContainer quitMessage) { this.quitMessage = quitMessage; } public void setQuitMessage(String quitMessage) { this.setQuitMessage(new TextContainer(quitMessage)); } public boolean getAutoSave() { return this.autoSave; } public void setAutoSave() { this.setAutoSave(true); } public void setAutoSave(boolean autoSave) { this.autoSave = autoSave; } public String getReason() { return reason; } }
2,277
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerMoveEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerMoveEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Location; public class PlayerMoveEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private Location from; private Location to; private boolean resetBlocksAround; public PlayerMoveEvent(Player player, Location from, Location to) { this(player, from, to, true); } public PlayerMoveEvent(Player player, Location from, Location to, boolean resetBlocks) { this.player = player; this.from = from; this.to = to; this.resetBlocksAround = resetBlocks; } public Location getFrom() { return from; } public void setFrom(Location from) { this.from = from; } public Location getTo() { return to; } public void setTo(Location to) { this.to = to; } public boolean isResetBlocksAround() { return resetBlocksAround; } public void setResetBlocksAround(boolean value) { this.resetBlocksAround = value; } @Override public void setCancelled() { super.setCancelled(); } }
1,344
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerJoinEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerJoinEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.HandlerList; import cn.nukkit.lang.TextContainer; public class PlayerJoinEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected TextContainer joinMessage; public PlayerJoinEvent(Player player, TextContainer joinMessage) { this.player = player; this.joinMessage = joinMessage; } public PlayerJoinEvent(Player player, String joinMessage) { this.player = player; this.joinMessage = new TextContainer(joinMessage); } public TextContainer getJoinMessage() { return joinMessage; } public void setJoinMessage(TextContainer joinMessage) { this.joinMessage = joinMessage; } public void setJoinMessage(String joinMessage) { this.setJoinMessage(new TextContainer(joinMessage)); } }
987
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerChatEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerChatEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.command.CommandSender; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.permission.Permissible; import java.util.HashSet; import java.util.Set; public class PlayerChatEvent extends PlayerMessageEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected String format; protected Set<CommandSender> recipients = new HashSet<>(); public PlayerChatEvent(Player player, String message) { this(player, message, "chat.type.text", null); } public PlayerChatEvent(Player player, String message, String format, Set<CommandSender> recipients) { this.player = player; this.message = message; this.format = format; if (recipients == null) { for (Permissible permissible : Server.getInstance().getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_USERS)) { if (permissible instanceof CommandSender) { this.recipients.add((CommandSender) permissible); } } } else { this.recipients = recipients; } } /** * Changes the player that is sending the message */ public void setPlayer(Player player) { this.player = player; } public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; } public Set<CommandSender> getRecipients() { return this.recipients; } public void setRecipients(Set<CommandSender> recipients) { this.recipients = recipients; } }
1,840
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerPreLoginEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerPreLoginEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; /** * Called when the player logs in, before things have been set up */ public class PlayerPreLoginEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } protected String kickMessage; public PlayerPreLoginEvent(Player player, String kickMessage) { this.player = player; this.kickMessage = kickMessage; } public void setKickMessage(String kickMessage) { this.kickMessage = kickMessage; } public String getKickMessage() { return this.kickMessage; } }
787
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
PlayerItemConsumeEvent.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/event/player/PlayerItemConsumeEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.item.Item; /** * Called when a player eats something */ public class PlayerItemConsumeEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private final Item item; public PlayerItemConsumeEvent(Player player, Item item) { this.player = player; this.item = item; } public Item getItem() { return this.item.clone(); } }
658
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TimingsExport.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/TimingsExport.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import cn.nukkit.Server; import cn.nukkit.command.CommandSender; import cn.nukkit.command.ConsoleCommandSender; import cn.nukkit.command.RemoteConsoleCommandSender; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.nbt.stream.PGZIPOutputStream; import cn.nukkit.timings.JsonUtil; import cn.nukkit.utils.TextFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.Deflater; import static co.aikar.timings.TimingsManager.HISTORY; public class TimingsExport extends Thread { private final CommandSender sender; private final JsonObject out; private final TimingsHistory[] history; private TimingsExport(CommandSender sender, JsonObject out, TimingsHistory[] history) { super("Timings paste thread"); this.sender = sender; this.out = out; this.history = history; } /** * Builds a JSON timings report and sends it to Aikar's viewer * * @param sender Sender that issued the command */ public static void reportTimings(CommandSender sender) { JsonObject out = new JsonObject(); out.addProperty("version", Server.getInstance().getVersion()); out.addProperty("maxplayers", Server.getInstance().getMaxPlayers()); out.addProperty("start", TimingsManager.timingStart / 1000); out.addProperty("end", System.currentTimeMillis() / 1000); out.addProperty("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000); if (!Timings.isPrivacy()) { out.addProperty("server", Server.getInstance().getName()); out.addProperty("motd", Server.getInstance().getMotd()); out.addProperty("online-mode", false); //In MCPE we have permanent offline mode. out.addProperty("icon", ""); //"data:image/png;base64," } final Runtime runtime = Runtime.getRuntime(); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); JsonObject system = new JsonObject(); system.addProperty("timingcost", getCost()); system.addProperty("name", System.getProperty("os.name")); system.addProperty("version", System.getProperty("os.version")); system.addProperty("jvmversion", System.getProperty("java.version")); system.addProperty("arch", System.getProperty("os.arch")); system.addProperty("maxmem", runtime.maxMemory()); system.addProperty("cpu", runtime.availableProcessors()); system.addProperty("runtime", ManagementFactory.getRuntimeMXBean().getUptime()); system.addProperty("flags", String.join(" ", runtimeBean.getInputArguments())); system.add("gc", JsonUtil.mapToObject(ManagementFactory.getGarbageCollectorMXBeans(), (input) -> new JsonUtil.JSONPair(input.getName(), JsonUtil.toArray(input.getCollectionCount(), input.getCollectionTime())))); out.add("system", system); TimingsHistory[] history = HISTORY.toArray(new TimingsHistory[HISTORY.size() + 1]); history[HISTORY.size()] = new TimingsHistory(); //Current snapshot JsonObject timings = new JsonObject(); for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) { for (Timing id : group.timings.stream().toArray(Timing[]::new)) { if (!id.timed && !id.isSpecial()) { continue; } timings.add(String.valueOf(id.id), JsonUtil.toArray(group.id, id.name)); } } JsonObject idmap = new JsonObject(); idmap.add("groups", JsonUtil.mapToObject(TimingIdentifier.GROUP_MAP.values(), (group) -> new JsonUtil.JSONPair(group.id, group.name))); idmap.add("handlers", timings); idmap.add("worlds", JsonUtil.mapToObject(TimingsHistory.levelMap.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getValue(), entry.getKey()))); idmap.add("tileentity", JsonUtil.mapToObject(TimingsHistory.blockEntityMap.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue()))); idmap.add("entity", JsonUtil.mapToObject(TimingsHistory.entityMap.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue()))); out.add("idmap", idmap); //Information about loaded plugins out.add("plugins", JsonUtil.mapToObject(Server.getInstance().getPluginManager().getPlugins().values(), (plugin) -> { JsonObject jsonPlugin = new JsonObject(); jsonPlugin.addProperty("version", plugin.getDescription().getVersion()); jsonPlugin.addProperty("description", plugin.getDescription().getDescription());// Sounds legit jsonPlugin.addProperty("website", plugin.getDescription().getWebsite()); jsonPlugin.addProperty("authors", String.join(", ", plugin.getDescription().getAuthors())); return new JsonUtil.JSONPair(plugin.getName(), jsonPlugin); })); //Information on the users Config JsonObject config = new JsonObject(); if (!Timings.getIgnoredConfigSections().contains("all")) { JsonObject nukkit = JsonUtil.toObject(Server.getInstance().getConfig().getRootSection()); Timings.getIgnoredConfigSections().forEach(nukkit::remove); config.add("nukkit", nukkit); } else { config.add("nukkit", null); } out.add("config", config); new TimingsExport(sender, out, history).start(); } private static long getCost() { int passes = 200; Timing SAMPLER1 = TimingsManager.getTiming(null, "Timings sampler 1", null); Timing SAMPLER2 = TimingsManager.getTiming(null, "Timings sampler 2", null); Timing SAMPLER3 = TimingsManager.getTiming(null, "Timings sampler 3", null); Timing SAMPLER4 = TimingsManager.getTiming(null, "Timings sampler 4", null); Timing SAMPLER5 = TimingsManager.getTiming(null, "Timings sampler 5", null); Timing SAMPLER6 = TimingsManager.getTiming(null, "Timings sampler 6", null); long start = System.nanoTime(); for (int i = 0; i < passes; i++) { SAMPLER1.startTiming(); SAMPLER2.startTiming(); SAMPLER3.startTiming(); SAMPLER4.startTiming(); SAMPLER5.startTiming(); SAMPLER6.startTiming(); SAMPLER6.stopTiming(); SAMPLER5.stopTiming(); SAMPLER4.stopTiming(); SAMPLER3.stopTiming(); SAMPLER2.stopTiming(); SAMPLER1.stopTiming(); } long timingsCost = (System.nanoTime() - start) / passes / 6; SAMPLER1.reset(true); SAMPLER2.reset(true); SAMPLER3.reset(true); SAMPLER4.reset(true); SAMPLER5.reset(true); SAMPLER6.reset(true); return timingsCost; } @Override public synchronized void start() { if (this.sender instanceof RemoteConsoleCommandSender) { this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.rcon")); run(); } else { super.start(); } } @Override public void run() { this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadStart")); this.out.add("data", JsonUtil.mapToArray(this.history, TimingsHistory::export)); String response = null; try { HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); con.setDoOutput(true); con.setRequestProperty("User-Agent", "Nukkit/" + Server.getInstance().getName() + "/" + InetAddress.getLocalHost().getHostName()); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); PGZIPOutputStream request = new PGZIPOutputStream(con.getOutputStream()); request.setLevel(Deflater.BEST_COMPRESSION); request.write(new Gson().toJson(this.out).getBytes("UTF-8")); request.close(); response = getResponse(con); if (con.getResponseCode() != 302) { this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadError", new String[]{String.valueOf(con.getResponseCode()), con.getResponseMessage()})); if (response != null) { Server.getInstance().getLogger().alert(response); } return; } String location = con.getHeaderField("Location"); this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsLocation", location)); if (!(this.sender instanceof ConsoleCommandSender)) { Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location)); } if (response != null && !response.isEmpty()) { Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsResponse", response)); } File timingFolder = new File(Server.getInstance().getDataPath() + File.separator + "timings"); timingFolder.mkdirs(); String fileName = timingFolder + File.separator + new SimpleDateFormat("'timings-'yyyy-MM-dd-hh-mm'.txt'").format(new Date()); FileWriter writer = new FileWriter(fileName); writer.write(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location) + "\n\n"); writer.write(new GsonBuilder().setPrettyPrinting().create().toJson(this.out)); writer.close(); Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsWrite", fileName)); } catch (IOException exception) { this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError")); if (response != null) { Server.getInstance().getLogger().alert(response); } Server.getInstance().getLogger().logException(exception); } } private String getResponse(HttpURLConnection con) throws IOException { InputStream is = null; try { is = con.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int bytesRead; while ((bytesRead = is.read(b)) != -1) { bos.write(b, 0, bytesRead); } return bos.toString(); } catch (IOException exception) { this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError")); Server.getInstance().getLogger().warning(con.getResponseMessage(), exception); return null; } finally { if (is != null) { is.close(); } } } }
12,690
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Timings.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/Timings.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import cn.nukkit.Server; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.command.Command; import cn.nukkit.entity.Entity; import cn.nukkit.event.Event; import cn.nukkit.event.Listener; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.plugin.EventExecutor; import cn.nukkit.plugin.MethodEventExecutor; import cn.nukkit.plugin.Plugin; import cn.nukkit.scheduler.PluginTask; import cn.nukkit.scheduler.TaskHandler; import static co.aikar.timings.TimingIdentifier.DEFAULT_GROUP; import java.util.HashSet; import java.util.Queue; import java.util.Set; public final class Timings { private static boolean timingsEnabled = false; private static boolean verboseEnabled = false; private static boolean privacy = false; private static Set<String> ignoredConfigSections = new HashSet<>(); private static final int MAX_HISTORY_FRAMES = 12; private static int historyInterval = -1; private static int historyLength = -1; public static final FullServerTickTiming fullServerTickTimer; public static final Timing timingsTickTimer; public static final Timing pluginEventTimer; public static final Timing connectionTimer; public static final Timing schedulerTimer; public static final Timing schedulerAsyncTimer; public static final Timing schedulerSyncTimer; public static final Timing commandTimer; public static final Timing serverCommandTimer; public static final Timing levelSaveTimer; public static final Timing playerNetworkSendTimer; public static final Timing playerNetworkReceiveTimer; public static final Timing playerChunkOrderTimer; public static final Timing playerChunkSendTimer; public static final Timing playerCommandTimer; public static final Timing tickEntityTimer; public static final Timing tickBlockEntityTimer; public static final Timing entityMoveTimer; public static final Timing entityBaseTickTimer; public static final Timing livingEntityBaseTickTimer; public static final Timing generationTimer; public static final Timing populationTimer; public static final Timing generationCallbackTimer; public static final Timing permissibleCalculationTimer; public static final Timing permissionDefaultTimer; static { setTimingsEnabled((boolean) Server.getInstance().getConfig("timings.enabled", false)); setVerboseEnabled((boolean) Server.getInstance().getConfig("timings.verbose", false)); setHistoryInterval((int) Server.getInstance().getConfig("timings.history-interval", 6000)); setHistoryLength((int) Server.getInstance().getConfig("timings.history-length", 72000)); privacy = (boolean) Server.getInstance().getConfig("timings.privacy", false); ignoredConfigSections.addAll(Server.getInstance().getConfig().getStringList("timings.ignore")); Server.getInstance().getLogger().debug("Timings: \n" + "Enabled - " + isTimingsEnabled() + "\n" + "Verbose - " + isVerboseEnabled() + "\n" + "History Interval - " + getHistoryInterval() + "\n" + "History Length - " + getHistoryLength()); fullServerTickTimer = new FullServerTickTiming(); timingsTickTimer = TimingsManager.getTiming(DEFAULT_GROUP.name, "Timings Tick", fullServerTickTimer); pluginEventTimer = TimingsManager.getTiming("Plugin Events"); connectionTimer = TimingsManager.getTiming("Connection Handler"); schedulerTimer = TimingsManager.getTiming("Scheduler"); schedulerAsyncTimer = TimingsManager.getTiming("## Scheduler - Async Tasks"); schedulerSyncTimer = TimingsManager.getTiming("## Scheduler - Sync Tasks"); commandTimer = TimingsManager.getTiming("Commands"); serverCommandTimer = TimingsManager.getTiming("Server Command"); levelSaveTimer = TimingsManager.getTiming("Level Save"); playerNetworkSendTimer = TimingsManager.getTiming("Player Network Send"); playerNetworkReceiveTimer = TimingsManager.getTiming("Player Network Receive"); playerChunkOrderTimer = TimingsManager.getTiming("Player Order Chunks"); playerChunkSendTimer = TimingsManager.getTiming("Player Send Chunks"); playerCommandTimer = TimingsManager.getTiming("Player Command"); tickEntityTimer = TimingsManager.getTiming("## Entity Tick"); tickBlockEntityTimer = TimingsManager.getTiming("## BlockEntity Tick"); entityMoveTimer = TimingsManager.getTiming("## Entity Move"); entityBaseTickTimer = TimingsManager.getTiming("## Entity Base Tick"); livingEntityBaseTickTimer = TimingsManager.getTiming("## LivingEntity Base Tick"); generationTimer = TimingsManager.getTiming("Level Generation"); populationTimer = TimingsManager.getTiming("Level Population"); generationCallbackTimer = TimingsManager.getTiming("Level Generation Callback"); permissibleCalculationTimer = TimingsManager.getTiming("Permissible Calculation"); permissionDefaultTimer = TimingsManager.getTiming("Default Permission Calculation"); } public static boolean isTimingsEnabled() { return timingsEnabled; } public static void setTimingsEnabled(boolean enabled) { timingsEnabled = enabled; TimingsManager.reset(); } public static boolean isVerboseEnabled() { return verboseEnabled; } public static void setVerboseEnabled(boolean enabled) { verboseEnabled = enabled; TimingsManager.needsRecheckEnabled = true; } public static boolean isPrivacy() { return privacy; } public static Set<String> getIgnoredConfigSections() { return ignoredConfigSections; } public static int getHistoryInterval() { return historyInterval; } public static void setHistoryInterval(int interval) { historyInterval = Math.max(20 * 60, interval); //Recheck the history length with the new Interval if (historyLength != -1) { setHistoryLength(historyLength); } } public static int getHistoryLength() { return historyLength; } public static void setHistoryLength(int length) { //Cap at 12 History Frames, 1 hour at 5 minute frames. int maxLength = historyInterval * MAX_HISTORY_FRAMES; //For special cases of servers with special permission to bypass the max. //This max helps keep data file sizes reasonable for processing on Aikar's Timing parser side. //Setting this will not help you bypass the max unless Aikar has added an exception on the API side. if (Server.getInstance().getConfig().getBoolean("timings.bypass-max", false)) { maxLength = Integer.MAX_VALUE; } historyLength = Math.max(Math.min(maxLength, length), historyInterval); Queue<TimingsHistory> oldQueue = TimingsManager.HISTORY; int frames = (getHistoryLength() / getHistoryInterval()); if (length > maxLength) { Server.getInstance().getLogger().warning( "Timings Length too high. Requested " + length + ", max is " + maxLength + ". To get longer history, you must increase your interval. Set Interval to " + Math.ceil(length / MAX_HISTORY_FRAMES) + " to achieve this length."); } TimingsManager.HISTORY = new TimingsManager.BoundedQueue<>(frames); TimingsManager.HISTORY.addAll(oldQueue); } public static void reset() { TimingsManager.reset(); } public static Timing getCommandTiming(Command command) { return TimingsManager.getTiming(DEFAULT_GROUP.name, "Command: " + command.getLabel(), commandTimer); } public static Timing getTaskTiming(TaskHandler handler, long period) { String repeating = " "; if (period > 0) { repeating += "(interval:" + period + ")"; } else { repeating += "(Single)"; } if (handler.getTask() instanceof PluginTask) { String owner = ((PluginTask) handler.getTask()).getOwner().getName(); return TimingsManager.getTiming(owner, "PluginTask: " + handler.getTaskId() + repeating, schedulerSyncTimer); } else if (!handler.isAsynchronous()) { return TimingsManager.getTiming(DEFAULT_GROUP.name, "Task: " + handler.getTaskId() + repeating, schedulerSyncTimer); } else { return null; } } public static Timing getPluginEventTiming(Class<? extends Event> event, Listener listener, EventExecutor executor, Plugin plugin) { Timing group = TimingsManager.getTiming(plugin.getName(), "Combined Total", pluginEventTimer); return TimingsManager.getTiming(plugin.getName(), "Event: " + listener.getClass().getName() + "." + (executor instanceof MethodEventExecutor ? ((MethodEventExecutor) executor).getMethod().getName() : "???") + " (" + event.getSimpleName() + ")", group); } public static Timing getEntityTiming(Entity entity) { return TimingsManager.getTiming(DEFAULT_GROUP.name, "## Entity Tick: " + entity.getClass().getSimpleName(), tickEntityTimer); } public static Timing getBlockEntityTiming(BlockEntity blockEntity) { return TimingsManager.getTiming(DEFAULT_GROUP.name, "## BlockEntity Tick: " + blockEntity.getClass().getSimpleName(), tickBlockEntityTimer); } public static Timing getReceiveDataPacketTiming(DataPacket pk) { return TimingsManager.getTiming(DEFAULT_GROUP.name, "## Receive Packet: " + pk.getClass().getSimpleName(), playerNetworkReceiveTimer); } public static Timing getSendDataPacketTiming(DataPacket pk) { return TimingsManager.getTiming(DEFAULT_GROUP.name, "## Send Packet: " + pk.getClass().getSimpleName(), playerNetworkSendTimer); } public static void stopServer() { setTimingsEnabled(false); TimingsManager.recheckEnabled(); } }
11,327
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TimingsHistoryEntry.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/TimingsHistoryEntry.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import com.google.gson.JsonArray; import cn.nukkit.timings.JsonUtil; class TimingsHistoryEntry { final TimingData data; final TimingData[] children; TimingsHistoryEntry(Timing timing) { this.data = timing.record.clone(); this.children = new TimingData[timing.children.size()]; int i = 0; for (TimingData child : timing.children.values()) { this.children[i++] = child.clone(); } } JsonArray export() { JsonArray json = this.data.export(); if (this.children.length > 0) json.add(JsonUtil.mapToArray(this.children, TimingData::export)); return json; } }
1,875
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
FullServerTickTiming.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/FullServerTickTiming.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import static co.aikar.timings.TimingIdentifier.DEFAULT_GROUP; import static co.aikar.timings.TimingsManager.*; public class FullServerTickTiming extends Timing { private static final TimingIdentifier IDENTIFIER = new TimingIdentifier(DEFAULT_GROUP.name, "Full Server Tick", null); final TimingData minuteData; double avgFreeMemory = -1D; double avgUsedMemory = -1D; FullServerTickTiming() { super(IDENTIFIER); this.minuteData = new TimingData(this.id); TIMING_MAP.put(IDENTIFIER, this); } @Override public Timing startTiming() { if (TimingsManager.needsFullReset) { TimingsManager.resetTimings(); } else if (TimingsManager.needsRecheckEnabled) { TimingsManager.recheckEnabled(); } super.startTiming(); return this; } @Override public void stopTiming() { super.stopTiming(); if (!this.enabled) { return; } if (TimingsHistory.timedTicks % 20 == 0) { final Runtime runtime = Runtime.getRuntime(); double usedMemory = runtime.totalMemory() - runtime.freeMemory(); double freeMemory = runtime.maxMemory() - usedMemory; if (this.avgFreeMemory == -1) { this.avgFreeMemory = freeMemory; } else { this.avgFreeMemory = (this.avgFreeMemory * (59 / 60D)) + (freeMemory * (1 / 60D)); } if (this.avgUsedMemory == -1) { this.avgUsedMemory = usedMemory; } else { this.avgUsedMemory = (this.avgUsedMemory * (59 / 60D)) + (usedMemory * (1 / 60D)); } } long start = System.nanoTime(); TimingsManager.tick(); long diff = System.nanoTime() - start; CURRENT = Timings.timingsTickTimer; Timings.timingsTickTimer.addDiff(diff); //addDiff for timingsTickTimer incremented this, bring it back down to 1 per tick. this.record.curTickCount--; this.minuteData.curTickTotal = this.record.curTickTotal; this.minuteData.curTickCount = 1; boolean violated = isViolated(); this.minuteData.tick(violated); Timings.timingsTickTimer.tick(violated); tick(violated); if (TimingsHistory.timedTicks % 1200 == 0) { MINUTE_REPORTS.add(new TimingsHistory.MinuteReport()); TimingsHistory.resetTicks(false); this.minuteData.reset(); } if (TimingsHistory.timedTicks % Timings.getHistoryInterval() == 0) { TimingsManager.HISTORY.add(new TimingsHistory()); TimingsManager.resetTimings(); } } boolean isViolated() { return this.record.curTickTotal > 50000000; } }
4,019
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TimingIdentifier.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/TimingIdentifier.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import java.util.ArrayDeque; import java.util.IdentityHashMap; import java.util.Map; class TimingIdentifier { static final Map<String, TimingGroup> GROUP_MAP = new IdentityHashMap<>(64); static final TimingGroup DEFAULT_GROUP = getGroup("Nukkit"); final String group; final String name; final Timing groupTiming; private final int hashCode; TimingIdentifier(String group, String name, Timing groupTiming) { this.group = group != null ? group.intern() : DEFAULT_GROUP.name; this.name = name.intern(); this.groupTiming = groupTiming; this.hashCode = (31 * this.group.hashCode()) + this.name.hashCode(); } static TimingGroup getGroup(String name) { if (name == null) { return DEFAULT_GROUP; } return GROUP_MAP.computeIfAbsent(name, k -> new TimingGroup(name)); } @Override @SuppressWarnings("all") public boolean equals(Object o) { if (o == null || !(o instanceof TimingIdentifier)) { return false; } TimingIdentifier that = (TimingIdentifier) o; //Using intern() method on strings makes possible faster string comparison with == return this.group == that.group && this.name == that.name; } @Override public int hashCode() { return this.hashCode; } static class TimingGroup { private static int idPool = 1; final int id = idPool++; final String name; ArrayDeque<Timing> timings = new ArrayDeque<>(64); TimingGroup(String name) { this.name = name.intern(); } } }
2,853
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TimingsManager.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/TimingsManager.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import cn.nukkit.Server; import java.util.*; public class TimingsManager { static final Map<TimingIdentifier, Timing> TIMING_MAP = Collections.synchronizedMap(new HashMap<>(256, 0.5f)); static final Queue<Timing> TIMINGS = new ArrayDeque<>(); static final ArrayDeque<TimingsHistory.MinuteReport> MINUTE_REPORTS = new ArrayDeque<>(); static Queue<TimingsHistory> HISTORY = new BoundedQueue<>(12); static Timing CURRENT; static long timingStart = 0; static long historyStart = 0; static boolean needsFullReset = false; static boolean needsRecheckEnabled = false; static void reset() { needsFullReset = true; } /** * Called every tick to count the number of times a timer caused TPS loss. */ static void tick() { if (Timings.isTimingsEnabled()) { boolean violated = Timings.fullServerTickTimer.isViolated(); for (Timing timing : TIMINGS) { if (timing.isSpecial()) { // Called manually continue; } timing.tick(violated); } TimingsHistory.playerTicks += Server.getInstance().getOnlinePlayers().size(); TimingsHistory.timedTicks++; } } static void recheckEnabled() { synchronized (TIMING_MAP) { TIMING_MAP.values().forEach(Timing::checkEnabled); } needsRecheckEnabled = false; } static void resetTimings() { if (needsFullReset) { // Full resets need to re-check every handlers enabled state // Timing map can be modified from async so we must sync on it. synchronized (TIMING_MAP) { for (Timing timing : TIMING_MAP.values()) { timing.reset(true); } } HISTORY.clear(); needsFullReset = false; needsRecheckEnabled = false; timingStart = System.currentTimeMillis(); } else { // Soft resets only need to act on timings that have done something // Handlers can only be modified on main thread. for (Timing timing : TIMINGS) { timing.reset(false); } } TIMINGS.clear(); MINUTE_REPORTS.clear(); TimingsHistory.resetTicks(true); historyStart = System.currentTimeMillis(); } public static Timing getTiming(String name) { return getTiming(null, name, null); } static Timing getTiming(String group, String name, Timing groupTiming) { TimingIdentifier id = new TimingIdentifier(group, name, groupTiming); return TIMING_MAP.computeIfAbsent(id, k -> new Timing(id)); } static final class BoundedQueue<E> extends LinkedList<E> { final int maxSize; BoundedQueue(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize must be greater than zero"); } this.maxSize = maxSize; } @Override public boolean add(E e) { if (this.size() == maxSize) { this.remove(); } return super.add(e); } } }
4,486
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TimingsHistory.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/TimingsHistory.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.entity.Entity; import cn.nukkit.level.Level; import cn.nukkit.level.format.FullChunk; import cn.nukkit.timings.JsonUtil; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.lang.management.ManagementFactory; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import static co.aikar.timings.Timings.fullServerTickTimer; import static co.aikar.timings.TimingsManager.MINUTE_REPORTS; public class TimingsHistory { public static long lastMinuteTime; public static long timedTicks; public static long playerTicks; public static long entityTicks; public static long tileEntityTicks; public static long activatedEntityTicks; private static int levelIdPool = 1; static Map<String, Integer> levelMap = new HashMap<>(); static Map<Integer, String> entityMap = new HashMap<>(); static Map<Integer, String> blockEntityMap = new HashMap<>(); private final long endTime; private final long startTime; private final long totalTicks; // Represents all time spent running the server this history private final long totalTime; private final MinuteReport[] minuteReports; private final TimingsHistoryEntry[] entries; private final JsonObject levels = new JsonObject(); TimingsHistory() { this.endTime = System.currentTimeMillis() / 1000; this.startTime = TimingsManager.historyStart / 1000; if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) { this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]); this.minuteReports[this.minuteReports.length - 1] = new MinuteReport(); } else { this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size()]); } long ticks = 0; for (MinuteReport mr : this.minuteReports) { ticks += mr.ticksRecord.timed; } this.totalTicks = ticks; this.totalTime = fullServerTickTimer.record.totalTime; this.entries = new TimingsHistoryEntry[TimingsManager.TIMINGS.size()]; int i = 0; for (Timing timing : TimingsManager.TIMINGS) { this.entries[i++] = new TimingsHistoryEntry(timing); } final Map<Integer, AtomicInteger> entityCounts = new HashMap<>(); final Map<Integer, AtomicInteger> blockEntityCounts = new HashMap<>(); final Gson GSON = new Gson(); // Information about all loaded entities/block entities for (Level level : Server.getInstance().getLevels().values()) { JsonArray jsonLevel = new JsonArray(); for (FullChunk chunk : level.getChunks().values()) { entityCounts.clear(); blockEntityCounts.clear(); //count entities for (Entity entity : chunk.getEntities().values()) { if (!entityCounts.containsKey(entity.getNetworkId())) entityCounts.put(entity.getNetworkId(), new AtomicInteger(0)); entityCounts.get(entity.getNetworkId()).incrementAndGet(); entityMap.put(entity.getNetworkId(), entity.getClass().getSimpleName()); } //count block entities for (BlockEntity blockEntity : chunk.getBlockEntities().values()) { if (!blockEntityCounts.containsKey(blockEntity.getBlock().getId())) blockEntityCounts.put(blockEntity.getBlock().getId(), new AtomicInteger(0)); blockEntityCounts.get(blockEntity.getBlock().getId()).incrementAndGet(); blockEntityMap.put(blockEntity.getBlock().getId(), blockEntity.getClass().getSimpleName()); } if (blockEntityCounts.isEmpty() && entityCounts.isEmpty()) { continue; } JsonArray jsonChunk = new JsonArray(); jsonChunk.add(chunk.getX()); jsonChunk.add(chunk.getZ()); jsonChunk.add(GSON.toJsonTree(JsonUtil.mapToObject(entityCounts.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue().get()))).getAsJsonObject()); jsonChunk.add(GSON.toJsonTree(JsonUtil.mapToObject(blockEntityCounts.entrySet(), (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue().get()))).getAsJsonObject()); jsonLevel.add(jsonChunk); } if (!levelMap.containsKey(level.getName())) levelMap.put(level.getName(), levelIdPool++); levels.add(String.valueOf(levelMap.get(level.getName())), jsonLevel); } } static void resetTicks(boolean fullReset) { if (fullReset) { timedTicks = 0; } lastMinuteTime = System.nanoTime(); playerTicks = 0; tileEntityTicks = 0; entityTicks = 0; activatedEntityTicks = 0; } JsonObject export() { JsonObject json = new JsonObject(); json.addProperty("s", this.startTime); json.addProperty("e", this.endTime); json.addProperty("tk", this.totalTicks); json.addProperty("tm", this.totalTime); json.add("w", this.levels); json.add("h", JsonUtil.mapToArray(this.entries, (entry) -> { if (entry.data.count == 0) { return null; } return entry.export(); })); json.add("mp", JsonUtil.mapToArray(this.minuteReports, MinuteReport::export)); return json; } static class MinuteReport { final long time = System.currentTimeMillis() / 1000; final TicksRecord ticksRecord = new TicksRecord(); final PingRecord pingRecord = new PingRecord(); final TimingData fst = Timings.fullServerTickTimer.minuteData.clone(); final double tps = 1E9 / (System.nanoTime() - lastMinuteTime) * this.ticksRecord.timed; final double usedMemory = Timings.fullServerTickTimer.avgUsedMemory; final double freeMemory = Timings.fullServerTickTimer.avgFreeMemory; final double loadAvg = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage(); JsonArray export() { return JsonUtil.toArray(this.time, Math.round(this.tps * 100D) / 100D, Math.round(this.pingRecord.avg * 100D) / 100D, this.fst.export(), JsonUtil.toArray(this.ticksRecord.timed, this.ticksRecord.player, this.ticksRecord.entity, this.ticksRecord.activatedEntity, this.ticksRecord.tileEntity), this.usedMemory, this.freeMemory, this.loadAvg); } } private static class TicksRecord { final long timed; final long player; final long entity; final long activatedEntity; final long tileEntity; TicksRecord() { this.timed = timedTicks - (TimingsManager.MINUTE_REPORTS.size() * 1200); this.player = playerTicks; this.entity = entityTicks; this.activatedEntity = activatedEntityTicks; this.tileEntity = tileEntityTicks; } } private static class PingRecord { final double avg; PingRecord() { final Collection<Player> onlinePlayers = Server.getInstance().getOnlinePlayers().values(); int totalPing = 0; for (Player player : onlinePlayers) { totalPing += player.getPing(); } this.avg = onlinePlayers.isEmpty() ? 0 : totalPing / onlinePlayers.size(); } } }
9,202
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
TimingData.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/TimingData.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import com.google.gson.JsonArray; import cn.nukkit.timings.JsonUtil; class TimingData { private int id; int count = 0; private int lagCount = 0; long totalTime = 0; private long lagTotalTime = 0; int curTickCount = 0; int curTickTotal = 0; TimingData(int id) { this.id = id; } TimingData(TimingData data) { this.id = data.id; this.count = data.count; this.lagCount = data.lagCount; this.totalTime = data.totalTime; this.lagTotalTime = data.lagTotalTime; } void add(long diff) { ++this.curTickCount; this.curTickTotal += diff; } void tick(boolean violated) { this.count += this.curTickCount; this.totalTime += this.curTickTotal; if (violated) { this.lagCount += this.curTickCount; this.lagTotalTime += this.curTickTotal; } this.curTickCount = 0; this.curTickTotal = 0; } void reset() { this.count = 0; this.lagCount = 0; this.totalTime = 0; this.lagTotalTime = 0; this.curTickCount = 0; this.curTickTotal = 0; } protected TimingData clone() { return new TimingData(this); } JsonArray export() { JsonArray json = JsonUtil.toArray(this.id, this.count, this.totalTime); if (this.lagCount > 0) { json.add(this.lagCount); json.add(this.lagTotalTime); } return json; } }
2,727
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
Timing.java
/FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/co/aikar/timings/Timing.java
/* * This file is licensed under the MIT License (MIT). * * Copyright (c) 2014 Daniel Ennis <http://aikar.co> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.aikar.timings; import java.util.HashMap; import java.util.Map; public class Timing implements AutoCloseable { private static int idPool = 1; final int id = idPool++; final String name; private final boolean verbose; final Map<Integer, TimingData> children = new HashMap<>(); private Timing parent; private final Timing groupTiming; final TimingData record; private long start = 0; private int timingDepth = 0; private boolean added; boolean timed; boolean enabled; Timing(TimingIdentifier id) { if (id.name.startsWith("##")) { this.verbose = true; this.name = id.name.substring(3); } else { this.name = id.name; this.verbose = false; } this.record = new TimingData(this.id); this.groupTiming = id.groupTiming; TimingIdentifier.getGroup(id.group).timings.add(this); this.checkEnabled(); } final void checkEnabled() { this.enabled = Timings.isTimingsEnabled() && (!this.verbose || Timings.isVerboseEnabled()); } void tick(boolean violated) { if (this.timingDepth != 0 || this.record.curTickCount == 0) { this.timingDepth = 0; this.start = 0; return; } this.record.tick(violated); for (TimingData data : this.children.values()) { data.tick(violated); } } public Timing startTiming() { if (!this.enabled) { return this; } if (++this.timingDepth == 1) { this.start = System.nanoTime(); this.parent = TimingsManager.CURRENT; TimingsManager.CURRENT = this; } return this; } public void stopTiming() { if (!this.enabled) { return; } if (--this.timingDepth == 0 && this.start != 0) { this.addDiff(System.nanoTime() - this.start); this.start = 0; } } public void abort() { if (this.enabled && this.timingDepth > 0) { this.start = 0; } } void addDiff(long diff) { if (TimingsManager.CURRENT == this) { TimingsManager.CURRENT = this.parent; if (this.parent != null) { if (!this.parent.children.containsKey(this.id)) this.parent.children.put(this.id, new TimingData(this.id)); this.parent.children.get(this.id).add(diff); } } this.record.add(diff); if (!this.added) { this.added = true; this.timed = true; TimingsManager.TIMINGS.add(this); } if (this.groupTiming != null) { this.groupTiming.addDiff(diff); if (!this.groupTiming.children.containsKey(this.id)) this.groupTiming.children.put(this.id, new TimingData(this.id)); this.groupTiming.children.get(this.id).add(diff); } } void reset(boolean full) { this.record.reset(); if (full) { this.timed = false; } this.start = 0; this.timingDepth = 0; this.added = false; this.children.clear(); this.checkEnabled(); } @Override public boolean equals(Object o) { return (o instanceof Timing && this == o); } @Override public int hashCode() { return this.id; } //For try-with-resources @Override public void close() { this.stopTiming(); } boolean isSpecial() { return this == Timings.fullServerTickTimer || this == Timings.timingsTickTimer; } }
4,894
Java
.java
Nukkit/Nukkit
821
272
171
2015-05-23T09:51:41Z
2024-03-21T12:28:05Z
MitmAPI.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/MitmAPI.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2022 - Emanuele Faranda */ package com.pcapdroid.mitm; import java.io.Serializable; /* API to integrate MitmAddon */ public class MitmAPI { public static final String PACKAGE_NAME = "com.pcapdroid.mitm"; public static final String MITM_SERVICE = PACKAGE_NAME + ".MitmService"; public static final int MSG_ERROR = -1; public static final int MSG_START_MITM = 1; public static final int MSG_GET_CA_CERTIFICATE = 2; public static final int MSG_STOP_MITM = 3; public static final int MSG_DISABLE_DOZE = 4; public static final String MITM_CONFIG = "mitm_config"; public static final String CERTIFICATE_RESULT = "certificate"; public static final String SSLKEYLOG_RESULT = "sslkeylog"; public static final class MitmConfig implements Serializable { public int proxyPort; // the SOCKS5 port to use to accept mitm-ed connections public boolean transparentMode; // true to use transparent proxy mode, false to use SOCKS5 proxy mode public boolean sslInsecure; // true to disable upstream certificate check public boolean dumpMasterSecrets; // true to enable the TLS master secrets dump messages (similar to SSLKEYLOG) public boolean shortPayload; // if true, only the initial portion of the payload will be sent public String proxyAuth; // SOCKS5 proxy authentication, "user:pass" public String additionalOptions; // provide additional options to mitmproxy } }
2,198
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
MitmService.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/MitmService.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2022-24 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Service; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.provider.Settings; import android.util.Log; import com.chaquo.python.PyObject; import com.chaquo.python.Python; import java.io.IOException; import java.lang.ref.WeakReference; import com.pcapdroid.mitm.MitmAPI.MitmConfig; public class MitmService extends Service implements Runnable { static final String TAG = "Mitmproxy"; static MitmService INSTANCE; Messenger mMessenger; ParcelFileDescriptor mFd; Thread mThread; PyObject mitm; MitmConfig mConf; String m_home; @SuppressLint("BatteryLife") @Override public void onCreate() { Python py = Python.getInstance(); mitm = py.getModule("mitm"); PyObject os = py.getModule("os"); PyObject env = os.get("environ"); m_home = env.callAttr("get", "HOME").toString(); Log.d(TAG, "Chaquopy home at " + m_home); INSTANCE = this; super.onCreate(); } @Override public void onDestroy() { _stop(); INSTANCE = null; super.onDestroy(); } static class IncomingHandler extends Handler { final WeakReference<MitmService> mReference; public IncomingHandler(Looper looper, MitmService service) { super(looper); mReference = new WeakReference<>(service); } @Override public void handleMessage(Message msg) { MitmService instance = mReference.get(); if(instance != null) instance.handleMessage(msg); } } @Override public IBinder onBind(Intent intent) { mMessenger = new Messenger(new IncomingHandler(getMainLooper(),this)); return mMessenger.getBinder(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_NOT_STICKY; } private void handleMessage(Message msg) { switch (msg.what) { case MitmAPI.MSG_START_MITM: mFd = (ParcelFileDescriptor) msg.obj; mConf = (MitmConfig) msg.getData().getSerializable(MitmAPI.MITM_CONFIG); if(mThread == null) { mThread = new Thread(MitmService.this); mThread.start(); } else log_w("Thread already active"); break; case MitmAPI.MSG_STOP_MITM: //Log.d(TAG, "stop called"); _stop(); break; case MitmAPI.MSG_GET_CA_CERTIFICATE: if(mThread == null) handleGetCaCertificate(msg.replyTo); else { log_w("Not supported while mitm running"); replyWithError(msg.replyTo); } break; case MitmAPI.MSG_DISABLE_DOZE: askDisableDoze(); break; default: log_w("Unknown message: " + msg.what); } } private String getMitmproxyArgs() { StringBuilder builder = new StringBuilder(); builder.append("-q --set onboarding=false --listen-host 127.0.0.1 -p "); builder.append(mConf.proxyPort); if(mConf.transparentMode) { builder.append(" --mode transparent"); } else { builder.append(" --mode socks5"); if(mConf.proxyAuth != null) { builder.append(" --proxyauth "); builder.append(mConf.proxyAuth); } } if(mConf.sslInsecure) builder.append(" --ssl-insecure"); if((mConf.additionalOptions != null) && !mConf.additionalOptions.isEmpty()) { builder.append(" "); builder.append(mConf.additionalOptions); } return builder.toString(); } @Override public void run() { String args = getMitmproxyArgs(); // SOCKS5 mode is used with VPNService, so we must dump the client (original) connection // Transparent mode is used with root mode where we capture the internet interface, so we must dump the server connection boolean dump_client = !mConf.transparentMode; AddonsActivity.copyAddonsToPrivDir(this, m_home + "/mitmproxy-addons"); String[] enabled_addons = AddonsActivity.getEnabledAddons(this).toArray(new String[]{}); try { mitm.callAttr("run", mFd.getFd(), enabled_addons, dump_client, mConf.dumpMasterSecrets, mConf.shortPayload, args); } finally { try { if(mFd != null) mFd.close(); } catch (IOException e) { e.printStackTrace(); } Log.d(TAG, "Done"); mFd = null; mConf = null; mThread = null; } } private void _stop() { mitm.callAttr("stop"); while((mThread != null) && (mThread.isAlive())) { try { mThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } stopSelf(); } private void log_i(String msg) { Log.i(TAG, msg); if(mitm != null) mitm.callAttr("log", Log.INFO, msg); } private void log_w(String msg) { Log.w(TAG, msg); if(mitm != null) mitm.callAttr("log", Log.WARN, msg); } private void log_e(String msg) { Log.e(TAG, msg); if(mitm != null) mitm.callAttr("log", Log.ERROR, msg); } private void handleGetCaCertificate(Messenger replyTo) { String cert = null; PyObject pyres = mitm.callAttr("getCAcert"); if(pyres != null) cert = pyres.toJava(String.class); if(replyTo != null) { Bundle bundle = new Bundle(); bundle.putString(MitmAPI.CERTIFICATE_RESULT, cert); Message msg = Message.obtain(null, MitmAPI.MSG_GET_CA_CERTIFICATE); msg.setData(bundle); try { replyTo.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } } @SuppressLint("BatteryLife") @TargetApi(Build.VERSION_CODES.M) private void askDisableDoze() { // NOTE: when the app is battery-optimized, MITM may get stuck, requiring a device reboot // to work again Log.i(TAG, "Ask to disable doze"); Intent intent = new Intent(); intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + BuildConfig.APPLICATION_ID)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void replyWithError(Messenger replyTo) { if(replyTo == null) return; Message msg = Message.obtain(null, MitmAPI.MSG_ERROR); try { replyTo.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } public static void reloadJsInjectorScripts() { MitmService instance = INSTANCE; if(instance != null) instance.mitm.callAttr("reloadJsUserscripts"); } public static boolean isRunning() { return (INSTANCE != null); } }
8,498
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
JsInjectorActivity.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/JsInjectorActivity.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2023 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import android.util.Log; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.chaquo.python.PyObject; import com.chaquo.python.Python; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.regex.Pattern; public class JsInjectorActivity extends Activity { private static final String TAG = "JsInjectorActivity"; private static final String SCRIPTS_PREF = "js-scripts"; private static final String SEPARATOR = "|"; private SharedPreferences mPrefs; private ArrayList<String> mUrls = new ArrayList<>(); private ListView mListView; private TextView mEmptyText; private ScriptsAdapter mAdapter; private final ExecutorService mDownloadWorkers = Executors.newFixedThreadPool(4); private final HashSet<String> mUrlsDownloading = new HashSet<>(); private final Handler mHandler = new Handler(Looper.getMainLooper()); private ActionMode mActionMode; private final ArrayList<IJsUserscript> mSelected = new ArrayList<>(); PyObject userscripts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.js_injector); setContentView(R.layout.simple_list); mListView = findViewById(R.id.listview); mEmptyText = findViewById(R.id.list_empty); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); String prefVal = mPrefs.getString(SCRIPTS_PREF, ""); if(!prefVal.isEmpty()) mUrls = new ArrayList<>(Arrays.asList( mPrefs.getString(SCRIPTS_PREF, "").split(Pattern.quote(SEPARATOR)))); mAdapter = new ScriptsAdapter(this); mListView.setAdapter(mAdapter); mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); mListView.setOnItemClickListener((parent, view, position, id) -> { IJsUserscript script = mAdapter.getItem(position); if(script != null) { String url = getScriptUrl(script.getFname()); if(url != null) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } } }); mListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.script_cab, menu); mActionMode = mode; return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { int id = item.getItemId(); if(id == R.id.delete) { confirmDelete(mode); return true; } else if(id == R.id.select_all) { if(mSelected.size() >= mAdapter.getCount()) mode.finish(); else { for(int i=0; i<mAdapter.getCount(); i++) { if(!mListView.isItemChecked(i)) mListView.setItemChecked(i, true); } } return true; } else if(id == R.id.update) { boolean already_in_progress = false; boolean reload = false; for(IJsUserscript script : mSelected) { String url = getScriptUrl(script.getFname()); if(url != null) { if(mUrlsDownloading.contains(url)) already_in_progress = true; else { downloadScript(url); reload = true; } } } if(already_in_progress) Toast.makeText(JsInjectorActivity.this, R.string.download_in_progress, Toast.LENGTH_SHORT) .show(); if(reload) refreshScripts(); return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { mSelected.clear(); mActionMode = null; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { IJsUserscript item = mAdapter.getItem(position); if(checked) mSelected.add(item); else mSelected.remove(item); mode.setTitle(getString(R.string.n_selected, mSelected.size())); } }); Python py = Python.getInstance(); userscripts = py.getModule("userscripts"); refreshScripts(); } private void confirmDelete(ActionMode mode) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.items_delete_confirm); builder.setCancelable(true); builder.setPositiveButton(android.R.string.yes, (dialog, which) -> { if(mSelected.size() >= mAdapter.getCount()) { mAdapter.clear(); mUrls.clear(); saveUrls(); } else { for(IJsUserscript item : mSelected) mAdapter.remove(item); updateListFromAdapter(); } mode.finish(); mActionMode = null; refreshScripts(); MitmService.reloadJsInjectorScripts(); recheckListSize(); }); builder.setNegativeButton(android.R.string.no, (dialog, whichButton) -> {}); final AlertDialog alert = builder.create(); alert.setCanceledOnTouchOutside(true); alert.show(); } private void updateListFromAdapter() { HashSet<String> toKeep = new HashSet<>(); // Remove the URLs which are not in the adapter dataset for(int i=0; i<mAdapter.getCount(); i++) toKeep.add(mAdapter.getItem(i).getFname()); Iterator<String> it = mUrls.iterator(); while(it.hasNext()) { String url = it.next(); String fname = urlFileName(url); if(!toKeep.contains(fname)) { it.remove(); mUrlsDownloading.remove(url); } } saveUrls(); } @Override protected void onDestroy() { mDownloadWorkers.shutdownNow(); mUrlsDownloading.clear(); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.js_injector, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.show_hint) { Utils.showHintDialog(this, R.string.js_injector_hint); return true; } else if(id == R.id.add) { showAddScriptDialog(); return true; } else if(id == R.id.update) { for (String url: mUrls) { if(!mUrlsDownloading.contains(url)) downloadScript(url); } refreshScripts(); return true; } return super.onOptionsItemSelected(item); } private void showAddScriptDialog() { LayoutInflater inflater = LayoutInflater.from(this); View view = inflater.inflate(R.layout.add_script_dialog, null); final EditText url_edit = view.findViewById(R.id.url); AlertDialog dialog = new AlertDialog.Builder(this) .setView(view) .setTitle(R.string.add_script) .setPositiveButton(R.string.add_action, (dialogInterface, i) -> {}) .setNegativeButton(R.string.cancel_action, (dialogInterface, i) -> {}) .show(); dialog.setCanceledOnTouchOutside(false); dialog.getButton(AlertDialog.BUTTON_POSITIVE) .setOnClickListener(v -> { String url = url_edit.getText().toString(); if(urlFileName(url).isEmpty()) { Toast.makeText(this, R.string.missing_required_parameter, Toast.LENGTH_SHORT) .show(); return; } addScript(url); dialog.dismiss(); }); } private String urlFileName(String url) { int idx = url.lastIndexOf('/'); if(idx == -1) return ""; return url.substring(idx + 1); } private void saveUrls() { mPrefs.edit() .putString(SCRIPTS_PREF, String.join(SEPARATOR, mUrls)) .apply(); } private boolean addScript(String url) { String fname = urlFileName(url); if(fname.isEmpty()) return false; if(hasScript(fname)) { Toast.makeText(this, R.string.script_already_defined, Toast.LENGTH_LONG) .show(); return false; } mUrls.add(url); saveUrls(); refreshScripts(); return true; } private ArrayList<IJsUserscript> getScriptsOnDisk() { ArrayList<IJsUserscript> rv = new ArrayList<>(); PyObject pyres = userscripts.callAttr("getJsUserscripts"); if(pyres != null) { List<PyObject> scripts_obj = pyres.asList(); for(PyObject script_obj: scripts_obj) { IJsUserscript script = script_obj.toJava(IJsUserscript.class); Log.d(TAG, "Js userscript: " + script.getName()); rv.add(script); } } return rv; } private String getScriptUrl(String fname) { for(String u: mUrls) { if(urlFileName(u).equals(fname)) return u; } return null; } private boolean hasScript(String fname) { return getScriptUrl(fname) != null; } private static class LoadInProgressScript implements IJsUserscript { private final String mFname; private final String mLoadInProgress; public LoadInProgressScript(String fname, String load_in_progress) { mFname = fname; mLoadInProgress = load_in_progress; } @Override public String getName() { return mFname; } @Override public String getAuthor() { return ""; } @Override public String getVersion() { return ""; } @Override public String getDescription() { return mLoadInProgress; } @Override public String getFname() { return mFname; } } private void recheckListSize() { mEmptyText.setVisibility((mAdapter.getCount() == 0) ? View.VISIBLE : View.GONE); } private void refreshScripts() { if(mActionMode != null) { mActionMode.finish(); mActionMode = null; } ArrayList<IJsUserscript> on_disk = getScriptsOnDisk(); HashMap<String, IJsUserscript> fname_to_script = new HashMap<>(); // Delete any unknown script for(IJsUserscript on_disk_script: on_disk) { String fname = on_disk_script.getFname(); if(!hasScript(fname)) { PyObject pyres = userscripts.callAttr("getScriptPath", fname); if(pyres != null) { Log.i(TAG, "Deleting unknown script " + fname); String path = pyres.toString(); //noinspection ResultOfMethodCallIgnored (new File(path)).delete(); } } else fname_to_script.put(fname, on_disk_script); } ArrayList<IJsUserscript> model = new ArrayList<>(); // Honor the order of mUrls for(String url: mUrls) { String fname = urlFileName(url); IJsUserscript script = fname_to_script.get(fname); if((script == null) || mUrlsDownloading.contains(url)) { script = new LoadInProgressScript(fname, getString(R.string.loading)); downloadScript(url); } model.add(script); } mAdapter.reload(model); recheckListSize(); } private void downloadScript(String url) { if(mUrlsDownloading.contains(url)) return; String fname = urlFileName(url); PyObject pyres = userscripts.callAttr("getScriptPath", fname); assert(pyres != null); final String outputPath = pyres.toString(); try { mDownloadWorkers.execute(() -> { Log.i(TAG, "Downloading " + url); boolean success = downloadFile(url, outputPath); mHandler.post(() -> onScriptDownloadFinished(url, success)); }); mUrlsDownloading.add(url); } catch (RejectedExecutionException e) { Log.e(TAG, e.toString()); } } private void onScriptDownloadFinished(String url, boolean success) { Log.d(TAG, "Script " + url + " download success? " + success); boolean found = mUrlsDownloading.remove(url); if(!found) return; if(success) { MitmService.reloadJsInjectorScripts(); refreshScripts(); } else Toast.makeText(this, getString(R.string.script_download_failed, urlFileName(url)), Toast.LENGTH_LONG) .show(); } private static boolean downloadFile(String _url, String path) { boolean has_contents = false; try (FileOutputStream out = new FileOutputStream(path)) { URL url = new URL(_url); try (BufferedOutputStream bos = new BufferedOutputStream(out)) { HttpURLConnection con = (HttpURLConnection) url.openConnection(); try { // Necessary otherwise the connection will stay open con.setRequestProperty("Connection", "Close"); con.setConnectTimeout(5000); con.setReadTimeout(5000); try (InputStream in = new BufferedInputStream(con.getInputStream())) { byte[] bytesIn = new byte[4096]; int read; while ((read = in.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); has_contents |= (read > 0); } } catch (SocketTimeoutException _ignored) { Log.w(TAG, "Timeout while fetching " + _url); } } finally { con.disconnect(); } } } catch (IOException e) { e.printStackTrace(); } if (!has_contents) { Log.d(TAG, "Downloaded file from " + _url + " is empty"); try { //noinspection ResultOfMethodCallIgnored (new File(path + ".tmp")).delete(); // if exists } catch (Exception ignored) { // ignore } return false; } // Only write the target path if it was successful File dst = new File(path); // NOTE: renameTo seem to return false even on success //noinspection ResultOfMethodCallIgnored (new File(path + ".tmp")).renameTo(dst); return dst.exists(); } }
18,073
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
ScriptsAdapter.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/ScriptsAdapter.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2023 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; public class ScriptsAdapter extends ArrayAdapter<IJsUserscript> { private final LayoutInflater mLayoutInflater; private final String mAuthorLineFmt; public ScriptsAdapter(Context context) { super(context, R.layout.script_item); mAuthorLineFmt = context.getString(R.string.version_and_author); mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) convertView = mLayoutInflater.inflate(R.layout.script_item, parent, false); TextView name = convertView.findViewById(R.id.name); TextView author = convertView.findViewById(R.id.author); TextView descr = convertView.findViewById(R.id.description); IJsUserscript script = getItem(position); name.setText(script.getName()); author.setText(script.getVersion().isEmpty() ? script.getAuthor() : String.format(mAuthorLineFmt, script.getVersion(), script.getAuthor())); descr.setText(script.getDescription()); return convertView; } public void reload(List<IJsUserscript> scripts) { clear(); addAll(scripts); } }
2,251
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
MainActivity.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/MainActivity.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2023 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.chaquo.python.PyObject; import com.chaquo.python.Python; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); Python py = Python.getInstance(); PyObject metadata = py.getModule("importlib.metadata"); PyObject sys = py.getModule("sys"); PyObject openssl_backend_module = py.getModule("cryptography.hazmat.backends.openssl.backend"); PyObject openssl_backend = openssl_backend_module.get("backend"); ((TextView)findViewById(R.id.addon_version)).setText("v" + BuildConfig.VERSION_NAME); ((TextView)findViewById(R.id.abi)).setText(BuildConfig.FLAVOR); ((TextView)findViewById(R.id.mitmproxy_version)).setText( metadata.callAttr("version", "mitmproxy").toString()); ((TextView)findViewById(R.id.cryptography_version)).setText( metadata.callAttr("version", "cryptography").toString()); ((TextView)findViewById(R.id.openssl_version)).setText( openssl_backend.callAttr("openssl_version_text").toString()); ((TextView)findViewById(R.id.python_version)).setText( sys.get("version").toString()); findViewById(R.id.open_pcapdroid).setOnClickListener(v -> { try { Intent intent = null; try { intent = getPackageManager().getLaunchIntentForPackage("com.emanuelef.remote_capture"); } catch (ActivityNotFoundException ignored) {} if(intent == null) intent = getPackageManager().getLaunchIntentForPackage("com.emanuelef.remote_capture.debug"); if(intent != null) { startActivity(intent); return; } } catch (ActivityNotFoundException | SecurityException ignored) {} (Toast.makeText(this, R.string.app_not_found, Toast.LENGTH_SHORT)).show(); }); findViewById(R.id.addons).setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, AddonsActivity.class); startActivity(intent); }); } }
3,224
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
Utils.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/Utils.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2023 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.app.AlertDialog; import android.content.Context; import android.text.method.LinkMovementMethod; import android.widget.TextView; public class Utils { public static void showHintDialog(Context ctx, int id) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setTitle(R.string.hint); builder.setMessage(ctx.getString(id)); builder.setCancelable(true); builder.setNeutralButton(android.R.string.ok, (dialog, id1) -> dialog.cancel()); AlertDialog alert = builder.create(); alert.show(); TextView message = (TextView)alert.findViewById(android.R.id.message); if(message != null) { message.setMovementMethod(LinkMovementMethod.getInstance()); message.setText(id); } } }
1,579
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
AddonsAdapter.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/AddonsAdapter.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2023 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.Switch; import android.widget.TextView; import java.lang.ref.WeakReference; import java.util.List; public class AddonsAdapter extends ArrayAdapter<Addon> { public interface AddonListener { void onAddonToggled(Addon addon, boolean enabled); void onAddonSettingsClicked(Addon addon); } private final LayoutInflater mLayoutInflater; private WeakReference<AddonListener> mListener; public AddonsAdapter(Context context) { super(context, R.layout.addon_item); mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mLayoutInflater.inflate(R.layout.addon_item, parent, false); convertView.findViewById(R.id.toggle_btn) .setOnClickListener((v) -> { AddonListener listener = mListener.get(); if(listener != null) listener.onAddonToggled(getItem(position), ((Switch)v).isChecked()); }); convertView.findViewById(R.id.settings) .setOnClickListener((v) -> { AddonListener listener = mListener.get(); if(listener != null) listener.onAddonSettingsClicked(getItem(position)); }); } TextView fname = convertView.findViewById(R.id.fname); TextView info = convertView.findViewById(R.id.info); Switch toggle = convertView.findViewById(R.id.toggle_btn); ImageButton settings = convertView.findViewById(R.id.settings); Addon addon = getItem(position); fname.setText(addon.fname); info.setText(addon.description); toggle.setChecked(addon.enabled); settings.setVisibility((addon.type == Addon.AddonType.UserAddon) ? View.GONE : View.VISIBLE); return convertView; } public void setListener(AddonListener listener) { mListener = new WeakReference<>(listener); } public void reload(List<Addon> addons) { clear(); addAll(addons); } }
3,241
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
IJsUserscript.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/IJsUserscript.java
package com.pcapdroid.mitm; public interface IJsUserscript { String getName(); String getAuthor(); String getVersion(); String getDescription(); String getFname(); }
187
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
Addon.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/Addon.java
package com.pcapdroid.mitm; public class Addon { public String fname; String description; boolean enabled; AddonType type; public enum AddonType { UserAddon, JsInjector } public Addon(String fname, String description, boolean enabled, AddonType type) { this.fname = fname; this.description = description; this.enabled = enabled; this.type = type; } public Addon(String fname, String description, boolean enabled) { this(fname, description, enabled, AddonType.UserAddon); } }
575
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
AddonsActivity.java
/FileExtraction/Java_unseen/emanuele-f_PCAPdroid-mitm/app/src/main/java/com/pcapdroid/mitm/AddonsActivity.java
/* * This file is part of PCAPdroid. * * PCAPdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PCAPdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PCAPdroid. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2023 - Emanuele Faranda */ package com.pcapdroid.mitm; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.UriPermission; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.DocumentsContract; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class AddonsActivity extends Activity implements AddonsAdapter.AddonListener { private static final String TAG = "UserAddons"; private static final String USER_DIR_PREF = "user-dir"; private static final String ENABLED_ADDONS_PREF = "enabled-addons"; private static final int OPEN_DIR_TREE_CODE = 1; private TextView mEmptyText; private SharedPreferences mPrefs; private AddonsAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.addons); setContentView(R.layout.simple_list); mEmptyText = findViewById(R.id.list_empty); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mAdapter = new AddonsAdapter(this); mAdapter.setListener(this); ((ListView)findViewById(R.id.listview)) .setAdapter(mAdapter); refreshAddons(); } private void refreshAddons() { Set<String> enabledAddons = getEnabledAddons(this); List<Addon> addons = new ArrayList<>(); // Internal addons addons.add(new Addon("Js Injector", "Inject javascript into web pages", enabledAddons.contains("Js Injector"), Addon.AddonType.JsInjector)); // User addons Uri publicUri = Uri.parse(mPrefs.getString(USER_DIR_PREF, "")); String descr = getString(R.string.user_addon); if((publicUri.getHost() != null) && hasUriPersistablePermission(this, publicUri)) { for (Uri uri : listUserAddons(this, publicUri)) { String path = uri.getPath(); int slash = path.lastIndexOf("/"); if (slash > 0) { String fname = path.substring(slash + 1); if (fname.endsWith(".py")) { String script = fname.substring(0, fname.length() - 3); addons.add(new Addon(script, descr, enabledAddons.contains(script))); } } } } mAdapter.reload(addons); recheckListSize(); if(MitmService.isRunning()) (Toast.makeText(this, R.string.restart_to_apply, Toast.LENGTH_SHORT)).show(); } // get the file name of the enabled addons public static Set<String> getEnabledAddons(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); return prefs.getStringSet(ENABLED_ADDONS_PREF, new HashSet<>()); } private void recheckListSize() { mEmptyText.setVisibility((mAdapter.getCount() == 0) ? View.VISIBLE : View.GONE); } public static List<Uri> listUserAddons(Context ctx, Uri publicUri) { List<Uri> rv = new ArrayList<>(); try { Uri srcFolder = DocumentsContract.buildChildDocumentsUriUsingTree(publicUri, DocumentsContract.getTreeDocumentId(publicUri)); try (Cursor cursor = ctx.getContentResolver().query(srcFolder, new String[]{ DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null)) { if ((cursor != null) && cursor.moveToFirst()) { do { Uri uri = DocumentsContract.buildDocumentUriUsingTree(publicUri, cursor.getString(0)); rv.add(uri); } while (cursor.moveToNext()); } } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, e.toString()); } return rv; } /* Since we can only access the addons dir via the ContentResolver, we copy all the addons * to the app private dir to make python import work. */ public static boolean copyAddonsToPrivDir(Context ctx, String privDir) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); Uri publicUri = Uri.parse(prefs.getString(USER_DIR_PREF, "")); if((publicUri.getHost() == null) || !hasUriPersistablePermission(ctx, publicUri)) return false; File privAddons = new File(privDir); privAddons.delete(); privAddons.mkdirs(); Uri srcFolder = DocumentsContract.buildChildDocumentsUriUsingTree(publicUri, DocumentsContract.getTreeDocumentId(publicUri)); Log.d(TAG, "Addons source dir: " + srcFolder); List<Uri> addonsUris = listUserAddons(ctx, publicUri); for(Uri srcUri: addonsUris) { String path = srcUri.getPath(); int slash = path.lastIndexOf("/"); if (slash > 0) { String srcFname = path.substring(slash + 1); File outFile = new File(privAddons.getAbsolutePath() + "/" + srcFname); Log.d(TAG, "Found addon: " + srcFname); // Copy from srcUri to outFile try { try (InputStream in = new BufferedInputStream(ctx.getContentResolver().openInputStream(srcUri))) { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile))) { byte[] bytesIn = new byte[4096]; int read; while ((read = in.read(bytesIn)) != -1) out.write(bytesIn, 0, read); } } } catch (IOException e) { e.printStackTrace(); Log.e(TAG, e.toString()); return false; } } } return true; } private static boolean hasUriPersistablePermission(Context ctx, Uri uri) { List<UriPermission> persistableUris = ctx.getContentResolver().getPersistedUriPermissions(); for(UriPermission perm: persistableUris) { if(perm.getUri().equals(uri) && perm.isReadPermission()) return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.addons, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.show_hint) { Utils.showHintDialog(this, R.string.addons_hint); return true; } else if(id == R.id.update) { refreshAddons(); return true; } else if(id == R.id.select_user_dir) { selectUserDir(); return true; } return super.onOptionsItemSelected(item); } private void selectUserDir() { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Initial path intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath())); } (Toast.makeText(this, R.string.specify_user_dir, Toast.LENGTH_LONG)).show(); startActivityForResult(intent, OPEN_DIR_TREE_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent resultData) { if((requestCode == OPEN_DIR_TREE_CODE) && (resultCode == RESULT_OK) && (resultData != null)) { Uri user_dir = resultData.getData(); // Persist access across restarts getContentResolver().takePersistableUriPermission(user_dir, Intent.FLAG_GRANT_READ_URI_PERMISSION); mPrefs.edit() .putString(USER_DIR_PREF, user_dir.toString()) .apply(); refreshAddons(); } } @Override public void onAddonToggled(Addon addon, boolean enabled) { Set<String> enabledAddons = getEnabledAddons(AddonsActivity.this); addon.enabled = enabled; if(enabled) enabledAddons.add(addon.fname); else enabledAddons.remove(addon.fname); mPrefs.edit() .putStringSet(ENABLED_ADDONS_PREF, enabledAddons) .apply(); refreshAddons(); } @Override public void onAddonSettingsClicked(Addon addon) { if(addon.type == Addon.AddonType.JsInjector) { Intent intent = new Intent(this, JsInjectorActivity.class); startActivity(intent); } } }
10,215
Java
.java
emanuele-f/PCAPdroid-mitm
149
23
2
2022-02-12T23:05:22Z
2024-03-14T01:36:52Z
ExampleUnitTest.java
/FileExtraction/Java_unseen/Shashank02051997_PhoneNumberVerificationUI-Android/app/src/test/java/com/shashank/platform/phonenumberverification/ExampleUnitTest.java
package com.shashank.platform.phonenumberverification; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
406
Java
.java
Shashank02051997/PhoneNumberVerificationUI-Android
75
47
1
2018-12-29T06:30:55Z
2019-10-02T10:24:38Z
MainActivity.java
/FileExtraction/Java_unseen/Shashank02051997_PhoneNumberVerificationUI-Android/app/src/main/java/com/shashank/platform/phonenumberverification/MainActivity.java
package com.shashank.platform.phonenumberverification; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.Html; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView otp; Button generate_otp; EditText mobile_number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); otp = findViewById(R.id.otp); generate_otp = findViewById(R.id.generate_otp); mobile_number = findViewById(R.id.mobile_number); otp.setText(Html.fromHtml(getResources().getString(R.string.otp))); generate_otp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(mobile_number.getText().toString().equals("")) Toast.makeText(getApplicationContext(),"Please enter the mobile no.",Toast.LENGTH_SHORT).show(); else if(mobile_number.getText().length()<10) Toast.makeText(getApplicationContext(),"Please enter correct mobile no.",Toast.LENGTH_SHORT).show(); else{ Intent intent = new Intent(getApplicationContext(),Main2Activity.class); startActivity(intent); } } }); } }
2,211
Java
.java
Shashank02051997/PhoneNumberVerificationUI-Android
75
47
1
2018-12-29T06:30:55Z
2019-10-02T10:24:38Z
Main2Activity.java
/FileExtraction/Java_unseen/Shashank02051997_PhoneNumberVerificationUI-Android/app/src/main/java/com/shashank/platform/phonenumberverification/Main2Activity.java
package com.shashank.platform.phonenumberverification; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.Html; import android.text.TextWatcher; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; public class Main2Activity extends AppCompatActivity { TextView otp; EditText otp_box_1,otp_box_2,otp_box_3,otp_box_4,otp_box_5,otp_box_6; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main2); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); otp = findViewById(R.id.otp); otp_box_1 = findViewById(R.id.otp_box_1); otp_box_2 = findViewById(R.id.otp_box_2); otp_box_3 = findViewById(R.id.otp_box_3); otp_box_4 = findViewById(R.id.otp_box_4); otp_box_5 = findViewById(R.id.otp_box_5); otp_box_6 = findViewById(R.id.otp_box_6); otp.setText(Html.fromHtml(getResources().getString(R.string.otp1))); otp_box_1.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if(editable!=null){ if(editable.length()==1) otp_box_2.requestFocus(); } } }); otp_box_2.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if(editable!=null){ if(editable.length()==1) otp_box_3.requestFocus(); } } }); otp_box_3.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if(editable!=null){ if(editable.length()==1) otp_box_4.requestFocus(); } } }); otp_box_4.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if(editable!=null){ if(editable.length()==1) otp_box_5.requestFocus(); } } }); otp_box_5.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { if(editable!=null){ if(editable.length()==1) otp_box_6.requestFocus(); } } }); } }
4,591
Java
.java
Shashank02051997/PhoneNumberVerificationUI-Android
75
47
1
2018-12-29T06:30:55Z
2019-10-02T10:24:38Z
ExampleInstrumentedTest.java
/FileExtraction/Java_unseen/Shashank02051997_PhoneNumberVerificationUI-Android/app/src/androidTest/java/com/shashank/platform/phonenumberverification/ExampleInstrumentedTest.java
package com.shashank.platform.phonenumberverification; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.shashank.platform.phonenumberverification", appContext.getPackageName()); } }
774
Java
.java
Shashank02051997/PhoneNumberVerificationUI-Android
75
47
1
2018-12-29T06:30:55Z
2019-10-02T10:24:38Z
TeamTest.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/test/eu/matejkormuth/pexel/PexelCore/teams/TeamTest.java
package eu.matejkormuth.pexel.PexelCore.teams; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.bukkit.Color; import org.bukkit.entity.Player; import org.junit.Test; import org.mockito.Mockito; public class TeamTest { @Test public void declaration() { Team team1 = new Team(Color.RED, "Team name", 20); assertEquals("team color", Color.RED, team1.getColor()); assertEquals("team name", "Team name", team1.getName()); assertEquals("max players", 20, team1.getMaximumPlayers()); } @Test public void joinleft() { Team team = new Team(Color.RED, "name", 1); Player p = Mockito.mock(Player.class); team.addPlayer(p); assertTrue("player in team", team.contains(p)); team.removePlayer(p); assertFalse("player not in team", team.contains(p)); } }
945
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PexelCore.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/PexelCore.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore; import java.io.File; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.messaging.PluginMessageListener; import com.sun.net.httpserver.HttpServer; import eu.matejkormuth.pexel.PexelCore.areas.Areas; import eu.matejkormuth.pexel.PexelCore.bans.BanListServer; import eu.matejkormuth.pexel.PexelCore.bans.BanStorage; import eu.matejkormuth.pexel.PexelCore.commands.AlternativeCommands; import eu.matejkormuth.pexel.PexelCore.commands.ArenaCommand; import eu.matejkormuth.pexel.PexelCore.commands.BukkitCommandManager; import eu.matejkormuth.pexel.PexelCore.commands.ChannelCommand; import eu.matejkormuth.pexel.PexelCore.commands.CommandManager; import eu.matejkormuth.pexel.PexelCore.commands.FriendCommand; import eu.matejkormuth.pexel.PexelCore.commands.GateCommand; import eu.matejkormuth.pexel.PexelCore.commands.LobbyCommand; import eu.matejkormuth.pexel.PexelCore.commands.MatchmakingCommand; import eu.matejkormuth.pexel.PexelCore.commands.PCMDCommand; import eu.matejkormuth.pexel.PexelCore.commands.PartyCommand; import eu.matejkormuth.pexel.PexelCore.commands.QJCommand; import eu.matejkormuth.pexel.PexelCore.commands.SettingsCommand; import eu.matejkormuth.pexel.PexelCore.commands.SpawnCommand; import eu.matejkormuth.pexel.PexelCore.commands.UnfriendCommand; import eu.matejkormuth.pexel.PexelCore.core.Achievements; import eu.matejkormuth.pexel.PexelCore.core.Auth; import eu.matejkormuth.pexel.PexelCore.core.AutoMessage; import eu.matejkormuth.pexel.PexelCore.core.License; import eu.matejkormuth.pexel.PexelCore.core.Log; import eu.matejkormuth.pexel.PexelCore.core.MagicClock; import eu.matejkormuth.pexel.PexelCore.core.Scheduler; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; import eu.matejkormuth.pexel.PexelCore.core.UpdatedParts; import eu.matejkormuth.pexel.PexelCore.matchmaking.Matchmaking; import eu.matejkormuth.pexel.PexelCore.matchmaking.MatchmakingSignUpdater; import eu.matejkormuth.pexel.PexelCore.util.AsyncWorker; import eu.matejkormuth.pexel.PexelCore.util.PlayerFreezer; import eu.matejkormuth.pexel.PexelNetworking.PexelMasterServer; import eu.matejkormuth.pexel.PexelNetworking.PexelServerClient; /** * Bukkit plugin class. */ public class PexelCore extends JavaPlugin implements PluginMessageListener { /** * Pexel matchmaking. */ public Matchmaking matchmaking; /** * Player freezer. */ public PlayerFreezer freezer; /** * Eent processor. */ public EventProcessor eventProcessor; /** * Magic clock instance. */ public MagicClock magicClock; /** * AutoMessage instance. */ public AutoMessage message; /** * Master server instance. */ public PexelMasterServer pexelserver; /** * Master server client instance. */ public PexelServerClient pexelclient; /** * AsyncWorker object. */ public AsyncWorker asyncWorker; /** * Pexel auth object. */ public Auth auth; /** * Pexel scheduler object. */ public Scheduler scheduler; /** * Pexel command manager. */ public CommandManager commandManager; /** * Pexel Ban storage. */ public BanStorage banStorage; public BanListServer banListServer; public HttpServer serv; public Achievements achievementsClient; /** * Pexel matchmaking sign updater. */ public MatchmakingSignUpdater matchmakingSignUpdater; @SuppressWarnings("deprecation") @Override public void onDisable() { Log.partDisable("Core"); //Shutdown all updated parts. UpdatedParts.shutdown(); this.pexelserver.close(); this.banListServer.stop(); this.banStorage.save(); this.serv.stop(0); this.matchmakingSignUpdater.stop(); //Save important data. StorageEngine.saveData(); //oldway StorageEngine.saveArenas(); StorageEngine.saveProfiles(); this.asyncWorker.shutdown(); Log.partDisable("Core"); } @Override public void onEnable() { Log.partEnable("Core"); try { this.loadLibs(); } catch (MalformedURLException | ClassNotFoundException e1) { e1.printStackTrace(); } // Print license to console. License.print(); Pexel.initialize(this); this.createDirectoryStructure(); this.freezer = new PlayerFreezer(); this.scheduler = new Scheduler(); try { this.pexelserver = new PexelMasterServer(30789); this.pexelserver.listen(); this.banListServer = new BanListServer(); this.serv = HttpServer.create(new InetSocketAddress(35000), 50); this.serv.createContext("/games", new Matchmaking.Handler()); this.serv.setExecutor(null); this.serv.start(); } catch (Exception e) { } this.message = new AutoMessage(); this.message.updateStart(); this.banStorage = new BanStorage(); this.banStorage.load(); this.auth = new Auth(); this.matchmaking = new Matchmaking(); this.matchmaking.updateStart(); this.achievementsClient = new Achievements(); try { this.matchmakingSignUpdater = new MatchmakingSignUpdater(); } catch (Exception exc) { exc.printStackTrace(); } this.magicClock = new MagicClock(); this.asyncWorker = new AsyncWorker(3); this.asyncWorker.start(); this.eventProcessor = new EventProcessor(); // Bukkit way this.getCommand("arena").setExecutor(new ArenaCommand()); this.getCommand("friend").setExecutor(new FriendCommand()); this.getCommand("unfriend").setExecutor(new UnfriendCommand()); this.getCommand("settings").setExecutor(new SettingsCommand()); this.getCommand("party").setExecutor(new PartyCommand()); this.getCommand("lobbyarena").setExecutor(new LobbyCommand()); this.getCommand("qj").setExecutor(new QJCommand()); this.getCommand("spawn").setExecutor(new SpawnCommand()); this.getCommand("gate").setExecutor(new GateCommand()); this.getCommand("pcmd").setExecutor(new PCMDCommand()); // Pexel way this.commandManager = new BukkitCommandManager(); this.commandManager.registerCommands(new PartyCommand()); this.commandManager.registerCommands(new ChannelCommand()); this.commandManager.registerCommands(new MatchmakingCommand()); StorageEngine.initialize(this); StorageEngine.loadData(); Log.___prblm_stp(); new AlternativeCommands(); try { this.pexelclient = new PexelServerClient("127.0.0.1", 30789); } catch (Exception e) { } HardCoded.main(); try { new PNBroadcastServer(); } catch (Exception e) { e.printStackTrace(); Log.severe("PNB-Service: " + e.toString()); } Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", this); } private void loadLibs() throws MalformedURLException, ClassNotFoundException { Log.info("Loading external libraries..."); URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class<?>[] parameters = new Class[] { URL.class }; Class<?> sysclass = URLClassLoader.class; for (File f : new File(this.getDataFolder().getAbsolutePath() + "/libs").listFiles()) { try { Log.info("[P-LIBLOAD] Loading " + f.getAbsolutePath()); Method method = sysclass.getDeclaredMethod("addURL", parameters); method.setAccessible(true); method.invoke(sysloader, new Object[] { f.toURI().toURL() }); } catch (Throwable t) { t.printStackTrace(); Log.severe("Error, could not add URL (" + f.getAbsolutePath() + ") to system classloader"); } } } private void createDirectoryStructure() { boolean created = false; String path = this.getDataFolder().getAbsolutePath(); created |= new File(path + "/arenas").mkdirs(); created |= new File(path + "/cache").mkdirs(); created |= new File(path + "/records").mkdirs(); created |= new File(path + "/profiles").mkdirs(); created |= new File(path + "/clips").mkdirs(); if (created) Log.info("Directory structure expanded!"); } @Override public List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { if (command.getName().equalsIgnoreCase("arena")) if (sender instanceof Player) if (args.length == 1) if (args[0] == "edit") return Arrays.asList(Areas.findArea( ((Player) sender).getLocation()).getName()); return null; } @Override public void onPluginMessageReceived(final String channel, final Player player, final byte[] payload) { // Nothing for now... } }
11,082
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
EventProcessor.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/EventProcessor.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore; import java.util.Arrays; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.block.Sign; import org.bukkit.entity.EntityType; import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; import org.bukkit.entity.Snowball; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockGrowEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPortalEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.util.Vector; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import eu.matejkormuth.pexel.PexelCore.animations.EntityAnimationPlayer; import eu.matejkormuth.pexel.PexelCore.animations.ParticleAnimation; import eu.matejkormuth.pexel.PexelCore.animations.ParticleFrame; import eu.matejkormuth.pexel.PexelCore.areas.AreaFlag; import eu.matejkormuth.pexel.PexelCore.areas.Areas; import eu.matejkormuth.pexel.PexelCore.areas.ProtectedArea; import eu.matejkormuth.pexel.PexelCore.bans.BanUtils; import eu.matejkormuth.pexel.PexelCore.chat.ChatManager; import eu.matejkormuth.pexel.PexelCore.chat.SubscribeMode; import eu.matejkormuth.pexel.PexelCore.core.Log; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; import eu.matejkormuth.pexel.PexelCore.menu.InventoryMenu; import eu.matejkormuth.pexel.PexelCore.util.Lang; import eu.matejkormuth.pexel.PexelCore.util.ParticleEffect2; import eu.matejkormuth.pexel.PexelNetworking.Server; /** * Event processor for pexel. * * @author Mato Kormuth * */ public class EventProcessor implements Listener { public EventProcessor() { Bukkit.getPluginManager().registerEvents(this, Pexel.getCore()); } @EventHandler private void onPlayerMove(final PlayerMoveEvent event) { // FIXME: Temporarly removed. if (event.getPlayer().isSprinting()) { if (StorageEngine.getProfile(event.getPlayer().getUniqueId()) .getParticleType() != null) { for (double i = 0; i < 1.5; i += 0.20D) { Location diff = event.getTo() .subtract(event.getFrom()) .multiply(1.2F); //StorageEngine.getProfile(event.getPlayer().getUniqueId()) // .getParticleType() // .display( // event.getFrom().subtract(diff).clone().add(0, i, 0), // 0.50F, 0.20F, 0.50F, 1, 8); } } } } @EventHandler private void onVehicleDestroyed(final EntityDamageByEntityEvent event) { if (event.getEntity() instanceof Minecart) { ProtectedArea area = Areas.findArea(event.getEntity().getLocation()); if (area != null) { if (event.getDamager() instanceof Player) { if (!((Player) event.getDamager()).isOp()) { event.setCancelled(true); } } } } } @EventHandler private void onVehicleMove(final VehicleMoveEvent event) { if (event.getVehicle() instanceof Minecart) { //ProtectedArea area = Areas.findArea(event.getVehicle().getLocation()); } } @EventHandler private void onGrow(final BlockGrowEvent event) { ProtectedArea area = Areas.findArea(event.getBlock().getLocation()); if (area != null) { event.setCancelled(true); } } @EventHandler private void onBlockBreak(final BlockBreakEvent event) { if (!this.hasPermission(event.getBlock().getLocation(), event.getPlayer(), AreaFlag.BLOCK_BREAK)) event.setCancelled(true); } @EventHandler private void onPlayerRespawn(final PlayerRespawnEvent event) { event.getPlayer().teleport(Pexel.getHubLocation()); } @EventHandler private void onBlockPlace(final BlockPlaceEvent event) { if (!this.hasPermission(event.getBlock().getLocation(), event.getPlayer(), AreaFlag.BLOCK_PLACE)) event.setCancelled(true); } @EventHandler private void onPlayerDropItem(final PlayerDropItemEvent event) { if (!this.hasPermission(event.getPlayer().getLocation(), event.getPlayer(), AreaFlag.PLAYER_DROPITEM)) event.setCancelled(true); } @EventHandler private void onPlayerDamageByEntity(final EntityDamageByEntityEvent event) { if (event.getEntity() instanceof Player) if (!this.hasPermission(event.getEntity().getLocation(), (Player) event.getEntity(), AreaFlag.PLAYER_GETDAMAGE)) event.setCancelled(true); if (event.getDamager() instanceof Player) if (!this.hasPermission(event.getDamager().getLocation(), (Player) event.getDamager(), AreaFlag.PLAYER_DODAMAGE)) event.setCancelled(true); } @EventHandler private void onPlayerDamageByBlock(final EntityDamageByBlockEvent event) { if (event.getEntity() instanceof Player) if (!this.hasPermission(event.getEntity().getLocation(), (Player) event.getEntity(), AreaFlag.PLAYER_GETDAMAGE)) event.setCancelled(true); } @EventHandler private void onPlayerDamage(final EntityDamageEvent event) { if (event.getEntity() instanceof Player) if (!this.hasPermission(event.getEntity().getLocation(), (Player) event.getEntity(), AreaFlag.PLAYER_GETDAMAGE)) event.setCancelled(true); } @SuppressWarnings("deprecation") @EventHandler private void onPlayerInteract(final PlayerInteractEvent event) { if (event.getClickedBlock() != null) { if (event.getClickedBlock().getType() == Material.SIGN || event.getClickedBlock().getType() == Material.SIGN_POST) { if (event.getPlayer().isOp() && event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK || !event.getPlayer().isOp()) { Sign sign = (Sign) event.getClickedBlock().getState(); String[] lines = sign.getLines(); if (lines.length > 1) { String command = lines[0].trim(); if (command.equalsIgnoreCase("[Server]")) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect"); out.writeUTF(lines[1]); event.getPlayer().sendPluginMessage(Pexel.getCore(), "BungeeCord", out.toByteArray()); } else if (command.equalsIgnoreCase("[Warp]")) { event.getPlayer().performCommand("warp " + lines[1]); } else if (command.equalsIgnoreCase("[Matchmaking]")) { Pexel.getMatchmakingSignUpdater().addSign( event.getClickedBlock()); Pexel.getMatchmaking().processSign(lines, event.getPlayer()); } else if (command.equalsIgnoreCase("[World]")) { World w = Bukkit.getWorld(lines[1]); if (w == null) event.getPlayer() .sendMessage( ChatManager.error(Lang.getTranslation("worldnotfound"))); else event.getPlayer().teleport(w.getSpawnLocation()); } } } } } if (event.getItem() != null) { if (event.getItem().hasItemMeta() && event.getItem() .getItemMeta() .getDisplayName() .equalsIgnoreCase("gun")) { event.getPlayer() .getWorld() .playSound(event.getPlayer().getLocation(), Sound.IRONGOLEM_HIT, 0.5F, 3F); Vector smer = event.getPlayer() .getEyeLocation() .getDirection() .normalize(); Snowball projectile = (Snowball) event.getPlayer() .getWorld() .spawnEntity( event.getPlayer().getEyeLocation().add(smer.multiply(2)), EntityType.SNOWBALL); projectile.setVelocity(smer.multiply(2)); projectile.remove(); Vector pos = event.getPlayer() .getLocation() .toVector() .add(new Vector(0, 1.62, 0)); smer.multiply(1.1F); Location loc = pos.add(smer).toLocation(event.getPlayer().getWorld()); for (int i = 0; i < 500; i++) { loc = pos.add(smer).toLocation(event.getPlayer().getWorld()); if (loc.getBlock() != null && loc.getBlock().getType().isSolid()) { //PacketPlayOutBlockBreakAnimation packet = new PacketPlayOutBlockBreakAnimation( /// 1000 + Pexel.getRandom().nextInt(100), loc.getBlockX(), /// loc.getBlockY(), loc.getBlockZ(), /// 1 + Pexel.getRandom().nextInt(5)); for (Player p : Bukkit.getOnlinePlayers()) { //PacketHelper.send(p, packet); }// //ParticleEffect.displayBlockCrack(loc, // loc.getBlock().getTypeId(), loc.getBlock().getData(), // 0.3F, 0.3F, 0.3F, 1, 50); //ParticleEffect.FIREWORKS_SPARK.display(loc, 0, 0, 0, 1, 1); break; } //ParticleEffect.FIREWORKS_SPARK.display(loc, 0, 0, 0, 0, 1); } } } } @EventHandler private void onPlayerPortal(final PlayerPortalEvent event) { // Pass the event further... StorageEngine.gateEnter(event.getPlayer(), event.getPlayer().getLocation()); } @EventHandler private void onChat(final AsyncPlayerChatEvent event) { ChatManager.__processChatEvent(event); /* * if (event.getPlayer().isOp()) event.setFormat(ChatManager.chatPlayerOp(event.getMessage(), * event.getPlayer())); else event.setFormat(ChatManager.chatPlayer(event.getMessage(), event.getPlayer())); */ } @EventHandler private void onInventoryClick(final InventoryClickEvent event) { if (event.getInventory().getHolder() instanceof InventoryMenu) { if (event.getWhoClicked() instanceof Player) { ((InventoryMenu) event.getInventory().getHolder()).inventoryClick( (Player) event.getWhoClicked(), event.getSlot()); event.setCancelled(true); if (((InventoryMenu) event.getInventory().getHolder()).shouldClose(event.getSlot())) { event.getView().close(); } } } } @EventHandler private void onPlayerLogin(final PlayerLoginEvent event) { // Check for ban if (Pexel.getBans().isBanned(event.getPlayer(), Server.THIS_SERVER)) { event.disallow( Result.KICK_BANNED, BanUtils.formatBannedMessage(Pexel.getBans().getBan( event.getPlayer(), Server.THIS_SERVER))); } if (event.getHostname().contains("login")) Pexel.getAuth().authenticateIp(event.getPlayer(), event.getHostname()); if (event.getPlayer().getName().equalsIgnoreCase("dobrakmato")) { ParticleAnimation animation = new ParticleAnimation(); double x = 0; double y = 0; for (int i = 0; i < 20; i++) { x = Math.sin(i / 3.14F); y = Math.cos(i / 3.14F); Log.info("Generated frame X:" + x + ", Y:" + y); animation.addFrame(new ParticleFrame( Arrays.asList(new ParticleFrame.Particle(x, 2.5, y, ParticleEffect2.HEART)))); } EntityAnimationPlayer player = new EntityAnimationPlayer(animation, event.getPlayer(), true); player.play(); } } @EventHandler private void onPlayerJoin(final PlayerJoinEvent event) { // Load profile to memory or create empty profile. StorageEngine.loadProfile(event.getPlayer().getUniqueId()); // Register chat channels. ChatManager.CHANNEL_GLOBAL.subscribe(event.getPlayer(), SubscribeMode.READ); ChatManager.CHANNEL_LOBBY.subscribe(event.getPlayer(), SubscribeMode.READ_WRITE); } @EventHandler private void onPlayerLeave(final PlayerQuitEvent event) { // Leave party. if (StorageEngine.getProfile(event.getPlayer().getUniqueId()).getParty() != null) { StorageEngine.getProfile(event.getPlayer().getUniqueId()) .getParty() .removePlayer(event.getPlayer()); StorageEngine.getProfile(event.getPlayer().getUniqueId()).setParty(null); } // Leave chat channels. ChatManager.CHANNEL_GLOBAL.unsubscribe(event.getPlayer()); ChatManager.CHANNEL_LOBBY.unsubscribe(event.getPlayer()); StorageEngine.__redirectEvent("PlayerQuitEvent", event); // Force save of player's profile. StorageEngine.saveProfile(event.getPlayer().getUniqueId()); } private boolean hasPermission(final Location location, final Player player, final AreaFlag flag) { ProtectedArea area = Areas.findArea(location); if (area != null) { if (!area.getPlayerFlag(flag, player.getUniqueId())) { // if (area.getPlayerFlag(AreaFlag.AREA_CHAT_PERMISSIONDENIED, // player.getUniqueId())) player.getPlayer().sendMessage( ChatManager.error("You don't have permission for '" + flag.toString() + "' in this area!")); return false; } return true; } return true; } }
16,539
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PNBroadcastServer.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/PNBroadcastServer.java
package eu.matejkormuth.pexel.PexelCore; import java.net.InetSocketAddress; import java.net.UnknownHostException; import org.java_websocket.WebSocket; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import eu.matejkormuth.pexel.PexelCore.chat.ChannelSubscriber; import eu.matejkormuth.pexel.PexelCore.chat.ChatManager; import eu.matejkormuth.pexel.PexelCore.chat.SubscribeMode; import eu.matejkormuth.pexel.PexelCore.core.Log; public class PNBroadcastServer { private final PNBSubscriber subscriber; private PNBWebSocketServer websockserv; public PNBroadcastServer() { Log.partEnable("PNBService"); this.subscriber = new PNBSubscriber(); ChatManager.CHANNEL_NETWORK.subscribe(this.subscriber); try { this.websockserv = new PNBWebSocketServer(); this.websockserv.start(); } catch (UnknownHostException e) { e.printStackTrace(); this.websockserv = null; } } public void broadcast(final String message) { try { for (WebSocket ws : this.websockserv.connections()) { ws.send(message); } } catch (Exception e) { Log.severe("[PNB] Cannot broadcast: " + e.toString()); } } class PNBSubscriber implements ChannelSubscriber { @Override public void sendMessage(final String message) { PNBroadcastServer.this.broadcast(message); } @Override public SubscribeMode getMode() { return SubscribeMode.READ; } @Override public boolean isOnline() { return true; } @Override public String getName() { return "PNBroadcastService"; } } class PNBWebSocketServer extends WebSocketServer { public PNBWebSocketServer() throws UnknownHostException { super(new InetSocketAddress(8877)); Log.partEnable("PNBService-WebSocketServer"); } @Override public void onClose(final WebSocket arg0, final int arg1, final String arg2, final boolean arg3) { Log.info("[PNBWS] Client " + arg0.getRemoteSocketAddress().getHostString() + " disconnected (" + arg1 + ") [" + arg2 + "]"); } @Override public void onError(final WebSocket arg0, final Exception arg1) { Log.severe("[PNBWS] ws: " + arg0.getRemoteSocketAddress().toString() + "; " + arg1.toString()); } @Override public void onMessage(final WebSocket arg0, final String arg1) { Log.info("Received message from " + arg0.getRemoteSocketAddress().getHostString() + "; cont: " + arg1); if (arg1.equalsIgnoreCase("command requestall")) { } else { arg0.send("Bad request! Can't respond!"); } } @Override public void onOpen(final WebSocket arg0, final ClientHandshake arg1) { //does nothing Log.info("[PNBWS] Client " + arg0.getRemoteSocketAddress().getHostString() + " has connected!"); arg0.send("Welcome! Current time: " + System.currentTimeMillis()); } } }
3,469
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
HardCoded.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/HardCoded.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore; import java.io.File; import java.util.UUID; import javax.xml.bind.JAXBException; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import eu.matejkormuth.pexel.PexelCore.actions.CommandAction; import eu.matejkormuth.pexel.PexelCore.actions.TeleportAction; import eu.matejkormuth.pexel.PexelCore.areas.AreaFlag; import eu.matejkormuth.pexel.PexelCore.areas.Lobby; import eu.matejkormuth.pexel.PexelCore.arenas.MapData; import eu.matejkormuth.pexel.PexelCore.core.Achievement; import eu.matejkormuth.pexel.PexelCore.core.Region; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; import eu.matejkormuth.pexel.PexelCore.core.TeleportGate; import eu.matejkormuth.pexel.PexelCore.util.SerializableLocation; import eu.matejkormuth.pexel.PexelNetworking.Server; /** * Class where is all hard coded stuff stored. * * @author Mato Kormuth * */ public class HardCoded { public static Vector antigravity = new Vector(0, 0.2F, 0); /** * Main method called from Plugin.onEnable() */ @SuppressWarnings("deprecation") public static final void main() { //Initialize color war mingiame //new ColorWarMinigame(); //Initialize zabi pitkesa minigame //new ZabiPitkesaMinigame(); //new TntTagMinigame(); //new KingdomWarsMingame(); /* * Pexel.getBans().addBan( new PlayerBan("nemam sa rad", new NamedBanAuthor("dobrakmato"), (Player) * Bukkit.getOfflinePlayer("test"), Server.THIS_SERVER)); * * Pexel.getBans().addBan( new PlayerBan(100000, "dementy dvodod", new NamedBanAuthor("dement"), (Player) * Bukkit.getOfflinePlayer("test2"), Server.THIS_SERVER)); * * Pexel.getBans().addBan( new PlayerBan(45000, "test", new NamedBanAuthor("dobrakmato"), (Player) * Bukkit.getOfflinePlayer("DeathlNom"), Server.THIS_SERVER)); */ // Test XML class SampleArenaMap extends MapData { public SampleArenaMap() { super("Sample map", "dobrakmato"); this.name = "sampleMap"; this.minigameName = "sampleMinigame"; this.locations.put("loc1", new SerializableLocation(Pexel.getHubLocation())); this.locations.put("testloc", SerializableLocation.fromLocation(new Location( Bukkit.getWorld("world"), 16, 32, 64))); this.options_string.put("option1", "yes"); this.options_string.put("option2", "yes"); this.options_string.put("option3", "no"); this.options_int.put("option4", 225); this.regions.put("region_one", new Region(new Vector(5, 10, 88), new Vector(50, 50, 70), Bukkit.getWorld("world"))); this.init(16, 4, 60, new Location(Bukkit.getWorld("world"), 11, 22, 33), this.regions.get("region_one")); } } try { new SampleArenaMap().save(new File(Pexel.getCore() .getDataFolder() .getAbsolutePath() + "/sampleMap.xml")); } catch (JAXBException e) { e.printStackTrace(); } //Initialize main gates initGates(); //Initialize lobbies initLobbies(); //Initialize achievements initAchievements(); // Gravity change Bukkit.getScheduler().scheduleSyncRepeatingTask(Pexel.getCore(), new Runnable() { @Override public void run() { for (Entity e : Bukkit.getWorld("space").getEntities()) { if (!e.isOnGround()) { if (e instanceof Player) { if (!((Player) e).isFlying()) { e.setVelocity(e.getVelocity().add(HardCoded.antigravity)); } } e.setVelocity(e.getVelocity().add(HardCoded.antigravity)); } } } }, 0L, 1L); } private static void initAchievements() { Pexel.getAchievements().registerAchievement( Achievement.global("allgames", "Tester", "Play all minigames on network!", 1)); } private static void initLobbies() { StorageEngine.addLobby(new Lobby("hub", new Region(new Vector(52, 107, 226), new Vector(-30, 1, 303), Bukkit.getWorld("world")))); StorageEngine.getLobby("hub").setThresholdY(10); //dobrakmato - block interactions StorageEngine.getLobby("hub").setPlayerFlag(AreaFlag.BLOCK_BREAK, true, UUID.fromString("966ad920-d45e-3fe5-8956-bf7a7a877ab4")); StorageEngine.getLobby("hub").setPlayerFlag(AreaFlag.BLOCK_PLACE, true, UUID.fromString("966ad920-d45e-3fe5-8956-bf7a7a877ab4")); StorageEngine.addLobby(new Lobby("minigamelobby", new Region(new Vector(2038, 0, 2571), new Vector(1910, 255, 2437), Bukkit.getWorld("world")))); StorageEngine.getLobby("minigamelobby").setSpawn( new Location(Bukkit.getWorld("world"), 1972.5, 148, 2492.5)); StorageEngine.getLobby("minigamelobby").setPlayerFlag(AreaFlag.BLOCK_BREAK, true, UUID.fromString("966ad920-d45e-3fe5-8956-bf7a7a877ab4")); StorageEngine.getLobby("minigamelobby").setPlayerFlag(AreaFlag.BLOCK_PLACE, true, UUID.fromString("966ad920-d45e-3fe5-8956-bf7a7a877ab4")); } private static void initGates() { StorageEngine.addGate("Lsurvival", new TeleportGate(new Region(new Vector(-7, 50, 258), new Vector(-9, 54, 264), Bukkit.getWorld("world")), new TeleportAction(null, new Server(null, "survival", "survival")))); StorageEngine.addGate("Lstarving", new TeleportGate(new Region(new Vector(26, 50, 266), new Vector(28, 55, 260), Bukkit.getWorld("world")), new TeleportAction(null, new Server(null, "starving", "starving")))); StorageEngine.addGate("Lminigame", new TeleportGate(new Region(new Vector(7, 50, 280), new Vector(13, 55, 282), Bukkit.getWorld("world")), new TeleportAction(new Location(Bukkit.getWorld("world"), 1972.5, 147.5, 2492.5), Server.THIS_SERVER))); //Initialize gates StorageEngine.addGate("mg_colorwar", new TeleportGate( new Region(new Vector(1976, 147, 2532), new Vector(1972, 153, 2534), Bukkit.getWorld("world")), new CommandAction("pcmd cwtest"))); StorageEngine.addGate("mg_tnttag", new TeleportGate(new Region(new Vector(1962, 147, 2532), new Vector(1967, 153, 2534), Bukkit.getWorld("world")), new CommandAction("pcmd tnttest"))); } }
8,183
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Pexel.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/Pexel.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore; import java.util.Random; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.bans.BanStorage; import eu.matejkormuth.pexel.PexelCore.core.Achievements; import eu.matejkormuth.pexel.PexelCore.core.Auth; import eu.matejkormuth.pexel.PexelCore.core.MagicClock; import eu.matejkormuth.pexel.PexelCore.core.PlayerProfile; import eu.matejkormuth.pexel.PexelCore.core.Scheduler; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; import eu.matejkormuth.pexel.PexelCore.core.ValidityChecker; import eu.matejkormuth.pexel.PexelCore.matchmaking.Matchmaking; import eu.matejkormuth.pexel.PexelCore.matchmaking.MatchmakingSignUpdater; import eu.matejkormuth.pexel.PexelCore.minigame.Minigame; import eu.matejkormuth.pexel.PexelCore.util.AsyncWorker; import eu.matejkormuth.pexel.PexelCore.util.PlayerFreezer; /** * Class used for API calls. */ public final class Pexel { //Pexel plugin. private static PexelCore instance; //Instance of random. private static Random random = new Random(); protected final static void initialize(final PexelCore plugin) { if (Pexel.instance == null) Pexel.instance = plugin; else throw new RuntimeException("Pexel object already initialized!"); } /** * Returns the main plugin instance. * * @return core */ public static final PexelCore getCore() { return Pexel.instance; } /** * Returns Matchmaking class. * * @return matchmaking */ public static final Matchmaking getMatchmaking() { return Pexel.instance.matchmaking; } /** * Returns {@link Achievements} class. * * @return achievements */ public static final Achievements getAchievements() { return Pexel.instance.achievementsClient; } /** * Returns player freezer. * * @return player freezer */ public static final PlayerFreezer getPlayerFreezer() { return Pexel.instance.freezer; } /** * Retruns player's profile. * * @param player * @return profile of specified player */ public PlayerProfile getProfile(final Player player) { return StorageEngine.getProfile(player.getUniqueId()); } /** * Retruns player's profile. * * @param player * @return profile of specified player */ public PlayerProfile getProfile(final UUID player) { return StorageEngine.getProfile(player); } /** * Returns instance of {@link Random}. * * @return pexel's {@link Random}. */ public final static Random getRandom() { return Pexel.random; } /** * Returns event processor. * * @return {@link EventProcessor} instance. */ public final static EventProcessor getEventProcessor() { return Pexel.instance.eventProcessor; } /** * Returns pexel's magic clock class. * * @return {@link MagicClock} instance. */ public final static MagicClock getMagicClock() { return Pexel.instance.magicClock; } /** * Returns pexel's async wokrer instance. * * @return {@link AsyncWorker} instance. */ public final static AsyncWorker getAsyncWorker() { return Pexel.instance.asyncWorker; } /** * Return's hub location. * * @return hub lcoation */ public final static Location getHubLocation() { return new Location(Bukkit.getWorld("Minigame"), -1983, 50.5, 489.5); } /** * Returns pexel's async wokrer instance. * * @return {@link Auth} instance. */ public final static Auth getAuth() { return Pexel.instance.auth; } /** * Returns pexel's scheduler instance. * * @return {@link Scheduler} instance. */ public final static Scheduler getScheduler() { return Pexel.instance.scheduler; } /** * @return Ban storage */ public final static BanStorage getBans() { return Pexel.instance.banStorage; } /** * */ public static MatchmakingSignUpdater getMatchmakingSignUpdater() { return Pexel.instance.matchmakingSignUpdater; } /** * Registers minigame to Pexel. * * @param minigame * specififed minigame to register. */ public static final void registerMinigame(final Minigame minigame) { ValidityChecker.checkMinigame(minigame); StorageEngine.addMinigame(minigame); Pexel.getMatchmaking().registerMinigame(minigame); } /** * Tries to register specified object to Pexel. If can't register object, throws RuntimeException. * * @param obj */ public static final void register(final Object obj) { if (obj instanceof Minigame) { Pexel.registerMinigame((Minigame) obj); } else { throw new IllegalArgumentException("Type " + obj.getClass().getSimpleName() + " is not type, that is supported by Pexel."); } } }
6,140
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
InventoryMenu.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/menu/InventoryMenu.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.menu; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import eu.matejkormuth.pexel.PexelCore.actions.Action; import eu.matejkormuth.pexel.PexelCore.core.Log; import eu.matejkormuth.pexel.PexelCore.util.ItemUtils; /** * Class used for Inventory Menu. * * @author Mato Kormuth * */ public class InventoryMenu implements InventoryHolder { /** * Inventory of this menu. */ private final Inventory inventory; /** * Items in inventory. */ private final Map<Integer, InventoryMenuItem> items = new HashMap<Integer, InventoryMenuItem>(); /** * Creates new Inventory menu object with specified type of inventory, title and list of items. * * @see InventoryMenuItem * @see Action * @see ItemUtils * * @param type * type of inventory * @param title * title of inventory * @param items * items */ public InventoryMenu(final InventoryType type, final String title, final List<InventoryMenuItem> items) { for (InventoryMenuItem item : items) if (!this.items.containsKey(item.getSlot())) this.items.put(item.getSlot(), item); else throw new RuntimeException("Can't put " + item.getItemStack().toString() + " to slot " + item.getSlot() + "! Slot " + item.getSlot() + " is alredy occupied by " + this.items.get(item.getSlot()).getItemStack().toString()); this.inventory = Bukkit.createInventory(this, type, title); for (InventoryMenuItem item : this.items.values()) this.inventory.setItem(item.getSlot(), item.getItemStack()); } /** * * Creates new Inventory menu object with specified size of inventory, title and list of items. * * @param size * size of inventory * @param title * inventory title * @param items * items */ public InventoryMenu(final int size, final String title, final List<InventoryMenuItem> items) { for (InventoryMenuItem item : items) if (!this.items.containsKey(item.getSlot())) this.items.put(item.getSlot(), item); else throw new RuntimeException("Can't put " + item.getItemStack().toString() + " to slot " + item.getSlot() + "! Slot " + item.getSlot() + " is alredy occupied by " + this.items.get(item.getSlot()).getItemStack().toString()); this.inventory = Bukkit.createInventory(this, size, title); for (InventoryMenuItem item : this.items.values()) this.inventory.setItem(item.getSlot(), item.getItemStack()); } /** * Opens this inventory menu to specified player. * * @param player * player to show menu to */ public void showTo(final Player player) { player.openInventory(this.getInventory()); } /** * Same as calling {@link InventoryMenu#showTo(Player)}. * * @see InventoryMenu#showTo(Player) * * @param player * player to show menu to */ public void openInventory(final Player player) { player.openInventory(this.getInventory()); } @Override public Inventory getInventory() { return this.inventory; } /** * Returns true, if the menu should be closed after the item in specified slot is clicked. * * @param slot * @return whether the inventory should close after click */ public boolean shouldClose(final int slot) { return this.items.get(slot).isCloseAfterClick(); } /** * Called when somebody clicks item in this inventory. * * @param player * @param item */ public void inventoryClick(final Player player, final int slot) { if (this.items.containsKey(slot)) { this.items.get(slot).executeAction(player); } else { Log.warn("Player '" + player + "' clicked on invalid item at slot '" + slot + "' in inventoryMenu!"); } } }
5,417
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
InventoryMenuItem.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/menu/InventoryMenuItem.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.menu; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import eu.matejkormuth.pexel.PexelCore.actions.Action; /** * Class that represents item in inventory menu. * * @author Mato Kormuth * */ public class InventoryMenuItem { /** * ItemStack of item. */ private final ItemStack item; /** * Action to execute when item is clicked. */ private final Action action; /** * Slot of inventory. */ private final int slot; /** * Specifies if the InventoryMenu have to close, after click. */ private final boolean closeAfterClick; /** * Creates new Inventory menu item from specified params. * * @param item * itemstack to use as icon. * @param action * action to execute when player clicks icon. * @param slot * slot in inventory, where the itemstack should be. * @param closeAfterClick * boolean, that specify, if the menu should close after click on this item. */ public InventoryMenuItem(final ItemStack item, final Action action, final int slot, final boolean closeAfterClick) { this.item = item; this.action = action; this.slot = slot; this.closeAfterClick = closeAfterClick; } /** * Executes action with specified player(sender). * * @param player * player that is task executed */ public void executeAction(final Player player) { this.action.execute(player); } /** * Returns bukkit compactibile ItemStack of this menu item. * * @return item stack */ public ItemStack getItemStack() { return this.item; } /** * Returns slot in minecraft inventory. * * @return id of slot */ public int getSlot() { return this.slot; } /** * Returns if the menu should close after click. */ public boolean isCloseAfterClick() { return this.closeAfterClick; } }
2,969
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ParticleAnimation.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/animations/ParticleAnimation.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.animations; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; public class ParticleAnimation implements Animation, Serializable { private static final long serialVersionUID = 5147694021142531376L; private final ArrayList<ParticleFrame> frames = new ArrayList<ParticleFrame>(); private final int framerate = 20; @Override public ParticleFrame getFrame(final int index) { return this.frames.get(index); } @Override public int getFramerate() { return this.framerate; } @Override public int getFrameCount() { return this.frames.size(); } public void addFrame(final ParticleFrame frame) { this.frames.add(frame); } public void addFrames(final Collection<? extends ParticleFrame> frames) { this.frames.addAll(frames); } }
1,804
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
EntityAnimationPlayer.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/animations/EntityAnimationPlayer.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.animations; import org.bukkit.entity.Entity; import eu.matejkormuth.pexel.PexelCore.util.BukkitTimer; public class EntityAnimationPlayer implements Runnable { private final Animation animation; private int currentFrame = 0; private int frameCount = 0; private BukkitTimer timer; private final Entity entity; private boolean repeating = false; public EntityAnimationPlayer(final Animation animation, final Entity entity, final boolean repeating) { this.repeating = repeating; this.animation = animation; this.entity = entity; this.frameCount = animation.getFrameCount(); } public void play() { this.timer = new BukkitTimer(1, this); this.timer.start(); } private void animate() { if (this.entity.isDead()) { this.timer.stop(); } if (this.currentFrame < this.frameCount) { this.animation.getFrame(this.currentFrame).play(this.entity.getLocation()); this.currentFrame++; } else { if (!this.repeating) { this.timer.stop(); } else { this.currentFrame = 0; } } } @Override public void run() { this.animate(); } }
2,240
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ParticleFrame.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/animations/ParticleFrame.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.animations; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.bukkit.Location; import eu.matejkormuth.pexel.PexelCore.util.ParticleEffect2; public class ParticleFrame implements Frame, Collection<ParticleFrame.Particle>, Serializable { private static final long serialVersionUID = 9092949433218439382L; private final Collection<ParticleFrame.Particle> particles; public ParticleFrame(final Collection<ParticleFrame.Particle> particles) { this.particles = particles; } public static class Particle implements Serializable { private static final long serialVersionUID = -2811955923388046769L; public double relX; public double relY; public double relZ; public ParticleEffect2 type; public Particle(final double relX, final double relY, final double relZ, final ParticleEffect2 type) { super(); this.relX = relX; this.relY = relY; this.relZ = relZ; this.type = type; } public void play(final Location loc) { //this.type.display(loc.add(this.relX, this.relY, this.relZ), 0, 0, 0, 1, 1); } } @Override public void play(final Location loc) { for (Particle p : this.particles) { p.play(loc); } } @Override public int size() { return this.particles.size(); } @Override public boolean isEmpty() { return this.particles.isEmpty(); } @Override public boolean contains(final Object o) { return this.particles.contains(o); } @Override public Iterator<Particle> iterator() { return this.particles.iterator(); } @Override public Object[] toArray() { return this.particles.toArray(); } @Override public <T> T[] toArray(final T[] a) { return this.particles.toArray(a); } @Override public boolean add(final Particle e) { return this.particles.add(e); } @Override public boolean remove(final Object o) { return this.particles.remove(o); } @Override public boolean containsAll(final Collection<?> c) { return this.particles.containsAll(c); } @Override public boolean addAll(final Collection<? extends Particle> c) { return this.particles.addAll(c); } @Override public boolean removeAll(final Collection<?> c) { return this.particles.removeAll(c); } @Override public boolean retainAll(final Collection<?> c) { return this.particles.retainAll(c); } @Override public void clear() { this.particles.clear(); } }
3,772
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Animation.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/animations/Animation.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.animations; /** * Class that specifies animation. */ public interface Animation { /** * Get frame by number. * * @param number * id of frame * @return frame */ public Frame getFrame(int number); /** * Number of frames per second. * * @return fps */ public int getFramerate(); /** * Returns total amount of frames in this animation. * * @return num of frames */ public int getFrameCount(); }
1,377
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MovingAnimationPlayer.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/animations/MovingAnimationPlayer.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.animations; import org.bukkit.Location; import eu.matejkormuth.pexel.PexelCore.Pexel; import eu.matejkormuth.pexel.PexelCore.core.Scheduler.ScheduledTask; import eu.matejkormuth.pexel.PexelCore.util.MovingObject; public class MovingAnimationPlayer extends MovingObject implements Runnable { protected Animation animation; protected int currentFrame = 0; protected int frameCount = 0; protected ScheduledTask task; protected boolean repeating = false; public MovingAnimationPlayer(final Animation animation, final Location startLoc, final boolean repeating) { this.repeating = repeating; this.animation = animation; this.location = startLoc; this.frameCount = animation.getFrameCount(); } public void play() { this.task = Pexel.getScheduler().each(1L, this); } public Animation getAnimation() { return this.animation; } public int getCurrentFrame() { return this.currentFrame; } public boolean isRepeating() { return this.repeating; } protected void animateFrame() { if (this.currentFrame < this.frameCount) { this.animation.getFrame(this.currentFrame).play(this.location); this.currentFrame++; } else { if (!this.repeating) { Pexel.getScheduler().cancel(this.task); } else { this.currentFrame = 0; } } } @Override public void run() { this.animateFrame(); } }
2,497
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Frame.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/animations/Frame.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.animations; import org.bukkit.Location; /** * Frame in {@link Animation}. */ public interface Frame { public void play(Location loc); }
1,009
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MatchmakingGame.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/matchmaking/MatchmakingGame.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.matchmaking; import java.util.List; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.arenas.DisconnectReason; /** * Specifies that the object is game participating in matchmaking. * * @author Mato Kormuth * */ public interface MatchmakingGame { /** * Returns number of free slots in the game. * * @return free slots count */ public int getFreeSlots(); /** * Returns number of all slots in game. * * @return all slots count. */ public int getMaximumSlots(); /** * Returns game actual state. * * @return state of arena */ public GameState getState(); /** * Returns list of players in game. * * @return */ public List<Player> getPlayers(); /** * Returns number of player in game. * * @return number of players in arena */ public int getPlayerCount(); /** * Returns if one player can join game. * * @return true or false */ public boolean canJoin(); /** * Returns if specified amount of players can join game. * * @param count * amount of players * @return true or false */ public boolean canJoin(int count); /** * Called when player joins the game. * * @param player * player who joined arena */ public void onPlayerJoin(Player player); /** * Called when player lefts the game. * * @param player * player who left arena */ public void onPlayerLeft(Player player, DisconnectReason reason); }
2,541
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
GameState.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/matchmaking/GameState.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.matchmaking; /** * Specifies minigame's current state. * * @author Mato Kormuth * */ public enum GameState { /** * Game state when game is operational and is not empty and it's avaiting more players to start game. */ WAITING_PLAYERS(false, true), /** * Game state when game is operational but it's empty. */ WAITING_EMPTY(false, true), /** * Game state, when game is runnning, but players can join in mid-game. */ PLAYING_CANJOIN(true, true), /** * Game sate, when game is running, but no more players can join the running game. */ PLAYING_CANTJOIN(true, false), /** * Game state, when game is reseting it's arena, thus is not operational. */ RESETING(false, false), /** * Game state, when game is not operational at all. */ DISABLED(false, false); private boolean playing; private boolean canjoin; private GameState(final boolean playing, final boolean canjoin) { this.playing = playing; this.canjoin = canjoin; } /** * Returns whether this state menas that arena is in playing state. * * @return true or false */ public boolean isPlaying() { return this.playing; } /** * Returns if this state allows joining players. * * @return true or false */ public boolean canJoin() { return this.canjoin; } }
2,315
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MatchmakingRequest.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/matchmaking/MatchmakingRequest.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.matchmaking; import java.util.Arrays; import java.util.List; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.minigame.Minigame; /** * Request for matchmaking. * * @author Mato Kormuth * */ public class MatchmakingRequest { /** * List of player in request. */ private final List<Player> players; /** * The minigame that the players want to play. */ private final Minigame minigame; /** * Arena that players want to play. */ private final MatchmakingGame game; /** * Number of tries to find match. */ public int tries = 0; public MatchmakingRequest(final List<Player> players, final Minigame minigame, final MatchmakingGame game) { this.players = players; this.minigame = minigame; this.game = game; } /** * Creates new request with random game and arena. * * @param player * player */ public static MatchmakingRequest create(final Player player) { return new MatchmakingRequest(Arrays.asList(player), null, null); } /** * Creates new request with random game and arena. * * @param player * players */ public static MatchmakingRequest create(final Player... player) { return new MatchmakingRequest(Arrays.asList(player), null, null); } /** * Creates new request with specified game and random arena. * * @param player * player */ public static MatchmakingRequest create(final Player player, final Minigame minigame) { return new MatchmakingRequest(Arrays.asList(player), minigame, null); } /** * Creates new request with specified game and random arena. * * @param player * players */ public static MatchmakingRequest create(final Minigame minigame, final Player... player) { return new MatchmakingRequest(Arrays.asList(player), minigame, null); } /** * Returns list of players in this request. */ public List<Player> getPlayers() { return this.players; } /** * Returns minigame of this request. */ public Minigame getMinigame() { return this.minigame; } /** * Returns arena of this request. */ public MatchmakingGame getGame() { return this.game; } /** * Returns player count in this request. */ public int playerCount() { return this.players.size(); } }
3,504
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MatchmakingSignUpdater.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/matchmaking/MatchmakingSignUpdater.java
package eu.matejkormuth.pexel.PexelCore.matchmaking; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.Sign; import eu.matejkormuth.pexel.PexelCore.Pexel; import eu.matejkormuth.pexel.PexelCore.arenas.AbstractArena; import eu.matejkormuth.pexel.PexelCore.core.Log; import eu.matejkormuth.pexel.PexelCore.core.Paths; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; import eu.matejkormuth.pexel.PexelCore.minigame.Minigame; import eu.matejkormuth.pexel.PexelCore.util.BukkitTimer; /** * Sign updater. */ public class MatchmakingSignUpdater implements Runnable { // Listo of cached signs. private final List<Block> cachedSigns = new ArrayList<Block>(); // Timer for updates. private final BukkitTimer timer = new BukkitTimer(20, this); public MatchmakingSignUpdater() { Log.partEnable("MatchmakingSignUpdater"); this.loadCache(); this.timer.start(); } public void stop() { Log.partDisable("MatchmakingSignUpdater"); this.timer.stop(); this.save(); } private void save() { try { Log.info("[MatchmakingSignUpdater] Saving cache..."); BufferedWriter bw = new BufferedWriter(new FileWriter(new File( Paths.msuCache()))); for (Block b : this.cachedSigns) { bw.append(b.getLocation().getWorld().getName() + "|" + b.getLocation().getBlockX() + "|" + b.getLocation().getBlockY() + "|" + b.getLocation().getBlockZ() + "\n"); } Log.info("[MatchmakingSignUpdater] Saved " + this.cachedSigns.size() + " blocks!"); bw.close(); } catch (IOException e) { e.printStackTrace(); } } public void addSign(final Block b) { if (((Sign) b.getState()).getLine(2).equalsIgnoreCase("")) { this.cachedSigns.add(b); } else { Log.severe("Can't register block " + b.toString() + " as matchmaking sign. Line 3 (2) is not empty."); } } private void loadCache() { Log.info("[MatchmakingSignUpdater] Loading cache..."); try { BufferedReader br = new BufferedReader(new FileReader(new File( Paths.msuCache()))); String line = null; while ((line = br.readLine()) != null) { String[] elems = line.split("\\|"); World w = Bukkit.getWorld(elems[0]); this.cachedSigns.add(w.getBlockAt(Integer.parseInt(elems[1]), Integer.parseInt(elems[2]), Integer.parseInt(elems[3]))); } Log.info("[MatchmakingSignUpdater] Loaded " + this.cachedSigns.size() + " blocks from cache!"); br.close(); } catch (IOException e) { e.printStackTrace(); } } public void updateSigns() { for (Iterator<Block> iterator = this.cachedSigns.iterator(); iterator.hasNext();) { Block b = iterator.next(); if (b.getChunk().isLoaded()) { if (b.getType() == Material.SIGN || b.getType() == Material.SIGN_POST) { if (!this.updateSign(b)) { iterator.remove(); } } else { iterator.remove(); } } } } private boolean updateSign(final Block b) { Sign sign = (Sign) b.getState(); if (sign.getLine(0).contains("[Matchmaking]")) { Minigame minigame = StorageEngine.getMinigame(sign.getLine(1)); if (minigame != null) { int arenaCountTotal = 0; int arenaCountJoinable = 0; int playersTotalOnline = 0; int playersTotalOnlineWaiting = 0; int playersTotal = 0; for (AbstractArena arena : Pexel.getMatchmaking().arenas.get(minigame)) { if (arena.canJoin()) { arenaCountJoinable++; arenaCountTotal++; } else { arenaCountTotal++; } if (arena.getState() == GameState.WAITING_PLAYERS) { playersTotalOnlineWaiting += arena.getPlayerCount(); } playersTotalOnline += arena.getPlayerCount(); playersTotal += arena.getMaximumSlots(); } ChatColor arenasColor = ChatColor.GREEN; if (arenaCountJoinable == 0) { arenasColor = ChatColor.RED; sign.setLine(3, ChatColor.RED + "All arenas full!"); } else { sign.setLine(3, ChatColor.GREEN + "Click to join!"); } sign.setLine(2, arenasColor.toString() + arenaCountJoinable + "/" + arenaCountTotal + "" + ChatColor.BLUE + playersTotalOnline + "/" + playersTotalOnlineWaiting + "/" + playersTotal); } else { sign.setLine(2, ChatColor.RED + "invalid minigame"); } sign.update(); return true; } else { return false; } } @Override public void run() { this.updateSigns(); } }
6,003
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Matchmaking.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/matchmaking/Matchmaking.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.matchmaking; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import eu.matejkormuth.pexel.PexelCore.Pexel; import eu.matejkormuth.pexel.PexelCore.arenas.AbstractArena; import eu.matejkormuth.pexel.PexelCore.chat.ChatManager; import eu.matejkormuth.pexel.PexelCore.core.Log; import eu.matejkormuth.pexel.PexelCore.core.Party; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; import eu.matejkormuth.pexel.PexelCore.core.Updatable; import eu.matejkormuth.pexel.PexelCore.core.UpdatedParts; import eu.matejkormuth.pexel.PexelCore.minigame.Minigame; import eu.matejkormuth.pexel.PexelCore.util.ServerLocation; import eu.matejkormuth.pexel.PexelCore.util.ServerLocationType; /** * Class used for matchmaking. * * @author Mato Kormuth * */ public class Matchmaking implements Updatable { /** * List of registered minigames. */ protected final Map<String, Minigame> minigames = new HashMap<String, Minigame>(); /** * List of registered arenas. */ protected final Map<Minigame, List<AbstractArena>> arenas = new HashMap<Minigame, List<AbstractArena>>(); /** * List of players in matchmaking. */ protected final List<Player> players = new ArrayList<Player>(); protected int taskId = 0; /** * Matchmaking server location. */ public static final ServerLocation QUICKJOIN_LOCATION = new ServerLocation( "QuickJoin", ServerLocationType.QUICKJOIN); /** * How often should server try to find match. */ protected final long matchMakingInterval = 40L; //40 ticks = 2 second /** * Pending matchmaking request. */ protected final List<MatchmakingRequest> requests = new ArrayList<MatchmakingRequest>(); /** * List of request being removed in this iteration. */ protected final List<MatchmakingRequest> removing = new ArrayList<MatchmakingRequest>(); /** * Registers minigame to Pexel matchmaking. * * @param minigame * minigame */ public void registerMinigame(final Minigame minigame) { Log.info("Matchmaking found a new minigame: " + minigame.getName()); this.minigames.put(minigame.getName(), minigame); StorageEngine.addMinigame(minigame); } /** * Registers arena to Pexel matchmaking. * * @param arena * minigame arena */ public void registerArena(final AbstractArena arena) { if (this.minigames.containsValue(arena.getMinigame())) { Log.info("Matchmaking found a new arena: " + arena.getName() + "-" + arena.getMinigame().getName()); if (this.arenas.containsKey(arena.getMinigame())) this.arenas.get(arena.getMinigame()).add(arena); else { List<AbstractArena> list = new ArrayList<AbstractArena>(); list.add(arena); this.arenas.put(arena.getMinigame(), list); } StorageEngine.addArena(arena); } else { throw new RuntimeException( "Can't register arena of minigame before minigame is registered!"); } } /** * Registers new matchmaking request. * * @param request * the request */ public void registerRequest(final MatchmakingRequest request) { boolean safe = true; String playername = null; if (request.getMinigame() != null) { for (Player p : request.getPlayers()) { if (this.players.contains(p)) { p.sendMessage(ChatManager.error("Can't register matchmaking request while in queue with another one! Type /leave to leave all requests.")); safe = false; if (playername == null) { playername = p.getDisplayName(); } else { playername += ", " + p.getDisplayName(); } } } if (safe) { request.tries = 0; this.requests.add(request); this.players.addAll(request.getPlayers()); } else { for (Player p : request.getPlayers()) { p.sendMessage(ChatManager.error("Matchmaking failed! Player(s) '" + playername + ChatColor.RED + "' are in another matchmaking request!")); } } } else { for (Player p : request.getPlayers()) { p.sendMessage(ChatManager.error("Matchmaking failed! Invalid request!")); } } } /** * Tries to find ideal matches for requests. */ public void makeMatches() { this.removing.clear(); int iterations = 0; int maxIterations = 256; int playercount = 0; int matchcount = 0; //Pokus sa sparovat vsetky poziadavky. for (MatchmakingRequest request : this.requests) { for (Player p : request.getPlayers()) { p.sendMessage(ChatColor.GOLD + "Finding best matches (" + (request.tries + 1) + ")... Please, be patient!"); } request.tries++; if (request.tries >= 20) { for (Player p : request.getPlayers()) { p.sendMessage(ChatManager.error("Matchmaking failed!")); } this.removing.add(request); } //Ak sme neprekrocili limit. if (iterations > maxIterations) break; if (request.getGame() != null) { //The best function. this.makeMatchesBySpecifiedMinigameAndMminigameArenaFromMatchMakingRequest_Version_1_0_0_0_1(request); } else { List<AbstractArena> minigame_arenas = this.arenas.get(request.getMinigame()); for (AbstractArena arena : minigame_arenas) { // If is not empty, and there is a place for them if (!arena.empty() && arena.canJoin(request.playerCount())) { // Connect all of them for (Player player : request.getPlayers()) arena.onPlayerJoin(player); //Odstran request zo zoznamu. this.removing.add(request); break; } } for (AbstractArena arena : minigame_arenas) { // If is not empty, and there is a place for them if (arena.canJoin(request.playerCount())) { // Connect all of them for (Player player : request.getPlayers()) arena.onPlayerJoin(player); // Remove request from queue. this.removing.add(request); break; } } } iterations++; } //Vymaz spracovane poziadavky zo zoznamu. for (MatchmakingRequest request : this.removing) { playercount += request.playerCount(); matchcount++; this.players.removeAll(request.getPlayers()); this.requests.remove(request); } if (playercount != 0) Log.info("[MM] Processed " + playercount + " players in " + matchcount + " matches! " + this.requests.size() + " requests left."); } private void makeMatchesBySpecifiedMinigameAndMminigameArenaFromMatchMakingRequest_Version_1_0_0_0_1( final MatchmakingRequest request) { for (AbstractArena arena : this.arenas.get(request.getMinigame())) { // If is not empty, and there is a place for them if (!arena.empty() && arena.canJoin(request.playerCount())) { // Connect all of them for (Player player : request.getPlayers()) arena.onPlayerJoin(player); // Remove request from queue. this.removing.add(request); break; } } for (AbstractArena arena : this.arenas.get(request.getMinigame())) { // If is not empty, and there is a place for them if (arena.canJoin(request.playerCount())) { // Connect all of them for (Player player : request.getPlayers()) arena.onPlayerJoin(player); // Remove request from queue. this.removing.add(request); break; } } } @Override public void updateStart() { Log.partEnable("Matchmaking"); UpdatedParts.registerPart(this); this.taskId = Pexel.getScheduler().scheduleSyncRepeatingTask(new Runnable() { @Override public void run() { Matchmaking.this.makeMatches(); } }, 0, this.matchMakingInterval); } @Override public void updateStop() { Log.partDisable("Matchmaking"); Pexel.getScheduler().cancelTask(this.taskId); } public void processSign(final String[] lines, final Player player) { String minigame = lines[1]; // Currently not used. //String map = lines[2]; //String arena = lines[3]; if (StorageEngine.getProfile(player.getUniqueId()).getParty() != null) { Party party = StorageEngine.getProfile(player.getUniqueId()).getParty(); if (party.isOwner(player)) { for (Player p : party.getPlayers()) p.sendMessage(ChatColor.YELLOW + "Your party joined matchmaking!"); this.registerRequest(party.toRequest( StorageEngine.getMinigame(minigame), null)); } else { player.sendMessage(ChatManager.error("You cannot join games while you are in party!")); } } else { player.sendMessage(ChatColor.YELLOW + "Your have joined matchmaking!"); MatchmakingRequest request = new MatchmakingRequest(Arrays.asList(player), StorageEngine.getMinigame(minigame), null); this.registerRequest(request); } } public static final class JSONArena { public String name; public String minigame; public String[] players; public String state; public int maxPlayers; } public static final class Handler implements HttpHandler { @Override public void handle(final HttpExchange conn) throws IOException { List<JSONArena> arenas = new ArrayList<JSONArena>(); for (AbstractArena arena : StorageEngine.getArenas().values()) { JSONArena a = new JSONArena(); a.name = arena.getName(); a.minigame = arena.getMinigame().getName(); a.maxPlayers = arena.getMaximumSlots(); a.state = arena.getState().name(); a.players = new String[arena.getPlayerCount()]; int i = 0; for (Player p : arena.getPlayers()) { a.players[i] = p.getName() + "/" + p.getUniqueId().toString(); i++; } arenas.add(a); } String response = "no gson"; conn.sendResponseHeaders(200, response.length()); conn.getResponseBody().write(response.getBytes()); conn.close(); } } }
13,494
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
TeamManager.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/teams/TeamManager.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.teams; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import eu.matejkormuth.pexel.PexelCore.Pexel; import eu.matejkormuth.pexel.PexelCore.arenas.AbstractArena; import eu.matejkormuth.pexel.PexelCore.chat.ChatManager; /** * Class used for managing teams. * * @author Mato Kormuth * */ public class TeamManager implements Listener { /** * List of teams */ private final List<Team> teams = new ArrayList<Team>(); /** * Caching of sign locations. */ private final Map<Location, Team> signs = new HashMap<Location, Team>(); private final int varience = 1; private final AbstractArena arena; /** * Creates new Team manager * * @param arena * arena in which team manager runs. */ public TeamManager(final AbstractArena arena) { Bukkit.getPluginManager().registerEvents(this, Pexel.getCore()); this.arena = arena; } /** * Resets team manager. */ public void reset() { this.teams.clear(); for (Location loc : this.signs.keySet()) this.updateSign(loc, this.signs.get(loc)); this.signs.clear(); } /** * Adds team to this manager. * * @param team * team to add */ public void addTeam(final Team team) { this.teams.add(team); } private void updateSignCache(final Team team) { for (Location loc : this.signs.keySet()) if (this.signs.get(loc) == team) this.updateSign(loc, team); } /** * Updates sign content on specified location with specified team infromation. * * @param location * location of sign * @param team * team */ public void updateSign(final Location location, final Team team) { this.signs.put(location, team); Sign s = (Sign) location.getBlock().getState(); s.setLine(1, team.getName()); if (team.getMaximumPlayers() == team.getPlayerCount()) s.setLine( 2, ChatColor.RED.toString() + team.getPlayerCount() + "/" + team.getMaximumPlayers() + " players"); else if (team.getPlayerCount() / team.getMaximumPlayers() > 0.75F) s.setLine( 2, ChatColor.GOLD.toString() + team.getPlayerCount() + "/" + team.getMaximumPlayers() + " players"); else s.setLine( 2, ChatColor.GREEN.toString() + team.getPlayerCount() + "/" + team.getMaximumPlayers() + " players"); s.update(); } @EventHandler private void onPlayerInteract(final PlayerInteractEvent event) { if (event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK || event.getAction() == org.bukkit.event.block.Action.LEFT_CLICK_BLOCK) if (event.getClickedBlock().getType() == Material.SIGN_POST || event.getClickedBlock().getType() == Material.SIGN) if (this.arena.getPlayers().contains(event.getPlayer())) this.signClick(event.getPlayer(), event.getClickedBlock()); } @EventHandler private void onPlayerLeft(final PlayerQuitEvent event) { for (Team t : this.teams) if (t.contains(event.getPlayer())) t.removePlayer(event.getPlayer()); } private void signClick(final Player player, final Block clickedBlock) { System.out.println("signClick: p: " + player.getName() + ", cb: " + clickedBlock.getLocation().toVector().toString()); Sign s = (Sign) clickedBlock.getState(); String teamName = s.getLine(1); if (s.getLine(0).contains("[Team]")) { Team team = null; for (Team t : this.teams) if (t.getName().equalsIgnoreCase(teamName)) team = t; if (team == null) throw new RuntimeException("Team not found in TeamManager: " + teamName); if (team.getPlayerCount() == team.getMaximumPlayers()) player.sendMessage(ChatManager.error("This team is full!")); else { if (team.canJoin()) { if (this.playerInTeam(player)) { Team oldTeam = this.getTeam(player); oldTeam.removePlayer(player); this.updateSignCache(oldTeam); } team.addPlayer(player); team.applyArmor(player); this.updateSign(clickedBlock.getLocation(), team); } else { player.sendMessage(ChatManager.error("You can't join this team at this time!")); } } } } /** * Returns team by player from this team manager. * * @param player * player to find * @return team, that specified players is in */ public Team getTeam(final Player player) { for (Team t : this.teams) if (t.contains(player)) return t; return null; } /** * Return whether specified player is in team, manager by this manager. * * @param player * player to find * @return true or false */ public boolean playerInTeam(final Player player) { for (Team t : this.teams) if (t.contains(player)) return true; return false; } /** * Returns if specified player can join specified team at this time. * * @param team * team player whats to join * @param player * specififed player * @return true or false */ public boolean canJoinTeam(final Team team, final Player player) { return team.getPlayerCount() > this.getAvarangePlayerCount(); } /** * Returns avarange player count in teams of this manager. * * @return avarange player count */ public int getAvarangePlayerCount() { int allPlayers = this.varience; for (Team team : this.teams) allPlayers += team.getPlayerCount(); return (int) ((allPlayers / this.teams.size()) + 0.5); } /** * Automatically joins team for specified player. * * @param p * player, that have no team. * @return team, that player joined */ public Team autoJoinTeam(final Player p) { Team leastCrowdedTeam = this.teams.get(0); for (Team t : this.teams) if (t.getPlayerCount() < leastCrowdedTeam.getPlayerCount()) leastCrowdedTeam = t; leastCrowdedTeam.addPlayer(p); return leastCrowdedTeam; } /** * Removes player from team and team chat. * * @param player * player to remove */ public void removePlayer(final Player player) { if (this.playerInTeam(player)) { this.getTeam(player).removePlayer(player); } } /** * Returns list of managed teams. * * @return list of managed teams */ public List<Team> getTeams() { return this.teams; } }
8,819
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Team.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/teams/Team.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.teams; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.chat.ChatChannel; import eu.matejkormuth.pexel.PexelCore.chat.SubscribeMode; import eu.matejkormuth.pexel.PexelCore.core.PlayerHolder; import eu.matejkormuth.pexel.PexelCore.util.ItemUtils; /** * Class representing a team. * * @author Mato Kormuth * */ public class Team implements PlayerHolder { /** * List of player in team. */ private final List<Player> players = new ArrayList<Player>(); /** * Color of team. */ private final Color color; /** * Name of team. */ private final String name; /** * Chat channel of the team. */ private final ChatChannel teamchat = ChatChannel.createRandom(); /** * Maximum amount of players in this team. */ private final int maxPlayers; /** * Creates a new Team with specified team color and team name. * * @param color * color of team * @param name * name of team * @param maximumPlayers * maximum amount of players in team */ public Team(final Color color, final String name, final int maximumPlayers) { this.color = color; this.name = name; this.maxPlayers = maximumPlayers; this.teamchat.setPrefix(ChatColor.YELLOW + "[TEAM] "); } /** * Teleports all players. * * @param loc * location, to teleport to players */ public void teleportAll(final Location loc) { for (Player p : this.players) p.teleport(loc); } /** * Applies dyed armor to all players. */ public void applyArmorAll() { for (Player p : this.players) this.applyArmor(p); } /** * Adds player to team. * * @param p * player to add */ public void addPlayer(final Player p) { p.sendMessage(ChatColor.GREEN + "You have joined team '" + this.name + "'!"); this.players.add(p); this.teamchat.subscribe(p, SubscribeMode.READ_WRITE); } /** * Adds players to team. * * @param players * players to add */ public void addPlayers(final Player... players) { for (Player p : players) this.addPlayer(p); } /** * Removes player from the team. * * @param p * player to remove */ public void removePlayer(final Player p) { p.sendMessage(ChatColor.GREEN + "You have left team '" + this.name + "'!"); this.players.remove(p); this.teamchat.unsubscribe(p); } /** * Return's this team chat channel. * * @return team chat channel */ public ChatChannel getTeamChannel() { return this.teamchat; } /** * Returns name of the team. * * @return name of team */ public String getName() { return this.name; } /** * Applies armor to specified player. * * @param player * player to apply armor to */ public void applyArmor(final Player player) { player.getInventory().setHelmet( ItemUtils.coloredLetherArmor(Material.LEATHER_HELMET, this.color)); player.getInventory().setChestplate( ItemUtils.coloredLetherArmor(Material.LEATHER_CHESTPLATE, this.color)); player.getInventory().setLeggings( ItemUtils.coloredLetherArmor(Material.LEATHER_LEGGINGS, this.color)); player.getInventory().setBoots( ItemUtils.coloredLetherArmor(Material.LEATHER_BOOTS, this.color)); } /** * Retruns list of players. * * @return list of players in this team */ @Override public List<Player> getPlayers() { return this.players; } /** * Returns if this team contains specified player. * * @param p * specified player * @return true or false */ @Override public boolean contains(final Player p) { return this.players.contains(p); } /** * Returns player count. * * @return amount of players */ @Override public int getPlayerCount() { return this.players.size(); } /** * Get maximum number of players in team. * * @return amount of players */ public int getMaximumPlayers() { return this.maxPlayers; } /** * Returns whether one player can join this team. * * @return boolean, if player can join */ public boolean canJoin() { return this.players.size() < this.maxPlayers; } /** * Returns whether specified amount of players can join this team. * * @param amount * amount of players * @return true, if they can, else false */ public boolean canJoin(final int amount) { return this.players.size() + amount < this.maxPlayers; } /** * Retrun's this team color. * * @return color of team */ public Color getColor() { return this.color; } /** * Applies colored armor to specified player. * * @param p * specified player */ public void applyArmorTo(final Player p) { this.applyArmor(p); } }
6,508
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
V3CompiledWriter.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/cinematics/V3CompiledWriter.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.cinematics; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.bukkit.Location; /** * Pouziva sa na ukladanie kompilovanych suborov klipov V3. * * @author Mato Kormuth * */ public class V3CompiledWriter { /** * Vystupny stream. */ private DataOutputStream output; /** * Kuzelne cislo 1. */ public final static int MAGIC_1 = 86; /** * Kuzelne cislo 2. */ public final static int MAGIC_2 = 114; /** * Verzia suboru. */ public final static int VERSION = 1; public static V3CompiledWriter createFile(final String path) { return new V3CompiledWriter(path); } // Sukromny konstruktor. private V3CompiledWriter(final String path) { try { this.output = new DataOutputStream(new FileOutputStream(path)); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Nezatvori subor! * * @param clip * @throws IOException */ public void writeClip(final V3CameraClip clip) throws IOException { this.checkForNull(clip); // Write FileHeader. this.writeFileHeader(clip.FPS); // Write Frames. for (V3CameraFrame frame : clip.frames) { // Write FrameHeader. Location l = frame.getCameraLocation(); this.writeFrameHeader(l.getX(), l.getY(), l.getZ(), l.getYaw(), l.getPitch(), frame.getZoom(), frame.isMetaOnly()); // Write FrameMeta (ExtraData). this.writeMetaHeader(frame.getMetaCount()); if (frame.hasMeta()) { for (V3Meta meta : frame.getMetas()) { // Write importatnt things. this.output.writeByte(meta.getType()); // Write data metas's way. meta.writeMeta(this.output); } } // Proceed to next frame. } } /** * @param clip */ private void checkForNull(final V3CameraClip clip) { } private void writeMetaHeader(final int metaCount) throws IOException { // Write Meta Header. this.output.writeShort(metaCount); } private void writeFileHeader(final int fps) throws IOException { // Write FileHeader. this.output.writeByte(V3CompiledWriter.MAGIC_1); this.output.writeByte(V3CompiledWriter.MAGIC_2); this.output.writeByte(V3CompiledWriter.VERSION); if (fps >= 255) throw new IOException("FPS must be lower than 255!"); else this.output.writeByte(fps); } private void writeFrameHeader(final double camX, final double camY, final double camZ, final float yaw, final float pitch, final float zoom, final boolean isMeta) throws IOException { // Write FrameHeader. this.output.writeDouble(camX); this.output.writeDouble(camY); this.output.writeDouble(camZ); this.output.writeFloat(yaw); this.output.writeFloat(pitch); this.output.writeFloat(zoom); this.output.writeBoolean(isMeta); } /** * Zatvori subor. * * @throws IOException */ public void close() throws IOException { this.output.close(); } }
4,386
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
V3Generator.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/cinematics/V3Generator.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.cinematics; import java.util.ArrayList; import java.util.List; import org.bukkit.util.Vector; /** * Pomocna trieda na generovanie rznych typov pohybov. * * @author Mato Kormuth * */ public class V3Generator { // Mala staticka classa. private V3Generator() { } /** * Vygeneruje ranmce pre rovnomerne rychlu cestu z pos1 do pos2 so specifikovanym pitch a yaw pocas specifikovaneho * casu v sekundach a specifikovaneho poctu ramcov za sekundu. * * @param pos1 * @param pos2 * @param fps * @param seconds * @param yaw * @param pitch * @return */ public static List<V3CameraFrame> line(final Vector pos1, final Vector pos2, final int fps, final int seconds, final float yaw, final float pitch) { List<V3CameraFrame> frameList = new ArrayList<V3CameraFrame>(); int frameCount = fps * seconds; // Vypocitaj vzdialenosti. Vector positionDifference = pos2.subtract(pos1); // Zisti posunutia (prirastky). Vector frameChange = new Vector(positionDifference.getX() / frameCount, positionDifference.getY() / frameCount, positionDifference.getZ() / frameCount); for (int frameNum = 0; frameNum < frameCount; frameNum++) { // Zvacsi pos1 o prirastok. pos1.add(frameChange); // Pridaj ramec. frameList.add(new V3CameraFrame(pos1.getX(), pos1.getY(), pos1.getZ(), yaw, pitch, false)); } return frameList; } public static List<V3CameraFrame> lineLookAt(final Vector pos1, final Vector pos2, final Vector lookAt, final int fps, final int seconds) { List<V3CameraFrame> frameList = new ArrayList<V3CameraFrame>(); int frameCount = fps * seconds; // Vypocitaj vzdialenosti. Vector positionDifference = pos2.subtract(pos1); // Zisti posunutia (prirastky). Vector frameChange = new Vector(positionDifference.getX() / frameCount, positionDifference.getY() / frameCount, positionDifference.getZ() / frameCount); for (int frameNum = 0; frameNum < frameCount; frameNum++) { // Zvacsi pos1 o prirastok. pos1.add(frameChange); float pitch = 0; float yaw = (float) -((Math.atan2(pos1.getX() - lookAt.getX(), pos1.getZ() - lookAt.getZ()) * 180 / Math.PI) - 180); // Pridaj ramec. frameList.add(new V3CameraFrame(pos1.getX(), pos1.getY(), pos1.getZ(), yaw, pitch, false)); } return frameList; } /** * Vygeneruje ramce pre pohyb po kruznici a lookAt specifikovany. * * @param center * @param lookAt * @param radius * @param fps * @param seconds * @param speed * @return */ public static List<V3CameraFrame> flyInCirleLookAt(final Vector center, final Vector lookAt, final int radius, final int fps, final int seconds, final float speed) { List<V3CameraFrame> frameList = new ArrayList<V3CameraFrame>(); int frameCount = fps * seconds; for (int frameNum = 0; frameNum < frameCount; frameNum++) { // Vypocitaj X a Z, Y zostava rovnake. double x = center.getX() + Math.sin(frameNum * speed) * radius; double z = center.getZ() + Math.cos(frameNum * speed) * radius; // Vypocitaj pitch a yaw. float pitch = 0; float yaw = (float) -((Math.atan2(x - lookAt.getX(), z - lookAt.getZ()) * 180 / Math.PI) - 180); // Pridaj ramec. frameList.add(new V3CameraFrame(x, center.getY(), z, yaw, pitch, false)); } return frameList; } public static List<V3CameraFrame> splinePath(final List<Vector> points) { List<V3CameraFrame> frameList = new ArrayList<V3CameraFrame>(); return frameList; } }
4,936
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z