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 |
---|---|---|---|---|---|---|---|---|---|---|---|
PreloadChunkListener.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/EventManagement/PreloadChunkListener.java | package com.github.catageek.ByteCart.EventManagement;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Minecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.util.Vector;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* Listener to load chunks around moving carts
*/
public final class PreloadChunkListener implements Listener {
private final Vector NullVector = new Vector(0,0,0);
@EventHandler(ignoreCancelled = true)
public void onVehicleMove(VehicleMoveEvent event) {
Location loc = event.getTo();
int to_x = loc.getBlockX() >> 4;
int to_z = loc.getBlockZ() >> 4;
if(event.getVehicle() instanceof Minecart) // we care only of minecart
{
// preload chunks
MathUtil.loadChunkAround(loc.getWorld(), to_x, to_z, 2);
}
}
/**
* We cancel this event if a cart is moving in the chunk or around
*
* @param event
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
@SuppressWarnings("ucd")
public void onChunkUnload(ChunkUnloadEvent event) {
int n, j, i = event.getChunk().getX()-2, k = i+4, l = event.getChunk().getZ()+2;
World world = event.getWorld();
Entity[] entities;
for (; i<=k; ++i) {
for (j=l-4; j<=l ; ++j) {
if (world.isChunkLoaded(i, j)) {
entities = world.getChunkAt(i, j).getEntities();
for (n = entities.length -1; n >=0; --n) {
if (entities[n] instanceof Minecart && !((Minecart)entities[n]).getVelocity().equals(NullVector)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
}
| 1,793 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ConstantSpeedListener.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/EventManagement/ConstantSpeedListener.java | package com.github.catageek.ByteCart.EventManagement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Rail;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleBlockCollisionEvent;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* Listener to maintain cart speed
*/
public final class ConstantSpeedListener implements Listener {
// We keep the speed of each cart in this map
private final Map<Integer, Double> speedmap = new HashMap<Integer, Double>();
// empty Location
private Location location = new Location(null, 0, 0, 0);
@EventHandler(ignoreCancelled = true)
@SuppressWarnings("ucd")
public void onVehicleMove(VehicleMoveEvent event) {
final Vehicle v = event.getVehicle();
if (! (v instanceof Minecart))
return;
final Minecart m = (Minecart) v;
double speed = MathUtil.getSpeed(m);
int id = m.getEntityId();
final BlockData data = m.getLocation(location).getBlock().getState().getBlockData();
if (speed != 0 && (data instanceof Rail)) {
Double storedspeed;
if (! speedmap.containsKey(id))
speedmap.put(id, speed);
else
if ((storedspeed = speedmap.get(id)) > speed
&& storedspeed <= m.getMaxSpeed())
MathUtil.setSpeed(m, storedspeed);
else
speedmap.put(id, speed);
} else
speedmap.remove(id);
}
@EventHandler (ignoreCancelled = false, priority = EventPriority.MONITOR)
@SuppressWarnings("ucd")
public void onVehicleDestroy(VehicleDestroyEvent event) {
speedmap.remove(event.getVehicle().getEntityId());
}
@EventHandler (ignoreCancelled = false, priority = EventPriority.MONITOR)
@SuppressWarnings("ucd")
public void onVehicleEntityCollision(VehicleEntityCollisionEvent event) {
final List<Entity> passengers = event.getVehicle().getPassengers();
for(Entity passenger : passengers) {
if(passenger.getEntityId() == event.getEntity().getEntityId()) {
return;
}
}
speedmap.remove(event.getVehicle().getEntityId());
}
@EventHandler (ignoreCancelled = false, priority = EventPriority.MONITOR)
@SuppressWarnings("ucd")
public void onVehicleBlockCollision(VehicleBlockCollisionEvent event) {
speedmap.remove(event.getVehicle().getEntityId());
}
}
| 2,664 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ByteCartInventoryListener.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/EventManagement/ByteCartInventoryListener.java | package com.github.catageek.ByteCart.EventManagement;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.ModifiableRunnable;
import com.github.catageek.ByteCartAPI.Event.UpdaterCreateEvent;
/**
* Class implementing a listener and waiting for a player to right-click an inventory holder
* and running a Runnable
*/
public class ByteCartInventoryListener implements Listener {
private final Player Player;
// the Runnable to update
private final ModifiableRunnable<Inventory> Execute;
// flag set when we deal with an updater command
private final boolean isUpdater;
public ByteCartInventoryListener(ByteCart plugin, Player player, ModifiableRunnable<Inventory> execute,
boolean isupdater) {
this.Player = player;
this.Execute = execute;
this.isUpdater = isupdater;
// self registering as Listener
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler (ignoreCancelled = false)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
Entity entity;
Inventory inv;
if (event.getPlayer().equals(Player) && ((entity = event.getRightClicked()) instanceof InventoryHolder)) {
// we set the member and run the Runnable
this.Execute.SetParam(inv = ((InventoryHolder) entity).getInventory());
this.Execute.run();
// we cancel the right-click
event.setCancelled(true);
if (isUpdater) {
// we launch an UpdaterCreateEvent
StorageMinecart v = (StorageMinecart) inv.getHolder();
UpdaterCreateEvent e = new UpdaterCreateEvent(v.getEntityId(), v.getLocation());
ByteCart.myPlugin.getServer().getPluginManager().callEvent(e);
}
}
// Self unregistering
PlayerInteractEntityEvent.getHandlerList().unregister(this);
}
}
| 2,090 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ByteCartListener.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/EventManagement/ByteCartListener.java | package com.github.catageek.ByteCart.EventManagement;
import java.util.Iterator;
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.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.vehicle.VehicleCreateEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.HAL.AbstractIC;
import com.github.catageek.ByteCart.Signs.Clickable;
import com.github.catageek.ByteCart.Signs.ClickedSignFactory;
import com.github.catageek.ByteCart.Signs.Powerable;
import com.github.catageek.ByteCart.Signs.PoweredSignFactory;
import com.github.catageek.ByteCart.Signs.Triggable;
import com.github.catageek.ByteCart.Signs.TriggeredSignFactory;
import com.github.catageek.ByteCartAPI.Event.SignCreateEvent;
import com.github.catageek.ByteCartAPI.Event.SignRemoveEvent;
import com.github.catageek.ByteCartAPI.HAL.IC;
/**
* The main listener
*/
public class ByteCartListener implements Listener {
private PoweredSignFactory MyPoweredICFactory;
public ByteCartListener() {
this.MyPoweredICFactory = new PoweredSignFactory();
}
/**
* Detect if a sign is under the cart moving
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
@SuppressWarnings("ucd")
public void onVehicleMove(VehicleMoveEvent event) {
Location loc = event.getFrom();
Integer from_x = loc.getBlockX();
Integer from_z = loc.getBlockZ();
loc = event.getTo();
int to_x = loc.getBlockX();
int to_z = loc.getBlockZ();
// Check if the vehicle crosses a cube boundary
if(from_x == to_x && from_z == to_z)
return; // no boundary crossed, resumed
if(event.getVehicle() instanceof Minecart) // we care only of minecart
{
Minecart vehicle = (Minecart) event.getVehicle();
// we instantiate a member of the BCXXXX class
// XXXX is read from the sign
Triggable myIC;
myIC = TriggeredSignFactory.getTriggeredIC(event.getTo().getBlock().getRelative(BlockFace.DOWN, 2),vehicle);
if (myIC != null) {
if(ByteCart.debug)
ByteCart.log.info("ByteCart: " + myIC.getName() + ".trigger()");
myIC.trigger();
}
}
}
/**
* Detect a sign under the cart created
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
@SuppressWarnings("ucd")
public void onVehicleCreate(VehicleCreateEvent event) {
if(event.getVehicle() instanceof Minecart) // we care only of minecart
{
Minecart vehicle = (Minecart) event.getVehicle();
// we instantiate a member of the BCXXXX class
// XXXX is read from the sign
Triggable myIC;
myIC = TriggeredSignFactory.getTriggeredIC(vehicle.getLocation().getBlock().getRelative(BlockFace.DOWN, 2),vehicle);
if (myIC != null) {
myIC.trigger();
}
}
}
/**
* Detect if we create a sign
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
@SuppressWarnings("ucd")
public void onSignChange(SignChangeEvent event) {
if (! AbstractIC.checkEligibility(event.getLine(1)))
return;
AbstractIC.removeFromCache(event.getBlock());
IC myIC = TriggeredSignFactory.getTriggeredIC(event.getBlock(), event.getLine(1), null);
if (myIC == null) {
myIC = ClickedSignFactory.getClickedIC(event.getBlock(), event.getLine(1), event.getPlayer());
}
if (myIC == null) {
myIC = PoweredSignFactory.getPoweredIC(event.getBlock(), event.getLine(1));
}
if (myIC != null) {
Player player = event.getPlayer();
if (! player.hasPermission(myIC.getBuildPermission())) {
player.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED +"You are not authorized to place " + myIC.getFriendlyName() + " block.");
player.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED +"You must have " + myIC.getBuildPermission());
event.setLine(1, "");
}
else
{
player.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + myIC.getFriendlyName() + " block created.");
int tax = myIC.getBuildtax();
if (tax > 0)
player.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "Tarif : " +myIC.getBuildtax() + " eur0x.");
if (event.getLine(2).compareTo("") == 0)
event.setLine(2, myIC.getFriendlyName());
Bukkit.getPluginManager().callEvent(new SignCreateEvent(myIC, player, event.getLines()));
}
}
}
/**
* Check if a sign was broken
*
* @param event
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
@SuppressWarnings("ucd")
public void onBlockBreak(BlockBreakEvent event) {
removeSignIfNeeded(event.getBlock(), event.getPlayer());
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
@SuppressWarnings("ucd")
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
removeSignIfNeeded(event.getBlock(), event.getEntity());
}
/**
* Check if a sign was destroyed in the explosion
*
* @param event
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
@SuppressWarnings("ucd")
public void onEntityExplode(EntityExplodeEvent event) {
Entity entity = event.getEntity();
Iterator<Block> it = event.blockList().iterator();
while (it.hasNext())
removeSignIfNeeded(it.next(), entity);
}
/**
* Check if a block is powered above a sign.
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
@SuppressWarnings("ucd")
public void onBlockPhysics(BlockPhysicsEvent event) {
if (event.getChangedType() != Material.SIGN || ! event.getBlock().isBlockIndirectlyPowered()) {
return;
}
final Powerable myIC = this.MyPoweredICFactory.getIC(event.getBlock());
if (myIC != null) {
myIC.power();
}
}
/*
@EventHandler(ignoreCancelled = true)
public void onBlockRedstone(BlockRedstoneEvent event) {
Block block = event.getBlock().getRelative(BlockFace.DOWN);
List<Block> blocks = new ArrayList<Block>(4);
blocks.add(block.getRelative(BlockFace.NORTH));
blocks.add(block.getRelative(BlockFace.EAST));
blocks.add(block.getRelative(BlockFace.SOUTH));
blocks.add(block.getRelative(BlockFace.WEST));
for (Block b : blocks) {
if (! AbstractIC.checkEligibility(b))
continue;
Powerable myIC = this.MyPoweredICFactory.getIC(b);
if (myIC != null) {
try {
if(ByteCart.debug)
ByteCart.log.info("ByteCart: power()");
myIC.power();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return;
}
}
*/
/**
* Detect a sign that a player right-clicks
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
@SuppressWarnings("ucd")
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getAction().compareTo(Action.RIGHT_CLICK_BLOCK) != 0)
return;
Clickable myIC = ClickedSignFactory.getClickedIC(event.getClickedBlock(), event.getPlayer());
if (myIC == null)
myIC = ClickedSignFactory.getBackwardClickedIC(event.getClickedBlock(), event.getPlayer());
if (myIC != null) {
if(ByteCart.debug)
ByteCart.log.info("ByteCart: " + myIC.getName() + ".click()");
myIC.click();
event.setCancelled(true);
}
}
/**
* Remove sign from cache and launch event
*
* @param block the sign
* @param entity the entity at origin of the event
*/
private static void removeSignIfNeeded(Block block, Entity entity) {
if (! (block.getState() instanceof Sign))
return;
IC myIC;
myIC = TriggeredSignFactory.getTriggeredIC(block, null);
if (myIC == null)
myIC = ClickedSignFactory.getClickedIC(block, null);
if (myIC != null) {
Bukkit.getPluginManager().callEvent(new SignRemoveEvent(myIC, entity));
AbstractIC.removeFromCache(block);
}
}
}
| 8,402 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/ThreadManagement/package-info.java | /**
*
*/
/**
* Utilities for threads
*/
package com.github.catageek.ByteCart.ThreadManagement; | 99 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Expirable.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/ThreadManagement/Expirable.java | package com.github.catageek.ByteCart.ThreadManagement;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.scheduler.BukkitTask;
/*
* HashMap that keeps entries during "duration" ticks
*/
public abstract class Expirable<K> {
private Map<K, BukkitTask> ThreadMap = Collections.synchronizedMap(new HashMap<K,BukkitTask>());
private final long Duration;
private final String name;
private final boolean IsSync;
abstract public void expire(Object...objects);
/**
* @param duration the timeout value
* @param isSync true if the element must be removed synchronously in the main thread
* @param name a name for the set
*/
public Expirable(long duration, boolean isSync, String name) {
super();
this.Duration = duration;
this.name = name;
this.IsSync = isSync;
}
public void reset(K key, Object...objects) {
if (Duration != 0)
(new BCBukkitRunnable<K>(this, key)).renewTaskLater(objects);
}
public void reset(long duration, K key, Object...objects) {
if (duration != 0)
(new BCBukkitRunnable<K>(this, key)).renewTaskLater(duration, objects);
}
public final void cancel(K key) {
if (Duration != 0)
(new BCBukkitRunnable<K>(this, key)).cancel();
}
protected final Map<K, BukkitTask> getThreadMap() {
return ThreadMap;
}
public final long getDuration() {
return Duration;
}
public final boolean isSync() {
return IsSync;
}
public final String getName() {
return name;
}
}
| 1,485 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BCBukkitRunnable.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/ThreadManagement/BCBukkitRunnable.java | package com.github.catageek.ByteCart.ThreadManagement;
import java.util.Map;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import com.github.catageek.ByteCart.ByteCart;
/**
* A class that schedule tasks to manage the automatic removal of elements
*
* @param <K> key used in the map or set
*/
final class BCBukkitRunnable<K> {
private final Expirable<K> Expirable;
private final K Key;
/**
* @param expirable the Collection implementing Expirable
* @param key the key of the collection to which this task will be referenced
*/
BCBukkitRunnable(Expirable<K> expirable, K key) {
this.Expirable = expirable;
this.Key = key;
}
/**
* Schedule or reschedule an Expirable task with a specific timeout delay
*
* @param duration the timeout to set
* @param objects arguments to pass to the abstract Expirable.expire() method
* @return the BukkitTask scheduled
*/
BukkitTask renewTaskLater(long duration, Object...objects) {
BukkitTask task;
Map<K,BukkitTask> map = Expirable.getThreadMap();
synchronized(map) {
if(! Expirable.getThreadMap().containsKey(Key)) {
task = (Expirable.isSync() ? this.runTaskLater(objects)
: this.runTaskLaterAsynchronously(objects));
}
else {
BukkitTask old = Expirable.getThreadMap().get(Key);
BukkitRunnable runnable = new Expire(Expirable, Key, objects);
if (old.isSync())
task = runnable.runTaskLater(ByteCart.myPlugin, duration);
else
task = runnable.runTaskLaterAsynchronously(ByteCart.myPlugin, duration);
old.cancel();
}
Expirable.getThreadMap().put(Key, task);
}
return task;
}
/**
* Schedule or reschedule an Expirable task with the default timeout delay
*
* @param objects arguments to pass to the abstract Expirable.expire() method
* @return the BukkitTask scheduled
*/
BukkitTask renewTaskLater(Object...objects) {
return renewTaskLater(Expirable.getDuration(), objects);
}
/**
* Cancel the task
*
*/
void cancel() {
if(Expirable.getThreadMap().containsKey(Key))
Expirable.getThreadMap().remove(Key);
}
/**
* Schedule an Expirable task synchronously
*
* @param objects the arguments to pass to Expirable.expire() method
* @return the task scheduled
*/
private BukkitTask runTaskLater(Object...objects) {
BukkitRunnable runnable = new Expire(Expirable, Key, objects);
org.bukkit.scheduler.BukkitTask task = runnable.runTaskLater(ByteCart.myPlugin, Expirable.getDuration());
return task;
}
/**
* Schedule an Expirable task asynchronously
*
* @param objects the arguments to pass to Expirable.expire() method
* @return the task scheduled
*/
private BukkitTask runTaskLaterAsynchronously(Object...objects) {
BukkitRunnable runnable = new Expire(Expirable, Key, objects);
org.bukkit.scheduler.BukkitTask task = runnable.runTaskLaterAsynchronously(ByteCart.myPlugin, Expirable.getDuration());
return task;
}
/**
* A runnable that will execute the expire() method and clean internal map
*/
private final class Expire extends BukkitRunnable {
private final Expirable<K> expirable;
private final K key;
private final Object[] params;
public Expire(Expirable<K> expirable, K key, Object...objects) {
this.key = key;
this.expirable = expirable;
this.params = objects;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
Map<K,BukkitTask> map = this.expirable.getThreadMap();
map.remove(key);
this.expirable.expire(params);
}
}
}
| 3,559 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandBCDMapSync.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandBCDMapSync.java | package com.github.catageek.ByteCart.Commands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import com.github.catageek.ByteCart.plugins.BCDynmapPlugin;
public class CommandBCDMapSync implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
BCDynmapPlugin.removeObsoleteMarkers();
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return Collections.emptyList();
}
}
| 721 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandBCTicket.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandBCTicket.java | package com.github.catageek.ByteCart.Commands;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.github.catageek.ByteCart.Signs.BC7010;
import com.github.catageek.ByteCartAPI.ByteCartPlugin;
public class CommandBCTicket extends AbstractTicketCommand implements CommandExecutor, TabCompleter {
public CommandBCTicket(ByteCartPlugin plugin) {
super(plugin);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
if (args.length < 2)
return false;
@SuppressWarnings("deprecation")
Player player = Bukkit.getServer().getPlayer(args[0]);
if(player == null) {
sender.sendMessage(ChatColor.DARK_GREEN + "[Bytecart] " + ChatColor.RED + "Can't find player " + args[0] + ".");
return false;
}
return parse(sender, player, 1, args);
} else {
return parse(sender, (Player) sender, 0, args);
}
}
@Override
protected boolean run(CommandSender sender, Player player, String addressString, boolean isTrain) {
(new BC7010(player.getLocation().getBlock(), player)).setAddress(addressString, null, isTrain);
player.sendMessage(ChatColor.DARK_GREEN + "[Bytecart] " + ChatColor.YELLOW + "Ticket created successfully.");
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (!(sender instanceof Player)) {
if (args.length <= 1) {
// List players
return null;
} else {
return tabComplete(1, args);
}
} else {
return tabComplete(0, args);
}
}
}
| 1,819 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/package-info.java | /**
* Contains command executors for various commands.
*/
package com.github.catageek.ByteCart.Commands; | 106 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandMeGo.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandMeGo.java | package com.github.catageek.ByteCart.Commands;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.github.catageek.ByteCart.Signs.BC7010;
import com.github.catageek.ByteCartAPI.ByteCartPlugin;
public class CommandMeGo extends AbstractTicketCommand implements CommandExecutor, TabCompleter {
public CommandMeGo(ByteCartPlugin plugin) {
super(plugin);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
return true;
} else {
return parse(sender, (Player) sender, 0, args);
}
}
@Override
protected boolean run(CommandSender sender, Player player, String addressString, boolean isTrain) {
(new BC7010(player.getLocation().getBlock(), player)).setAddress(addressString, null, isTrain);
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return tabComplete(0, args);
}
}
| 1,215 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandBCReload.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandBCReload.java | package com.github.catageek.ByteCart.Commands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.Util.LogUtil;
public class CommandBCReload implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
ByteCart.myPlugin.reloadConfig();
ByteCart.myPlugin.loadConfig();
String s = "Configuration file reloaded.";
if (!(sender instanceof Player)) {
sender.sendMessage(s);
} else {
Player player = (Player) sender;
LogUtil.sendError(player, s);
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return Collections.emptyList();
}
}
| 1,011 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandSendTo.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandSendTo.java | package com.github.catageek.ByteCart.Commands;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.ModifiableRunnable;
import com.github.catageek.ByteCart.AddressLayer.AddressFactory;
import com.github.catageek.ByteCart.AddressLayer.AddressRouted;
import com.github.catageek.ByteCart.EventManagement.ByteCartInventoryListener;
import com.github.catageek.ByteCart.Signs.BC7011;
import com.github.catageek.ByteCart.Util.LogUtil;
import com.github.catageek.ByteCartAPI.ByteCartPlugin;
public class CommandSendTo extends AbstractTicketCommand implements CommandExecutor, TabCompleter {
public CommandSendTo(ByteCartPlugin plugin) {
super(plugin);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
return true;
} else {
return parse(sender, (Player) sender, 0, args);
}
}
private static final class Execute implements ModifiableRunnable<Inventory> {
private final Player player;
private final String address;
private Inventory inventory;
private boolean istrain;
private Execute(Player player, String host_or_address, boolean isTrain) {
this.player = player;
this.address = host_or_address;
this.istrain = isTrain;
}
@Override
public void run() {
if ((new BC7011(player.getLocation().getBlock(), ((org.bukkit.entity.Vehicle) inventory.getHolder()))).setAddress(address, null, this.istrain)) {
LogUtil.sendSuccess(player, ByteCart.myPlugin.getConfig().getString("Info.SetAddress") + " " + address);
LogUtil.sendSuccess(player, ByteCart.myPlugin.getConfig().getString("Info.GetTTL") + AddressFactory.<AddressRouted>getAddress(inventory).getTTL());
}
else
LogUtil.sendError(player, ByteCart.myPlugin.getConfig().getString("Error.SetAddress") );
}
/**
* @param inventory
* @param inventory the inventory to set
*/
@Override
public void SetParam(Inventory inventory) {
this.inventory = inventory;
}
}
@Override
protected boolean run(CommandSender sender, Player player, String addressString, boolean isTrain) {
player.sendMessage(ChatColor.DARK_GREEN + "[Bytecart] " + ChatColor.YELLOW + ByteCart.myPlugin.getConfig().getString("Info.RightClickCart") );
new ByteCartInventoryListener(ByteCart.myPlugin, player, new Execute(player, addressString, isTrain), false);
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return tabComplete(0, args);
}
}
| 2,910 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandBCUpdater.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandBCUpdater.java | package com.github.catageek.ByteCart.Commands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.util.StringUtil;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.ModifiableRunnable;
import com.github.catageek.ByteCart.EventManagement.ByteCartInventoryListener;
import com.github.catageek.ByteCart.EventManagement.ByteCartUpdaterMoveListener;
import com.github.catageek.ByteCart.Updaters.UpdaterFactory;
import com.github.catageek.ByteCart.Util.LogUtil;
import com.github.catageek.ByteCart.Wanderer.BCWandererManager;
import com.github.catageek.ByteCartAPI.Wanderer.Wanderer;
import com.google.common.collect.Lists;
public class CommandBCUpdater implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 1 && args[0].equalsIgnoreCase("remove")) {
BCWandererManager wm = ByteCart.myPlugin.getWandererManager();
wm.getFactory("Updater").removeAllWanderers();
wm.unregister("Updater");
return true;
}
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
} else {
Player player = (Player) sender;
int region = 0;
if(args.length == 0 || args.length > 4 || !Wanderer.Level.isMember(args[0].toLowerCase()))
return false;
if (args.length == 1 && ! args[0].equalsIgnoreCase("backbone")
&& ! args[0].equalsIgnoreCase("reset_backbone"))
return false;
boolean full_reset = false;
boolean isnew = false;
if (! ByteCart.myPlugin.getWandererManager().isRegistered("Updater"))
ByteCart.myPlugin.getWandererManager().register(new UpdaterFactory(), "Updater");
if (args.length >= 2){
if (! args[0].equalsIgnoreCase("region")
&& ! args[0].equalsIgnoreCase("local")
&& ! args[0].equalsIgnoreCase("reset_region")
&& ! args[0].equalsIgnoreCase("reset_local"))
return false;
region = Integer.parseInt(args[1]);
if (region < 1 || region > 2047)
return false;
if (args.length == 3) {
if (args[0].startsWith("reset")) {
if (args[2].equalsIgnoreCase("full"))
full_reset = true;
else
return false;
}
else
if (args[2].equalsIgnoreCase("new"))
isnew = true;
else
return false;
}
}
final class Execute implements ModifiableRunnable<Inventory> {
private final Player player;
private final Wanderer.Level level;
private final int region;
private Inventory inventory;
private boolean isfullreset;
private boolean isnew;
private Execute(Player player, Wanderer.Level level, int region, boolean isfullreset, boolean isnew) {
this.player = player;
this.level = level;
this.region = region;
this.isfullreset = isfullreset;
this.isnew = isnew;
}
@Override
public void run() {
int id = ((StorageMinecart) inventory.getHolder()).getEntityId();
// register updater factory
final BCWandererManager wm = ByteCart.myPlugin.getWandererManager();
if (! wm.isRegistered("Updater"))
wm.register(new UpdaterFactory(), "Updater");
wm.getFactory("Updater").createWanderer(id, inventory, region, level, player, isfullreset, isnew);
if (! ByteCartUpdaterMoveListener.isExist()) {
Listener updatermove = new ByteCartUpdaterMoveListener();
ByteCart.myPlugin.getServer().getPluginManager().registerEvents(updatermove, ByteCart.myPlugin);
ByteCartUpdaterMoveListener.setExist(true);
}
}
/**
* @param inventory
* @param inventory the inventory to set
*/
@Override
public void SetParam(Inventory inventory) {
this.inventory = inventory;
}
}
LogUtil.sendSuccess(player, ByteCart.myPlugin.getConfig().getString("Info.RightClickCart") );
new ByteCartInventoryListener(ByteCart.myPlugin, player
,new Execute(player, Wanderer.Level.valueOf(args[0].toUpperCase()), region
,full_reset, isnew)
,true);
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (!(sender instanceof Player)) {
if (args.length == 1 && StringUtil.startsWithIgnoreCase("remove", args[0])) {
return Lists.newArrayList("remove");
} else {
return Collections.emptyList();
}
}
if (args.length == 1) {
List<String> options = Lists.newArrayList("remove");
for (Wanderer.Level level : Wanderer.Level.values()) {
options.add(level.name);
}
return StringUtil.copyPartialMatches(args[0], options, Lists.newArrayList());
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("reset_backbone")) {
if (StringUtil.startsWithIgnoreCase("full", args[1])) {
return Lists.newArrayList("full");
}
}
} else if (args.length == 3) {
if (args[0].equalsIgnoreCase("region") || args[0].equalsIgnoreCase("local")) {
if (StringUtil.startsWithIgnoreCase("new", args[2])) {
return Lists.newArrayList("new");
}
} else if (args[0].equalsIgnoreCase("reset_region") || args[0].equalsIgnoreCase("reset_local")) {
if (StringUtil.startsWithIgnoreCase("full", args[2])) {
return Lists.newArrayList("full");
}
}
}
return Collections.emptyList();
}
}
| 5,646 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CommandBCBack.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/CommandBCBack.java | package com.github.catageek.ByteCart.Commands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.github.catageek.ByteCart.Signs.BC7017;
import com.github.catageek.ByteCart.Util.LogUtil;
public class CommandBCBack implements CommandExecutor, TabCompleter {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
return true;
}
Player player = (Player) sender;
(new BC7017(player.getLocation().getBlock(), player)).trigger();
LogUtil.sendSuccess(player, "Return back");
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return Collections.emptyList();
}
}
| 1,025 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractTicketCommand.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Commands/AbstractTicketCommand.java | package com.github.catageek.ByteCart.Commands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.github.catageek.ByteCart.AddressLayer.AddressString;
import com.github.catageek.ByteCartAPI.ByteCartPlugin;
import com.google.common.collect.Lists;
public abstract class AbstractTicketCommand {
protected final ByteCartPlugin plugin;
protected AbstractTicketCommand(ByteCartPlugin plugin) {
this.plugin = plugin;
}
/**
* Parses command arguments and then calls {@link #run}
*
* @param sender The entity that called the command
* @param player The player to execute on
* @param startIndex The index at which to start parsing the address
* @param args Arguments to parse from.
* @return true if successful
*/
protected final boolean parse(CommandSender sender, Player player, int startIndex, String[] args) {
if (args.length <= startIndex) {
return false;
}
String addressString;
boolean isTrain = false;
if (args[args.length-1].equalsIgnoreCase("train")) {
isTrain = true;
addressString = concat(args, startIndex, 1);
} else {
addressString = concat(args, startIndex, 0);
}
if (!AddressString.isResolvableAddressOrName(addressString)) {
sender.sendMessage(ChatColor.DARK_GREEN + "[Bytecart] " + ChatColor.RED + "No valid destination supplied.");
return false;
}
return run(sender, player, addressString, isTrain);
}
/**
* Gets a list of possible tab completion options.
*/
protected final List<String> tabComplete(int startIndex, String[] args) {
if (args.length <= startIndex) {
return Collections.emptyList();
}
String written = concat(args, startIndex, 1);
List<String> options = Lists.newArrayList();
if (plugin.getResolver() != null) {
String prefix = concat(args, startIndex, 0);
List<String> names = plugin.getResolver().getMatchingNames(prefix);
for (String name : names) {
name = name.substring(prefix.length());
if (name.contains(" ")) {
name = name.substring(0, name.indexOf(' '));
}
options.add(name);
}
}
if (StringUtil.startsWithIgnoreCase("train", args[args.length - 1])) {
if (AddressString.isResolvableAddressOrName(written)) {
options.add("train");
}
}
return options;
}
/**
* Performs actual command logic.
*
* @param sender The entity that called the command
* @param player The player to execute on
* @param addressString The address parsed from command arguments
* @param isTrain True if this is a train
* @return true if successful
*/
protected abstract boolean run(CommandSender sender, Player player, String addressString, boolean isTrain);
private static String concat(String[] s, int first, int omitted) {
if (s.length <= first) {
return "";
}
String ret = s[first];
for (int i = first + 1; i < s.length - omitted; ++i) {
ret += " ";
ret += s[i];
}
return ret;
}
}
| 3,026 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RightRouter.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/RightRouter.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCartAPI.Util.DirectionRegistry;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* A router where the cart turns right
*/
final class RightRouter extends AbstractRouter implements
Router {
RightRouter(BlockFace from, org.bukkit.Location loc, boolean b) {
super(from, loc, b);
FromTo.put(Side.BACK, Side.RIGHT);
FromTo.put(Side.LEFT, Side.LEFT);
FromTo.put(Side.STRAIGHT, Side.STRAIGHT);
FromTo.put(Side.RIGHT, Side.BACK);
setSecondpos(Integer.parseInt("00101001", 2));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractRouter#route(org.bukkit.block.BlockFace)
*/
@Override
public void route(BlockFace from) {
// activate main levers
this.getOutput(0).setAmount((new DirectionRegistry(MathUtil.anticlockwise(from))).getAmount());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractRouter#getTo()
*/
@Override
public BlockFace getTo() {
return MathUtil.anticlockwise(this.getFrom());
}
}
| 1,138 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CollisionAvoider.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/CollisionAvoider.java | package com.github.catageek.ByteCart.CollisionManagement;
import com.github.catageek.ByteCart.Signs.Triggable;
/**
* A state machine depending of 2 elements
*/
interface CollisionAvoider {
/**
* Get the value stored as second pos
*
* @return the value of the second position
*/
public int getSecondpos();
/**
* Add the second triggered IC to current CollisonAvoider
*
*
* @param t
*/
public void Add(Triggable t);
}
| 445 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/package-info.java | /**
*
*/
/**
* This package provides classes for collision management
*/
package com.github.catageek.ByteCart.CollisionManagement; | 135 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
LeftRouter.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/LeftRouter.java | package com.github.catageek.ByteCart.CollisionManagement;
import java.util.EnumSet;
import java.util.Set;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* A router where a cart turns left
*/
final class LeftRouter extends AbstractRouter implements
Router {
LeftRouter(BlockFace from, org.bukkit.Location loc, boolean b) {
super(from, loc, b);
FromTo.put(Side.BACK, Side.LEFT);
Set<Side> left = EnumSet.of(Side.LEFT, Side.STRAIGHT, Side.RIGHT);
Possibility.put(Side.LEFT, left);
Set<Side> straight = EnumSet.of(Side.STRAIGHT, Side.LEFT, Side.BACK);
Possibility.put(Side.STRAIGHT, straight);
Set<Side> right = EnumSet.of(Side.LEFT, Side.BACK);
Possibility.put(Side.RIGHT, right);
setSecondpos(Integer.parseInt("01000000", 2));
setPosmask(Integer.parseInt("11100000", 2));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractRouter#getTo()
*/
@Override
public BlockFace getTo() {
return MathUtil.clockwise(this.getFrom());
}
}
| 1,055 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BackRouter.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/BackRouter.java | package com.github.catageek.ByteCart.CollisionManagement;
import java.util.EnumSet;
import java.util.Set;
import org.bukkit.block.BlockFace;
/**
* A router where the cart goes back
*/
final class BackRouter extends AbstractRouter implements
Router {
BackRouter(BlockFace from, org.bukkit.Location loc, boolean b) {
super(from, loc, b);
FromTo.put(Side.BACK, Side.BACK);
Set<Side> left = EnumSet.of(Side.BACK, Side.LEFT);
Possibility.put(Side.LEFT, left);
Set<Side> straight = EnumSet.of(Side.RIGHT, Side.LEFT, Side.BACK);
Possibility.put(Side.STRAIGHT, straight);
Set<Side> right = EnumSet.of(Side.STRAIGHT, Side.BACK, Side.RIGHT);
Possibility.put(Side.RIGHT, right);
setSecondpos(Integer.parseInt("10000000", 2));
setPosmask(Integer.parseInt("11000001", 2));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractRouter#getTo()
*/
@Override
public final BlockFace getTo() {
return this.getFrom();
}
}
| 982 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractRouter.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/AbstractRouter.java | package com.github.catageek.ByteCart.CollisionManagement;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.HAL.PinRegistry;
import com.github.catageek.ByteCart.IO.OutputPin;
import com.github.catageek.ByteCart.IO.OutputPinFactory;
import com.github.catageek.ByteCart.Signs.Triggable;
import com.github.catageek.ByteCart.Storage.ExpirableMap;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
abstract class AbstractRouter extends AbstractCollisionAvoider implements Router {
private static final ExpirableMap<Location, Boolean> recentlyUsedMap = new ExpirableMap<Location, Boolean>(40, false, "recentlyUsedRouter");
private static final ExpirableMap<Location, Boolean> hasTrainMap = new ExpirableMap<Location, Boolean>(14, false, "hasTrainRouter");
private BlockFace From;
protected Map<Side, Side> FromTo = new ConcurrentHashMap<Side, Side>();
protected Map<Side, Set<Side>> Possibility = new ConcurrentHashMap<Side, Set<Side>>();
private int secondpos = 0;
private int posmask = 255;
private boolean IsOldVersion;
AbstractRouter(BlockFace from, org.bukkit.Location loc, boolean isOldVersion) {
super(loc);
this.setFrom(from);
this.IsOldVersion = isOldVersion;
this.addIO(from, loc.getBlock());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.CollisionAvoider#Add(com.github.catageek.ByteCart.Signs.Triggable)
*/
@Override
public void Add(Triggable t) {
return;
}
/**
* @return the isOldVersion
*/
private boolean isIsOldVersion() {
return IsOldVersion;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#WishToGo(org.bukkit.block.BlockFace, org.bukkit.block.BlockFace, boolean)
*/
@Override
public final BlockFace WishToGo(BlockFace from, BlockFace to, boolean isTrain) {
// IntersectionSide sfrom = getSide(from);
// IntersectionSide sto = getSide(to);
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Router : coming from " + from + " going to " + to);
/* if(ByteCart.debug)
ByteCart.log.info("ByteCart : Router : going to " + sto);
*/
Router ca = this;
/*
if(ByteCart.debug) {
ByteCart.log.info("ByteCart : position found " + ca.getClass().toString());
ByteCart.log.info("ByteCart : Recently used ? " + recentlyUsed);
ByteCart.log.info("ByteCart : hasTrain ? " + hasTrain );
ByteCart.log.info("ByteCart : isTrain ? " + isTrain );
}
*/
Side s = getSide(from, to);
boolean cond = !this.getRecentlyUsed() && !this.getHasTrain();
if (this.getPosmask() != 255 || cond) {
switch(s) {
case STRAIGHT:
ca = new StraightRouter(from, getLocation(), this.isIsOldVersion());
if ( (cond) || this.ValidatePosition(ca))
break;
case RIGHT:
ca = new RightRouter(from, getLocation(), this.isIsOldVersion());
if ( (cond) || this.ValidatePosition(ca))
break;
case LEFT:
ca = new LeftRouter(from, getLocation(), this.isIsOldVersion());
if ( (cond) || this.ValidatePosition(ca))
break;
case BACK:
ca = new BackRouter(from, getLocation(), this.isIsOldVersion());
if ( (cond) || this.ValidatePosition(ca))
break;
default:
ca = new LeftRouter(from, getLocation(), this.isIsOldVersion());
if ( (cond) || this.ValidatePosition(ca))
break;
ca = this;
}
/*
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Router : position changed to " + ca.getClass().toString());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Router : really going to " + ca.getTo());
*/ // save router in collision avoider map
ByteCart.myPlugin.getCollisionAvoiderManager().setCollisionAvoider(this.getLocation(), ca);
// activate secondary levers
ca.getOutput(1).setAmount(ca.getSecondpos());
ca.getOutput(2).setAmount(ca.getSecondpos());
//activate primary levers
ca.route(from);
}
ca.Book(isTrain);
return ca.getTo();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#route(org.bukkit.block.BlockFace)
*/
@Override
public void route(BlockFace from) {
return;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#getTo()
*/
@Override
public abstract BlockFace getTo();
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#getFrom()
*/
@Override
public final BlockFace getFrom() {
return From;
}
/**
* Tell if a transition is necessary for the router to satisfy direction request
*
* @param ca the collision avoider against which to check the state
* @return false if a transition is needed
*/
private final boolean ValidatePosition(Router ca) {
Side side = getSide(this.getFrom(), ca.getFrom());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : pos value befor rotation : " + Integer.toBinaryString(getSecondpos()));
if(ByteCart.debug)
ByteCart.log.info("ByteCart : rotation of bits : " + side.Value());
int value = AbstractRouter.leftRotate8(getSecondpos(), side.Value());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : pos value after rotation : " + Integer.toBinaryString(value));
int mask = AbstractRouter.leftRotate8(getPosmask(), side.Value());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : mask after rotation : " + Integer.toBinaryString(mask));
ca.setSecondpos(value | ca.getSecondpos());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : value after OR : " + Integer.toBinaryString(ca.getSecondpos()));
ca.setPosmask(mask | ca.getPosmask());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : mask after OR : " + Integer.toBinaryString(ca.getPosmask()));
if(ByteCart.debug)
ByteCart.log.info("ByteCart : compatible ? : " + (((value ^ ca.getSecondpos()) & mask) == 0));
return ((value ^ ca.getSecondpos()) & mask) == 0;
}
/**
* @param from the from to set
*/
private final void setFrom(BlockFace from) {
From = from;
}
/**
* Get the relative direction of an absolute direction
*
* @param to the absolute direction
* @return the relative direction
*/
@SuppressWarnings("unused")
private final Side getSide(BlockFace to) {
return getSide(getFrom(), to);
}
/**
* Get the relative direction of an absolute direction with a specific origin
*
* @param from the origin axis
* @param to the absolute direction
* @return the relative direction
*/
private final static Side getSide(BlockFace from, BlockFace to) {
BlockFace t = to;
if (from == t)
return Side.BACK;
t = turn(t);
if (from == t)
return Side.LEFT;
t = turn(t);
if (from == t)
return Side.STRAIGHT;
return Side.RIGHT;
}
/**
* Get the next absolute direction on the left
*
* @param b the initial direction
* @return the next direction
*/
private final static BlockFace turn(BlockFace b) {
return MathUtil.anticlockwise(b);
}
/**
* Registers levers as output
*
* @param from the origin axis
* @param center the center of the router
*/
private final void addIO(BlockFace from, org.bukkit.block.Block center) {
BlockFace f = from;
BlockFace g = MathUtil.clockwise(from);
// Main output
OutputPin[] sortie = new OutputPin[4];
if(this.isIsOldVersion()) {
// East
sortie[0] = OutputPinFactory.getOutput(center.getRelative(BlockFace.WEST,3).getRelative(BlockFace.SOUTH));
// North
sortie[1] = OutputPinFactory.getOutput(center.getRelative(BlockFace.EAST,3).getRelative(BlockFace.NORTH));
// South
sortie[3] = OutputPinFactory.getOutput(center.getRelative(BlockFace.SOUTH,3).getRelative(BlockFace.EAST));
// West
sortie[2] = OutputPinFactory.getOutput(center.getRelative(BlockFace.NORTH,3).getRelative(BlockFace.WEST));
}
else {
// East
sortie[0] = OutputPinFactory.getOutput(center.getRelative(BlockFace.SOUTH,3).getRelative(BlockFace.EAST));
// North
sortie[1] = OutputPinFactory.getOutput(center.getRelative(BlockFace.NORTH,3).getRelative(BlockFace.WEST));
// South
sortie[3] = OutputPinFactory.getOutput(center.getRelative(BlockFace.WEST,3).getRelative(BlockFace.SOUTH));
// West
sortie[2] = OutputPinFactory.getOutput(center.getRelative(BlockFace.EAST,3).getRelative(BlockFace.NORTH));
}
checkIOPresence(sortie);
RegistryOutput main = new PinRegistry<OutputPin>(sortie);
// output[0] is main levers
this.addOutputRegistry(main);
// Secondary output to make U-turn
OutputPin[] secondary = new OutputPin[8];
// Alternate secondary output to make U-turn (for new BC8011 router)
OutputPin[] altsecond = new OutputPin[8];
for (int i=0; i<7; i++) {
// the first is Back
altsecond[i] = OutputPinFactory.getOutput(center.getRelative(f, 3).getRelative(g, 1));
secondary[i++] = OutputPinFactory.getOutput(center.getRelative(f, 4).getRelative(g, 2));
altsecond[i] = OutputPinFactory.getOutput(center.getRelative(f, 5).getRelative(g, 1));
secondary[i] = OutputPinFactory.getOutput(center.getRelative(f, 6));
f = g;
g = MathUtil.clockwise(g);
}
checkIOPresence(secondary, altsecond);
RegistryOutput second = new PinRegistry<OutputPin>(secondary);
RegistryOutput altsec = new PinRegistry<OutputPin>(altsecond);
// output[1] is second and third levers
this.addOutputRegistry(second);
// output[2] is alternate second and third levers
this.addOutputRegistry(altsec);
}
/**
* Check if there are levers as expected
*
* @param secondary an array of levers
* @param altsecond alternative array of levers
*/
private void checkIOPresence(OutputPin[] secondary, OutputPin[] altsecond) {
for (int i = 0; i < secondary.length; i++)
if (secondary[i] == null && altsecond[i] == null) {
ByteCart.log.log(java.util.logging.Level.SEVERE, "ByteCart : Lever missing or wrongly positioned in router " + this.getLocation());
throw new NullPointerException();
}
}
/**
* Check if there are levers as expected
*
* @param sortie an array of levers
*/
private void checkIOPresence(OutputPin[] sortie) {
for (int i = 0; i < sortie.length; i++)
if (sortie[i] == null) {
ByteCart.log.log(java.util.logging.Level.SEVERE, "ByteCart : Lever missing or wrongly positioned in router " + this.getLocation());
throw new NullPointerException();
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#getSecondpos()
*/
@Override
public final int getSecondpos() {
return secondpos;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#getPosmask()
*/
@Override
public final int getPosmask() {
return posmask;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#setPosmask(int)
*/
@Override
public final void setPosmask(int posmask) {
this.posmask = posmask;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.Router#setSecondpos(int)
*/
@Override
public final void setSecondpos(int secondpos) {
this.secondpos = secondpos;
}
/**
* Bit-rotate a value on 8 bits
*
* @param value the value to rotate
* @param d the numbers of bits to shift left
* @return the result
*/
private final static int leftRotate8(int value, int d) {
int b = 8 - d;
return (value >> (b)) | ((value & ((1 << b) - 1)) << d);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractCollisionAvoider#getRecentlyUsedMap()
*/
@Override
protected ExpirableMap<Location, Boolean> getRecentlyUsedMap() {
return recentlyUsedMap;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractCollisionAvoider#getHasTrainMap()
*/
@Override
protected ExpirableMap<Location, Boolean> getHasTrainMap() {
return hasTrainMap;
}
}
| 11,970 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RouterCollisionAvoiderBuilder.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/RouterCollisionAvoiderBuilder.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.Signs.Triggable;
/**
* A builder for router collision avoider
*/
public class RouterCollisionAvoiderBuilder extends AbstractCollisionAvoiderBuilder implements CollisionAvoiderBuilder {
private boolean IsOldVersion;
public RouterCollisionAvoiderBuilder(Triggable ic, Location loc, boolean isOldVersion) {
super(ic, loc);
this.IsOldVersion = isOldVersion;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.CollisionAvoiderBuilder#getCollisionAvoider()
*/
@SuppressWarnings("unchecked")
@Override
public <T extends CollisionAvoider> T getCollisionAvoider() {
return (T) new StraightRouter (this.ic.getCardinal().getOppositeFace(), this.loc, this.IsOldVersion);
}
}
| 837 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
SimpleCollisionAvoiderBuilder.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/SimpleCollisionAvoiderBuilder.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.Signs.Triggable;
/**
* A builder for simple collision avoider, i.e for a T cross-roads
*/
public class SimpleCollisionAvoiderBuilder extends AbstractCollisionAvoiderBuilder implements CollisionAvoiderBuilder {
public SimpleCollisionAvoiderBuilder(Triggable ic, Location loc) {
super(ic, loc);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.CollisionAvoiderBuilder#getCollisionAvoider()
*/
@Override
@SuppressWarnings("unchecked")
public <T extends CollisionAvoider> T getCollisionAvoider() {
return (T) new SimpleCollisionAvoider (this.ic, this.loc);
}
}
| 734 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Router.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/Router.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
/**
* A router representation in the collision management layer
*/
public interface Router extends CollisionAvoider {
/**
* Ask for a direction, requesting a possible transition
*
* @param from the direction from where comes the cart
* @param to the direction where the cart goes to
* @param isTrain true if it is a train
* @return the direction actually taken
*/
public <T extends Router> BlockFace WishToGo(BlockFace from, BlockFace to, boolean isTrain);
/**
* Book the router, i.e mark it as currently in use
*
* @param b true if this is a train
*/
public void Book(boolean b);
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.CollisionAvoider#getSecondpos()
*/
@Override
public int getSecondpos() ;
/**
* Get the mask of the current usage of the router, starting from the origin axis.
*
* <p>a bit to 1 means the lever is blocked, a bit to 0 means the lever is not blocked</p>
*
* @return the mask
*/
public int getPosmask() ;
/**
* Set the mask of the current usage of the router, starting from the origin axis.
*
* <p>a bit to 1 means the lever is blocked, a bit to 0 means the lever is not blocked</p>
*
* @param posmask the mask to set
*/
public void setPosmask(int posmask) ;
/**
* Set the value of the position of the 8 exterior levers, starting from the origin axis.
*
* <p>a bit to 1 means the lever is on, a bit to 0 means the lever is off</p>
*
* @param secondpos the value to set
*/
public void setSecondpos(int secondpos) ;
/**
* Get the direction from where the cart is coming.
*
* <p>This direction is also the origin axis of the registries</p>
*
*
* @return the direction
*/
public BlockFace getFrom();
/**
* Activate levers according to registry
*
*
* @param from the origin direction
*/
public void route(BlockFace from);
/**
* Get the lever registry
*
* @param i 0 for main levers, 1 for secondary levers
* @return the value of the registry
*/
public RegistryOutput getOutput(int i);
/**
* Get the direction where the cart eventually go
*
*
* @return the direction
*/
public BlockFace getTo();
}
| 2,333 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CollisionAvoiderManager.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/CollisionAvoiderManager.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.Storage.ExpirableMap;
/**
* Manage the persistence of collision avoiders
*/
public final class CollisionAvoiderManager {
/**
* The map where collision avoiders are stored for 4 seconds
*/
private final ExpirableMap<Location, CollisionAvoider> manager = new ExpirableMap<Location, CollisionAvoider>(40, false, "CollisionAvoider");
/**
* Get the map
*
* @return the map
*/
private ExpirableMap<Location, CollisionAvoider> getManager() {
return manager;
}
/**
* Get an existing collision avoider, or create one
*
* @param builder a class providing an instance of the collision avoider
* @return the collision avoider
*/
@SuppressWarnings("unchecked")
public final synchronized <T extends CollisionAvoider> T getCollisionAvoider(CollisionAvoiderBuilder builder) {
Location loc = builder.getLocation();
T cm;
// Get an instance from the map
cm = (T) this.getManager().get(loc);
if(cm != null) {
// if a collision avoider exists, attach itself as second IC
cm.Add(builder.getIc());
this.getManager().reset(loc);
}
else
{
// Get a new instance
cm = builder.<T>getCollisionAvoider();
// store the instance in the map
this.getManager().put(loc, cm);
}
return cm;
}
/**
* Set or replace the collision avoider stored at a specific location
*
* @param loc the location
* @param ca the collision avoider to store
*/
final void setCollisionAvoider(Location loc, CollisionAvoider ca) {
this.getManager().put(loc, ca);
}
}
| 1,632 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
SimpleCollisionAvoider.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/SimpleCollisionAvoider.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.Signs.Triggable;
import com.github.catageek.ByteCart.Storage.ExpirableMap;
import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
/**
* A collision avoider for T cross-roads
*/
public class SimpleCollisionAvoider extends AbstractCollisionAvoider implements CollisionAvoider {
private static final ExpirableMap<Location, Boolean> recentlyUsedMap = new ExpirableMap<Location, Boolean>(20, false, "recentlyUsed9000");
private static final ExpirableMap<Location, Boolean> hasTrainMap = new ExpirableMap<Location, Boolean>(14, false, "hastrain");
private RegistryOutput Lever1 = null, Lever2 = null, Active = null;
private final Location loc1;
private IntersectionSide.Side state;
private boolean reversed;
SimpleCollisionAvoider(Triggable ic, org.bukkit.Location loc) {
super(loc);
if(ByteCart.debug)
ByteCart.log.info("ByteCart: new IntersectionSide() at " + loc);
Lever1 = ic.getOutput(0);
Active = Lever1;
reversed = ic.isLeverReversed();
loc1 = ic.getLocation();
state = (Lever1.getAmount() == 0 ? IntersectionSide.Side.LEVER_OFF : IntersectionSide.Side.LEVER_ON);
}
/**
* Ask for a direction, requesting a possible transition
*
* @param s the direction where the cart goes to
* @param isTrain true if it is a train
* @return the direction actually taken
*/
public IntersectionSide.Side WishToGo(IntersectionSide.Side s, boolean isTrain) {
IntersectionSide.Side trueside = getActiveTrueSide(s);
if(ByteCart.debug)
ByteCart.log.info("ByteCart : WishToGo to side " + trueside + " and isTrain is " + isTrain);
if(ByteCart.debug)
ByteCart.log.info("ByteCart : state is " + state);
if(ByteCart.debug)
ByteCart.log.info("ByteCart : recentlyUsed is " + this.getRecentlyUsed() + " and hasTrain is " + this.getHasTrain());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Lever1 is " + Lever1.getAmount());
if ( trueside != state
&& (Lever2 == null
|| ( !this.getRecentlyUsed()) && !this.getHasTrain())) {
Set(trueside);
}
this.setRecentlyUsed(true);
return state;
}
/**
* Get the fixed side of the active lever.
* the second IC lever can be reversed
*
* @param s the original side
* @return the fixed side
*/
private final IntersectionSide.Side getActiveTrueSide(IntersectionSide.Side s) {
if (Active != Lever2)
return s;
return getSecondLeverSide(s);
}
/**
* Get the fixed side of the second lever
* @param s the original side
* @return the fixed side
*/
private final IntersectionSide.Side getSecondLeverSide(IntersectionSide.Side s) {
return reversed ? s : s.opposite();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.CollisionAvoider#Add(com.github.catageek.ByteCart.Signs.Triggable)
*/
@Override
public void Add(Triggable t) {
if (t.getLocation().equals(loc1)) {
Active = Lever1;
return;
}
if (Lever2 != null) {
Active = Lever2;
return;
}
Lever2 = t.getOutput(0);
Active = Lever2;
reversed ^= t.isLeverReversed();
Lever2.setAmount(getSecondLeverSide(state).Value());
if(ByteCart.debug)
ByteCart.log.info("ByteCart: Add and setting lever2 to " + Lever2.getAmount());
}
/**
* Activate levers. The 2 levers are in opposition
*
* @param s the side of the lever of the IC that created this collision avoider
*/
private void Set(IntersectionSide.Side s) {
this.Lever1.setAmount(s.Value());
if(ByteCart.debug)
ByteCart.log.info("ByteCart: Setting lever1 to " + Lever1.getAmount());
if (this.Lever2 != null) {
this.Lever2.setAmount(getSecondLeverSide(state).Value());
if(ByteCart.debug)
ByteCart.log.info("ByteCart: Setting lever2 to " + Lever2.getAmount());
}
state = s;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.CollisionAvoider#getSecondpos()
*/
@Override
public int getSecondpos() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractCollisionAvoider#getRecentlyUsedMap()
*/
@Override
protected ExpirableMap<Location, Boolean> getRecentlyUsedMap() {
return recentlyUsedMap;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractCollisionAvoider#getHasTrainMap()
*/
@Override
protected ExpirableMap<Location, Boolean> getHasTrainMap() {
return hasTrainMap;
}
}
| 4,620 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
StraightRouter.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/StraightRouter.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCartAPI.Util.DirectionRegistry;
/**
* A router where the cart goes straight
*/
class StraightRouter extends AbstractRouter implements Router {
StraightRouter(BlockFace from, org.bukkit.Location loc, boolean isOldVersion) {
super(from, loc, isOldVersion);
FromTo.put(Side.BACK, Side.STRAIGHT);
FromTo.put(Side.LEFT, Side.LEFT);
FromTo.put(Side.STRAIGHT, Side.RIGHT);
FromTo.put(Side.RIGHT, Side.BACK);
setSecondpos(Integer.parseInt("00100101", 2));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractRouter#route(org.bukkit.block.BlockFace)
*/
@Override
public void route(BlockFace from) {
// activate main levers
this.getOutput(0).setAmount((new DirectionRegistry(from.getOppositeFace())).getAmount());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.CollisionManagement.AbstractRouter#getTo()
*/
@Override
public final BlockFace getTo() {
return this.getFrom().getOppositeFace();
}
}
| 1,097 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractCollisionAvoiderBuilder.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/AbstractCollisionAvoiderBuilder.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.Signs.Triggable;
/**
* Abstract class for colllision avoider builders
*/
abstract class AbstractCollisionAvoiderBuilder {
/**
* The first IC attached to the collision avoiders created
*/
protected final Triggable ic;
/**
* The location to where the collision avoiders will be attached
*/
protected final Location loc;
AbstractCollisionAvoiderBuilder(Triggable ic, Location loc) {
this.ic = ic;
this.loc = loc;
}
/**
* Get the location to where the collision avoiders created will be attached
*
* @return the location
*/
public Location getLocation() {
return this.loc;
}
/**
* Get the IC to which the collision avoiders created will be attached
*
*
* @return the IC
*/
public Triggable getIc() {
return ic;
}
}
| 890 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
CollisionAvoiderBuilder.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/CollisionAvoiderBuilder.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.Signs.Triggable;
/**
* A builder for a collision manager
*/
public interface CollisionAvoiderBuilder {
/**
* Get an instance of the collision manager
*
* @return an instance of collision manager
*/
public <T extends CollisionAvoider> T getCollisionAvoider();
/**
* Get the location to where the collision managers built will be attached
*
*
* @return the location
*/
public Location getLocation();
/**
* Get the IC attached to the collision managers built
*
*
* @return the IC
*/
public Triggable getIc();
}
| 670 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractCollisionAvoider.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/CollisionManagement/AbstractCollisionAvoider.java | package com.github.catageek.ByteCart.CollisionManagement;
import org.bukkit.Location;
import com.github.catageek.ByteCart.HAL.AbstractIC;
import com.github.catageek.ByteCart.Storage.ExpirableMap;
/**
* Abstract class for collision avoiders
*/
abstract class AbstractCollisionAvoider extends AbstractIC {
/**
* Get a map of locations that have been recently used
*
* @return the map
*/
abstract protected ExpirableMap<Location, Boolean> getRecentlyUsedMap();
/**
* Get a map of locations that have the train flag
*
*
* @return the map
*/
abstract protected ExpirableMap<Location, Boolean> getHasTrainMap();
/**
* Relative direction for the router. BACK is the direction from where the cart is arriving
*/
enum Side {
BACK (0),
LEFT (2),
STRAIGHT (4),
RIGHT(6);
private int Value;
Side(int b) {
Value = b;
}
int Value() {
return Value;
}
}
/**
* @param loc the location where the collision avoider will be attached
*/
AbstractCollisionAvoider(org.bukkit.Location loc) {
super(loc.getBlock());
}
/**
* Tell if this collision avoider has the train flag set
*
* @return true if the flag is set
*/
protected boolean getHasTrain() {
return this.getHasTrainMap().contains(getLocation());
}
/**
* Tell if this collision avoider has been recently used
*
* @return true if recently used
*/
protected boolean getRecentlyUsed() {
return this.getRecentlyUsedMap().contains(getLocation());
}
/**
* @param hasTrain the hasTrain to set
*/
private void setHasTrain(boolean hasTrain) {
this.getHasTrainMap().put(getLocation(), hasTrain);
}
/**
* @param recentlyUsed the recentlyUsed to set
*/
protected void setRecentlyUsed(boolean recentlyUsed) {
this.getRecentlyUsedMap().put(getLocation(), recentlyUsed);
}
/**
* {@link Router#Book(boolean)}
*/
public void Book(boolean isTrain) {
setRecentlyUsed(true);
setHasTrain(this.getHasTrain() | isTrain);
}
@Override
public final String getName() {
return "Collision avoider";
}
@Override
public final String getFriendlyName() {
return getName();
}
}
| 2,129 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
LogUtil.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Util/LogUtil.java | package com.github.catageek.ByteCart.Util;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.catageek.ByteCart.ByteCart;
public final class LogUtil {
public static void sendError(CommandSender sender, String message) {
display(sender, ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + message);
}
public static void sendSuccess(CommandSender sender, String message) {
display(sender, ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + message);
}
private static void display(CommandSender sender, String message) {
if (sender != null && (sender instanceof Player) && ((Player) sender).isOnline())
sender.sendMessage(message);
else
ByteCart.log.info(ChatColor.stripColor(message));
}
}
| 790 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Base64.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Util/Base64.java | package com.github.catageek.ByteCart.Util;
import java.util.Arrays;
public class Base64
{
private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static final int[] IA = new int[256];
static {
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
private final static char[] encodeToChar(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new char[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
char[] dArr = new char[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = CA[(i >>> 18) & 0x3f];
dArr[d++] = CA[(i >>> 12) & 0x3f];
dArr[d++] = CA[(i >>> 6) & 0x3f];
dArr[d++] = CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = CA[i >> 12];
dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
byte[] dArr = new byte[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
dArr[d++] = (byte) CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't an even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = (byte) CA[i >> 12];
dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
public final static String encodeToString(byte[] sArr, boolean lineSep)
{
// Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
return new String(encodeToChar(sArr, lineSep));
}
public final static byte[] decodeFast(String s)
{
// Check special case
int sLen = s.length();
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[s.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
} | 5,218 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ComponentButton.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/ComponentButton.java | package com.github.catageek.ByteCart.IO;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Powerable;
import org.bukkit.block.data.type.Switch;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* A button
*/
class ComponentButton extends AbstractComponent implements OutputPin, InputPin {
final static private Map<Location, Integer> ActivatedButtonMap = new ConcurrentHashMap<Location, Integer>();
/**
* @param block the block containing the component
*/
protected ComponentButton(Block block) {
super(block);
/* if(ByteCart.debug)
ByteCart.log.info("ByteCart : adding Button at " + block.getLocation().toString());
*/
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.IO.OutputPin#write(boolean)
*/
@Override
public void write(boolean bit) {
final Block block = this.getBlock();
final BlockData blockdata = block.getBlockData();
if(blockdata instanceof Switch) {
final ComponentButton component = this;
int id;
final Switch button = (Switch) block.getBlockData();
if (bit) {
if (ActivatedButtonMap.containsKey(block)) {
// if button is already on, we cancel the scheduled thread
ByteCart.myPlugin.getServer().getScheduler().cancelTask(ActivatedButtonMap.get(block));
// and we reschedule one
id = ByteCart.myPlugin.getServer().getScheduler().scheduleSyncDelayedTask(ByteCart.myPlugin, new SetButtonOff(component, ActivatedButtonMap)
, 40);
// We update the HashMap
ActivatedButtonMap.put(block.getLocation(), id);
}
else {
// if button is off, we power the button
button.setPowered(true);
block.setBlockData(button);
MathUtil.forceUpdate(block.getRelative(button.getFacing().getOppositeFace()));
// delayed action to unpower the button after 2 s.
id = ByteCart.myPlugin.getServer().getScheduler().scheduleSyncDelayedTask(ByteCart.myPlugin, new SetButtonOff(component, ActivatedButtonMap)
, 40);
// We update the HashMap
ActivatedButtonMap.put(block.getLocation(), id);
}
}
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.IO.InputPin#read()
*/
@Override
public boolean read() {
final BlockData md = this.getBlock().getBlockData();
if(md instanceof Powerable) {
return ((Powerable) md).isPowered();
}
return false;
}
}
| 2,563 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
SetButtonOff.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/SetButtonOff.java | package com.github.catageek.ByteCart.IO;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.data.type.Switch;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* this call represents a thread that powers off a button
*/
class SetButtonOff implements Runnable {
final private Component component;
final private Map<Location, Integer> ActivatedButtonMap;
/**
* @param component the component to power off
* @param ActivatedButtonMap a map containing the task id of current task
*/
SetButtonOff(Component component, Map<Location, Integer> ActivatedButtonMap){
this.component = component;
this.ActivatedButtonMap = ActivatedButtonMap;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
final Block block = component.getBlock();
if (block.getBlockData() instanceof Switch) {
final Switch button = (Switch) block.getBlockData();
button.setPowered(false);
block.setBlockData(button);
MathUtil.forceUpdate(block.getRelative(button.getFacing().getOppositeFace()));
}
ActivatedButtonMap.remove(block.getLocation());
}
}
| 1,161 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractComponent.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/AbstractComponent.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.block.Block;
/**
* Abstract class containing common methods for all components
*/
public abstract class AbstractComponent implements Component {
private final Block block;
/**
* @param block the block containing the component
*/
protected AbstractComponent(Block block) {
this.block = block;
}
/**
* @return the block
*/
@Override
public Block getBlock() {
return block;
}
}
| 461 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/package-info.java | /**
*
*/
/**
* This package contains all classes for accessing in-game components
*/
package com.github.catageek.ByteCart.IO; | 130 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
OutputPinFactory.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/OutputPinFactory.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.data.type.Switch;
/**
* Factory to get an instance of an output component
*/
final public class OutputPinFactory {
/**
* Get an instance of the output component
*
* @param block block containing the component
* @return the instance
*/
static public OutputPin getOutput(Block block) {
if(block.getBlockData() instanceof Switch) {
final Switch myswitch = (Switch) block.getBlockData();
if(myswitch.getMaterial().equals(Material.LEVER)) {
return new ComponentLever(block);
}
else {
return new ComponentButton(block);
}
}
return null;
}
}
| 712 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
OutputPin.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/OutputPin.java | package com.github.catageek.ByteCart.IO;
/**
* Represents a writable component, storing a single bit
*/
public interface OutputPin {
/**
* write the bit
*
* @param bit true to write 1, false to write 0
*/
public void write(boolean bit);
}
| 253 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
InputFactory.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/InputFactory.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.block.Block;
import org.bukkit.block.data.AnaloguePowerable;
import org.bukkit.block.data.Powerable;
/**
* A factory for input pins
*/
final public class InputFactory {
/**
* Get an instance of the input component
*
* @param block block containing the component
* @return the instance
*/
@SuppressWarnings("unchecked")
static public <T> T getInput(Block block) {
if(block.getBlockData() instanceof AnaloguePowerable) {
return (T) new ComponentWire(block);
}
if(block.getBlockData() instanceof Powerable) {
return (T) new ComponentLever(block);
}
return null;
}
}
| 667 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ComponentSign.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/ComponentSign.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.github.catageek.ByteCart.ByteCart;
/**
* A sign
*/
public final class ComponentSign extends AbstractComponent {
/**
* @param block the block containing the component
*/
public ComponentSign(Block block) {
super(block);
}
/**
* Set a line of the sign
*
* @param line index of the line
* @param s the text to write
*/
public void setLine(int line, String s) {
final BlockState blockstate = this.getBlock().getState();
if (blockstate instanceof org.bukkit.block.Sign) {
((org.bukkit.block.Sign) blockstate).setLine(line, s);
blockstate.update();
}
}
/**
* Get a line of a sign
*
* @param line index of the line
* @return the text
*/
public String getLine(int line) {
final BlockState blockstate = this.getBlock().getState();
if (blockstate instanceof org.bukkit.block.Sign)
return ((org.bukkit.block.Sign) blockstate).getLine(line);
else {
ByteCart.log.info("ByteCart: AddressSign cannot be built");
throw new IllegalArgumentException();
}
}
}
| 1,134 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ComponentWire.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/ComponentWire.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.block.Block;
import org.bukkit.block.data.AnaloguePowerable;
import com.github.catageek.ByteCartAPI.HAL.RegistryInput;
/**
* A Redstone wire
*/
class ComponentWire extends AbstractComponent implements InputPin, RegistryInput {
/**
* @param block the block containing the wire
*/
ComponentWire(Block block) {
super(block);
/* if(ByteCart.debug)
ByteCart.log.info("ByteCart : adding Redstone wire at " + block.getLocation().toString());
*/ }
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.IO.InputPin#read()
*/
@Override
public boolean read() {
if(((AnaloguePowerable) this.getBlock().getBlockData()).getPower() != 0) {
// if(ByteCart.debug)
// ByteCart.log.info("Redstone wire on at (" + this.getBlock().getLocation().toString() + ")");
return true;
}
// if(ByteCart.debug)
// ByteCart.log.info("Redstone wire off at (" + this.getBlock().getLocation().toString() + ")");
return false;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryInput#getBit(int)
*/
@Override
public boolean getBit(int index) {
final AnaloguePowerable wire = ((AnaloguePowerable) this.getBlock().getBlockData());
return (wire.getPower() & 1 << (length() - index)) != 0;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#getAmount()
*/
@Override
public int getAmount() {
return ((AnaloguePowerable) this.getBlock().getBlockData()).getPower();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#length()
*/
@Override
public int length() {
return 4;
}
}
| 1,624 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ComponentLever.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/ComponentLever.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Powerable;
import org.bukkit.block.data.type.Switch;
import org.bukkit.block.data.type.Switch.Face;
import com.github.catageek.ByteCartAPI.HAL.RegistryInput;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
/**
* A lever
*/
class ComponentLever extends AbstractComponent implements OutputPin, InputPin, RegistryInput {
/**
* @param block the block containing the component
*/
ComponentLever(Block block) {
super(block);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.IO.OutputPin#write(boolean)
*/
@Override
public void write(boolean bit) {
final Block block = this.getBlock();
final BlockData md = block.getBlockData();
if(md instanceof Switch) {
Switch pw = (Switch) md;
pw.setPowered(bit);
block.setBlockData(pw);
Face face = pw.getFace();
switch (face) {
case CEILING:
MathUtil.forceUpdate(block.getRelative(BlockFace.UP,2));
break;
case WALL:
MathUtil.forceUpdate(block.getRelative(pw.getFacing().getOppositeFace()));
break;
default:
MathUtil.forceUpdate(block.getRelative(BlockFace.DOWN));
}
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.IO.InputPin#read()
*/
@Override
public boolean read() {
BlockData md = this.getBlock().getBlockData();
if(md instanceof Powerable) {
return ((Powerable) md).isPowered();
}
return false;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryInput#getBit(int)
*/
@Override
public boolean getBit(int index) {
return read();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#getAmount()
*/
@Override
public int getAmount() {
return (read() ? 15 : 0);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#length()
*/
@Override
public int length() {
return 4;
}
}
| 1,990 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
InputPin.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/InputPin.java | package com.github.catageek.ByteCart.IO;
/**
* Represents a readable component, giving 1 bit
*/
public interface InputPin {
/**
* Read the bit
*
* @return true if 1, false otherwise
*/
public boolean read();
}
| 223 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Component.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/IO/Component.java | package com.github.catageek.ByteCart.IO;
import org.bukkit.block.Block;
/**
* Represents a component, i.e a lever, a button, etc.
*/
interface Component {
/**
* Get the block containing the component
*
* @return the block
*/
public Block getBlock();
}
| 267 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BookInputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/BookInputStream.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.ByteArrayInputStream;
import org.bukkit.ChatColor;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.Util.Base64;
/**
* An input stream to read from book
*/
class BookInputStream extends ByteArrayInputStream {
/**
* @param book the book
* @param binary set binary mode
*/
BookInputStream(BookMeta book, boolean binary) {
super(readPagesAsBytes(book, binary));
}
/**
* @param outputstream the output stream from where we read data
*/
BookInputStream(ItemStackMetaOutputStream outputstream) {
super(outputstream.getBuffer());
}
public String getBuffer() {
return new String(this.buf);
}
/**
* Copy all pages of a book in a array of bytes
*
* @param book the book
* @param binary binary mode
* @return the array of bytes
*/
public static String readPages(BookMeta book, boolean binary) {
String sb = getRawPages(book);
if (binary)
return new String(Base64.decodeFast(sb));
return sb;
}
/**
* Copy all pages of a book in a array of bytes
*
* @param book the book
* @param binary binary mode
* @return the array of bytes
*/
private static byte[] readPagesAsBytes(BookMeta book, boolean binary) {
String sb = getRawPages(book);
if (binary)
return Base64.decodeFast(sb);
return sb.getBytes();
}
private static String getRawPages(BookMeta book) {
int len = book.getPageCount() * BookOutputStream.PAGESIZE;
StringBuilder sb = new StringBuilder(len);
for (int i = 1; i <= book.getPageCount(); ++i) {
sb.append(ChatColor.stripColor(book.getPage(i)));
}
sb.trimToSize();
return sb.toString();
}
} | 1,682 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BookProperties.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/BookProperties.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import com.github.catageek.ByteCart.ByteCart;
/**
* A property file with a book as container
*/
public final class BookProperties implements Closeable, Flushable {
private final Properties Properties = new Properties();
private final Conf PageNumber;
private final BCFile file;
private boolean isClosed = false;
private OutputStream os = null;
/**
* The page names
*/
public enum Conf {
NETWORK("Network"),
BILLING("Billing"),
ACCESS("Access"),
PROTECTION("Protection"),
HISTORY("History");
private final String name;
Conf(String name) {
this.name = name;
}
}
/**
* @param file the file
* @param page the page
*/
public BookProperties(BCFile file, Conf page) {
super();
this.file = file;
try {
Properties.load(file.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PageNumber = page;
}
/**
* Set a property
*
* @param key the key
* @param value the value
* @throws IOException
*/
public void setProperty(String key, String value) throws IOException {
if (ByteCart.debug)
ByteCart.log.info("ByteCart: BookProperties : setting key " + key + " to " + value);
Properties.setProperty(key, value);
}
/**
* Save the content of the property buffer to the book
*
* @throws IOException
*/
private void save() throws IOException {
file.clear();
os = file.getOutputStream();
Properties.store(os, PageNumber.name);
}
/**
* Removes a property
*
* @param key the key to remove
* @throws IOException
*/
public void clearProperty(String key) throws IOException {
if (ByteCart.debug)
ByteCart.log.info("ByteCart: BookProperties : clearing key " + key);
Properties.remove(key);
}
/**
* Get the property value
*
* @param key the property key
* @return the value
*/
public String getString(String key) {
return Properties.getProperty(key);
}
/**
* Get the property value or a default value
*
* @param key the property key
* @param defaultvalue the default value
* @return the value, or the default value
*/
public String getString(String key, String defaultvalue) {
return Properties.getProperty(key, defaultvalue);
}
/**
* Get a property value as an integer or a default value
*
* @param key the property key
* @param defaultvalue the default value
* @return the value
*/
public int getInt(String key, int defaultvalue) {
if (ByteCart.debug)
ByteCart.log.info("ByteCart: property string : "+ Properties.getProperty(key, ""+defaultvalue));
return Integer.parseInt(Properties.getProperty(key, ""+defaultvalue));
}
/* (non-Javadoc)
* @see java.io.Flushable#flush()
*/
@Override
public void flush() throws IOException {
if(isClosed)
throw new IOException("Property file has been already closed");
save();
}
/* (non-Javadoc)
* @see java.io.Closeable#close()
*/
@Override
public void close() throws IOException {
if(isClosed)
throw new IOException("Property file has been already closed");
isClosed = true;
}
/**
* Get the container that contains this property file
*
* @return the container file
*/
public final BCFile getFile() {
return file;
}
}
| 3,407 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/package-info.java | /**
*
*/
/**
* Package with classes to mount books as file
*/
package com.github.catageek.ByteCart.FileStorage; | 116 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ItemStackOutputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/ItemStackOutputStream.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.OutputStream;
import org.bukkit.inventory.ItemStack;
/**
* An output stream associated with an ItemStack
*/
abstract class ItemStackOutputStream extends OutputStream {
ItemStackOutputStream(org.bukkit.inventory.ItemStack itemStack) {
super();
ItemStack = itemStack;
}
private final ItemStack ItemStack;
final ItemStack getItemStack() {
return ItemStack;
}
}
| 443 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BookOutputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/BookOutputStream.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.ByteCart;
/**
* An output stream to write in book
*/
class BookOutputStream extends ByteArrayOutputStream {
static final int PAGESIZE = 255;
private static final int MAXPAGE = 50;
static final int MAXSIZE = MAXPAGE * PAGESIZE;
private final BookMeta book;
private boolean isClosed = false;
BookOutputStream(BookMeta book) {
super(book.getPageCount() * PAGESIZE);
this.book = book;
}
/* (non-Javadoc)
* @see java.io.ByteArrayOutputStream#write(byte[], int, int)
*/
@Override
public void write (byte[] bytes, int off, int len) {
// this.reset();
// if(ByteCart.debug)
// ByteCart.log.info("ByteCart : empty data cache buffer");
super.write(bytes, off, len);
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[])
*/
@Override
public void write(byte[] bytes) throws IOException {
if (isClosed)
throw new IOException("Book has been already closed");
this.write(bytes, 0, bytes.length);
}
/**
* Get the content as a byte array
*
* @return the buffer
*/
protected byte[] getBuffer() {
return this.toByteArray();
}
/* (non-Javadoc)
* @see java.io.OutputStream#flush()
*/
@Override
public void flush() throws IOException {
if (isClosed)
throw new IOException("Book has been already closed");
if (this.size() == 0)
return;
StringBuilder sb = new StringBuilder(getEncodedString());
int len= sb.length();
int i, j = 1;
// number of pages to write
int count = 1 + (len - 1) / PAGESIZE;
// Throw if too many pages are needed
if (count > MAXPAGE) {
if (ByteCart.debug)
ByteCart.log.info(count + " pages are needed, maximum is " + MAXPAGE);
throw new IOException();
}
String[] strings = new String[count];
// loop for full pages
count -= 1;
for (i = 0; i < count; i++) {
strings[i] = sb.substring(i * PAGESIZE, j * PAGESIZE);
j++;
}
// last page
strings[count] = sb.substring(i * PAGESIZE);
this.book.setPages(strings);
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Flushing " + len + " bytes of data to meta");
}
/**
* Get the content as a string
*
* @return the content of the book
*/
protected String getEncodedString() {
return this.toString();
}
/* (non-Javadoc)
* @see java.io.ByteArrayOutputStream#close()
*/
@Override
public void close() throws IOException {
if (isClosed)
throw new IOException("Book has been already closed");
isClosed = true;
}
/**
* Get the book
*
* @return the book
*/
final BookMeta getBook() {
return book;
}
}
| 2,738 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BookFile.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/BookFile.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.FileStorage.BookInputStream;;
/**
* A class handling a file stored in a book
*/
public final class BookFile implements BCFile {
static final int MAXSIZE = BookOutputStream.MAXSIZE;
private static final String prefix = ByteCart.myPlugin.getConfig().getString("author");
private BookMeta book;
private final ItemStack stack;
private ItemStackMetaOutputStream outputstream;
private boolean isClosed = false;
private final Inventory container;
private final boolean binarymode;
private final int slot;
/**
* @param inventory the inventory
* @param index the slot index
* @param binary true to set binary mode
* @param name the suffix of the author name, or null
*/
private BookFile(Inventory inventory, int index, boolean binary) {
this.binarymode = binary;
this.container = inventory;
this.slot = index;
this.stack = inventory.getItem(index);
this.book = (BookMeta) stack.getItemMeta();
}
static public BookFile getFrom(Inventory inventory, int index, boolean binary, String name) {
ItemStack mystack = inventory.getItem(index);
if (mystack == null || ! mystack.getType().equals(Material.WRITTEN_BOOK)) {
return null;
}
BookMeta mybook = null;
if (mystack.hasItemMeta()) {
mybook = (BookMeta) mystack.getItemMeta();
}
else {
return null;
}
if ( ! mybook.hasAuthor() || ! mybook.getAuthor().startsWith(prefix)) {
return null;
}
if (name != null && ! mybook.getAuthor().equals(prefix + "." + name)) {
return null;
}
BookFile bookfile = new BookFile(inventory, index, binary);
// fix corrupted books in MC 1.8
try {
@SuppressWarnings("unused")
List<String> test = mybook.getPages();
}
catch(NullPointerException e) {
inventory.clear(index);
bookfile = create(inventory, index, binary, name);
}
return bookfile;
}
private static boolean isBookFile(String name, BookMeta mybook) {
return mybook.getAuthor().equals(prefix + "." + name);
}
static public BookFile create(Inventory inventory, int index, boolean binary, String name) {
ItemStack mystack = inventory.getItem(index);
return BookFile.create(inventory, mystack, index, binary, name);
}
static private BookFile create(Inventory inventory, ItemStack mystack, int index, boolean binary, String name) {
if (mystack == null || ! mystack.getType().equals(Material.WRITTEN_BOOK)) {
mystack = new ItemStack(Material.WRITTEN_BOOK);
}
final BookMeta mybook = (BookMeta) Bukkit.getServer().getItemFactory().getItemMeta(Material.WRITTEN_BOOK);
if (name != null) {
final String myauthor = prefix + "." + name;
mybook.setAuthor(myauthor);
}
else {
mybook.setAuthor(prefix);
}
mystack.setItemMeta(mybook);
inventory.setItem(index, mystack);
return new BookFile(inventory, index, binary);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#getCapacity()
*/
@Override
public int getCapacity() {
return MAXSIZE;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#clear()
*/
@Override
public void clear() {
if (outputstream != null)
this.outputstream.getBook().setPages(new ArrayList<String>());
else
book.setPages(new ArrayList<String>());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#isEmpty()
*/
@Override
public boolean isEmpty() {
if (outputstream != null)
return ! outputstream.getBook().hasPages() || outputstream.getBook().getPage(1).length() == 0;
else
return ! book.hasPages() || book.getPage(1).length() == 0;
}
@Override
public String getPages() {
return BookInputStream.readPages(book, binarymode);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#getOutputStream()
*/
@Override
public OutputStream getOutputStream() throws IOException {
if (isClosed)
throw new IOException("Book File has already been closed");
if (outputstream != null)
return outputstream;
BookOutputStream bookoutputstream = binarymode ? new Base64BookOutputStream(book) : new BookOutputStream(book);
return outputstream = new ItemStackMetaOutputStream(stack, bookoutputstream);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#getInputStream()
*/
@Override
public BookInputStream getInputStream() throws IOException {
if (isClosed)
throw new IOException("Book File has already been closed");
if (outputstream != null && outputstream.getBuffer().length != 0){
return new BookInputStream(outputstream);
}
return new BookInputStream(book, binarymode);
}
/* (non-Javadoc)
* @see java.io.Flushable#flush()
*/
@Override
public void flush() throws IOException {
if (outputstream != null){
if (isClosed)
throw new IOException("Book File has already been closed");
outputstream.flush();
book = outputstream.getBook();
}
else {
stack.setItemMeta(book);
this.getContainer().setItem(slot, stack);
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#getContainer()
*/
@Override
public Inventory getContainer() {
return container;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#setDescription(java.lang.String)
*/
@Override
public void setDescription(String s) throws IOException {
if (isClosed)
throw new IOException("Book File has already been closed");
if (outputstream != null) {
outputstream.getBook().setTitle(s);
book = outputstream.getBook();
}
else
book.setTitle(s);
}
/**
* Tell if a slot of an inventory contains a file in a book
*
* @param inventory the inventory
* @param index the slot number
* @param suffix suffix of the author name
* @return true if the slot contains a file and the author field begins with author configuration parameter
*/
static boolean isBookFile(Inventory inventory, int index, String suffix) {
return isBookFile(inventory.getItem(index), suffix);
}
/**
* Tell if an ItemStack contains a file in a book
*
* @param stack the ItemStack
* @param suffix suffix of the author name
* @return true if the slot contains a file and the author field begins with author configuration parameter
*/
public static boolean isBookFile(ItemStack stack, String suffix) {
if (stack != null && stack.getType().equals(Material.WRITTEN_BOOK) && stack.hasItemMeta())
return isBookFile(suffix, (BookMeta) stack.getItemMeta()) || suffix == null;
return false;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BCFile#getDescription()
*/
@Override
public String getDescription() throws IOException {
if (isClosed)
throw new IOException("Book File has already been closed");
if (outputstream != null) {
return outputstream.getBook().getTitle();
}
else
return book.getTitle();
}
public static ItemStack sign(ItemStack mystack, String name) {
if (mystack == null || mystack.getType() != Material.WRITABLE_BOOK) {
return null;
}
mystack.setType(Material.WRITTEN_BOOK);
final BookMeta mybook = (BookMeta) mystack.getItemMeta();
if (name != null)
mybook.setAuthor(BookFile.prefix + "." + "name");
else
mybook.setAuthor(BookFile.prefix);
return mystack;
}
}
| 7,617 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
InventoryFile.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/InventoryFile.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.bukkit.inventory.Inventory;
public final class InventoryFile implements BCFile {
private final Inventory inventory;
private final boolean binarymode;
private final String name;
private InventoryOutputStream outputstream;
private String title = "";
public InventoryFile(Inventory inventory, boolean binary, String name) {
this.inventory = inventory;
this.binarymode = binary;
this.name = name;
}
@Override
public void flush() throws IOException {
if (outputstream != null)
outputstream.flush();
}
@Override
public int getCapacity() {
return BookFile.MAXSIZE * inventory.getSize();
}
@Override
public void clear() {
this.inventory.clear();
}
@Override
public boolean isEmpty() {
return this.inventory.firstEmpty() == 0;
}
@Override
public OutputStream getOutputStream() throws IOException {
if (outputstream != null)
return outputstream;
return outputstream = new InventoryOutputStream(inventory, binarymode, title, name);
}
@Override
public InputStream getInputStream() throws IOException {
if (outputstream != null && outputstream.toByteArray().length != 0){
return new InventoryInputStream(outputstream);
}
return new InventoryInputStream(inventory, binarymode, name);
}
public static boolean isInventoryFile(Inventory inv, String name) {
return InventoryInputStream.isInventoryInputStream(inv, name);
}
@Override
public Inventory getContainer() {
return inventory;
}
@Override
public void setDescription(String s) throws IOException {
this.title = s;
}
@Override
public String getDescription() throws IOException {
return this.title;
}
@Override
public String getPages() {
return InventoryInputStream.readPages(inventory, name, binarymode);
}
}
| 1,897 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
InventoryInputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/InventoryInputStream.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.Util.Base64;
final class InventoryInputStream extends ByteArrayInputStream {
/**
* @param book the book
* @param binary set binary mode
*/
InventoryInputStream(Inventory inv, boolean binary, String name) {
super(readPagesAsBytes(inv, name, binary));
}
public InventoryInputStream(InventoryOutputStream outputstream) {
super(outputstream.toByteArray());
}
public static String readPages(Inventory inv, String name, boolean binary) {
String sb = getRawContent(inv, name);
if (binary)
return new String(Base64.decodeFast(sb));
return sb;
}
static boolean isInventoryInputStream(Inventory inv, String name) {
for (int i = 0; i < inv.getSize(); ++i) {
if (BookFile.isBookFile(inv, i, name)) {
return true;
}
}
return false;
};
/**
* Get the underlying inputstream
*
* @param slot the slot where the book is
* @return the book inputstream
* @throws IOException
*/
private static BookInputStream getBookInputStream(Inventory inventory, int slot, String name) {
BookFile book = BookFile.getFrom(inventory, slot, false, name);
if (book == null) {
return null;
}
BookInputStream ret = null;
try {
ret = book.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
private static byte[] readPagesAsBytes(Inventory inv, String name, boolean binary) {
String sb = getRawContent(inv, name);
if (binary)
return Base64.decodeFast(sb);
return sb.getBytes();
}
private static String getRawContent(Inventory inv, String name) {
int bookcount = inv.all(Material.WRITTEN_BOOK).size();
int len = bookcount * BookFile.MAXSIZE;
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < bookcount; ++i) {
final BookInputStream bookInputStream = getBookInputStream(inv, i, name);
if (bookInputStream != null) {
sb.append(bookInputStream.getBuffer());
}
}
sb.trimToSize();
return sb.toString();
}
}
| 2,160 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
FileStorageTest.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/FileStorageTest.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
public final class FileStorageTest {
private final Inventory inventory;
private final static Random rng = new Random();
private final static String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public FileStorageTest(Inventory inv) {
this.inventory = inv;
}
static String generateString(int length)
{
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
public void runTest() {
run(1);
run(512);
run(32767);
run(128000);
int len = inventory.getSize() * BookFile.MAXSIZE;
run(len);
run(len + 1);
}
public void run(int len) {
inventory.clear();
ByteCart.log.info("isInventoryFile() ? empty inventory : " + (InventoryFile.isInventoryFile(inventory, "test") ? "NOK" : "OK"));
InventoryFile file1 = new InventoryFile(inventory, false, "test");
ByteCart.log.info("isEmpty() ? empty inventory : " + (file1.isEmpty() ? "OK" : "NOK"));
OutputStream outputstream = null;
String string1 = generateString(len);
try {
outputstream = file1.getOutputStream();
outputstream.write(string1.getBytes());
outputstream.flush();
outputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
ByteCart.log.info("isEmpty() ? test inventory : " + (file1.isEmpty() ? "NOK" : "OK"));
ByteCart.log.info("isInventoryFile() ? test inventory : " + (InventoryFile.isInventoryFile(inventory, "test") ? "OK" : "NOK"));
ByteCart.log.info("isInventoryFile() ? wrong name : " + (InventoryFile.isInventoryFile(inventory, "othertest") ? "NOK" : "OK"));
InventoryFile file2 = new InventoryFile(inventory, false, "test");
ByteCart.log.info("isEmpty() ? test2 inventory : " + (file2.isEmpty() ? "NOK" : "OK"));
String string2 = file2.getPages();
for (int i = 0; i < len; i += BookFile.MAXSIZE) {
ByteCart.log.info("Test of string of " + len + " bytes : " + i + " " + (string2.regionMatches(i, string1, i, Math.min(BookFile.MAXSIZE, len - i * BookFile.MAXSIZE)) ? "OK" : "NOK"));
}
}
}
| 2,345 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ItemStackMetaOutputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/ItemStackMetaOutputStream.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.IOException;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.ByteCart;
/**
* An outputstream for a book in an ItemStack. Write operations in the book update the ItemStack object
*/
final class ItemStackMetaOutputStream extends ItemStackOutputStream {
private final BookOutputStream OutputStream;
private boolean isClosed = false;
/**
* @param stack the stack containing the book
* @param outputstream an output stream for the book
*/
ItemStackMetaOutputStream(ItemStack stack, BookOutputStream outputstream) {
super(stack);
OutputStream = outputstream;
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(byte[], int, int)
*/
@Override
public void write(byte[] cbuf, int off, int len) throws IOException {
if (isClosed)
throw new IOException("ItemStack has been already closed");
OutputStream.write(cbuf, off, len);
}
/* (non-Javadoc)
* @see java.io.OutputStream#flush()
*/
@Override
public void flush() throws IOException {
if (isClosed)
throw new IOException("ItemStack has been already closed");
OutputStream.flush();
getItemStack().setItemMeta(OutputStream.getBook());
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Flushing meta to itemstack");
}
/* (non-Javadoc)
* @see java.io.OutputStream#close()
*/
@Override
public void close() throws IOException {
if (isClosed)
throw new IOException("ItemStack has been already closed");
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Closing itemstack");
OutputStream.close();
isClosed = true;
}
/* (non-Javadoc)
* @see java.io.OutputStream#write(int)
*/
@Override
public void write(int b) throws IOException {
if (isClosed)
throw new IOException("ItemStack has been already closed");
OutputStream.write(b);
}
/**
* Get the current buffer
*
* @return the buffer
*/
final byte[] getBuffer() {
return OutputStream.getBuffer();
}
/**
* Get the book
*
* @return the book
*/
final BookMeta getBook() {
return OutputStream.getBook();
}
}
| 2,154 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BCFile.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/BCFile.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.bukkit.inventory.Inventory;
/**
* Represents a file with various operations
*/
public interface BCFile extends Flushable {
/**
* Get the capacity, in bytes, of the file
*
* @return the capacity
*/
int getCapacity();
/**
* clear the file content
*
*/
void clear();
/**
* Tell if a file is empty
*
* @return true if empty
*/
boolean isEmpty();
/**
* Get an output stream for this file
*
* @return the stream
* @throws IOException
*/
OutputStream getOutputStream() throws IOException;
/**
* Get an input stream
*
* @return the stream
* @throws IOException
*/
InputStream getInputStream() throws IOException;
/**
* Get the inventory containing this file
*
* @return the inventory
*/
Inventory getContainer();
/**
* Set a title to this file
*
* @param s the title to set
* @throws IOException
*/
void setDescription(String s) throws IOException;
/**
* Get the title for this file
*
* @return the title
* @throws IOException
*/
String getDescription() throws IOException;
/**
* Get all the pages in one string
* @return all the pages
*/
String getPages();
}
| 1,339 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
InventoryOutputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/InventoryOutputStream.java | package com.github.catageek.ByteCart.FileStorage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.Util.Base64;
class InventoryOutputStream extends ByteArrayOutputStream {
private final Inventory inventory;
private final boolean binary;
private final String name;
private final String title;
InventoryOutputStream(Inventory inventory, boolean binary, String title, String name) {
this.inventory = inventory;
this.binary = binary;
this.name = name;
this.title = title;
}
/**
* Get the content as a string
*
* @return the content of the book
*/
private String getEncodedString() {
return binary ? Base64.encodeToString(buf, false) : this.toString();
}
/**
* Get the underlying OutputStream
*
* @param slot the slot where the book is
* @return the book outputstream
* @throws IOException
*/
private void writeData(byte[] data, int slot) throws IOException {
final BookFile book = BookFile.create(inventory, slot, false, name);
book.setDescription(this.title);
OutputStream outputstream = book.getOutputStream();
outputstream.write(data);
outputstream.flush();
}
/* (non-Javadoc)
* @see java.io.OutputStream#flush()
*/
@Override
public void flush() throws IOException {
if (this.size() == 0)
return;
StringBuilder sb = new StringBuilder(getEncodedString());
int len= sb.length();
int i, j = 1;
// number of books to write
int count = 1 + (len - 1) / BookFile.MAXSIZE;
// Throw if too many books are needed
if (count > this.inventory.getSize()) {
if (ByteCart.debug)
ByteCart.log.info(count + " books are needed, maximum is " + this.inventory.getSize());
throw new IOException();
}
String mystring;
// loop for full books
count -= 1;
for (i = 0; i < count; i++) {
mystring = sb.substring(i * BookFile.MAXSIZE, j * BookFile.MAXSIZE);
writeData(mystring.getBytes(), i);
j++;
}
// last page
mystring = sb.substring(i * BookFile.MAXSIZE);
writeData(mystring.getBytes(), i++);
// Clear last slots
for(; i < this.inventory.getSize(); i++) {
this.inventory.clear(i);
}
if(ByteCart.debug)
ByteCart.log.info("ByteCart : Flushing " + len + " bytes of data to books");
}
}
| 2,381 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Base64BookOutputStream.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/FileStorage/Base64BookOutputStream.java | package com.github.catageek.ByteCart.FileStorage;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.Util.Base64;
/**
* Base64 encoder/decoder for BookOutPutStream
*/
final class Base64BookOutputStream extends BookOutputStream {
public Base64BookOutputStream(BookMeta book) {
super(book);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BookOutputStream#getEncodedString()
*/
@Override
protected String getEncodedString() {
return Base64.encodeToString(buf, false);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.FileStorage.BookOutputStream#getBuffer()
*/
@Override
protected byte[] getBuffer() {
return Base64.encodeToByte(buf, false);
}
}
| 731 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Wanderer/package-info.java | /**
*
*/
/**
* Package to mark a cart as a wanderer that will trigger events
*/
package com.github.catageek.ByteCart.Wanderer; | 131 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
WandererContent.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Wanderer/WandererContent.java | package com.github.catageek.ByteCart.Wanderer;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.Routing.BCCounter;
import com.github.catageek.ByteCart.Routing.Metric;
import com.github.catageek.ByteCartAPI.Util.DirectionRegistry;
import com.github.catageek.ByteCartAPI.Wanderer.InventoryContent;
import com.github.catageek.ByteCartAPI.Wanderer.RoutingTable;
import com.github.catageek.ByteCartAPI.Wanderer.Wanderer;
public class WandererContent implements InventoryContent {
/**
*
*/
private static final long serialVersionUID = -9068486630910859194L;
private transient Inventory inventory = null;
private UUID player;
private BCCounter counter;
private long creationtime = Calendar.getInstance().getTimeInMillis();
private int lastrouterid;
private Stack<Integer> Start;
private Stack<Integer> End;
//internal variable used by updaters
private int Current = -2;
private long expirationtime;
protected Map<Integer, Metric> tablemap = new HashMap<Integer, Metric>();
public WandererContent(Inventory inv, Wanderer.Level level, int region, Player player) {
this.Region = region;
this.Level = level;
this.inventory = inv;
this.player = player.getUniqueId();
counter = new BCCounter();
setStart(new Stack<Integer>());
setEnd(new Stack<Integer>());
}
/**
* Set the counter instance
*
* @param counter the counter instance to set
*/
final void setCounter(BCCounter counter) {
this.counter = counter;
}
private Wanderer.Level Level;
private int Region;
/**
* Set the level of the updater
*
* @param level the level to store
*/
final void setLevel(Wanderer.Level level) {
Level = level;
}
/**
* Set the region of the updater
*
* @param region the region to set
*/
final void setRegion(int region) {
Region = region;
}
/**
* Get the level of the updater
*
* @return the level
*/
@Override
public Wanderer.Level getLevel() {
return Level;
}
/**
* Get the region of the updater
*
* @return the region
*/
@Override
public int getRegion() {
return Region;
}
/**
* Get the ring id where the updater thinks it is in
*
* @return the ring id
*/
@Override
public int getCurrent() {
return Current;
}
/**
* Set the ring id where the updater thinks it is in
*
* @param current the ring id
*/
@Override
public void setCurrent(int current) {
Current = current;
}
/**
* @return the counter
*/
@Override
public BCCounter getCounter() {
return counter;
}
/**
* @return the inventory
*/
@Override
public Inventory getInventory() {
return inventory;
}
/**
* @param inventory the inventory to set
*/
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public long getCreationtime() {
return creationtime;
}
/**
* @param creationtime the creationtime to set
*/
@SuppressWarnings("unused")
private void setCreationtime(long creationtime) {
this.creationtime = creationtime;
}
/**
* @return the player
*/
@Override
public Player getPlayer() {
return Bukkit.getPlayer(player);
}
/**
* Get the id previously stored
*
* @return the id
*/
public final int getLastrouterid() {
return lastrouterid;
}
/**
* Store an id in the updater book
*
* @param lastrouterid the id to store
*/
public final void setLastrouterid(int lastrouterid) {
this.lastrouterid = lastrouterid;
}
/**
* @return the start
*/
@Override
public Stack<Integer> getStart() {
return Start;
}
/**
* @return the end
*/
@Override
public Stack<Integer> getEnd() {
return End;
}
/**
* @param start the start to set
*/
private void setStart(Stack<Integer> start) {
Start = start;
}
/**
* @param end the end to set
*/
private void setEnd(Stack<Integer> end) {
End = end;
}
public long getExpirationTime() {
return expirationtime;
}
/**
* Set the expiration time
*
* @param lastupdate the lastupdate to set
*/
@Override
public void setExpirationTime(long lastupdate) {
this.expirationtime = lastupdate;
}
/**
* Insert an entry in the IGP packet
*
* @param number the ring id
* @param metric the metric value
*/
@Override
public void setRoute(int number, int metric) {
tablemap.put(number, new Metric(metric));
if(ByteCart.debug)
ByteCart.log.info("ByteCart : setting metric of ring " + number + " to " + metric);
}
/**
* Get the metric value of a ring of the IGP exchange packet
*
* @param entry the ring id
* @return the metric
*/
@Override
public int getMetric(int entry) {
return tablemap.get(entry).value();
}
/**
* Get the ring that has the minimum metric in the IGP packet
*
* @param routingTable the routing table
* @param from the direction to exclude from the search
* @return the ring id, or -1
*/
@Override
public int getMinDistanceRing(RoutingTable routingTable, DirectionRegistry from) {
Iterator<Integer> it = routingTable.getOrderedRouteNumbers();
if (! it.hasNext())
return -1;
//skip ring 0
it.next();
int route;
int min = 10000, ret = -1; // big value
while (it.hasNext()) {
route = it.next();
if (routingTable.getDirection(route) != from.getBlockFace()) {
if (! this.hasRouteTo(route)) {
if(ByteCart.debug)
ByteCart.log.info("ByteCart : found ring " + route + " was never visited");
return route;
}
else {
if (getMetric(route) < min) {
min = getMetric(route);
ret = route;
}
}
}
}
if(ByteCart.debug)
ByteCart.log.info("ByteCart : minimum found ring " + ret + " with " + min);
return ret;
}
/**
* Tells if the IGP packet has data on a ring
*
* @param ring the ring id
* @return true if there is data on this ring
*/
@Override
public boolean hasRouteTo(int ring) {
return tablemap.containsKey(ring);
}
}
| 6,138 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BCWandererManager.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Wanderer/BCWandererManager.java | package com.github.catageek.ByteCart.Wanderer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.FileStorage.InventoryFile;
import com.github.catageek.ByteCart.Util.LogUtil;
import com.github.catageek.ByteCartAPI.Wanderer.InventoryContent;
import com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Level;
import com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Scope;
import com.github.catageek.ByteCartAPI.Wanderer.WandererFactory;
import com.github.catageek.ByteCartAPI.Wanderer.WandererManager;
public class BCWandererManager implements WandererManager {
private static final Map<String, WandererFactory> map = new HashMap<String, WandererFactory>();
/**
* Register a wanderer type
*
* @param wanderer the wanderer class implementing the wanderer
* @param type the name that will reference this type of wanderer
*/
@Override
public boolean register(WandererFactory factory, String type) {
if (map.containsKey(type))
return false;
map.put(type, factory);
return true;
}
/**
* Get a wanderer
*
* @param bc the sign that request the wanderer
* @param inv the inventory where to extract the wanderercontent from
* @return the wanderer
* @throws ClassNotFoundException
* @throws IOException
*/
@Override
public WandererFactory getFactory(Inventory inv) throws ClassNotFoundException, IOException {
if (isWanderer(inv)
&& getWandererContent(inv) != null)
return map.get(getType(inv));
return null;
}
public WandererFactory getFactory(String type) {
if (isRegistered(type))
return map.get(type);
return null;
}
@Override
public boolean isWanderer(Inventory inv, Scope scope) {
return isWanderer(inv, scope, null, null);
}
@Override
public boolean isWanderer(Inventory inv, Level level, String type) {
return isWanderer(inv, level.scope, level.type, type);
}
@Override
public boolean isWanderer(Inventory inv, String type) {
return isWanderer(inv, null, null, type);
}
private boolean isWanderer(Inventory inv, Scope scope, String suffix, String type) {
if (! isWanderer(inv))
return false;
ItemStack stack = inv.getItem(0);
if (stack != null && stack.getType().equals(Material.WRITTEN_BOOK) && stack.hasItemMeta()) {
final BookMeta book = (BookMeta) stack.getItemMeta();
final String booktitle = book.getTitle();
final String dot = "\\.";
final StringBuilder match = new StringBuilder();
match.append("^");
final String alphanums = "[a-zA-Z]{1,}";
if (type != null)
match.append(type).append(dot);
else
match.append(alphanums).append(dot);
if (scope != null)
match.append(scope.name).append(dot);
else
match.append(alphanums).append(dot);
if (suffix != null)
match.append(suffix).append(dot);
match.append(".*");
if (InventoryFile.isInventoryFile(inv, type)
&& booktitle.matches(match.toString())) {
return true;
}
}
return false;
}
public boolean isWanderer(Inventory inv) {
String prefix = getType(inv);
if (prefix != null)
return isRegistered(prefix);
return false;
}
private String getType(Inventory inv) {
ItemStack stack = inv.getItem(0);
String prefix = null;
if (stack != null && stack.getType().equals(Material.WRITTEN_BOOK) && stack.hasItemMeta()) {
BookMeta book = (BookMeta) stack.getItemMeta();
String booktitle = book.getTitle();
int index = booktitle.indexOf(".");
if (index > 0)
prefix = booktitle.substring(0, index);
}
return prefix;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.WandererManager#isWandererType(java.lang.String)
*/
@Override
public boolean isRegistered(String type) {
return map.containsKey(type);
}
@Override
public WandererContent getWandererContent(Inventory inv)
throws IOException, ClassNotFoundException {
WandererContent rte = null;
InventoryFile file = null;
if (InventoryFile.isInventoryFile(inv, null)) {
file = new InventoryFile(inv, true, null);
}
if (file == null) {
throw new IOException("No book found");
}
if (! file.isEmpty()) {
ObjectInputStream ois = new ObjectInputStream(file.getInputStream());
rte = (WandererContent) ois.readObject();
}
rte.setInventory(inv);
return rte;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.WandererManager#saveContent(com.github.catageek.ByteCartAPI.Wanderer.InventoryContent, java.lang.String, com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Level)
*/
@Override
public void saveContent(InventoryContent rte, String suffix, Level level) throws ClassNotFoundException, IOException {
Inventory inv = rte.getInventory();
// delete content if expired
long creation = rte.getCreationtime();
long expiration = rte.getExpirationTime();
if (creation != expiration && Calendar.getInstance().getTimeInMillis() > expiration) {
LogUtil.sendSuccess(rte.getPlayer(), "ByteCart : " + suffix + " created " + (new Date(rte.getCreationtime())).toString() + " expired");
WandererFactory factory = getFactory(inv);
if (factory != null) {
factory.destroyWanderer(inv);
}
return;
}
InventoryFile file = createWanderer(inv, rte.getRegion(), rte.getLevel(), rte.getPlayer(), suffix, level);
ObjectOutputStream oos = new ObjectOutputStream(file.getOutputStream());
oos.writeObject(rte);
try {
oos.flush();
}
catch (IOException e) {
getFactory(inv).destroyWanderer(inv);
ByteCart.log.info("Bytecart: I/O error (maximum capacity reached), updater deleted");
}
}
private static InventoryFile createWanderer(Inventory inv, int region, Level level, Player player
, String name, Level type) throws IOException {
InventoryFile file = new InventoryFile(inv, true, name);
String dot = ".";
StringBuilder match = new StringBuilder();
match.append(name).append(dot).append(level.scope.name);
match.append(dot).append(type.type).append(dot);
file.setDescription(match.toString());
return file;
}
@Override
public void unregister(String name) {
map.remove(name);
}
}
| 6,433 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
SuperRegistry.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/HAL/SuperRegistry.java | package com.github.catageek.ByteCart.HAL;
import com.github.catageek.ByteCartAPI.HAL.Registry;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
import com.github.catageek.ByteCartAPI.HAL.RegistryInput;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
// This class represents 2 registries merged
/**
* A registry grouping 2 registries
*
* @param <T> A type extending Registry
*/
public class SuperRegistry<T extends Registry> implements RegistryBoth {
// Registry1 est le registre de poids fort
private final Registry Registry1, Registry2;
/**
* @param reg1 The left part, i.e MSB side
* @param reg2 The right part, i.e LSB side
*/
public SuperRegistry(T reg1, T reg2) {
this.Registry1 = reg1;
this.Registry2 = reg2;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryOutput#setBit(int, boolean)
*/
@Override
public void setBit(int index, boolean value) {
if (index < this.Registry1.length())
( (RegistryOutput) this.Registry1).setBit(index, value);
else
((RegistryOutput) this.Registry2).setBit(index-this.Registry1.length(), value);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryInput#getBit(int)
*/
@Override
public boolean getBit(int index) {
if (index < this.Registry1.length())
return ((RegistryInput) this.Registry1).getBit(index);
return ((RegistryInput) this.Registry2).getBit(index-this.Registry1.length());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#length()
*/
@Override
public int length() {
return this.Registry1.length() + this.Registry2.length();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#getAmount()
*/
@Override
public int getAmount() {
return (this.Registry1.getAmount() << this.Registry2.length()) + this.Registry2.getAmount();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryOutput#setAmount(int)
*/
@Override
public void setAmount(int amount) {
((RegistryOutput) this.Registry1).setAmount(amount >> (this.Registry2.length()) % ( 1 << this.Registry1.length()));
((RegistryOutput) this.Registry2).setAmount(amount & (( 1 << this.Registry2.length() ) - 1));
}
}
| 2,214 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/HAL/package-info.java | /**
*/
/**
* Abstraction layer for various ingame components.
*
* Basic element of this layer are pins representing a single component.
*
* Registries are composite elements grouping a set of pins.
*/
package com.github.catageek.ByteCart.HAL; | 252 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractIC.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/HAL/AbstractIC.java | package com.github.catageek.ByteCart.HAL;
import java.util.Map;
import java.util.WeakHashMap;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.block.data.Rotatable;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.IO.ComponentSign;
import com.github.catageek.ByteCartAPI.HAL.IC;
import com.github.catageek.ByteCartAPI.HAL.RegistryInput;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
import com.github.catageek.ByteCartAPI.Util.MathUtil;
// All ICs must inherit from this class
/**
* An abstract class implementing common methods for all ICs
*/
abstract public class AbstractIC implements IC {
final private Block Block;
final private org.bukkit.Location Location;
private static final Map<String,Boolean> icCache = new WeakHashMap<String, Boolean>();
private static org.bukkit.Location emptyLocation = new org.bukkit.Location(null, 0, 0, 0);
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getName()
*/
@Override
abstract public String getName();
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getFriendlyName()
*/
@Override
public String getFriendlyName() {
return ((Sign) this.getBlock().getState()).getLine(2);
}
private RegistryInput[] input = new RegistryInput[9];
private int input_args = 0;
private RegistryOutput[] output = new RegistryOutput[6];
private int output_args = 0;
public AbstractIC(Block block) {
this.Block = block;
if (block != null) {
this.Location = block.getLocation();
}
else {
this.Location = new org.bukkit.Location(null, 0, 0, 0);
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#addInputRegistry(com.github.catageek.ByteCart.HAL.RegistryInput)
*/
@Override
public final void addInputRegistry(RegistryInput reg) {
this.input[this.input_args++] = reg;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#addOutputRegistry(com.github.catageek.ByteCart.HAL.RegistryOutput)
*/
@Override
public final void addOutputRegistry(RegistryOutput reg) {
this.output[this.output_args++] = reg;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getInput(int)
*/
@Override
public final RegistryInput getInput(int index) {
return input[index];
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getOutput(int)
*/
@Override
public final RegistryOutput getOutput(int index) {
return output[index];
}
static public final void removeFromCache(Block block) {
icCache.remove(block.getLocation(emptyLocation).toString());
}
// This function checks if we have a ByteCart sign at this location
static public final boolean checkEligibility(Block b){
if(!(b.getState() instanceof Sign)) {
return false;
}
Boolean ret;
String s;
if ((ret = icCache.get(s = b.getLocation(emptyLocation).toString())) != null)
return ret;
String line_content = ((Sign) b.getState()).getLine(1);
if (ByteCart.myPlugin.getConfig().getBoolean("FixBroken18", false)) {
if (ret = AbstractIC.checkLooseEligibility(line_content)) {
(new ComponentSign(b)).setLine(1,"["+line_content+"]");
}
else {
ret = AbstractIC.checkEligibility(line_content);
}
}
else {
ret = AbstractIC.checkEligibility(line_content);
}
icCache.put(s, ret);
return ret;
}
static public final boolean checkEligibility(String s){
if(! (s.matches("^\\[BC[0-9]{4,4}\\]$"))) {
return false;
}
return true;
}
static private final boolean checkLooseEligibility(String s){
if(! (s.matches("^BC[0-9]{4,4}$"))) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getCardinal()
*/
@Override
public final BlockFace getCardinal() {
final BlockData blockdata = this.getBlock().getState().getBlockData();
if(blockdata instanceof Directional) {
return ((Directional) blockdata).getFacing().getOppositeFace();
}
if(blockdata instanceof Rotatable) {
BlockFace f = ((Rotatable) blockdata).getRotation().getOppositeFace();
f = MathUtil.straightUp(f);
if (f == BlockFace.UP) {
ByteCart.log.severe("ByteCart: Tilted sign found at " + this.getLocation() + ". Please straight it up in the axis of the track");
return null;
}
return f;
}
return null;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getBlock()
*/
@Override
public final Block getBlock() {
return Block;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getBuildPermission()
*/
@Override
public final String getBuildPermission() {
return "bytecart." + getName();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getTriggertax()
*/
@Override
public final int getTriggertax() {
return ByteCart.myPlugin.getConfig().getInt("usetax." + this.getName());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getBuildtax()
*/
@Override
public final int getBuildtax() {
return ByteCart.myPlugin.getConfig().getInt("buildtax." + this.getName());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.IC#getLocation()
*/
@Override
public org.bukkit.Location getLocation() {
return Location;
}
}
| 5,352 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
PinRegistry.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/HAL/PinRegistry.java | package com.github.catageek.ByteCart.HAL;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import com.github.catageek.ByteCart.IO.InputPin;
import com.github.catageek.ByteCart.IO.OutputPin;
import com.github.catageek.ByteCartAPI.HAL.Registry;
import com.github.catageek.ByteCartAPI.HAL.RegistryInput;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
/**
* A registry implementation
*
* @param <T> InputPin or OutputPin type
*/
public class PinRegistry<T> implements RegistryInput, RegistryOutput, Registry {
final private List<T> PinArray;
/**
* @param pins an array of pins
*/
public PinRegistry(T[] pins) {
this.PinArray = Arrays.asList(pins);
/* if(ByteCart.debug)
ByteCart.log.info("ByteCart : creating PinRegistry with" + this.length() + "pin(s)");
*/
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#length()
*/
@Override
public int length() {
return PinArray.size();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#getAmount()
*/
@Override
public int getAmount() {
int amount = 0;
int i = 1;
for (ListIterator<T> it = this.PinArray.listIterator(this.length()); it.hasPrevious(); i = i << 1)
{
if(it.previous() != null) {
it.next();
if (((InputPin) it.previous()).read()) {
amount += i;
}
}
}
return amount;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryOutput#setBit(int, boolean)
*/
@Override
public void setBit(int index, boolean value) {
((OutputPin) this.PinArray.get(index)).write(value);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryOutput#setAmount(int)
*/
@Override
public void setAmount(int amount) {
int i = amount;
for (ListIterator<T> it = this.PinArray.listIterator(this.length()); it.hasPrevious(); i = i >> 1)
{
if(it.previous() != null) {
it.next();
if ( (i & 1) !=0 ) {
((OutputPin) it.previous()).write(true);
}
else {
((OutputPin) it.previous()).write(false);
}
}
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryInput#getBit(int)
*/
@Override
public boolean getBit(int index) {
return ((InputPin) this.PinArray.get(index)).read();
}
}
| 2,320 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
SubRegistry.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/HAL/SubRegistry.java | package com.github.catageek.ByteCart.HAL;
import com.github.catageek.ByteCartAPI.HAL.Registry;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
import com.github.catageek.ByteCartAPI.HAL.RegistryInput;
import com.github.catageek.ByteCartAPI.HAL.RegistryOutput;
/**
* A restricted view of a registry
*
* @param <T> A type implementing Registry
*/
public class SubRegistry <T extends Registry> implements RegistryBoth {
private final Registry Registry;
private final int Length;
private final int First;
/**
* @param reg the original registry
* @param length the length of the restricted view
* @param first the index of the first bit of the restricted view
*/
public SubRegistry(T reg, int length, int first) {
this.Registry = reg;
this.Length = length;
this.First = first;
/* if(ByteCart.debug)
ByteCart.log.info("ByteCart : creating SubRegistry " + reg.length() + " -> " + length + " bits beginning at index "+ first);
*/
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#length()
*/
@Override
public int length() {
return this.Length;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.Registry#getAmount()
*/
@Override
public int getAmount() {
return (this.Registry.getAmount() >> (this.Registry.length() - (this.First + this.length())) & ( 1 << this.length()) - 1);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryOutput#setBit(int, boolean)
*/
@Override
public void setBit(int index, boolean value) {
((RegistryOutput) this.Registry).setBit(index + this.First, value);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryInput#getBit(int)
*/
@Override
public boolean getBit(int index) {
return ((RegistryInput) this.Registry).getBit(index+ this.First);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.HAL.RegistryOutput#setAmount(int)
*/
@Override
public void setAmount(int amount) {
((RegistryOutput) this.Registry).setAmount(this.Registry.getAmount() - this.getAmount() + ((amount % (1 << this.length())) << (this.Registry.length() - (this.First + this.length()))));
}
}
| 2,149 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Storage/package-info.java | /**
*
*/
/**
* A package providing some persistent in-memory storage
*/
package com.github.catageek.ByteCart.Storage; | 122 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ExternalizableTreeMap.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Storage/ExternalizableTreeMap.java | package com.github.catageek.ByteCart.Storage;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A treemap that can be saved (i.e externalized) as a binary stream
*
* @param <K> the key type of the map
* @param <V> the value type of the map
*/
public final class ExternalizableTreeMap<K extends Externalizable, V extends Externalizable>
extends TreeMap<K, V> implements Externalizable {
private static final long serialVersionUID = 1074583778619610579L;
public ExternalizableTreeMap() {
super();
}
public ExternalizableTreeMap(Comparator<? super K> comparator) {
super(comparator);
}
public ExternalizableTreeMap(Map<? extends K, ? extends V> m) {
super(m);
}
public ExternalizableTreeMap(SortedMap<K, ? extends V> arg0) {
super(arg0);
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
@SuppressWarnings("unchecked")
@Override
public void readExternal(ObjectInput s) throws IOException,
ClassNotFoundException {
// Read in size
int size = s.readShort();
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
this.put(key, value);
}
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
@Override
public void writeExternal(ObjectOutput s) throws IOException {
// Write out size (number of Mappings)
s.writeShort(size());
// Write out keys and values (alternating)
for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
Map.Entry<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
| 1,830 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ExpirableMap.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Storage/ExpirableMap.java | package com.github.catageek.ByteCart.Storage;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.github.catageek.ByteCart.ThreadManagement.Expirable;
/**
* A map in which elements are deleted after a timeout
*
* @param <K> the type of keys of the set
* @param <T> the type of values of the set
*/
public final class ExpirableMap<K, T> extends Expirable<K> {
private final Map<K, T> Map = Collections.synchronizedMap(new HashMap<K,T>());
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#Expirable(long, boolean, String)
*/
public ExpirableMap(long duration, boolean isSync, String name) {
super(duration, isSync, name);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#expire(java.lang.Object[])
*/
@SuppressWarnings("unchecked")
@Override
public void expire(Object... objects) {
((Map<K,?>)objects[1]).remove(objects[0]);
}
/**
* Add an element to the map
*
* @param key key of the element
* @param value value of the element
* @param reset must be set to true to reset the timeout to initial value, false otherwise
* @return true if the element was added
*/
private boolean put(K key, T value, boolean reset) {
// if(ByteCart.debug)
// ByteCart.log.info("ByteCart: create ephemeral key (" + key +") in " + this.getName() + " for " + this.getDuration() + " ticks");
if (reset)
this.reset(key, key, Map);
return (Map.put(key, value) == null);
}
/**
* Add an element to the map
*
* @param key key of the element
* @param value value of the element
* @return true if the element was added
*/
public boolean put(K key, T value) {
return this.put(key, value, true);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#reset(java.lang.Object, java.lang.Object[])
*/
@Override
public void reset(K key, Object...objects) {
super.reset(key, key, Map);
}
/**
* Remove an element from the map
*
* @param key the key of the element
*/
public final void remove(K key) {
Map.remove(key);
this.cancel(key);
}
/**
* Get the value of the element having a specific key
*
* @param key the key of the element
* @return the value
*/
public T get(K key) {
return Map.get(key);
}
/**
* Tell if the map contains an element
*
* @param key the element to check
* @return true if the element is in the map
*/
public boolean contains(K key) {
return Map.containsKey(key);
}
/**
* Remove all the elements of the map
*
*/
public void clear() {
Map.clear();
}
/**
* Tell if the map is empty
*
* @return true if the map is empty
*/
public boolean isEmpty() {
return Map.isEmpty();
}
}
| 2,756 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
PartitionedHashSet.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Storage/PartitionedHashSet.java | package com.github.catageek.ByteCart.Storage;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import com.github.catageek.ByteCartAPI.Storage.Partitionable;
/**
* A set containing powers of 2 of an integer
*
* @param <E> A partitionable type
*/
public class PartitionedHashSet<E extends Partitionable> extends HashSet<E> {
/**
*
*/
private static final long serialVersionUID = 7798172721619367114L;
public PartitionedHashSet() {
}
public PartitionedHashSet(Collection<? extends E> c) {
super(c);
}
public PartitionedHashSet(int initialCapacity) {
super(initialCapacity);
}
public PartitionedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
/**
* Get the addition of values from the set
*
* @return the value
*/
public final int getPartitionedValue() {
int ret = 0;
Iterator<E> it = this.iterator();
while (it.hasNext()) {
ret |= it.next().getAmount();
}
return ret;
}
}
| 1,001 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ExpirableSet.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Storage/ExpirableSet.java | package com.github.catageek.ByteCart.Storage;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.github.catageek.ByteCart.ThreadManagement.Expirable;
/**
* A set in which elements are deleted after a timeout
*
* @param <K> the type of elements of the set
*/
public final class ExpirableSet<K> extends Expirable<K> {
private final Set<K> Set = Collections.synchronizedSet(new HashSet<K>());
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#Expirable(long, boolean, String)
*/
public ExpirableSet(long duration, boolean isSync, String name) {
super(duration, isSync, name);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#expire(java.lang.Object[])
*/
@SuppressWarnings("unchecked")
@Override
public void expire(Object... objects) {
((Set<K>)objects[1]).remove(objects[0]);
}
/**
* Add an element to the set
*
* @param key the element to add
* @return true if the element was added
*/
public boolean add(K key) {
// if(ByteCart.debug)
// ByteCart.log.info("ByteCart: create ephemeral key (" + key +") in " + this.getName() + " for " + this.getDuration() + " ticks");
this.reset(key, key, Set);
return Set.add(key);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#reset(java.lang.Object, java.lang.Object[])
*/
@Override
public void reset(K key, Object...objects) {
super.reset(key, key, Set);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.ThreadManagement.Expirable#reset(long, java.lang.Object, java.lang.Object[])
*/
@Override
public void reset(long duration, K key, Object...objects) {
super.reset(duration, key, key, Set);
}
/**
* Remove the element from the set
*
* @param key the element to remove
*/
public final void remove(K key) {
Set.remove(key);
this.cancel(key);
}
/**
* Tells if the set contains an element
*
* @param key the element to check
* @return true if the element is in the set
*/
public boolean contains(K key) {
return Set.contains(key);
}
/**
* Tells if the set is empty
*
* @return true if the set is empty
*/
public boolean isEmpty() {
return Set.isEmpty();
}
/**
* Empty the set
*/
public void clear() {
Iterator<K> it = Set.iterator();
while (it.hasNext())
this.cancel(it.next());
Set.clear();
}
public Iterator<K> getIterator() {
return Set.iterator();
}
} | 2,509 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
IsTrainManager.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Storage/IsTrainManager.java | package com.github.catageek.ByteCart.Storage;
import org.bukkit.Location;
/**
* A map that contain the train bit for each component
*
* The train bit set to true means that a train is currently using the component
*/
public final class IsTrainManager {
private ExpirableMap<Location, Boolean> IsTrain = new ExpirableMap<Location, Boolean>(14, false, "isTrain");
/**
* Get the map
*
* @return the map
*/
public ExpirableMap<Location, Boolean> getMap() {
return IsTrain;
}
}
| 500 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Returnable.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/Returnable.java | package com.github.catageek.ByteCart.AddressLayer;
/**
* Represent a return address
*/
interface Returnable extends AddressRouted {
}
| 138 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AddressString.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/AddressString.java | package com.github.catageek.ByteCart.AddressLayer;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
import com.github.catageek.ByteCartAPI.AddressLayer.Resolver;
import com.github.catageek.ByteCartAPI.HAL.VirtualRegistry;
/**
* This class represents a canonical address like xx.xx.xx
*/
public class AddressString extends AbstractAddress implements Address {
/**
* String used as internal storage
*/
private String String; // address as displayed
private final static Resolver resolver;
static {
resolver = ByteCart.myPlugin.getResolver();
}
/**
* Creates the address
*
* @param s the string containing the address or a name to resolve to an address
*/
public AddressString(String s, boolean resolve) {
if (isAddress(s)) {
this.String = s;
return;
}
if (isResolvableName(s)) {
if (resolve) {
this.String = resolver.resolve(s);
}
else {
this.String = s;
}
return;
}
this.String = null;
this.isValid = false;
}
/**
* Static method to check the format of an address
*
* A resolvable name will return true
*
* This method does not check if the address fields are in a valid range
*
* @param s the string containing the address to check
* @return true if the address is in the valid format or a resolvable name
*/
static public boolean isResolvableAddressOrName(String s) {
if((s.matches("([0-9]{1,4}\\.){2,2}[0-9]{1,3}"))
|| isResolvableName(s)) {
return true;
}
return false;
}
/**
* Static method to check the format of an address
*
* This method does not check if the address fields are in a valid range
*
* @param s the string containing the address to check
* @return true if the address is in the valid format
*/
static private boolean isAddress(String s) {
if(! (s.matches("([0-9]{1,4}\\.){2,2}[0-9]{1,3}"))) {
return false;
}
return true;
}
/**
* Static method to check if a name resolution gives a valid address
*
* @param s the string containing the name to check
* @return true if the resolution gives an address
*/
static private boolean isResolvableName(String name) {
if (resolver != null) {
String a = resolver.resolve(name);
if (a != null && AddressString.isAddress(a))
return true;
}
return false;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getRegion()
*/
@Override
public VirtualRegistry getRegion() {
VirtualRegistry ret;
(ret = new VirtualRegistry(Offsets.REGION.getLength())).setAmount(this.getField(0));
return ret;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getTrack()
*/
@Override
public VirtualRegistry getTrack() {
VirtualRegistry ret;
(ret = new VirtualRegistry(Offsets.TRACK.getLength())).setAmount(this.getField(1));
return ret;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getStation()
*/
@Override
public VirtualRegistry getStation() {
VirtualRegistry ret;
(ret = new VirtualRegistry(Offsets.STATION.getLength())).setAmount(this.getField(2));
return ret;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isTrain()
*/
@Override
public boolean isTrain() {
throw new UnsupportedOperationException();
}
/**
* Return a field by index
*
* @param index a number between 0 and 2
* @return the number contained in the field
*/
private int getField(int index) {
if (this.String == null)
throw new IllegalStateException("Address is not valid.");
String[] st = this.String.split("\\.");
return Integer.parseInt(st[ index ].trim());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#setRegion(int)
*/
@Override
public void setRegion(int region) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#setTrack(int)
*/
@Override
public void setTrack(int track) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#setStation(int)
*/
@Override
public void setStation(int station) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#setIsTrain(boolean)
*/
@Override
public void setIsTrain(boolean isTrain) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#toString()
*/
@Override
public java.lang.String toString() {
if (this.String != null)
return this.String;
return "";
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#setAddress(java.lang.String)
*/
@Override
public boolean setAddress(java.lang.String s) {
if (isResolvableAddressOrName(s)) {
this.String = s;
this.isValid = true;
}
else {
this.String = null;
this.isValid = false;
}
return this.isValid;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AbstractAddress#UpdateAddress()
*/
@Override
protected boolean UpdateAddress() {
finalizeAddress();
return true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#remove()
*/
@Override
public void remove() {
this.String = null;
this.isValid = false;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isReturnable()
*/
@Override
public boolean isReturnable() {
return false;
}
}
| 5,610 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/package-info.java | /**
* Address layer package
*/
/**
* This package provides classes to manage destination and return address on various support: Book, sign, string.
*/
package com.github.catageek.ByteCart.AddressLayer; | 205 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AddressSign.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/AddressSign.java | package com.github.catageek.ByteCart.AddressLayer;
import org.bukkit.block.Block;
import com.github.catageek.ByteCart.IO.AbstractComponent;
import com.github.catageek.ByteCart.IO.ComponentSign;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
/**
* Implements an address using a line of a sign as support
*/
final class AddressSign extends AbstractComponent implements Address {
/**
* String used as internal storage
*/
private final AddressString Address;
/**
* Creates the address
*
* @param block the sign block containing the address
* @param ligne the line number containing the address
*/
AddressSign(Block block, int ligne) {
super(block);
this.Address = new AddressString((new ComponentSign(block)).getLine(ligne), false);
/*
if(ByteCart.debug)
ByteCart.log.info("ByteCart: creating AddressSign line #" + ligne + " at " + block.getLocation().toString());
*/
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getRegion()
*/
@Override
public final RegistryBoth getRegion() {
return Address.getRegion();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getTrack()
*/
@Override
public final RegistryBoth getTrack() {
return Address.getTrack();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getStation()
*/
@Override
public final RegistryBoth getStation() {
return Address.getStation();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String)
*/
@Override
public final boolean setAddress(String s) {
this.Address.setAddress(s);
return true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String, java.lang.String)
*/
@Override
public boolean setAddress(String s, String name) {
(new ComponentSign(this.getBlock())).setLine(2, name);
return setAddress(s);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isTrain()
*/
@Override
public boolean isTrain() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setTrain(boolean)
*/
@Override
public boolean setTrain(boolean istrain) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#finalizeAddress()
*/
@Override
public final void finalizeAddress() {
(new ComponentSign(this.getBlock())).setLine(3, this.Address.toString());
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isValid()
*/
@Override
public boolean isValid() {
return this.Address.isValid;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#remove()
*/
@Override
public void remove() {
this.Address.remove();
(new ComponentSign(this.getBlock())).setLine(3, "");
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
final public String toString() {
return Address.toString();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isReturnable()
*/
@Override
public boolean isReturnable() {
return false;
}
}
| 3,322 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AddressRouted.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/AddressRouted.java | package com.github.catageek.ByteCart.AddressLayer;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
/**
* Represents an address currently routed
*/
public interface AddressRouted extends Address {
/**
* Get the TTL (time-to-live) associated with the address
*
*
* @return the TTL
*/
public int getTTL();
/**
* Set the TTL
*
* {@link Address#finalizeAddress()} should be called later to actually set the TTL
*
* @param i the value to set
*/
public void updateTTL(int i);
/**
* Initialize TTL to its default value
*
* {@link Address#finalizeAddress()} should be called later to actually initialize the TTL
*
*/
public void initializeTTL();
}
| 701 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AddressBook.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/AddressBook.java | package com.github.catageek.ByteCart.AddressLayer;
import org.bukkit.entity.Player;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
/**
* A class implementing an address using a book as support
*/
final class AddressBook implements AddressRouted {
/**
* Parameters name used in the book
*/
public enum Parameter {
DESTINATION("net.dst.addr"),
RETURN("net.src.addr"),
TTL("net.ttl"),
TRAIN("net.train");
private final String name;
Parameter(String s) {
name = s;
}
/**
* @return the name
*/
public String getName() {
return name;
}
}
/**
* The ticket used as support for the address
*/
private final Ticket ticket;
/**
* The type of the address
*/
private final Parameter parameter;
/**
* Creates an address using a ticket and a parameter
*
* @param ticket the ticket where to store the address
* @param parameter the type of address to store
*/
AddressBook(Ticket ticket, Parameter parameter) {
this.ticket = ticket;
this.parameter = parameter;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getRegion()
*/
@Override
public RegistryBoth getRegion() {
return getAddress().getRegion();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getTrack()
*/
@Override
public RegistryBoth getTrack() {
return getAddress().getTrack();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getStation()
*/
@Override
public RegistryBoth getStation() {
return getAddress().getStation();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isTrain()
*/
@Override
public boolean isTrain() {
return ticket.getString(Parameter.TRAIN, "false").equalsIgnoreCase("true");
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String)
*/
@Override
public boolean setAddress(String s) {
return setAddress(s, null);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String, java.lang.String)
*/
@Override
public boolean setAddress(String value, String stationname) {
boolean ret = this.ticket.setEntry(parameter, value);
if (parameter.equals(Parameter.DESTINATION)) {
if(ByteCart.debug)
ByteCart.log.info("ByteCart : set title");
ticket.appendTitle(stationname, value);
}
return ret;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setTrain(boolean)
*/
@Override
public boolean setTrain(boolean istrain) {
if (istrain)
return ticket.setEntry(Parameter.TRAIN, "true");
ticket.remove(Parameter.TRAIN);
return true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isValid()
*/
@Override
public boolean isValid() {
return getAddress().isValid();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AddressRouted#getTTL()
*/
@Override
public int getTTL() {
return ticket.getInt(Parameter.TTL, ByteCart.myPlugin.getConfig().getInt("TTL.value"));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AddressRouted#updateTTL(int)
*/
@Override
public void updateTTL(int i) {
ticket.setEntry(Parameter.TTL, ""+i);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AddressRouted#initializeTTL()
*/
@Override
public void initializeTTL() {
this.ticket.resetValue(Parameter.TTL, ByteCart.myPlugin.getConfig().getString("TTL.value"));
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getAddress().toString();
}
/**
* Read the address from the ticket
*
* @return the address
*/
private Address getAddress() {
String defaultaddr = ByteCart.myPlugin.getConfig().getString("EmptyCartsDefaultRoute", "0.0.0");
return new AddressString(ticket.getString(parameter, defaultaddr),true);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#remove()
*/
@Override
public void remove() {
ticket.remove(parameter);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isReturnable()
*/
@Override
public boolean isReturnable() {
return ticket.getString(Parameter.RETURN) != null;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#finalizeAddress()
*/
@SuppressWarnings("deprecation")
@Override
public void finalizeAddress() {
ticket.close();
if (ticket.getTicketHolder() instanceof Player) {
if(ByteCart.debug)
ByteCart.log.info("ByteCart : update player inventory");
((Player) ticket.getTicketHolder()).updateInventory();
}
}
}
| 4,813 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AddressFactory.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/AddressFactory.java | package com.github.catageek.ByteCart.AddressLayer;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.AddressLayer.AddressBook.Parameter;
import com.github.catageek.ByteCart.FileStorage.BookFile;
import com.github.catageek.ByteCart.FileStorage.BookProperties.Conf;
import com.github.catageek.ByteCart.Signs.BC7010;
import com.github.catageek.ByteCart.Signs.BC7011;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
/**
* Factory to create address using various supports
*/
public class AddressFactory {
/**
* Get an address with a ticket as support
*
* @param inv the inventory containing the ticket
* @return the address or null if there is no ticket
*/
@SuppressWarnings("unchecked")
public final static <T extends Address> T getAddress(Inventory inv){
int slot = Ticket.getTicketslot(inv);
if (slot != -1) {
BookFile bookfile = BookFile.getFrom(inv, slot, false, "ticket");
if (bookfile != null)
return (T) new AddressBook(new Ticket(bookfile, Conf.NETWORK), Parameter.DESTINATION);
}
return null;
}
/**
* Creates a ticket with default address
*
* @param inv the inventory containing the ticket
* @return the address
*/
@SuppressWarnings("unchecked")
public final static <T extends Address> T getDefaultTicket(Inventory inv){
String destination;
if (inv.getHolder() instanceof Player) {
destination = ByteCart.myPlugin.getConfig().getString("PlayersNoTicketDefaultRoute", "0.0.0");
if ((new BC7010(null,(Player)inv.getHolder())).setAddress(destination,"No ticket found !")) {
return (T) new AddressBook(new Ticket(BookFile.getFrom(inv, Ticket.getTicketslot(inv), false, "ticket"), Conf.NETWORK), Parameter.DESTINATION);
}
}
else if (inv.getHolder() instanceof Vehicle) {
destination = ByteCart.myPlugin.getConfig().getString("EmptyCartsDefaultRoute", "0.0.0");
if ((new BC7011(null,(Vehicle)inv.getHolder())).setAddress(destination,"No ticket found !")) {
return (T) new AddressBook(new Ticket(BookFile.getFrom(inv, Ticket.getTicketslot(inv), false, "ticket"), Conf.NETWORK), Parameter.DESTINATION);
}
}
return null;
}
/**
* Creates an address with a sign as support
*
* @param b the sign block
* @param line the line number
* @return the address
*/
public final static Address getAddress(Block b, int line){
return new AddressSign(b, line);
}
/**
* Creates an address with a string as internal support
*
* The address is resolved.
*
* @param s the address in the form aa.bb.cc
* @return the address
*/
public final static Address getAddress(String s){
return new AddressString(s, true);
}
/**
* Creates an address with a string as internal support
*
* The address is not resolved.
*
* @param s the address in the form aa.bb.cc
* @return the address
*/
final static Address getUnresolvedAddress(String s){
return new AddressString(s, false);
}
}
| 3,078 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ReturnAddressBook.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/ReturnAddressBook.java | package com.github.catageek.ByteCart.AddressLayer;
import com.github.catageek.ByteCart.AddressLayer.AddressBook.Parameter;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
/**
* A class implementing a return address in a book
*/
final class ReturnAddressBook implements Returnable {
/**
* Creates a return address from a ticket of a certain type
*
* @param ticket the ticket to use as support
* @param parameter the type of the address
*/
ReturnAddressBook(Ticket ticket, Parameter parameter) {
this.address = new AddressBook(ticket, parameter);
}
/**
* The book address that this class will proxify
*/
private final AddressBook address;
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getRegion()
*/
@Override
public RegistryBoth getRegion() {
return address.getRegion();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getTrack()
*/
@Override
public RegistryBoth getTrack() {
return address.getTrack();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#getStation()
*/
@Override
public RegistryBoth getStation() {
return address.getStation();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isTrain()
*/
@Override
public boolean isTrain() {
return address.isTrain();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String)
*/
@Override
public boolean setAddress(String s) {
return address.setAddress(s);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String, java.lang.String)
*/
@Override
public boolean setAddress(String s, String name) {
return address.setAddress(s);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setTrain(boolean)
*/
@Override
public boolean setTrain(boolean istrain) {
return address.setTrain(istrain);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isValid()
*/
@Override
public boolean isValid() {
return address.isValid();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#remove()
*/
@Override
public void remove() {
address.remove();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AddressRouted#getTTL()
*/
@Override
public int getTTL() {
return address.getTTL();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AddressRouted#updateTTL(int)
*/
@Override
public void updateTTL(int i) {
address.updateTTL(i);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.AddressRouted#initializeTTL()
*/
@Override
public void initializeTTL() {
address.initializeTTL();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#isReturnable()
*/
@Override
public boolean isReturnable() {
return address.isReturnable();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return address.toString();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#finalizeAddress()
*/
@Override
public void finalizeAddress() {
address.finalizeAddress();
}
}
| 3,294 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractAddress.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/AbstractAddress.java | package com.github.catageek.ByteCart.AddressLayer;
import com.github.catageek.ByteCartAPI.ByteCartAPI;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
/**
* Abstract class implementing basic operations on address
*
* All address subclass must extend this class
*/
abstract class AbstractAddress implements Address {
/**
* A flag to tell to the world if the address should be considered as valid or not
*/
protected boolean isValid = true;
@Override
public final boolean isValid() {
return isValid;
}
/**
* Length (in bits) for various fields of address
*
* position is deprecated
*/
protected enum Offsets {
// length (default : 6), pos (default : 0)
REGION(ByteCartAPI.MAXRINGLOG, 0),
TRACK(ByteCartAPI.MAXRINGLOG, 0),
STATION(ByteCartAPI.MAXSTATIONLOG, 0);
private final int Length, Offset;
private Offsets() {
Length = 6;
Offset = 0;
}
private Offsets(int length, int offset) {
Length = length;
Offset = offset;
}
/**
* @return the length
*/
public int getLength() {
return Length;
}
/**
* @return the offset
*/
public int getOffset() {
return Offset;
}
}
/**
* Copy the fields of the address object
*
* @param a the source address to copy
* @return true if the address was copied
*/
private boolean setAddress(Address a) {
this.setStation(a.getStation().getAmount());
this.setIsTrain(a.isTrain());
this.setTrack(a.getTrack().getAmount());
this.setRegion(a.getRegion().getAmount());
return this.UpdateAddress();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(com.github.catageek.ByteCart.AddressLayer.Address, java.lang.String)
*/
@Override
public boolean setAddress(String a, String name) {
return this.setAddress(a);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setAddress(java.lang.String)
*/
@Override
public boolean setAddress(String s) {
return setAddress(AddressFactory.getUnresolvedAddress(s));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#setTrain(boolean)
*/
@Override
public final boolean setTrain(boolean istrain) {
this.setIsTrain(istrain);
return this.UpdateAddress();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "" + this.getRegion().getAmount() + "." + this.getTrack().getAmount() + "." + (this.getStation().getAmount());
}
/**
* flush the address to its support
*
*
* @return always true
*/
protected boolean UpdateAddress() {
finalizeAddress();
return true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.AddressLayer.Address#finalizeAddress()
*/
@Override
public void finalizeAddress() {
}
/**
* Set the region field
*
*
* @param region the region number to set
*/
abstract protected void setRegion(int region);
/**
* Set the ring field
*
*
* @param track the ring number to set
*/
abstract protected void setTrack(int track);
/**
* Set the station field
*
*
* @param station the station number to set
*/
abstract protected void setStation(int station);
/**
* Set the train flag
*
*
* @param isTrain true if the flag must be set
*/
abstract protected void setIsTrain(boolean isTrain);
}
| 3,358 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
ReturnAddressFactory.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/ReturnAddressFactory.java | package com.github.catageek.ByteCart.AddressLayer;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.AddressLayer.AddressBook.Parameter;
import com.github.catageek.ByteCart.FileStorage.BookFile;
import com.github.catageek.ByteCart.FileStorage.BookProperties.Conf;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
/**
* Factory class to create a return address from various supports
*/
public final class ReturnAddressFactory {
/**
* Creates a return address from a ticket
*
* @param inv the inventory containing the ticket
* @return the return address
*/
@SuppressWarnings("unchecked")
public final static <T extends Address> T getAddress(Inventory inv){
int slot;
if ((slot = Ticket.getTicketslot(inv)) != -1)
return (T) new ReturnAddressBook(new Ticket(BookFile.getFrom(inv, slot, false, "ticket"), Conf.NETWORK), Parameter.RETURN);
return null;
}
}
| 918 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
TicketFactory.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/TicketFactory.java | package com.github.catageek.ByteCart.AddressLayer;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import com.github.catageek.ByteCart.ByteCart;
/**
* Factory to create or get a ticket
*/
public final class TicketFactory {
/**
* Put a ticket in a player's inventory if necessary
*
* @param player the player
* @param forcereuse must be true to force the reuse of existing ticket
*/
@SuppressWarnings("deprecation")
public static final void getOrCreateTicket(Player player, boolean forcereuse) {
int slot;
Inventory inv = player.getInventory();
if (forcereuse || ByteCart.myPlugin.getConfig().getBoolean("reusetickets", true)) {
// if storage cart or we must reuse a existing ticket
// check if a ticket exists and return
// otherwise continue
slot = Ticket.getTicketslot(inv);
if (slot != -1)
return;
}
// get a slot containing an emtpy book (or nothing)
if ((slot = Ticket.getEmptyOrBookAndQuillSlot(player)) == -1)
return;
if (inv.getItem(slot) == null
&& ByteCart.myPlugin.getConfig().getBoolean("mustProvideBooks")) {
String msg = "No empty book in your inventory, you must provide one.";
player.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + msg);
return;
}
Ticket.createTicket(inv, slot);
player.updateInventory();
}
/**
* Put a ticket in an inventory, if necessary. The inventory is not updated.
*
* @param inv the inventory where to put the ticket
*/
public static final void getOrCreateTicket(Inventory inv) {
int slot;
// if storage cart or we must reuse a existing ticket
// check if a ticket exists and return
// otherwise continue
slot = Ticket.getTicketslot(inv);
if (slot != -1)
return;
Ticket.createTicket(inv, Ticket.searchSlot(inv));
}
/**
* Remove a ticket from an inventory
*
* @param inv
*/
@SuppressWarnings("deprecation")
public static final void removeTickets(Inventory inv) {
int slot;
while ((slot = Ticket.getTicketslot(inv)) != -1) {
inv.clear(slot);
}
InventoryHolder holder;
if ((holder = inv.getHolder()) instanceof Player)
((Player) holder).updateInventory();
}
}
| 2,256 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Ticket.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/AddressLayer/Ticket.java | package com.github.catageek.ByteCart.AddressLayer;
import java.io.IOException;
import java.util.ListIterator;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.BookMeta;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.AddressLayer.AddressBook.Parameter;
import com.github.catageek.ByteCart.FileStorage.BookFile;
import com.github.catageek.ByteCart.FileStorage.BookProperties;
import com.github.catageek.ByteCart.FileStorage.BookProperties.Conf;
/**
* Implement a ticket
*/
final class Ticket {
/**
* Internal storage of the ticket
*/
private final BookProperties properties;
/**
* Create a ticket using a book at a specific page
*
* @param bookfile the book FS to use
* @param network the name of the page
*/
Ticket(BookFile bookfile, Conf network) {
properties = new BookProperties(bookfile, network);
}
/**
* Get a slot containing a ticket
*
*
* @param inv The inventory to search in
* @return a slot number, or -1
*/
static int getTicketslot(Inventory inv) {
if (inv.contains(Material.WRITTEN_BOOK)) {
// priority given to book in hand
if (inv instanceof PlayerInventory) {
if (isTicket(((PlayerInventory) inv).getItemInMainHand())) {
return ((PlayerInventory) inv).getHeldItemSlot();
}
}
ListIterator<ItemStack> it = inv.iterator();
while (it.hasNext()) {
if (isTicket(it.next()))
return it.previousIndex();
}
}
return -1;
}
/**
* Tell if a stack is a ticket
*
* @param stack the stack to check
* @return true if it is a ticket
*/
private final static boolean isTicket(ItemStack stack) {
return BookFile.isBookFile(stack, "ticket");
}
/**
* Get a slot containing an empty book or nothing
*
*
* @param inv The inventory to search in
* @return a slot number, or -1
*/
private static int getEmptyOrBookAndQuillSlot(Inventory inv) {
ItemStack stack;
if (ByteCart.myPlugin.getConfig().getBoolean("mustProvideBooks")
&& inv.contains(Material.WRITABLE_BOOK)) {
// priority given to book in hand
if (inv instanceof PlayerInventory) {
if (isEmptyBook(stack = ((PlayerInventory) inv).getItemInMainHand())) {
return ((PlayerInventory) inv).getHeldItemSlot();
}
}
ListIterator<? extends ItemStack> it = inv.iterator();
while (it.hasNext()) {
stack = it.next();
if (isEmptyBook(stack)) {
int slot = it.previousIndex();
// found a book
return slot;
}
}
}
// no book found or user must provide one, return empty slot
int slot = inv.firstEmpty();
if (slot != -1) {
return slot;
}
return -1;
}
/**
* Get a slot containing an empty book or nothing
*
*
* @param player The player having the inventory to search in
* @return a slot number, or -1
*/
static int getEmptyOrBookAndQuillSlot(Player player) {
int slot;
if ((slot = getEmptyOrBookAndQuillSlot(player.getInventory())) == -1) {
String msg = "Error: No space in inventory.";
player.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + msg);
}
return slot;
}
/**
* Get a slot containing an empty book or nothing
*
*
* @param inv The inventory to search in
* @return a slot number, or -1
*/
static int searchSlot(Inventory inv) {
int slot;
// get a slot containing an emtpy book (or nothing)
slot = Ticket.getEmptyOrBookAndQuillSlot(inv);
if (slot != -1) {
if (inv.getItem(slot) == null
&& ByteCart.myPlugin.getConfig().getBoolean("mustProvideBooks")
&& ByteCart.myPlugin.getConfig().getBoolean("usebooks")) {
return -1;
}
return slot;
}
return -1;
}
/**
* Initialize a ticket in a inventory
*
* @param inv the inventory where to put the ticket
* @param slot the slot number where to put the ticket
*/
static void createTicket(Inventory inv, int slot) {
if (slot == -1)
return;
// swap with an existing book if needed
int existingticket = Ticket.getTicketslot(inv);
if (existingticket != -1 && existingticket != slot) {
inv.setItem(slot, inv.getItem(existingticket));
slot = existingticket;
}
try {
BookFile bookfile = BookFile.create(inv, slot, false, "ticket");
bookfile.setDescription(ByteCart.myPlugin.getConfig().getString("title"));
bookfile.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Tell if a book_and_quill is empty
*
* @param stack the ItemStack to check
* @return true if it is an empty book_and_quill
*/
private static boolean isEmptyBook(ItemStack stack) {
BookMeta book;
if (stack != null && stack.getType().equals(Material.WRITABLE_BOOK)) {
if (stack.hasItemMeta()) {
if ((book = (BookMeta)stack.getItemMeta()).hasPages()
&& (book.getPage(1).isEmpty()))
return true;
}
else {
return true;
}
}
return false;
}
/**
* Get the holder of the ticket
*
* @return the holder
*/
InventoryHolder getTicketHolder() {
return properties.getFile().getContainer().getHolder();
}
/**
* Set a parameter value in the ticket
*
* <p>{@link Ticket#close()} must be called to actually perform the operation</p>
*
* @param parameter parameter to set
* @param value value to set
* @return true
*/
final boolean setEntry(Parameter parameter, String value) {
try {
properties.setProperty(parameter.getName(), value);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
/**
* Return the value of a parameter or a default value
*
* @param parameter the parameter to return
* @param defaultvalue the default value
* @return a string containing the parameter value, or the default value
*/
final String getString(Parameter parameter, String defaultvalue) {
return properties.getString(parameter.getName(), defaultvalue);
}
/**
* Return the value of a parameter
*
* @param parameter the parameter to return
* @return a string containing the parameter value
*/
final String getString(Parameter parameter) {
return properties.getString(parameter.getName());
}
/**
* Append a name and a string to the title
*
* <p>{@link Ticket#close()} must be called to actually perform the operation</p>
*
* <p>The appended value is " name (string)"</p>
*
* @param name
* @param s
*/
void appendTitle(String name, String s) {
StringBuilder build = new StringBuilder(ByteCart.myPlugin.getConfig().getString("title"));
if (name != null)
build.append(" ").append(name);
build.append(" ").append(s);
try {
properties.getFile().setDescription(build.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Get a parameter value as an integer or a default value
*
* @param parameter the parameter to get
* @param defaultvalue the default value
* @return the parameter value
*/
final int getInt(Parameter parameter, int defaultvalue) {
return properties.getInt(parameter.getName(), defaultvalue);
}
/**
* Reset the parameter to default value
*
* <p>{@link Ticket#close()} must be called to actually perform the operation</p>
*
* @param parameter the parameter to set
* @param defaultvalue the value to set
*/
void resetValue(Parameter parameter, String defaultvalue) {
try {
properties.setProperty(parameter.getName(), defaultvalue);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Remove a parameter
*
* <p>{@link Ticket#close()} must be called to actually perform the operation</p>
*
* @param parameter parameter to remove
*/
void remove(Parameter parameter) {
try {
properties.clearProperty(parameter.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Write the parameters and close the ticket
*
*/
void close() {
try {
properties.flush();
properties.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 8,321 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
AbstractRoutingTable.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/AbstractRoutingTable.java | package com.github.catageek.ByteCart.Routing;
import java.util.Iterator;
import java.util.Set;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCartAPI.Wanderer.RoutingTable;
/**
* An abstract class for routing tables
*/
abstract class AbstractRoutingTable implements RoutingTable {
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#isDirectlyConnected(int, org.bukkit.block.BlockFace)
*/
@Override
public final boolean isDirectlyConnected(int ring, BlockFace direction) {
if (this.getDirection(ring) != null)
return this.getMetric(ring, direction) == 0;
return false;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getDirectlyConnected(org.bukkit.block.BlockFace)
*/
@Override
public final int getDirectlyConnected(BlockFace direction) {
Set<Integer> rings = getDirectlyConnectedList(direction);
return rings.size() == 1 ? rings.iterator().next() : -1 ;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getFirstUnknown()
*/
@Override
public final BlockFace getFirstUnknown() {
for (BlockFace face : BlockFace.values()) {
switch(face) {
case NORTH:
case EAST:
case SOUTH:
case WEST:
if (this.getDirectlyConnectedList(face).isEmpty())
return face;
default:
break;
}
}
return null;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getDirectlyConnectedList(org.bukkit.block.BlockFace)
*/
@Override
abstract public Set<Integer> getDirectlyConnectedList(BlockFace direction);
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getMetric(int, org.bukkit.block.BlockFace)
*/
@Override
abstract public int getMetric(int entry, BlockFace direction);
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getMinMetric(int)
*/
@Override
abstract public int getMinMetric(int entry);
/**
* Store a line in the routing table
*
* @param entry the track number
* @param direction the direction to associate
* @param metric the metric to associate
*/
abstract public void setEntry(int entry, BlockFace direction, int metric);
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#isEmpty(int)
*/
@Override
abstract public boolean isEmpty(int entry);
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getOrderedRouteNumbers()
*/
@Override
public abstract Iterator<Integer> getOrderedRouteNumbers();
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getNotDirectlyConnectedList(org.bukkit.block.BlockFace)
*/
@Override
public abstract Set<Integer> getNotDirectlyConnectedList(BlockFace direction);
/**
* Remove a line from the routing table
*
* @param entry the track number
* @param from the direction to remove
*/
abstract public void removeEntry(int entry, BlockFace from);
/* (non-Javadoc)
* @see com.github.catageek.ByteCartAPI.Wanderer.RoutingTable#getDirection(int)
*/
@Override
abstract public BlockFace getDirection(int entry);
}
| 3,164 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/package-info.java | /**
*
*/
/**
* A package that provides the routing layer
*
*/
package com.github.catageek.ByteCart.Routing; | 113 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RoutingTableWritable.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RoutingTableWritable.java | package com.github.catageek.ByteCart.Routing;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.block.BlockFace;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.Updaters.UpdaterContent;
import com.github.catageek.ByteCartAPI.Wanderer.RoutingTable;
/**
* A routing table
*/
public interface RoutingTableWritable extends RoutingTable {
/**
* Store a line in the routing table
*
* @param entry the track number
* @param direction the direction to associate
* @param metric the metric to associate
*/
public void setEntry(int entry, BlockFace direction, int metric);
/**
* Remove a line from the routing table
*
* @param entry the track number
* @param from the direction to remove
*/
public void removeEntry(int entry, BlockFace from);
/**
* Performs the IGP protocol to update the routing table
*
* @param neighbour the IGP packet received
* @param from the direction from where we received it
*/
public default void Update(UpdaterContent neighbour, BlockFace from) {
// Djikstra algorithm
// search for better routes in the received ones
int interfacedelay = neighbour.getInterfaceDelay();
for (Map.Entry<Integer, Metric> entry : neighbour.getEntrySet()) {
int ring = entry.getKey();
Metric metric = entry.getValue();
int computedmetric = metric.value();
if (interfacedelay > 0)
computedmetric += interfacedelay;
int routermetric = this.getMetric(ring, from);
boolean directlyconnected = (this.getMinMetric(ring) == 0);
if ( ! directlyconnected && (routermetric > computedmetric || routermetric < 0)) {
this.setEntry(ring, from, computedmetric);
if(ByteCart.debug) {
ByteCart.log.info("ByteCart : Update : ring = " + ring + ", metric = " + computedmetric + ", direction " + from);
}
ByteCart.myPlugin.getWandererManager().getFactory("Updater").updateTimestamp(neighbour);
}
}
// search for routes that are no more announced and not directly connected
// to remove them
Iterator<Integer> it = this.getNotDirectlyConnectedList(from).iterator();
while (it.hasNext()) {
Integer route;
if(!neighbour.hasRouteTo(route = it.next())) {
this.removeEntry(route, from);
if(ByteCart.debug) {
ByteCart.log.info("ByteCart : Remove : ring = " + route + " from " + from);
}
ByteCart.myPlugin.getWandererManager().getFactory("Updater").updateTimestamp(neighbour);
}
}
}
/**
* Clear the routing table
*
* @param fullreset if set to false, route to entry 0 is kept.
*/
public void clear(boolean fullreset);
/**
* Serialize the routing table
*
* @param allowconversion if set to false, non conversion to another format
* @throws IOException
*/
void serialize(boolean allowconversion) throws IOException;
}
| 2,860 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RoutingTableBook.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RoutingTableBook.java | package com.github.catageek.ByteCart.Routing;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.bukkit.block.BlockFace;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.FileStorage.InventoryFile;
import com.github.catageek.ByteCart.Storage.ExternalizableTreeMap;
import com.github.catageek.ByteCart.Storage.PartitionedHashSet;
import com.github.catageek.ByteCartAPI.Util.DirectionRegistry;
/**
* A routing table in a book
*/
final class RoutingTableBook extends AbstractRoutingTable implements
RoutingTableWritable, Externalizable {
private boolean wasModified = false;
private ExternalizableTreeMap<RouteNumber, RouteProperty> map = new ExternalizableTreeMap<RouteNumber,RouteProperty>();
private static final long serialVersionUID = -7013741680310224056L;
private Inventory inventory;
/**
* Set the inventory
*
* @param inventory the inventory
*/
final void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public RoutingTableBook() {
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#clear(boolean)
*/
@Override
public void clear(boolean fullreset) {
if (map.isEmpty())
return;
RouteProperty routes = null;
RouteNumber route = new RouteNumber(0);
if (! fullreset && map.containsKey(route))
routes = map.get(route);
map.clear();
if (! fullreset && routes != null)
map.put(route, routes);
if (ByteCart.debug)
ByteCart.log.info("ByteCart : clear routing table map");
wasModified = true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#getRouteNumbers()
*/
@Override
public final Iterator<Integer> getOrderedRouteNumbers() {
TreeSet<Integer> newmap = new TreeSet<Integer>();
for(RouteNumber key : map.keySet()) {
newmap.add(key.value());
}
return ((SortedSet<Integer>) newmap).iterator();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getMetric(int, com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public int getMetric(int entry, BlockFace direction) {
SortedMap<Metric, PartitionedHashSet<DirectionRegistry>> smap;
RouteNumber route = new RouteNumber(entry);
if (map.containsKey(route) && (smap = map.get(route).getMap()) != null
&& ! smap.isEmpty()) {
Iterator<Metric> it = smap.keySet().iterator();
Metric d;
while (it.hasNext())
if (smap.get((d = it.next())).contains(new DirectionRegistry(direction)))
return d.value();
}
return -1;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getMinMetric(int)
*/
@Override
public int getMinMetric(int entry) {
SortedMap<Metric, PartitionedHashSet<DirectionRegistry>> smap;
RouteNumber route = new RouteNumber(entry);
if (map.containsKey(route) && (smap = map.get(route).getMap()) != null
&& ! smap.isEmpty()) {
return smap.firstKey().value();
}
return -1;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#setEntry(int, com.github.catageek.ByteCart.Util.DirectionRegistry, com.github.catageek.ByteCart.Routing.Metric)
*/
private void setMapEntry(int entry, DirectionRegistry direction, Metric metric) {
RouteNumber route = new RouteNumber(entry);
Metric dist = new Metric(metric);
RouteProperty smap;
PartitionedHashSet<DirectionRegistry> set;
if (metric.value() < this.getMetric(entry, direction.getBlockFace())) {
this.removeEntry(entry, direction.getBlockFace());
}
if ((smap = map.get(route)) == null) {
smap = new RouteProperty();
map.put(route, smap);
wasModified = true;
}
if ((set = smap.getMap().get(dist)) == null) {
set = new PartitionedHashSet<DirectionRegistry>(3);
smap.getMap().put(dist, set);
wasModified = true;
}
wasModified |= set.add(direction);
}
private RoutingTableBookJSON convertToJSON() {
final RoutingTableBookJSON jtable = new RoutingTableBookJSON();
jtable.setInventory(this.inventory, 0);
for (Entry<RouteNumber, RouteProperty> entry : map.entrySet()) {
for (Entry<Metric, PartitionedHashSet<DirectionRegistry>> routemap : entry.getValue().getMap().entrySet()) {
for (DirectionRegistry route : routemap.getValue()) {
jtable.setEntry(entry.getKey().value(), route.getBlockFace(), routemap.getKey().value());
}
}
}
return jtable;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#setEntry(int, com.github.catageek.ByteCart.Util.DirectionRegistry, com.github.catageek.ByteCart.Routing.Metric)
*/
@Override
public void setEntry(int entry, BlockFace direction, int metric) {
setMapEntry(entry, new DirectionRegistry(direction), new Metric(metric));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#isEmpty(int)
*/
@Override
public boolean isEmpty(int entry) {
return ! map.containsKey(new RouteNumber(entry));
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getDirection(int)
*/
@Override
public BlockFace getDirection(int entry) {
RouteNumber route = new RouteNumber(entry);
Set<DirectionRegistry> set;
TreeMap<Metric, PartitionedHashSet<DirectionRegistry>> pmap;
if (map.containsKey(route) && (pmap = map.get(route).getMap()) != null && ! pmap.isEmpty()) {
set = pmap.firstEntry().getValue();
if (! set.isEmpty())
return set.toArray(new DirectionRegistry[set.size()])[0].getBlockFace();
throw new AssertionError("Set<DirectionRegistry> in RoutingTableWritable is empty.");
}
return null;
}
@Override
public BlockFace getAllowedDirection(int entry) {
return getDirection(entry);
}
@Override
public Boolean isAllowedDirection(BlockFace direction) {
return true;
}
@Override
public void allowDirection(BlockFace direction, Boolean enable) {
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getDirectlyConnectedList(com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public Set<Integer> getDirectlyConnectedList(BlockFace direction) {
SortedMap<Integer, Metric> list = new TreeMap<Integer, Metric>();
Iterator<Entry<RouteNumber, RouteProperty>> it = map.entrySet().iterator();
Entry<RouteNumber, RouteProperty> entry;
Metric zero = new Metric(0);
TreeMap<Metric, PartitionedHashSet<DirectionRegistry>> smap;
PartitionedHashSet<DirectionRegistry> set;
while (it.hasNext()) {
entry = it.next();
if ((smap = entry.getValue().getMap()) != null && smap.containsKey(zero)
&& ! (set = smap.get(zero)).isEmpty()
&& set.contains(new DirectionRegistry(direction))) {
// just extract the connected route
list.put(entry.getKey().value(), zero);
}
}
return list.keySet();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getNotDirectlyConnectedList(com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public Set<Integer> getNotDirectlyConnectedList(
BlockFace direction) {
SortedMap<Integer, Metric> list = new TreeMap<Integer, Metric>();
Iterator<Entry<RouteNumber, RouteProperty>> it = map.entrySet().iterator();
Entry<RouteNumber, RouteProperty> entry;
Metric zero = new Metric(0);
Metric one = new Metric(1);
SortedMap<Metric, PartitionedHashSet<DirectionRegistry>> smap;
PartitionedHashSet<DirectionRegistry> set;
while (it.hasNext()) {
entry = it.next();
if ((smap = entry.getValue().getMap()) == null
|| ! (smap = entry.getValue().getMap()).containsKey(zero)
|| ! (! (set = smap.get(zero)).isEmpty()
&& set.contains(new DirectionRegistry(direction)))) {
// extract routes going to directions with distance > 0
smap = smap.tailMap(one);
Iterator<Metric> it2 = smap.keySet().iterator();
while (it2.hasNext()) {
Metric d = it2.next();
if (smap.get(d).contains(new DirectionRegistry(direction))) {
list.put(entry.getKey().value(), d);
break;
}
}
}
}
return list.keySet();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#removeEntry(int, com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public void removeEntry(int entry, BlockFace from) {
RouteNumber route = new RouteNumber(entry);
TreeMap<Metric,PartitionedHashSet<DirectionRegistry>> smap;
Set<DirectionRegistry> set;
if (map.containsKey(route) && (smap = map.get(route).getMap()) != null) {
Iterator<Metric> it = smap.keySet().iterator();
while (it.hasNext()) {
wasModified |= (set = smap.get(it.next())).remove(new DirectionRegistry(from));
if (set.isEmpty())
it.remove();
if (smap.isEmpty())
map.remove(route);
}
}
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#serialize()
*/
@Override
public void serialize(boolean allowconversion) throws IOException {
if (! wasModified)
return;
try {
// we try to convert to JSON
if (allowconversion) {
this.convertToJSON().serialize(false);
return;
}
} catch(IOException e) {
}
// if not possible, try with binary format
if (ByteCart.debug)
ByteCart.log.info("ByteCart: JSON conversion failed, trying binary format");
InventoryFile file = new InventoryFile(inventory, true, "RoutingTableBinary");
file.setDescription("Bytecart Routing Table");
file.clear();
ObjectOutputStream oos = new ObjectOutputStream(file.getOutputStream());
oos.writeObject(this);
if(ByteCart.debug)
ByteCart.log.info("ByteCart: binary object written, now closing");
oos.flush();
wasModified = false;
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
@SuppressWarnings("unchecked")
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.map = (ExternalizableTreeMap<RouteNumber, RouteProperty>) in.readObject();
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(map);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#size()
*/
@Override
public int size() {
return map.size();
}
}
| 10,660 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Metric.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/Metric.java | package com.github.catageek.ByteCart.Routing;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
/**
* The metric component of a routing table entry
*/
public final class Metric implements Comparable<Metric>, Externalizable {
/**
*
*/
private static final long serialVersionUID = 7625856925617432369L;
private Delay delay;
public Metric() {
}
Metric(Metric m) {
this(m.delay.getValue());
}
public Metric(int delay) {
this.delay = new Delay(delay);
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Metric o) {
return new CompareToBuilder().append(value(), o.value()).toComparison();
}
/**
* @return the value
*/
public int value() {
return delay.getValue();
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
delay = (Delay) in.readObject();
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(delay);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return value();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (o == this)
return true;
if (!(o instanceof Metric))
return false;
Metric rhs = (Metric) o;
return new EqualsBuilder().append(value(),rhs.value()).isEquals();
}
}
| 1,827 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RoutingTableContent.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RoutingTableContent.java | package com.github.catageek.ByteCart.Routing;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
import com.github.catageek.ByteCartAPI.HAL.VirtualRegistry;
/**
* A raw routing table entry, i.e a registry
*
* @param <T> the type of content that will be stored
*/
abstract class RoutingTableContent<T extends RoutingTableContent<T>> implements Comparable<T> {
/**
*
*/
private final int length;
private final RegistryBoth data;
/**
* @return the size of the registry in bits
*/
final int size() {
return length;
}
RoutingTableContent(int length) {
this.length = length;
data = new VirtualRegistry(length);
}
RoutingTableContent(int amount, int length) {
this(length);
this.data.setAmount(amount);
}
/**
* @param amount the value to store
*/
protected void setValue(int amount) {
data.setAmount(amount);
}
/**
* @return the value stored
*/
public final int value() {
return data.getAmount();
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(T o) {
return new CompareToBuilder().append(value(), o.value()).toComparison();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return value();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (o == this)
return true;
if (!(o instanceof RoutingTableContent<?>))
return false;
RoutingTableContent<?> rhs = (RoutingTableContent<?>) o;
return new EqualsBuilder().append(value(),rhs.value()).isEquals();
}
} | 1,782 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RoutingTableFactory.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RoutingTableFactory.java | package com.github.catageek.ByteCart.Routing;
import java.io.IOException;
import java.io.ObjectInputStream;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.FileStorage.InventoryFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
/**
* Factory for routing tables
*/
public final class RoutingTableFactory {
/**
* Get a routing table
*
* @param inv the inventory to open
* @return the RoutingTableWritable object
* @throws IOException
* @throws ClassNotFoundException
*/
static public RoutingTableWritable getRoutingTable(Inventory inv, int slot) throws ClassNotFoundException, IOException, JsonSyntaxException {
InventoryFile file = null;
if (InventoryFile.isInventoryFile(inv, ".BookFile")) {
file = new InventoryFile(inv, true, ".BookFile");
}
else if (InventoryFile.isInventoryFile(inv, "RoutingTableBinary")) {
file = new InventoryFile(inv, true, "RoutingTableBinary");
}
RoutingTableBook rt = null;
if (file != null && ! file.isEmpty()) {
ObjectInputStream ois = new ObjectInputStream(file.getInputStream());
rt = (RoutingTableBook) ois.readObject();
rt.setInventory(inv);
return rt;
}
if (InventoryFile.isInventoryFile(inv, "RoutingTable")) {
file = new InventoryFile(inv, false, "RoutingTable");
}
if (file == null || file.isEmpty()) {
if (inv.getItem(slot) == null) {
return new RoutingTableBookJSON(inv, slot);
}
throw new IOException("Slot " + slot + " is not empty.");
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
RoutingTableBookJSON rtj = gson.fromJson(file.getPages(), RoutingTableBookJSON.class);
rtj.setInventory(inv, slot);
return rtj;
}
}
| 1,777 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RouteProperty.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RouteProperty.java | package com.github.catageek.ByteCart.Routing;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.github.catageek.ByteCart.Storage.PartitionedHashSet;
import com.github.catageek.ByteCartAPI.Util.DirectionRegistry;
/**
* The content of a routing table entry
*/
final class RouteProperty implements Externalizable {
/**
*
*/
private static final long serialVersionUID = -3548458365177323172L;
private TreeMap<Metric,PartitionedHashSet<DirectionRegistry>> map = new TreeMap<Metric,PartitionedHashSet<DirectionRegistry>>();
public RouteProperty() {
}
/**
* @return the map associating each metric with a DirectionRegistry
*/
final TreeMap<Metric,PartitionedHashSet<DirectionRegistry>> getMap() {
return map;
}
/**
* Decompose the registry value to a set of DirectionRegistry
*
* @param value the value to decompose
* @return the set
*/
private final PartitionedHashSet<DirectionRegistry> getPartitionedHashSet(int value) {
int reg = value;
int cur = 1;
PartitionedHashSet<DirectionRegistry> set = new PartitionedHashSet<DirectionRegistry>();
while (reg != 0) {
if ((reg & 1) !=0) {
set.add(new DirectionRegistry(cur));
}
cur = cur << 1;
reg = reg >> 1;
}
return set;
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
@Override
public void readExternal(ObjectInput arg0) throws IOException,
ClassNotFoundException {
int size = arg0.readInt();
for (int i = 0; i < size; i++) {
int value = arg0.readUnsignedShort();
PartitionedHashSet<DirectionRegistry> set;
if (! (set = getPartitionedHashSet(value & 15)).isEmpty()) {
map.put(new Metric(value >> 4), set);
}
}
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
@Override
public void writeExternal(ObjectOutput arg0) throws IOException {
arg0.writeInt(map.size());
Iterator<Entry<Metric, PartitionedHashSet<DirectionRegistry>>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<Metric, PartitionedHashSet<DirectionRegistry>> entry = it.next();
arg0.writeShort((entry.getKey().value() << 4) + entry.getValue().getPartitionedValue());
}
}
}
| 2,350 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
Delay.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/Delay.java | package com.github.catageek.ByteCart.Routing;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import com.github.catageek.ByteCartAPI.HAL.RegistryBoth;
import com.github.catageek.ByteCartAPI.HAL.VirtualRegistry;
/**
* A time metric
*/
class Delay implements Externalizable {
/**
*
*/
private static final long serialVersionUID = 970735722356168776L;
// hard coded value, if modified, change RouteProperty.writeObject() and readObject()
private final RegistryBoth value = new VirtualRegistry(12);
public Delay() {
}
Delay(int value) {
this.value.setAmount(value);
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeShort(this.getValue());
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.value.setAmount(in.readUnsignedShort());
}
/**
* @return the value
*/
int getValue() {
return value.getAmount();
}
}
| 1,190 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BCCounter.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/BCCounter.java | package com.github.catageek.ByteCart.Routing;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCartAPI.Util.DirectionRegistry;
import com.github.catageek.ByteCartAPI.Wanderer.Counter;
/**
* A map containing counters with id
*/
public final class BCCounter implements Serializable, Counter {
/**
*
*/
private static final long serialVersionUID = 6858180714411403984L;
private final Map<Integer, Integer> map = new HashMap<Integer,Integer>();
public BCCounter() {
}
/**
* Get a counter by its id
*
* @param counter
* @return the counter
*/
@Override
public int getCount(int counter) {
return this.map.containsKey(counter) ? this.map.get(counter) : 0;
}
/**
* Increment the counter by 1
*
* @param counter the counter id
*/
public void incrementCount(int counter) {
incrementCount(counter, 1);
}
/**
* Add a value to a counter
*
* @param counter the counter id
* @param value the value to add
*/
@Override
public void incrementCount(int counter, int value) {
this.map.put(counter, getCount(counter) + value);
}
/**
* Set the value of a counter
*
* @param counter the counter id
* @param amount the value to set
*/
@Override
public void setCount(int counter, int amount) {
this.map.put(counter, amount);
}
/**
* Get the first empty counter id
*
* @return the id
*/
public int firstEmpty() {
int i = 1;
while (getCount(i) != 0) {
i++;
}
return i;
}
/**
* Reset a counter to zero
*
* @param counter the id of the counter
*/
public void reset(int counter) {
this.map.remove(counter);
}
/**
* Reset all counters to zero
*/
@Override
public void resetAll() {
this.map.clear();
}
/**
* Tell if counters have reached the amount of 64 or more
*
* @param start the first counter id
* @param end the last counter id
* @return true if the amont of all counters between start and end (inclusive) are equal or superior to 64
*/
@Override
public boolean isAllFull(int start, int end) {
Iterator<Integer> it = map.keySet().iterator();
int limit = 64;
int count;
while (it.hasNext()) {
if ((count = it.next()) >= start && count <= end && map.get(count) < limit)
return false;
}
return true;
}
/**
* Get the ring number that has the minimum counter value and the direction is different from from parameter
*
* @param routes the routing table
* @param from the direction to exclude from the search
* @return the ring number, or 0 if no result
*/
public int getMinimum(RoutingTableWritable routes, DirectionRegistry from) {
Iterator<Integer> it = routes.getOrderedRouteNumbers();
int min = 10000000; //big value
int index = -1;
while (it.hasNext()) {
int ring = it.next();
if (ring == 0)
continue;
if (! map.containsKey(ring))
return ring;
int value;
if((value = map.get(ring)) < min
&& routes.getDirection(ring) != from.getBlockFace()
&& ring != 0) {
min = value;
index = ring;
}
}
if(ByteCart.debug)
ByteCart.log.info("ByteCart : minimum found ring " + index + " with " + min);
return index;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public final String toString() {
Iterator<Integer> it = map.keySet().iterator();
String s = "";
while (it.hasNext()) {
int ring = it.next();
int count = map.get(ring);
s += "ByteCart: Count for ring " + ring + " = " + count + "\n";
}
return s;
}
/**
* @return the number of counters the map can contain
*/
public int getCounterLength() {
return 32;
}
}
| 3,730 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RouteNumber.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RouteNumber.java | package com.github.catageek.ByteCart.Routing;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import com.github.catageek.ByteCartAPI.ByteCartAPI;
import com.github.catageek.ByteCartAPI.Wanderer.RouteValue;
/**
* A track number on ByteCartAPI.MAXRINGLOG bits
*/
final class RouteNumber extends RoutingTableContent<RouteNumber>
implements Comparable<RouteNumber>, Externalizable, RouteValue {
private static final int rlength = ByteCartAPI.MAXRINGLOG;
/**
*
*/
private static final long serialVersionUID = -8112012047943458459L;
public RouteNumber() {
super(rlength);
}
RouteNumber(int route) {
super(route, rlength);
}
/* (non-Javadoc)
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeShort(this.value());
}
/* (non-Javadoc)
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.setValue(in.readShort() & ((1 << rlength) - 1));
}
}
| 1,171 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
RoutingTableBookJSON.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Routing/RoutingTableBookJSON.java | package com.github.catageek.ByteCart.Routing;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import org.bukkit.block.BlockFace;
import org.bukkit.inventory.Inventory;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.FileStorage.InventoryFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
/**
* A routing table in a book
*/
final class RoutingTableBookJSON extends AbstractRoutingTable implements
RoutingTableWritable {
private boolean wasModified = false;
private static class RouteEntry {
private @Expose
TreeMap<Integer,Set<BlockFace>> routes;
RouteEntry() {
this.routes = new TreeMap<Integer, Set<BlockFace>>();
}
}
@Expose
private Boolean readonly = false;
@Expose
private Set<BlockFace> interfaces = new HashSet<>();
@Expose
private TreeMap<Integer, RouteEntry> table = new TreeMap<>();
private Inventory inventory;
private int slot;
/**
* Set the inventory
*
* @param inventory the inventory
*/
final void setInventory(Inventory inventory, int slot) {
this.inventory = inventory;
this.slot = slot;
}
public RoutingTableBookJSON() {
}
RoutingTableBookJSON(Inventory inv, int slot) {
this.inventory = inv;
this.slot = slot;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#clear(boolean)
*/
@Override
public void clear(boolean fullreset) {
if (table.isEmpty())
return;
RouteEntry routes = null;
BlockFace route_to_zero = null;
if (! fullreset && table.containsKey(0)) {
routes = table.get(0);
if (this.getMinMetric(0) == 0) {
route_to_zero = this.getDirection(0);
}
}
table.clear();
interfaces.clear();
if (! fullreset && routes != null) {
table.put(0, routes);
if (route_to_zero != null) {
interfaces.add(route_to_zero);
}
}
if (ByteCart.debug)
ByteCart.log.info("ByteCart : clear routing table table");
wasModified = true;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#getRouteNumbers()
*/
@Override
public final Iterator<Integer> getOrderedRouteNumbers() {
Iterator<Integer> it = ((SortedSet<Integer>) table.keySet()).iterator();
return it;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getMetric(int, com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public int getMetric(int entry, BlockFace direction) {
SortedMap<Integer, Set<BlockFace>> smap;
if (table.containsKey(entry) && (smap = table.get(entry).routes) != null
&& ! smap.isEmpty()) {
Iterator<Integer> it = smap.keySet().iterator();
int d;
while (it.hasNext())
if (smap.get((d = it.next())).contains(direction))
return d;
}
return -1;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getMinMetric(int)
*/
@Override
public int getMinMetric(int entry) {
SortedMap<Integer, Set<BlockFace>> smap;
if (table.containsKey(entry) && (smap = table.get(entry).routes) != null
&& ! smap.isEmpty()) {
return smap.firstKey();
}
return -1;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#setEntry(int, com.github.catageek.ByteCart.Util.DirectionRegistry, com.github.catageek.ByteCart.Routing.Metric)
*/
private void setMapEntry(int entry, BlockFace direction, int metric) {
RouteEntry smap;
Set<BlockFace> set;
if (metric < this.getMetric(entry, direction)) {
this.removeEntry(entry, direction);
}
if ((smap = table.get(entry)) == null) {
smap = new RouteEntry();
table.put(entry, smap);
wasModified = true;
}
if ((set = smap.routes.get(metric)) == null) {
set = new HashSet<BlockFace>(3);
smap.routes.put(metric, set);
wasModified = true;
}
if (metric == 0) {
wasModified |= interfaces.add(direction);
}
wasModified |= set.add(direction);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#setEntry(int, com.github.catageek.ByteCart.Util.DirectionRegistry, com.github.catageek.ByteCart.Routing.Metric)
*/
@Override
public void setEntry(int entry, BlockFace direction, int metric) {
setMapEntry(entry, direction, metric);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#isEmpty(int)
*/
@Override
public boolean isEmpty(int entry) {
return ! table.containsKey(entry);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getDirection(int)
*/
@Override
public BlockFace getDirection(int entry) {
Set<BlockFace> set;
TreeMap<Integer, Set<BlockFace>> pmap;
if (table.containsKey(entry) && (pmap = table.get(entry).routes) != null && ! pmap.isEmpty()) {
set = pmap.firstEntry().getValue();
if (! set.isEmpty())
return set.toArray(new BlockFace[set.size()])[0];
throw new AssertionError("Set<DirectionRegistry> in RoutingTableWritable is empty.");
}
return null;
}
@Override
public BlockFace getAllowedDirection(int entry) {
TreeMap<Integer, Set<BlockFace>> pmap;
if (table.containsKey(entry) && (pmap = table.get(entry).routes) != null) {
for (Entry<Integer, Set<BlockFace>> metricroute : pmap.entrySet()) {
for (BlockFace direction : metricroute.getValue()) {
if (isAllowedDirection(direction)) {
return direction;
}
}
}
}
return null;
}
@Override
public Boolean isAllowedDirection(BlockFace direction) {
return interfaces.contains(direction);
}
@Override
public void allowDirection(BlockFace direction, Boolean enable) {
this.wasModified |= enable ? interfaces.add(direction) : interfaces.remove(direction);
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getDirectlyConnectedList(com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public Set<Integer> getDirectlyConnectedList(BlockFace direction) {
SortedMap<Integer, Integer> list = new TreeMap<Integer, Integer>();
Iterator<Entry<Integer, RouteEntry>> it = table.entrySet().iterator();
Entry<Integer, RouteEntry> entry;
RouteEntry smap;
Set<BlockFace> set;
while (it.hasNext()) {
entry = it.next();
if ((smap = entry.getValue()) != null && smap.routes.containsKey(0)
&& ! (set = smap.routes.get(0)).isEmpty()
&& set.contains(direction)) {
// just extract the connected route
list.put(entry.getKey(), 0);
}
}
return list.keySet();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#getNotDirectlyConnectedList(com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public Set<Integer> getNotDirectlyConnectedList(BlockFace direction) {
SortedMap<Integer, Integer> list = new TreeMap<Integer, Integer>();
Iterator<Entry<Integer, RouteEntry>> it = table.entrySet().iterator();
Entry<Integer, RouteEntry> entry;
SortedMap<Integer, Set<BlockFace>> smap;
Set<BlockFace> set;
while (it.hasNext()) {
entry = it.next();
if ((smap = entry.getValue().routes) == null
|| ! (smap = entry.getValue().routes).containsKey(0)
|| ! (! (set = smap.get(0)).isEmpty()
&& set.contains(direction))) {
// extract routes going to directions with distance > 0
smap = smap.tailMap(1);
Iterator<Integer> it2 = smap.keySet().iterator();
while (it2.hasNext()) {
int d = it2.next();
if (smap.get(d).contains(direction)) {
list.put(entry.getKey(), d);
break;
}
}
}
}
return list.keySet();
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.AbstractRoutingTable#removeEntry(int, com.github.catageek.ByteCart.Util.DirectionRegistry)
*/
@Override
public void removeEntry(int entry, BlockFace from) {
TreeMap<Integer, Set<BlockFace>> smap;
Set<BlockFace> set;
if (table.containsKey(entry) && (smap = table.get(entry).routes) != null) {
Iterator<Integer> it = smap.keySet().iterator();
while (it.hasNext()) {
int metric = it.next();
if (metric == 0) {
wasModified |= interfaces.remove(from);
}
wasModified |= (set = smap.get(metric)).remove(from);
if (set.isEmpty())
it.remove();
if (smap.isEmpty())
table.remove(entry);
}
}
}
private RoutingTableBook convertToBinary() {
final RoutingTableBook btable = new RoutingTableBook();
btable.setInventory(this.inventory);
for (Entry<Integer, RouteEntry> entry : table.entrySet()) {
for (Entry<Integer, Set<BlockFace>> routemap : entry.getValue().routes.entrySet()) {
for (BlockFace route : routemap.getValue()) {
btable.setEntry(entry.getKey().intValue(), route, routemap.getKey().intValue());
}
}
}
return btable;
}
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#serialize()
*/
@Override
public void serialize(boolean allowconversion) throws IOException {
if (! this.wasModified || this.readonly)
return;
if (ByteCart.debug)
ByteCart.log.info("ByteCart: Trying to store in JSON format");
Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(this);
InventoryFile file = new InventoryFile(inventory, false, "RoutingTable");
file.setDescription("Bytecart Routing Table");
file.clear();
file.getOutputStream().write(json.getBytes());
try {
file.flush();
}
catch (IOException e) {
if (allowconversion) {
this.convertToBinary().serialize(false);
}
else
throw e;
}
/*
wasModified = false;
if (ByteCart.debug)
ByteCart.log.info("Storing in JSON format successful");
*/ }
/* (non-Javadoc)
* @see com.github.catageek.ByteCart.Routing.RoutingTableWritable#size()
*/
@Override
public int size() {
return table.size();
}
}
| 10,016 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
package-info.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/plugins/package-info.java | /**
*
*/
/**
* A package that provides addons to ByteCart
*/
package com.github.catageek.ByteCart.plugins; | 111 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
searchObsoleteMarkers.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/plugins/searchObsoleteMarkers.java | package com.github.catageek.ByteCart.plugins;
import java.util.Iterator;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.dynmap.markers.Marker;
import com.github.catageek.ByteCart.HAL.AbstractIC;
/**
* Synchronous task to remove markers
*/
final class searchObsoleteMarkers implements Runnable {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
Iterator<Marker> it = BCDynmapPlugin.markerset.getMarkers().iterator();
int x, y, z;
while (it.hasNext()) {
Marker m = it.next();
x = Location.locToBlock(m.getX());
y = Location.locToBlock(m.getY());
z = Location.locToBlock(m.getZ());
Block block = Bukkit.getServer().getWorld(m.getWorld()).getBlockAt(x, y, z);
if (! AbstractIC.checkEligibility(block))
m.deleteMarker();
}
}
}
| 851 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BCWandererTracker.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/plugins/BCWandererTracker.java | package com.github.catageek.ByteCart.plugins;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import com.github.catageek.ByteCart.Util.LogUtil;
import com.github.catageek.ByteCartAPI.Event.UpdaterCreateEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterMoveEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterRemoveEvent;
public final class BCWandererTracker implements Listener, CommandExecutor, TabCompleter {
private Map<Integer,Location> locations = new HashMap<>();
@EventHandler
public void onUpdaterCreate(UpdaterCreateEvent event) {
locations.put(event.getVehicleId(), event.getLocation());
}
@EventHandler
public void onUpdaterMove(UpdaterMoveEvent event) {
VehicleMoveEvent e = event.getEvent();
locations.put(e.getVehicle().getEntityId(), e.getTo());
}
@EventHandler
public void onUpdaterRemove(UpdaterRemoveEvent event) {
locations.remove(event.getVehicleId());
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (locations.isEmpty()) {
LogUtil.sendSuccess(sender, "No updaters found");
return true;
}
sender.sendMessage("List of locations of updaters:");
for (Location loc : locations.values()) {
StringBuilder s = new StringBuilder();
s.append("World: ").append(loc.getWorld().getName()).append(" ");
s.append("X: ").append(loc.getBlockX()).append(" ");
s.append("Y: ").append(loc.getBlockY()).append(" ");
s.append("Z: ").append(loc.getBlockZ());
LogUtil.sendSuccess(sender, s.toString());
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return Collections.emptyList();
}
}
| 2,080 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |
BCDynmapPlugin.java | /FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/plugins/BCDynmapPlugin.java | package com.github.catageek.ByteCart.plugins;
import java.io.IOException;
import java.io.InputStream;
import java.util.MissingResourceException;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.dynmap.DynmapCommonAPI;
import org.dynmap.markers.Marker;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.MarkerIcon;
import org.dynmap.markers.MarkerSet;
import com.github.catageek.ByteCart.ByteCart;
import com.github.catageek.ByteCart.AddressLayer.AddressFactory;
import com.github.catageek.ByteCartAPI.AddressLayer.Address;
import com.github.catageek.ByteCartAPI.Event.SignCreateEvent;
import com.github.catageek.ByteCartAPI.Event.SignRemoveEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterClearStationEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterCreateEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterMoveEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterPassStationEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterRemoveEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterSetStationEvent;
import com.github.catageek.ByteCartAPI.Event.UpdaterSignInvalidateEvent;
import com.github.catageek.ByteCartAPI.HAL.IC;
import com.github.catageek.ByteCartAPI.Signs.BCSign;
import com.github.catageek.ByteCartAPI.Signs.Station;
/**
* A Dynmap addon
*/
public final class BCDynmapPlugin implements Listener {
private static final String name = ByteCart.myPlugin.getConfig().getString("dynmap.layer", "ByteCart");
static MarkerSet markerset;
private static MarkerIcon defaulticon;
private static MarkerIcon erroricon;
private static MarkerIcon updatericon;
public BCDynmapPlugin() {
DynmapCommonAPI api = (DynmapCommonAPI) Bukkit.getPluginManager().getPlugin("dynmap");
MarkerAPI markerapi = null;
try {
markerapi = api.getMarkerAPI();
} catch (NullPointerException e) {
throw new MissingResourceException("Dynmap plugin is not present, please install it or set dynmap = false in config file", MarkerAPI.class.getName(), "dynmap");
}
if (markerapi == null)
throw new MissingResourceException("Dynmap API could not be loaded", MarkerAPI.class.getName(), "dynmap");
defaulticon = loadIcon(markerapi,"bytecart_station", "station", "resources/bc2.png");
if (defaulticon == null) {
throw new MissingResourceException("Station icon could not be loaded", MarkerAPI.class.getName(), "station");
}
erroricon = loadIcon(markerapi,"bytecart_error", "error", "resources/error.png");
if (erroricon == null) {
throw new MissingResourceException("Error icon could not be loaded", MarkerAPI.class.getName(), "error");
}
updatericon = loadIcon(markerapi,"bytecart_updater", "updater", "resources/updater.png");
if (updatericon == null) {
throw new MissingResourceException("Updater icon could not be loaded", MarkerAPI.class.getName(), "updater");
}
markerset = markerapi.getMarkerSet(name);
if (markerset == null) {
markerset = markerapi.createMarkerSet(name, name, null, true);
markerset.addAllowedMarkerIcon(defaulticon);
markerset.addAllowedMarkerIcon(erroricon);
markerset.addAllowedMarkerIcon(updatericon);
markerset.setDefaultMarkerIcon(defaulticon);
}
}
/**
* Load the ByteCart icon
*
* @param markerapi dynmap marker API
* @param id the id of the icon
* @param label the label
* @param file the file to load
* @return the icon loaded
*/
private MarkerIcon loadIcon(MarkerAPI markerapi, String id, String label, String file) {
MarkerIcon icon = markerapi.getMarkerIcon(id);
if (icon == null) {
try (InputStream png = getClass().getResourceAsStream(file)) {
icon = markerapi.createMarkerIcon(id, label, png);
} catch (IOException e) {
throw new MissingResourceException("ByteCart : icon could not be loaded", this.getClass().getName(), file);
}
}
return icon;
}
/**
* Updates the map if a station is updated
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterSetStation(UpdaterSetStationEvent event) {
Block block = event.getIc().getBlock();
Marker marker = markerset.findMarker(buildId(block));
if (marker != null)
marker.deleteMarker();
Address address = event.getNewAddress();
selectAndAddMarker(event.getName(), block, address);
}
/**
* Check that marker information about the station is correct, or fix it
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterPassStation(UpdaterPassStationEvent event) {
Block block = event.getIc().getBlock();
Address address = event.getAddress();
Marker marker = markerset.findMarker(buildId(block));
if (marker != null) {
if (address.isValid() && checkMarkerInformation(marker, block, address.toString(), event.getIc().getFriendlyName()))
return;
marker.deleteMarker();
}
selectAndAddMarker(event.getName(), block, address);
}
/**
* Delete the marker if the station sign is cleared
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterClearStation(UpdaterClearStationEvent event) {
deleteMarker(event);
}
/**
* Delete the marker
*
* @param event
*/
private void deleteMarker(UpdaterEvent event) {
Block block = event.getIc().getBlock();
Marker marker = markerset.findMarker(buildId(block));
if (marker != null)
marker.deleteMarker();
}
/**
* Delete the marker if the sign is removed
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onSignRemove(SignRemoveEvent event) {
IC ic;
if (! ((ic = event.getIc()) instanceof BCSign))
return;
Block block = ic.getBlock();
Marker marker = markerset.findMarker(buildId(block));
if (marker != null)
marker.deleteMarker();
}
/**
* Delete the marker if invalid
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterSignInvalidate(UpdaterSignInvalidateEvent event) {
deleteMarker(event);
}
/**
* Create a marker for manually created signs
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onSignCreate(SignCreateEvent event) {
IC ic;
if (! ((ic = event.getIc()) instanceof Station))
return;
Block block = ic.getBlock();
String address = event.getStrings()[3];
Marker marker = markerset.findMarker(buildId(block));
if (marker != null)
marker.deleteMarker();
selectAndAddMarker(event.getStrings()[2], block, AddressFactory.getAddress(address));
}
/**
* Create a marker for new updaters
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterCreate(UpdaterCreateEvent event) {
Marker marker = markerset.findMarker(String.valueOf(event.getVehicleId()));
if (marker != null) {
marker.deleteMarker();
}
addMarker(String.valueOf(event.getVehicleId()), "Updater", event.getLocation(), updatericon);
}
/**
* Move a marker of updater
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterMove(UpdaterMoveEvent event) {
VehicleMoveEvent mve = event.getEvent();
int id = mve.getVehicle().getEntityId();
Location loc = mve.getTo();
Marker marker = markerset.findMarker(String.valueOf(id));
if (marker != null) {
marker.setLocation(loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ());
}
}
/**
* Delete a marker of updater
*
* @param event
*/
@EventHandler(ignoreCancelled = true)
public void onUpdaterRemove(UpdaterRemoveEvent event) {
Marker marker = markerset.findMarker(String.valueOf(event.getVehicleId()));
if (marker != null) {
marker.deleteMarker();
}
}
/**
* Register the marker with the right icon
*
* @param friendlyname the name to write
* @param block the block
* @param address the address to write
*/
private static void selectAndAddMarker(String friendlyname, Block block, Address address) {
MarkerIcon icon;
String label;
if (address.isValid()) {
icon = defaulticon;
label = buildLabel(address.toString(), friendlyname);
}
else {
icon = erroricon;
label = "Error setting address for " + friendlyname;
}
addMarker(label, block.getLocation(), icon);
}
/**
* Create the marker using API
*
* @param label the label to write
* @param block the block
* @param markericon the icon to draw
*/
private static void addMarker(String label, Location loc, MarkerIcon markericon) {
addMarker(loc.toString(), label,
loc, markericon);
}
/**
* Create the marker using API
*
* @param label the label to write
* @param block the block
* @param markericon the icon to draw
*/
private static void addMarker(String key, String label, Location loc, MarkerIcon markericon) {
markerset.createMarker(key, label,
loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ(), markericon, true);
}
/**
* Build a sting containing name and address
*
* @param address the address
* @param friendlyname the name
* @return a string containing "name (address)"
*/
private static String buildLabel(String address, String friendlyname) {
if (friendlyname.equals("")) {
return address;
}
return friendlyname + " (" + address + ")";
}
/**
* Get a string used as unique id for a marker
*
* @param block the block
* @return A unique string for the block
*/
private static String buildId(Block block) {
return block.getLocation().toString();
}
/**
* Check marker information consistency
*
* @param marker the marker to check
* @param block the block to check against
* @param address the address to check against
* @param friendlyName the name to check against
* @return true if information is matching
*/
private static boolean checkMarkerInformation(Marker marker, Block block, String address, String friendlyName) {
boolean ret = false;
ret &= (block.getX() == marker.getX());
ret &= (block.getY() == marker.getY());
ret &= (block.getZ() == marker.getZ());
ret &= (buildLabel(address, friendlyName).equals(marker.getLabel()));
return ret;
}
/**
* Search for stations that do not exist anymore and
* remove corresponding markers.
*
*/
public static void removeObsoleteMarkers() {
if (markerset != null)
Bukkit.getScheduler().runTask(ByteCart.myPlugin, new searchObsoleteMarkers());
}
}
| 10,486 | Java | .java | catageek/ByteCart | 28 | 9 | 5 | 2012-03-11T08:15:46Z | 2018-10-18T04:55:47Z |