answer stringlengths 17 10.2M |
|---|
package net.silentchaos512.gems.lib.buff;
import java.util.ArrayList;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.silentchaos512.gems.SilentGems;
import net.silentchaos512.gems.core.handler.GemsExtendedPlayer;
import net.silentchaos512.gems.core.util.LocalizationHelper;
import net.silentchaos512.gems.core.util.LogHelper;
import net.silentchaos512.gems.item.ChaosGem;
import net.silentchaos512.gems.item.CraftingMaterial;
import net.silentchaos512.gems.item.ModItems;
import net.silentchaos512.gems.lib.Names;
import net.silentchaos512.gems.lib.Strings;
import net.silentchaos512.gems.network.MessageSetFlight;
import cpw.mods.fml.common.registry.GameRegistry;
public enum ChaosBuff {
SPEED(0, "speed", 4, Potion.moveSpeed.id, 20, "ingotGold"),
HASTE(1, "haste", 4, Potion.digSpeed.id, 20, "dustGlowstone"),
JUMP(2, "jump", 4, Potion.jump.id, 10, CraftingMaterial.getStack(Names.PLUME)),
FLIGHT(3, "flight", 1, -1, 80, CraftingMaterial.getStack(Names.GOLDEN_PLUME)),
NIGHT_VISION(4, "nightVision", 1, Potion.nightVision.id, 10, Items.golden_carrot),
REGENERATION(5, "regeneration", 2, Potion.regeneration.id, 40, Items.ghast_tear),
RESISTANCE(6, "resistance", 2, Potion.resistance.id, 30, Items.leather_chestplate),
FIRE_RESISTANCE(7, "fireResistance", 1, Potion.fireResistance.id, 30, Items.blaze_rod),
WATER_BREATHING(8, "waterBreathing", 1, Potion.waterBreathing.id, 30, "blockLapis"),
STRENGTH(9, "strength", 2, Potion.damageBoost.id, 30, "blockRedstone"),
CAPACITY(10, "capacity", 4, -1, 0, null),
BOOSTER(11, "booster", 4, -1, 0, null),
ABSORPTION(12, "absorption", 1, -1, 50, null),
INVISIBILITY(13, "invisibility", 1, Potion.invisibility.id, 40, Items.fermented_spider_eye);
public static final int APPLY_DURATION_REGEN = 80;
public static final int APPLY_DURATION_NIGHT_VISION = 400;
public static final int APPLY_DURATION_DEFAULT = 20;
public final int id;
public final String name;
public final int maxLevel;
public final int potionId;
public final int cost;
public final Object material;
private ChaosBuff(int id, String name, int maxLevel, int potionId, int cost, Object material) {
this.id = id;
this.name = name;
this.maxLevel = maxLevel;
this.potionId = potionId;
this.cost = cost;
this.material = material;
}
public static void initRecipes() {
ItemStack refinedEssence = CraftingMaterial.getStack(Names.CHAOS_ESSENCE_PLUS);
String redstone = "dustRedstone";
for (ChaosBuff buff : values()) {
if (buff.material != null) {
ItemStack result = new ItemStack(ModItems.chaosRune, 1, buff.id);
GameRegistry.addRecipe(new ShapedOreRecipe(result, "mcm", "cmc", "rcr", 'm', buff.material,
'c', refinedEssence, 'r', redstone));
}
}
}
public int getCostPerTick(int level) {
return (int) (this.cost * (1 + 0.20f * (level - 1)));
}
public int getApplyTime(EntityPlayer player, int level) {
switch (this) {
case REGENERATION:
// Should apply every 2 seconds for regen I, every second for regen II.
// Regen resets it timer when reapplied, so it won't work if applied too often.
boolean shouldApply = false;
PotionEffect activeRegen = player.getActivePotionEffect(Potion.regeneration);
if (activeRegen == null) {
shouldApply = true;
} else {
int remainingTime = activeRegen.getDuration();
int healTime = level == 2 ? 20 : 40;
if (remainingTime + healTime <= APPLY_DURATION_REGEN) {
shouldApply = true;
}
}
return shouldApply ? APPLY_DURATION_REGEN : 0;
case NIGHT_VISION:
return APPLY_DURATION_NIGHT_VISION;
default:
return APPLY_DURATION_DEFAULT;
}
}
public void apply(EntityPlayer player, int level) {
if (potionId > -1) {
int time = getApplyTime(player, level);
if (time > 0) {
player.addPotionEffect(new PotionEffect(potionId, time, level - 1, true));
}
}
// Apply other effects here.
if (this.id == FLIGHT.id) {
player.capabilities.allowFlying = true;
player.fallDistance = 0.0f;
// Prevents "lingering" flight effect, which allowed infinite flight.
GemsExtendedPlayer properties = GemsExtendedPlayer.get(player);
if (properties != null) {
properties.refreshFlightTime();
}
// Send an "allow flight" message to the client, but only once per second.
if (player.ticksExisted % 20 == 0 && player instanceof EntityPlayerMP) {
SilentGems.instance.network.sendTo(new MessageSetFlight(true), (EntityPlayerMP) player);
}
}
}
public void remove(EntityPlayer player) {
if (potionId > -1) {
player.removePotionEffect(potionId);
}
// Apply other effects here.
if (this.id == FLIGHT.id) {
ChaosGem.removeFlight(player);
}
}
public String getDisplayName(int level) {
String s = LocalizationHelper.getLocalizedString(Strings.BUFF_RESOURCE_PREFIX + this.name);
s += " ";
if (level == 1) {
s += "I";
} else if (level == 2) {
s += "II";
} else if (level == 3) {
s += "III";
} else if (level == 4) {
s += "IV";
} else if (level == 5) {
s += "V";
} else {
s += level;
}
return s;
}
} |
package cpw.mods.fml.server;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Logger;
import org.bukkit.Material;
import net.minecraft.server.Block;
import net.minecraft.server.Item;
import net.minecraft.server.LocaleLanguage;
import net.minecraft.server.MLProp;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.BaseMod;
import net.minecraft.server.BiomeBase;
import net.minecraft.server.EntityItem;
import net.minecraft.server.EntityHuman;
import net.minecraft.server.IChunkProvider;
import net.minecraft.server.ICommandListener;
import net.minecraft.server.IInventory;
import net.minecraft.server.ItemStack;
import net.minecraft.server.NetworkManager;
import net.minecraft.server.Packet1Login;
import net.minecraft.server.Packet250CustomPayload;
import net.minecraft.server.Packet3Chat;
import net.minecraft.server.BukkitRegistry;
import net.minecraft.server.SidedProxy;
import net.minecraft.server.World;
import net.minecraft.server.WorldType;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IFMLSidedHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.ModMetadata;
import cpw.mods.fml.common.ProxyInjector;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.modloader.ModLoaderModContainer;
import cpw.mods.fml.common.modloader.ModProperty;
import cpw.mods.fml.common.registry.FMLRegistry;
/**
* Handles primary communication from hooked code into the system
*
* The FML entry point is {@link #onPreLoad(MinecraftServer)} called from {@link MinecraftServer}
*
* Obfuscated code should focus on this class and other members of the "server" (or "client") code
*
* The actual mod loading is handled at arms length by {@link Loader}
*
* It is expected that a similar class will exist for each target environment: Bukkit and Client side.
*
* It should not be directly modified.
*
* @author cpw
*
*/
public class FMLBukkitHandler implements IFMLSidedHandler
{
/**
* The singleton
*/
private static final FMLBukkitHandler INSTANCE = new FMLBukkitHandler();
/**
* A reference to the server itself
*/
private MinecraftServer server;
/**
* A handy list of the default overworld biomes
*/
private BiomeBase[] defaultOverworldBiomes;
/**
* Called to start the whole game off from {@link MinecraftServer#startServer}
* @param minecraftServer
*/
public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
MinecraftServer.log.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http:
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().beginLoading(this);
FMLRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
/**
* Called a bit later on during server initialization to finish loading mods
*/
public void onLoadComplete()
{
Loader.instance().initializeMods();
for (Item i : Item.byId) {
if (i!=null && Material.getMaterial(i.id).name().startsWith("X")) {
Material.setMaterialName(i.id, i.l());
}
}
}
public void onWorldLoadTick()
{
FMLCommonHandler.instance().tickStart(EnumSet.of(TickType.WORLDLOAD));
}
/**
* Every tick just before world and other ticks occur
*/
public void onPreWorldTick(World world)
{
FMLCommonHandler.instance().tickStart(EnumSet.of(TickType.WORLD),world);
}
/**
* Every tick just after world and other ticks occur
*/
public void onPostWorldTick(World world)
{
FMLCommonHandler.instance().tickEnd(EnumSet.of(TickType.WORLD), world);
}
/**
* Get the server instance
*
* @return
*/
public MinecraftServer getServer()
{
return server;
}
/**
* Get a handle to the server's logger instance
*/
public Logger getMinecraftLogger()
{
return MinecraftServer.log;
}
/**
* Called from ChunkProviderServer when a chunk needs to be populated
*
* To avoid polluting the worldgen seed, we generate a new random from the world seed and
* generate a seed from that
*
* @param chunkProvider
* @param chunkX
* @param chunkZ
* @param world
* @param generator
*/
public void onChunkPopulate(IChunkProvider chunkProvider, int chunkX, int chunkZ, World world, IChunkProvider generator)
{
Random fmlRandom = new Random(world.getSeed());
long xSeed = fmlRandom.nextLong() >> 2 + 1L;
long zSeed = fmlRandom.nextLong() >> 2 + 1L;
fmlRandom.setSeed((xSeed * chunkX + zSeed * chunkZ) ^ world.getSeed());
for (ModContainer mod : Loader.getModList())
{
if (mod.generatesWorld())
{
mod.getWorldGenerator().generate(fmlRandom, chunkX, chunkZ, world, generator, chunkProvider);
}
}
}
/**
* Called from the furnace to lookup fuel values
*
* @param itemId
* @param itemDamage
* @return
*/
public int fuelLookup(int itemId, int itemDamage)
{
int fv = 0;
for (ModContainer mod : Loader.getModList())
{
fv = Math.max(fv, mod.lookupFuelValue(itemId, itemDamage));
}
return fv;
}
/**
* Is the offered class and instance of BaseMod and therefore a ModLoader mod?
*/
public boolean isModLoaderMod(Class<?> clazz)
{
return BaseMod.class.isAssignableFrom(clazz);
}
/**
* Load the supplied mod class into a mod container
*/
public ModContainer loadBaseModMod(Class<?> clazz, File canonicalFile)
{
@SuppressWarnings("unchecked")
Class <? extends BaseMod > bmClazz = (Class <? extends BaseMod >) clazz;
return new ModLoaderModContainer(bmClazz, canonicalFile);
}
/**
* Called to notify that an item was picked up from the world
*
* @param entityItem
* @param entityPlayer
*/
public void notifyItemPickup(EntityItem entityItem, EntityHuman entityPlayer)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPickupNotification())
{
mod.getPickupNotifier().notifyPickup(entityItem, entityPlayer);
}
}
}
/**
* Raise an exception
*
* @param exception
* @param message
* @param stopGame
*/
public void raiseException(Throwable exception, String message, boolean stopGame)
{
FMLCommonHandler.instance().getFMLLogger().throwing("FMLHandler", "raiseException", exception);
throw new RuntimeException(exception);
}
/**
* Attempt to dispense the item as an entity other than just as a the item itself
*
* @param world
* @param x
* @param y
* @param z
* @param xVelocity
* @param zVelocity
* @param item
* @return
*/
public boolean tryDispensingEntity(World world, double x, double y, double z, byte xVelocity, byte zVelocity, ItemStack item)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsToDispense() && mod.getDispenseHandler().dispense(x, y, z, xVelocity, zVelocity, world, item))
{
return true;
}
}
return false;
}
/**
* @return the instance
*/
public static FMLBukkitHandler instance()
{
return INSTANCE;
}
/**
* Build a list of default overworld biomes
*
* @return
*/
public BiomeBase[] getDefaultOverworldBiomes()
{
if (defaultOverworldBiomes == null)
{
ArrayList<BiomeBase> biomes = new ArrayList<BiomeBase>(20);
for (int i = 0; i < 23; i++)
{
if ("Sky".equals(BiomeBase.biomes[i].y) || "Hell".equals(BiomeBase.biomes[i].y))
{
continue;
}
biomes.add(BiomeBase.biomes[i]);
}
defaultOverworldBiomes = new BiomeBase[biomes.size()];
biomes.toArray(defaultOverworldBiomes);
}
return defaultOverworldBiomes;
}
/**
* Called when an item is crafted
*
* @param player
* @param craftedItem
* @param craftingGrid
*/
public void onItemCrafted(EntityHuman player, ItemStack craftedItem, IInventory craftingGrid)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onCrafting(player, craftedItem, craftingGrid);
}
}
}
/**
* Called when an item is smelted
*
* @param player
* @param smeltedItem
*/
public void onItemSmelted(EntityHuman player, ItemStack smeltedItem)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onSmelting(player, smeltedItem);
}
}
}
/**
* Called when a chat packet is received
*
* @param chat
* @param player
* @return true if you want the packet to stop processing and not echo to the rest of the world
*/
public boolean handleChatPacket(Packet3Chat chat, EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsNetworkPackets() && mod.getNetworkHandler().onChat(chat, player))
{
return true;
}
}
return false;
}
/**
* Called when a packet 250 packet is received from the player
*
* @param packet
* @param player
*/
public void handlePacket250(Packet250CustomPayload packet, EntityHuman player)
{
if ("REGISTER".equals(packet.tag) || "UNREGISTER".equals(packet.tag))
{
handleClientRegistration(packet, player);
return;
}
ModContainer mod = FMLCommonHandler.instance().getModForChannel(packet.tag);
if (mod != null)
{
mod.getNetworkHandler().onPacket250Packet(packet, player);
}
}
/**
* Handle register requests for packet 250 channels
*
* @param packet
*/
private void handleClientRegistration(Packet250CustomPayload packet, EntityHuman player)
{
if (packet.data==null) {
return;
}
try
{
for (String channel : new String(packet.data, "UTF8").split("\0"))
{
// Skip it if we don't know it
if (FMLCommonHandler.instance().getModForChannel(channel) == null)
{
continue;
}
if ("REGISTER".equals(packet.tag))
{
FMLCommonHandler.instance().activateChannel(player, channel);
}
else
{
FMLCommonHandler.instance().deactivateChannel(player, channel);
}
}
}
catch (UnsupportedEncodingException e)
{
getMinecraftLogger().warning("Received invalid registration packet");
}
}
/**
* Handle a login
*
* @param loginPacket
* @param networkManager
*/
public void handleLogin(Packet1Login loginPacket, NetworkManager networkManager)
{
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.tag = "REGISTER";
packet.data = FMLCommonHandler.instance().getPacketRegistry();
packet.length = packet.data.length;
if (packet.length>0) {
networkManager.queue(packet);
}
}
public void announceLogin(EntityHuman player) {
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogin(player);
}
}
}
@Override
public File getMinecraftRootDirectory()
{
try {
return server.a(".").getCanonicalFile();
} catch (IOException ioe) {
return new File(".");
}
}
/**
* @param var2
* @return
*/
public boolean handleServerCommand(String command, String player, ICommandListener listener)
{
for (ModContainer mod : Loader.getModList()) {
if (mod.wantsConsoleCommands() && mod.getConsoleHandler().handleCommand(command, player, listener)) {
return true;
}
}
return false;
}
/**
* @param player
*/
public void announceLogout(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogout(player);
}
}
}
/**
* @param p_28168_1_
*/
public void announceDimensionChange(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerChangedDimension(player);
}
}
}
/**
* @param biome
*/
public void addBiomeToDefaultWorldGenerator(BiomeBase biome)
{
WorldType.NORMAL.addNewBiome(biome);
}
@Override
public Object getMinecraftInstance() {
return server;
}
@Override
public String getCurrentLanguage()
{
return LocaleLanguage.a().getCurrentLanguage();
}
@Override
public Properties getCurrentLanguageTable()
{
return LocaleLanguage.a().getCurrentLanguageTable();
}
@Override
public String getObjectName(Object instance)
{
String objectName;
if (instance instanceof Item) {
objectName=((Item)instance).getName();
} else if (instance instanceof Block) {
objectName=((Block)instance).getName();
} else if (instance instanceof ItemStack) {
objectName=Item.byId[((ItemStack)instance).id].a((ItemStack)instance);
} else {
throw new IllegalArgumentException(String.format("Illegal object for naming %s",instance));
}
objectName+=".name";
return objectName;
}
@Override
public ModMetadata readMetadataFrom(InputStream input, ModContainer mod) throws Exception {
// TODO Auto-generated method stub
return null;
}
@Override
public void profileStart(String profileLabel) {
// NOOP on bukkit
}
@Override
public void profileEnd() {
// NOOP on bukkit
}
@Override
public ModProperty getModLoaderPropertyFor(Field f) {
if (f.isAnnotationPresent(MLProp.class)) {
MLProp prop = f.getAnnotation(MLProp.class);
return new ModProperty(prop.info(), prop.min(), prop.max(), prop.name());
}
return null;
}
@Override
public List<String> getAdditionalBrandingInformation() {
return null;
}
@Override
public Side getSide() {
return Side.BUKKIT;
}
@Override
public ProxyInjector findSidedProxyOn(cpw.mods.fml.common.modloader.BaseMod mod) {
for (Field f : mod.getClass().getDeclaredFields())
{
if (f.isAnnotationPresent(SidedProxy.class))
{
SidedProxy sp = f.getAnnotation(SidedProxy.class);
return new ProxyInjector(sp.clientSide(), sp.serverSide(), sp.bukkitSide(), f);
}
}
return null;
}
public void onServerPostTick() {
FMLCommonHandler.instance().tickEnd(EnumSet.of(TickType.GAME));
}
public void onServerPreTick() {
FMLCommonHandler.instance().tickStart(EnumSet.of(TickType.GAME));
}
} |
package cgeo.geocaching.enumerations;
import cgeo.geocaching.R;
import cgeo.geocaching.cgeoapplication;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Enum listing waypoint types
*
* @author koem
*/
public enum WaypointType {
FINAL("flag", R.string.wp_final, R.drawable.waypoint_flag),
OWN("own", R.string.wp_waypoint, R.drawable.waypoint_waypoint),
PARKING("pkg", R.string.wp_pkg, R.drawable.waypoint_pkg),
PUZZLE("puzzle", R.string.wp_puzzle, R.drawable.waypoint_puzzle),
STAGE("stage", R.string.wp_stage, R.drawable.waypoint_stage),
TRAILHEAD("trailhead", R.string.wp_trailhead, R.drawable.waypoint_trailhead),
WAYPOINT("waypoint", R.string.wp_waypoint, R.drawable.waypoint_waypoint);
public final String id;
public final int stringId;
private String l10n; // not final because the locale can be changed
public final int markerId;
private WaypointType(String id, int stringId, int markerId) {
this.id = id;
this.stringId = stringId;
setL10n();
this.markerId = markerId;
}
/**
* inverse lookup of waypoint IDs<br/>
* non public so that <code>null</code> handling can be handled centrally in the enum type itself
*/
private static final Map<String, WaypointType> FIND_BY_ID;
public static final Map<WaypointType, String> ALL_TYPES_EXCEPT_OWN = new HashMap<WaypointType, String>();
static {
final HashMap<String, WaypointType> mapping = new HashMap<String, WaypointType>();
for (WaypointType wt : values()) {
mapping.put(wt.id, wt);
if (wt != WaypointType.OWN) {
ALL_TYPES_EXCEPT_OWN.put(wt, wt.getL10n());
}
}
FIND_BY_ID = Collections.unmodifiableMap(mapping);
}
/**
* inverse lookup of waypoint IDs<br/>
* here the <code>null</code> handling shall be done
*/
public static WaypointType findById(final String id) {
if (null == id) {
return WAYPOINT;
}
WaypointType waypointType = FIND_BY_ID.get(id);
if (null == waypointType) {
return WAYPOINT;
}
return waypointType;
}
public final String getL10n() {
return l10n;
}
public void setL10n() {
this.l10n = cgeoapplication.getInstance().getBaseContext().getResources().getString(this.stringId);
if (WaypointType.ALL_TYPES_EXCEPT_OWN != null && WaypointType.ALL_TYPES_EXCEPT_OWN.containsKey(this)) {
WaypointType.ALL_TYPES_EXCEPT_OWN.put(this, this.getL10n());
}
}
} |
package miner.topo.bolt;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import miner.parse.Generator;
import miner.parse.RuleItem;
import miner.parse.data.DataItem;
import miner.parse.data.Packer;
import miner.spider.pojo.Data;
import miner.spider.utils.MysqlUtil;
import miner.topo.platform.PlatformUtils;
import miner.topo.platform.Reflect;
import miner.utils.MySysLogger;
import miner.utils.RedisUtil;
import redis.clients.jedis.Jedis;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseBolt extends BaseRichBolt {
private static MySysLogger logger = new MySysLogger(ParseBolt.class);
private OutputCollector _collector;
private HashMap<String, Data> _dataScheme;
private HashMap<String, String> _regex;
private RedisUtil _ru;
private Jedis _redis;
public void execute(Tuple tuple) {
logger.info("ParseBolt execute......");
try {
String globalInfo = tuple.getString(0);
String resource = tuple.getString(1);
String projectInfo = globalInfo.split("-")[0]+globalInfo.split("-")[1]+globalInfo.split("-")[2];
HashMap<String, Data> parseData = new HashMap<String, Data>();
boolean findDataScheme = true;
for (Map.Entry<String, Data> entry : _dataScheme.entrySet()) {
String dataInfo = entry.getKey();
String tempProjectInfo = dataInfo.split("-")[0]+dataInfo.split("-")[1]+dataInfo.split("-")[2];
if(projectInfo.equals(tempProjectInfo)){
parseData.put(dataInfo, entry.getValue());
findDataScheme = false;
}
}
//data define not in _dataScheme
if(findDataScheme){
HashMap<String, Data> newData = MysqlUtil.getDataByDataInfo(globalInfo.split("-")[0], globalInfo.split("-")[1], globalInfo.split("-")[2]);
for (Map.Entry<String, Data> entry : newData.entrySet()) {
parseData.put(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, Data> entry : parseData.entrySet()) {
String parseResource = resource;
String dataInfo = entry.getKey();
String taskInfo = dataInfo.split("-")[0]+"-"+dataInfo.split("-")[1]+"-"+dataInfo.split("-")[2];
Data data = entry.getValue();
String[] properties = data.getProperty().split("\\$");
Map<String, RuleItem> data_rule_map = new HashMap<String, RuleItem>();
if(properties[0].equals("reflect")){
for(int i = 1; i < properties.length; i++){
String tagName = properties[i];
String path = _regex.get(taskInfo+"-"+tagName);
data_rule_map.put(tagName, new RuleItem(tagName, path));
int k = i-1;
properties[k] = properties[i];
}
// logger.info("reflect.jar path:"+PlatformParas.reflect_dir+"reflect.jar");
// parseResource = Reflect.GetReflect(PlatformParas.reflect_dir+"reflect.jar", parseResource);
parseResource = Reflect.GetReflect("/opt/build/reflect/reflect.jar", parseResource);
// parseResource = PlatformUtils.PaseRef(parseResource);
}else {
for (int i = 0; i < properties.length; i++) {
String tagName = properties[i];
String path = _regex.get(taskInfo + "-" + tagName);
data_rule_map.put(tagName, new RuleItem(tagName, path));
}
}
Set<DataItem> data_item_set = new HashSet<DataItem>();
data_item_set.add(new DataItem(data.getWid(), data.getPid(), data.getTid(), data.getDid(), data.getRowKey(), data.getForeignKey(),
data.getForeignValue(), data.getLink(), properties));
Generator g = new Generator();
g.create_obj(parseResource);
for (Map.Entry<String, RuleItem> entry1 : data_rule_map.entrySet()) {
g.set_rule(entry1.getValue());
}
g.generate_data();
Map<String, Object> m = g.get_result();
Iterator<DataItem> data_item_it = data_item_set.iterator();
if(data.getProcessWay().equals("s")) {
logger.info("......");
logger.info("data_item_it:"+data_item_set.size()+"=========");
while (data_item_it.hasNext()) {
logger.info("while......");
Packer packerData = new Packer(data_item_it.next(), m, data_rule_map);
String[] result_str=packerData.pack();
System.out.println("result_str:"+result_str.length);
for(int i=0;i<result_str.length;i++){
emit("store", tuple, globalInfo, result_str[i]);
logger.info("......");
}
}
}else if(data.getProcessWay().equals("e") || data.getProcessWay().equals("E")){
while (data_item_it.hasNext()) {
String loopTaskId = data.getLcondition();
String loopTaskInfo = taskInfo.split("-")[0]+"-"+dataInfo.split("-")[1]+"-"+loopTaskId;
Packer packerData = new Packer(data_item_it.next(), m, data_rule_map);
String[] result_str=packerData.pack();
for(int i=0;i<result_str.length;i++){
emit("generate-loop", tuple, loopTaskInfo, result_str[i]);
//set url to redis for LoopSpout get
//_redis.hset("message_loop", loopTaskInfo, result_str[i]);
}
}
}else if(data.getProcessWay().equals("l") || data.getProcessWay().equals("L")){
while (data_item_it.hasNext()) {
String loopTaskId = data.getLcondition();
String loopTaskInfo = taskInfo.split("-")[0]+"-"+dataInfo.split("-")[1]+"-"+loopTaskId;
Packer packerData = new Packer(data_item_it.next(), m, data_rule_map);
String[] result_str=packerData.pack();
for(int i=0;i<result_str.length;i++){
//set url to redis for LoopSpout get
String uuid = PlatformUtils.getUUID();
String tempEmitInfo = loopTaskInfo+"-"+uuid;
_redis.hset("message_loop", tempEmitInfo, result_str[i]);
logger.info(tempEmitInfo + "--" + result_str[i] + "--store to message_loop.");
}
}
}else{
logger.error("there is no valid way to process "+taskInfo+" data");
}
}
_collector.ack(tuple);
}catch (Exception ex){
logger.error("parse error!"+ex);
ex.printStackTrace();
_collector.fail(tuple);
}
}
private void emit(String streamId, Tuple tuple,String globalInfo, String message){
_collector.emit(streamId, tuple, new Values(globalInfo, message));
logger.info("Parse, message emitted: globalInfo=" + globalInfo + ", message=" + message);
}
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector){
this._collector = collector;
_dataScheme = MysqlUtil.getData();
_regex = MysqlUtil.getRegex();
_ru = new RedisUtil();
_redis = _ru.getJedisInstance();
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declareStream("generate-loop", new Fields("p_globalinfo", "p_data"));
declarer.declareStream("store", new Fields("p_globalinfo", "p_data"));
}
public void cleanup() {
_ru.release_jedis(_redis);
}
public String PaseRef(String res) throws IOException {
String result = res;
String price,sale,mydate = "";
String pattern = "(?<=(price = \\[))\\S+(?=(]))";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(result);
if (m.find( )) {
price = (String) m.group(0);
// System.out.println("Found value: " + m.group(0) );
} else {
price = "none";
// System.out.println("NO MATCH");
}
pattern = "(?<=(sale = \\\"))\\S+(?=(\\\"))";
r = Pattern.compile(pattern);
m = r.matcher(result);
if (m.find( )) {
sale = (String) m.group(0);
// System.out.println("Found value: " + m.group(0) );
} else {
sale = "none";
// System.out.println("NO MATCH");
}
pattern = "(?<=(date = \\\"))\\S+(?=(\\\"))";
r = Pattern.compile(pattern);
m = r.matcher(result);
if (m.find( )) {
mydate = (String) m.group(0);
// System.out.println("Found value: " + m.group(0) );
} else {
mydate = "none";
// System.out.println("NO MATCH");
}
return "{\"price\":\""+price+"\""+","+"\"sale\":"+"\""+sale+"\""+","+"\"date\":"+"\""+mydate+"\""+"}";
}
} |
package org.lichess.compression.game;
class Square {
public static final int C1 = 2;
public static final int D1 = 3;
public static final int F1 = 5;
public static final int G1 = 6;
public static int file(int square) {
return square & 7;
}
public static int rank(int square) {
return square >>> 3;
}
public static int combine(int file, int rank) {
return file(file) ^ (rank(rank) << 3);
}
public static int distance(int a, int b) {
return Integer.max(Math.abs(file(a) - file(b)),
Math.abs(rank(a) - rank(b)));
}
public static boolean aligned(int a, int b, int c) {
return Bitboard.contains(Bitboard.RAYS[a][b], c);
}
} |
package net.tomp2p.rcon;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import net.tomp2p.futures.FutureBootstrap;
import net.tomp2p.futures.FutureDirect;
import net.tomp2p.futures.FutureDiscover;
import net.tomp2p.nat.FutureNAT;
import net.tomp2p.nat.FutureRelayNAT;
import net.tomp2p.nat.PeerNAT;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.rpc.ObjectDataReply;
public class SimpleRconClient {
private static int port = 4001;
private static Peer peer;
private static PeerAddress master;
private static String ipAddress;
public static void start() {
// Create a peer with a random peerID, on port 4001, listening to the
// interface eth0
try {
int rand = RandomUtil.getNext();
System.out.println("RandomUtil: " + rand);
peer = new PeerBuilder(new Number160(RandomUtil.getNext())).ports(
port).start();
peer.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(PeerAddress sender, Object request)
throws Exception {
System.out.println("HITHITHITHITHITHITHITHIT");
String req = (String) request;
System.out.println(req);
String reply = "reply";
return (Object) reply;
}
});
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(peer.peerAddress().toString());
}
public static Peer getPeer() {
return peer;
}
public static boolean usualBootstrap(String ip) {
boolean success = false;
ipAddress = ip;
master = createPeerAddress(ipAddress);
// do PeerDiscover
FutureDiscover fd = peer.discover().peerAddress(peer.peerAddress())
.start().awaitUninterruptibly();
if (!fd.isSuccess()) {
return success;
}
FutureBootstrap fb = peer.bootstrap()
.peerAddress(master).start();
fb.awaitUninterruptibly();
if (fb.isSuccess()) {
System.out.println("Bootstrap success!");
success = true;
} else {
System.out.println("Bootstrap fail!");
}
return success;
}
public static boolean sendDummy(String dummy, boolean nat) {
boolean success = false;
// if (nat == true) {
try {
master = new PeerAddress(Number160.ZERO, InetAddress.getByName(ipAddress), port, port);
} catch (UnknownHostException e) {
e.printStackTrace();
}
FutureDirect fd = peer.sendDirect(master).object(dummy).start();
fd.awaitUninterruptibly();
if(fd.isSuccess()) {
System.out.println("FUTURE DIRECT SUCCESS!");
success = true;
} else {
}
return success;
}
/*
* Creates peer address
*/
private static PeerAddress createPeerAddress(String ip) {
// Format IP
InetAddress address = null;
try {
address = Inet4Address.getByName(ip);
} catch (UnknownHostException e) {
e.printStackTrace();
}
// Create PeerAddress for MasterNode
PeerAddress peerAddress = null;
FutureDiscover fd = peer.discover().inetAddress(address).ports(port)
.start();
fd.awaitUninterruptibly();
if (fd.isSuccess()) {
peerAddress = fd.peerAddress();
} else {
System.out.println("Discover is not working");
}
if (peerAddress == null) {
System.out.println("PeerAddress fail");
} else {
if (peerAddress.peerId() == null) {
System.out.println("PeerAddress ID is zero");
} else {
System.out.println("Create PeerAddress: " + peerAddress.toString());
}
}
return peerAddress;
}
public static void natBootstrap(String ip) {
try {
peer.shutdown();
peer = new PeerBuilder(new Number160(RandomUtil.getNext())).behindFirewall(true).ports(port).start();
} catch (IOException e1) {
e1.printStackTrace();
}
PeerNAT peerNAT = new PeerNAT(peer);
PeerAddress pa = null;
try {
pa = new PeerAddress(Number160.ZERO, InetAddress.getByName(ip), port, port);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (peerNAT.bootstrapBuilder() == null) {
System.out.println();
System.out.println("BOOTSTRAPBUILDER IS STILL NULL");
System.out.println();
peerNAT.bootstrapBuilder(peer.bootstrap().peerAddress(pa));
}
//Check if peer is reachable from the internet
FutureDiscover fd = peer.discover().peerAddress(pa).start();
// Try to set up port forwarding with UPNP and NATPMP if peer is not reachable
FutureNAT fn = peerNAT.startSetupPortforwarding(fd);
//if port forwarding failed, this will set up relay peers
FutureRelayNAT frn = peerNAT.startRelay(fn);
fd.awaitUninterruptibly();
frn.awaitUninterruptibly();
//now the peer should be reachable
}
} |
package ASSET.Models.Vessels;
public class Buoy extends SSN
{
private static final long serialVersionUID = 1L;
public Buoy(final int id)
{
super(id);
}
public Buoy(final int id, final ASSET.Participants.Status status, final ASSET.Participants.DemandedStatus demStatus, final String name)
{
super(id, status, demStatus, name);
}
public void initialise()
{
if(getStatus() != null)
this.getStatus().setFuelLevel(100);
}
} |
// $RCSfile: CircleShape.java,v $
// @version $Revision: 1.7 $
// $Log: CircleShape.java,v $
// Revision 1.7 2006/05/02 13:21:37 Ian.Mayo
// Make things draggable
// Revision 1.6 2006/04/21 07:48:36 Ian.Mayo
// Make things draggable
// Revision 1.5 2006/03/22 16:09:13 Ian.Mayo
// Tidying
// Revision 1.4 2004/10/19 14:36:32 Ian.Mayo
// Make guts more visible, to aid inheritance
// Revision 1.3 2004/08/31 09:38:14 Ian.Mayo
// Rename inner static tests to match signature **Test to make automated testing more consistent
// Revision 1.2 2004/05/25 15:37:10 Ian.Mayo
// Commit updates from home
// Revision 1.1.1.1 2004/03/04 20:31:22 ian
// no message
// Revision 1.1.1.1 2003/07/17 10:07:33 Ian.Mayo
// Initial import
// Revision 1.12 2003-07-04 11:00:56+01 ian_mayo
// Reflect name change of parent editor test
// Revision 1.11 2003-07-03 14:59:53+01 ian_mayo
// Reflect new signature of PlainShape constructor, where we don't need to set the default colour
// Revision 1.10 2003-06-25 08:51:01+01 ian_mayo
// Only plot if we are visible
// Revision 1.9 2003-03-18 12:07:20+00 ian_mayo
// extended support for transparent filled shapes
// Revision 1.8 2003-03-03 11:54:34+00 ian_mayo
// Implement filled shape management
// Revision 1.7 2003-01-31 11:31:33+00 ian_mayo
// Remove duff method
// Revision 1.6 2003-01-23 16:04:29+00 ian_mayo
// provide methods to return the shape as a series of segments
// Revision 1.5 2003-01-21 16:31:57+00 ian_mayo
// Try 3-d support, move getColor property management to ShapeWrapper
// Revision 1.4 2002-11-01 14:44:01+00 ian_mayo
// minor tidying
// Revision 1.3 2002-10-30 16:27:01+00 ian_mayo
// tidy (shorten) up display names for editables
// Revision 1.2 2002-05-28 09:25:53+01 ian_mayo
// after switch to new system
// Revision 1.1 2002-05-28 09:14:22+01 ian_mayo
// Initial revision
// Revision 1.1 2002-04-11 14:01:07+01 ian_mayo
// Initial revision
// Revision 1.2 2002-03-19 11:04:05+00 administrator
// Add a "type" property to indicate type of shape (label, rectangle, etc)
// Revision 1.1 2002-01-17 20:40:26+00 administrator
// Reflect switch to Duration/WorldDistance
// Revision 1.0 2001-07-17 08:43:15+01 administrator
// Initial revision
// Revision 1.3 2001-01-22 19:40:36+00 novatech
// reflect optimised projection.toScreen plotting
// Revision 1.2 2001-01-22 12:29:28+00 novatech
// added JUnit testing code
// Revision 1.1 2001-01-03 13:42:20+00 novatech
// Initial revision
// Revision 1.1.1.1 2000/12/12 21:49:07 ianmayo
// initial version
// Revision 1.9 2000-09-21 09:06:48+01 ian_mayo
// make Editable.EditorType a transient parameter, to prevent it being written to file
// Revision 1.8 2000-08-18 13:36:02+01 ian_mayo
// implement singleton of Editable.EditorType
// Revision 1.7 2000-08-14 15:49:29+01 ian_mayo
// tidy up descriptions
// Revision 1.6 2000-08-11 08:41:58+01 ian_mayo
// tidy beaninfo
// Revision 1.5 2000-02-14 16:50:44+00 ian_mayo
// Added boolean methods to allow user to specify "filled" or "not filled"
// Revision 1.4 1999-11-18 11:11:26+00 ian_mayo
// minor tidying up
// Revision 1.3 1999-11-11 18:19:04+00 ian_mayo
// allow for clicking around the edge of the circle
// Revision 1.2 1999-10-14 11:59:20+01 ian_mayo
// added property support and location editing
// Revision 1.1 1999-10-12 15:36:35+01 ian_mayo
// Initial revision
package MWC.GUI.Shapes;
import java.awt.Color;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.Iterator;
import java.util.Vector;
import MWC.GUI.CanvasType;
import MWC.GUI.Editable;
import MWC.GUI.ExtendedCanvasType;
import MWC.GUI.Layer;
import MWC.GUI.PlainWrapper;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldVector;
public class CircleShape extends PlainShape implements Editable,
HasDraggableComponents
{
// member variables
// keep track of versions
static final long serialVersionUID = 1;
/**
* the area covered by this circle
*/
protected WorldArea _theArea;
/**
* the shape, broken down into a series of points
*
*/
protected Vector<WorldLocation> _myPoints = new Vector<WorldLocation>();
/**
* the centre of this circle
*/
protected WorldLocation _theCentre;
/**
* the radius of this circle (in yards)
*/
protected WorldDistance _theRadius;
/**
* our editor
*/
transient protected Editable.EditorType _myEditor;
/**
* the number of segments to use to plot this shape (when applicable)
*/
public static final int NUM_SEGMENTS = 40;
// constructor
/**
* constructor
*
* @param theCentre
* the WorldLocation marking the centre of the circle
* @param theRadius
* the radius of the circle (in yards)
*/
public CircleShape(final WorldLocation theCentre, final double theRadius)
{
this(theCentre, new WorldDistance(theRadius, WorldDistance.YARDS));
}
/**
* constructor
*
* @param theCentre
* the WorldLocation marking the centre of the circle
* @param theRadius
* the radius of the circle (in yards)
*/
public CircleShape(final WorldLocation theCentre,
final WorldDistance theRadius)
{
super(0, "Circle");
// store the values
_theCentre = theCentre;
_theRadius = theRadius;
// now represented our circle as an area
calcPoints();
}
// public CircleShape(){
// // scrap, in case we are serializing
// _theArea = null;
// member functions
public void paint(final CanvasType dest)
{
// are we visible?
if (!getVisible())
return;
if (this.getColor() != null)
{
// create a transparent colour
final Color newcol = getColor();
dest.setColor(new Color(newcol.getRed(), newcol.getGreen(), newcol
.getBlue(), TRANSPARENCY_SHADE));
}
// break the circle down into points
final int STEPS = _myPoints.size();
final int[] xP = new int[STEPS];
final int[] yP = new int[STEPS];
int ctr = 0;
final Iterator<WorldLocation> iter = _myPoints.iterator();
while (iter.hasNext())
{
final Point pt = dest.toScreen(iter.next());
xP[ctr] = pt.x;
yP[ctr++] = pt.y;
}
// and plot the polygon
if (getFilled())
{
if (getSemiTransparent() && dest instanceof ExtendedCanvasType)
{
ExtendedCanvasType ext = (ExtendedCanvasType) dest;
ext.semiFillPolygon(xP, yP, STEPS);
}
else
dest.fillPolygon(xP, yP, STEPS);
}
else
{
dest.drawPolygon(xP, yP, STEPS);
}
}
/**
* calculate some convenience values based on the radius and centre of the
* circle
*/
protected void calcPoints()
{
// calc the radius in degrees
final double radDegs = _theRadius.getValueIn(WorldDistance.DEGS);
// create our area
_theArea = new WorldArea(_theCentre, _theCentre);
// create & extend to top left
WorldLocation other = _theCentre.add(new WorldVector(0, radDegs, 0));
_theArea.extend(other);
other.addToMe(new WorldVector(MWC.Algorithms.Conversions.Degs2Rads(270),
radDegs, 0));
_theArea.extend(other);
// create & extend to bottom right
other = _theCentre.add(new WorldVector(MWC.Algorithms.Conversions
.Degs2Rads(180), radDegs, 0));
_theArea.extend(other);
other.addToMe(new WorldVector(MWC.Algorithms.Conversions.Degs2Rads(90),
radDegs, 0));
_theArea.extend(other);
// clear our local list of points
_myPoints.removeAllElements();
// and the circle as a series of points (so it turns properly in relative
// mode)
final int STEPS = 100;
for (int i = 0; i < STEPS; i++)
{
final double thisAngle = (Math.PI * 2) / (double) STEPS * i;
// create & extend to top left
final WorldLocation newPt = _theCentre.add(new WorldVector(thisAngle,
radDegs, 0));
_myPoints.add(newPt);
}
}
public MWC.GenericData.WorldArea getBounds()
{
return _theArea;
}
/**
* get the range from the indicated world location - making this abstract
* allows for individual shapes to have 'hit-spots' in various locations.
*/
public double rangeFrom(final WorldLocation point)
{
final double res = this._theCentre.rangeFrom(point);
/**
* note, also allow us to recognise that the user may be clicking on the
* circle itself, so do a second check using the difference between the
* range from the centre of the circle and the radius of the circle
*/
final double res2 = Math.abs(_theRadius.getValueIn(WorldDistance.DEGS)
- res);
return Math.min(res, res2);
}
/**
* return the radius of this circle
*
* @return the radius of this circle
*/
public WorldDistance getRadius()
{
return _theRadius;
}
/**
* set the centre location of the circle
*
* @param centre
* the WorldLocation marking the centre
*/
public void setCentre(final WorldLocation centre)
{
// remember the old value of centre
final WorldLocation oldCentre = _theCentre;
// make the change
_theCentre = centre;
// and calc the new summary data
calcPoints();
// inform our listeners, including the parent (so it can move the label)
firePropertyChange(PlainWrapper.LOCATION_CHANGED, oldCentre, centre);
}
/**
* @return the centre of the circle
*/
public WorldLocation getCentre()
{
return _theCentre;
}
public void setCircleColor(final Color val)
{
super.setColor(val);
}
public Color getCircleColor()
{
return super.getColor();
}
/**
* set the radius of this circle
*/
public void setRadius(final WorldDistance val)
{
_theRadius = val;
// and calc the new summary data
calcPoints();
// and inform the parent (so it can move the label)
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, null);
}
public boolean hasEditor()
{
return true;
}
public Editable.EditorType getInfo()
{
if (_myEditor == null)
_myEditor = new CircleInfo(this, this.getName());
return _myEditor;
}
/**
* get the 'anchor point' for any labels attached to this shape
*/
public MWC.GenericData.WorldLocation getAnchor()
{
return _theCentre;
}
// 3-d support
// bean info for this class
public class CircleInfo extends Editable.EditorType
{
public CircleInfo(final CircleShape data, final String theName)
{
super(data, theName, "");
}
public String getName()
{
return CircleShape.this.getName();
}
public PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final PropertyDescriptor[] res =
{
prop("Radius", "the circle radius", SPATIAL),
prop("Centre", "the centre of the circle", SPATIAL),
prop("Filled", "whether to fill the circle", FORMAT),
displayProp("SemiTransparent", "Semi transparent",
"whether the filled circle is semi-transparent", FORMAT), };
return res;
}
catch (final IntrospectionException e)
{
return super.getPropertyDescriptors();
}
}
}
public void shift(final WorldLocation feature, final WorldVector vector)
{
// ok, just shift it...
feature.addToMe(vector);
// and calc the new summary data
calcPoints();
// and inform the parent (so it can move the label)
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, null);
}
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final ComponentConstruct currentNearest,
final Layer parentLayer)
{
// right, see if the cursor is at the centre (that's the easy component)
checkThisOne(_theCentre, cursorLoc, currentNearest, this, parentLayer);
// now for the more difficult one. See if it is on the radius.
// - how far is it from the centre
final WorldVector vec = cursorLoc.subtract(_theCentre);
final WorldDistance sep = new WorldDistance(vec);
// ahh, now subtract the radius from this separation
final WorldDistance newSep = new WorldDistance(Math.abs(sep
.getValueIn(WorldDistance.YARDS)
- this._theRadius.getValueIn(WorldDistance.YARDS)), WorldDistance.YARDS);
// now we have to wrap this operation in a made-up location
final WorldLocation dragCentre = new WorldLocation(cursorLoc)
{
private static final long serialVersionUID = 100L;
public void addToMe(final WorldVector delta)
{
// ok - process the drag
super.addToMe(delta);
// ok, what's this distance from the origin?
final WorldVector newSep1 = subtract(_theCentre);
final WorldDistance dist = new WorldDistance(newSep1);
setRadius(dist);
// WorldDistance newDist = new
// WorldDistance(dist.getValueIn(WorldDistance.YARDS) + _theRadius,
// WorldDistance.YARDS);
// hmm, are we going in or out?
// now, change the radius to this
}
};
// try range
currentNearest.checkMe(this, newSep, null, parentLayer, dragCentre);
}
// testing for this class
static public class CircleTest extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public CircleTest(final String val)
{
super(val);
}
public void testMyParams()
{
MWC.GUI.Editable ed = new CircleShape(new WorldLocation(2d, 2d, 2d), 2d);
MWC.GUI.Editable.editableTesterSupport.testParams(ed, this);
ed = null;
}
}
public void shift(final WorldVector vector)
{
final WorldLocation oldCentre = getCentre();
final WorldLocation newCentre = oldCentre.add(vector);
setCentre(newCentre);
// and calc the new summary data
calcPoints();
// and inform the parent (so it can move the label)
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, null);
}
} |
package com.gallatinsystems.survey.dao;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.NotPersistent;
import net.sf.jsr107cache.Cache;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import com.gallatinsystems.common.util.MemCacheUtils;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.exceptions.IllegalDeletionException;
import com.gallatinsystems.framework.servlet.PersistenceFilter;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.Translation.ParentType;
import com.gallatinsystems.surveyal.dao.SurveyalValueDao;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
/**
* saves/finds question objects
*/
public class QuestionDao extends BaseDAO<Question> {
private QuestionOptionDao optionDao;
private QuestionHelpMediaDao helpDao;
private TranslationDao translationDao;
private ScoringRuleDao scoringRuleDao;
private Cache cache;
public QuestionDao() {
super(Question.class);
optionDao = new QuestionOptionDao();
helpDao = new QuestionHelpMediaDao();
translationDao = new TranslationDao();
scoringRuleDao = new ScoringRuleDao();
cache = MemCacheUtils.initCache(4 * 60 * 60); // cache questions list for 4 hours
}
/**
* lists all questions filtered by type optionally filtered by surveyId as well.
*
* @param surveyId
* @param type
* @return
*/
public List<Question> listQuestionByType(Long surveyId, Question.Type type) {
if (surveyId == null) {
return listByProperty("type", type.toString(), "String", "order",
"asc");
} else {
List<Question> allQuestionsInOrder = listQuestionInOrder(surveyId);
List<Question> typeQuestions = new ArrayList<Question>();
if (type != null) {
if (allQuestionsInOrder != null) {
for (Question q : allQuestionsInOrder) {
if (type.equals(q.getType())) {
typeQuestions.add(q);
}
}
return typeQuestions;
}
}
return allQuestionsInOrder;
}
}
/**
* loads the Question object but NOT any associated options
*
* @param id
* @return
*/
public Question getQuestionHeader(Long id) {
return getByKey(id);
}
/**
* lists minimal question information by surveyId
* retrieves question list from the cache whenever possible
*
* @param surveyId
* @return
*/
public List<Question> listQuestionsBySurvey(Long surveyId) {
String surveyQuestionsCacheKey = MemCacheUtils.SURVEY_QUESTIONS_PREFIX + surveyId;
List<Question> questionsList = null;
if (MemCacheUtils.containsKey(cache, surveyQuestionsCacheKey)) {
questionsList = (List<Question>) cache.get(surveyQuestionsCacheKey);
} else {
questionsList = (List<Question>) listByProperty("surveyId", surveyId, "Long", "order", "asc");
MemCacheUtils.putObject(cache, surveyQuestionsCacheKey, questionsList);
}
if(questionsList == null) return Collections.emptyList();
return questionsList;
}
/**
* Returns a map of questions by surveyId with the question id as key
* and question object as value
*
* @param surveyId
* @return
*/
public Map<Long, Question> mapQuestionsBySurvey(Long surveyId) {
Map<Long, Question> questionMap = new LinkedHashMap<Long, Question>();
for(Question q : listByProperty("surveyId", surveyId, "Long", "order", "asc")) {
questionMap.put(q.getKey().getId(), q);
}
return questionMap;
}
/**
* Delete a list of questions
*
* @param qList
*/
public void delete(List<Question> qList) {
super.delete(qList);
uncache(qList);
}
/**
* Delete question from data store.
* @param question
*/
public void delete(Question question) throws IllegalDeletionException {
delete(question, Boolean.TRUE);
}
public void delete(Question question, Boolean adjustQuestionOrder)
throws IllegalDeletionException {
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
SurveyalValueDao svDao = new SurveyalValueDao();
if (qasDao.listByQuestion(question.getKey().getId()).size() > 0
|| svDao.listByQuestion(question.getKey().getId()).size() > 0) {
throw new IllegalDeletionException(
"Cannot delete question with id "
+ question.getKey().getId()
+ " ("
+ question.getText()
+ ") because there are already survey responses stored for this question. Please delete all survey responses first.");
}
helpDao.deleteHelpMediaForQuestion(question.getKey().getId());
optionDao.deleteOptionsForQuestion(question.getKey().getId());
translationDao.deleteTranslationsForParent(question.getKey().getId(),
Translation.ParentType.QUESTION_TEXT);
// to use later when adjust question order
Long deletedQuestionGroupId = question.getQuestionGroupId();
Integer deletedQuestionOrder = question.getOrder();
// only delete after extracting group ID and order
super.delete(question);
uncache(Arrays.asList(question));
if(adjustQuestionOrder != null && adjustQuestionOrder) {
// update question order
TreeMap<Integer, Question> groupQs = listQuestionsByQuestionGroup(
deletedQuestionGroupId, false);
if (groupQs != null) {
for (Question gq : groupQs.values()) {
if (gq.getOrder() >= deletedQuestionOrder) {
gq.setOrder(gq.getOrder() - 1);
}
}
}
}
}
public void deleteQuestionsForGroup(Long questionGroupId) throws IllegalDeletionException {
for (Question q : listQuestionsByQuestionGroup(questionGroupId, Boolean.TRUE).values()) {
delete(q, Boolean.FALSE);
}
}
/**
* lists all questions in a group and orders them by their sortOrder
*
* @param groupId
* @return
*/
public List<Question> listQuestionsInOrderForGroup(Long groupId) {
return listByProperty("questionGroupId", groupId, "Long", "order",
"asc");
}
/**
* lists all questions for a survey and orders them by sort order. THIS METHOD SHOULD NOT BE
* USED AS SORT ORDERS MAY BE DUPLICATED ACROSS QUESTIONGROUPS SO THE ORDERING IS UNDEFINED
*
* @param surveyId
* @return
* @deprecated
*/
@Deprecated
public List<Question> listQuestionInOrder(Long surveyId) {
List<Question> orderedQuestionList = new ArrayList<Question>();
List<Question> unknownOrder = listByProperty("surveyId", surveyId,
"Long", "order", "asc");
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.listQuestionGroupBySurvey(surveyId);
for (QuestionGroup qg : qgList) {
for (Question q : unknownOrder) {
if (qg.getKey().getId() == q.getQuestionGroupId()) {
orderedQuestionList.add(q);
}
}
}
return orderedQuestionList;
}
public List<Question> listQuestionsInOrder(Long surveyId, Question.Type type) {
List<Question> orderedQuestionList = new ArrayList<Question>();
QuestionGroupDao qgDao = new QuestionGroupDao();
List<QuestionGroup> qgList = qgDao.listQuestionGroupBySurvey(surveyId);
// for each question group, get the questions in the right order and put them in the list
List<Question> qList;
for (QuestionGroup qg : qgList) {
if (type == null) {
qList = listByProperty("questionGroupId", qg
.getKey().getId(), "Long", "order", "asc");
} else {
qList = getByQuestiongroupAndType(qg.getKey().getId(), type);
}
if (qList != null && qList.size() > 0) {
for (Question q : qList) {
orderedQuestionList.add(q);
}
}
}
return orderedQuestionList;
}
/**
* Lists questions by questionGroupId and type
*
* @param questionGroupId
* @param type
* @return
*/
@SuppressWarnings("unchecked")
private List<Question> getByQuestiongroupAndType(long questionGroupId, Question.Type type) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(Question.class);
query.setFilter(" questionGroupId == questionGroupIdParam && type == questionTypeParam");
query.declareParameters("Long questionGroupIdParam, String questionTypeParam");
query.setOrdering("order asc");
List<Question> results = (List<Question>) query.execute(questionGroupId, type.toString());
if (results != null && results.size() > 0) {
return results;
} else {
return null;
}
}
/**
* saves a question object in a transaction
*
* @param q
* @return
*/
public Question saveTransactional(Question q) {
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Transaction txn = datastore.beginTransaction();
Entity question = null;
try {
if (q.getKey() != null) {
try {
question = datastore.get(q.getKey());
} catch (Exception e) {
log.log(Level.WARNING,
"Key is set but not found. Assuming this is an import");
question = new Entity(q.getKey());
}
} else {
question = new Entity("Question");
}
Field[] f = Question.class.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
if (!"key".equals(f[i].getName())
&& f[i].getAnnotation(NotPersistent.class) == null
&& !"type".equals(f[i].getName())
&& !f[i].getName().startsWith("jdo")
&& !f[i].getName().equals("serialVersionUID")) {
f[i].setAccessible(true);
question.setProperty(f[i].getName(), f[i].get(q));
}
}
// now set the type
question.setProperty("type", q.getType().toString());
} catch (Exception e) {
log.log(Level.SEVERE, "Could not set entity fields", e);
}
Key key = datastore.put(question);
q.setKey(key);
cache(Arrays.asList(q));
txn.commit();
return q;
}
/**
* saves a question, including its question options, translations, and help media (if any).
*
* @param question
* @param questionGroupId
* @return
*/
public Question save(Question question, Long questionGroupId) {
if (questionGroupId != null) {
question.setQuestionGroupId(questionGroupId);
QuestionGroup group = getByKey(questionGroupId, QuestionGroup.class);
if (group != null) {
question.setSurveyId(group.getSurveyId());
}
}
question = saveTransactional(question);
// delete existing options
QuestionOptionDao qoDao = new QuestionOptionDao();
TreeMap<Integer, QuestionOption> qoMap = qoDao
.listOptionByQuestion(question.getKey().getId());
if (qoMap != null) {
for (Map.Entry<Integer, QuestionOption> entry : qoMap.entrySet()) {
qoDao.delete(entry.getValue());
}
}
if (question.getQuestionOptionMap() != null) {
for (QuestionOption opt : question.getQuestionOptionMap().values()) {
opt.setQuestionId(question.getKey().getId());
if (opt.getText() != null && opt.getText().contains(",")) {
opt.setText(opt.getText().replaceAll(",", "-"));
if (opt.getCode() != null) {
opt.setCode(opt.getCode().replaceAll(",", "-"));
}
}
save(opt);
if (opt.getTranslationMap() != null) {
for (Translation t : opt.getTranslationMap().values()) {
if (t.getParentId() == null) {
t.setParentId(opt.getKey().getId());
}
}
super.save(opt.getTranslationMap().values());
}
}
}
if (question.getTranslationMap() != null) {
for (Translation t : question.getTranslationMap().values()) {
if (t.getParentId() == null) {
t.setParentId(question.getKey().getId());
}
}
super.save(question.getTranslationMap().values());
}
if (question.getQuestionHelpMediaMap() != null) {
for (QuestionHelpMedia help : question.getQuestionHelpMediaMap()
.values()) {
help.setQuestionId(question.getKey().getId());
save(help);
if (help.getTranslationMap() != null) {
for (Translation t : help.getTranslationMap().values()) {
if (t.getParentId() == null) {
t.setParentId(help.getKey().getId());
}
}
super.save(help.getTranslationMap().values());
}
}
}
return question;
}
/**
* Saves question and update cache
*
* @param question
*/
public Question save(Question question) {
// first save and get Id
Question savedQuestion = super.save(question);
cache(Arrays.asList(savedQuestion));
return savedQuestion;
}
/**
* Save a collection of questions and cache
*
* @param qList
* @return
*/
public List<Question> save(List<Question> qList) {
List<Question> savedQuestions = (List<Question>) super.save(qList);
cache(savedQuestions);
return savedQuestions;
}
/**
* Add a collection of questions to the cache
*
* @param qList
*/
public void cache(List<Question> qList) {
if(qList == null || qList.isEmpty()) {
return;
}
String surveyQuestionsCacheKey = MemCacheUtils.SURVEY_QUESTIONS_PREFIX + qList.get(0).getSurveyId();
if(MemCacheUtils.containsKey(cache, surveyQuestionsCacheKey)){
List<Question> cachedList = (List<Question>) cache.get(surveyQuestionsCacheKey);
cachedList.addAll(qList);
MemCacheUtils.putObject(cache, surveyQuestionsCacheKey, cachedList);
}
}
/**
* Remove a collection of questions from the cache
*
* @param qList
*/
public void uncache(List<Question> qList) {
if(qList == null || qList.isEmpty()) {
return;
}
String surveyQuestionsCacheKey = MemCacheUtils.SURVEY_QUESTIONS_PREFIX + qList.get(0).getSurveyId();
if(MemCacheUtils.containsKey(cache, surveyQuestionsCacheKey)){
List<Question> cachedList = (List<Question>) cache.get(surveyQuestionsCacheKey);
cachedList.removeAll(qList);
MemCacheUtils.putObject(cache, surveyQuestionsCacheKey, cachedList);
}
}
/**
* finds a question by its reference id
*
* @param refid
* @return
* @deprecated
*/
@Deprecated
public Question findByReferenceId(String refid) {
Question q = findByProperty("referenceIndex", refid, "String");
return q;
}
/**
* finds a question by its id. If needDetails is true, all child objects (options, help,
* translations) will also be loaded.
*
* @param id
* @param needDetails
* @return
*/
public Question getByKey(Long id, boolean needDetails) {
Question q = getByKey(id);
if (needDetails) {
q.setQuestionHelpMediaMap(helpDao.listHelpByQuestion(q.getKey()
.getId()));
if (Question.Type.OPTION == q.getType()) {
q.setQuestionOptionMap(optionDao.listOptionByQuestion(q
.getKey().getId()));
}
q.setTranslationMap(translationDao.findTranslations(
Translation.ParentType.QUESTION_TEXT, q.getKey().getId()));
// only load scoring rules for types that support scoring
if (Question.Type.OPTION == q.getType()
|| Question.Type.FREE_TEXT == q.getType()
|| Question.Type.NUMBER == q.getType()) {
q.setScoringRules(scoringRuleDao.listRulesByQuestion(q.getKey()
.getId()));
}
}
return q;
}
/**
* finds the base question (no child objects) by id
*/
@Override
public Question getByKey(Key key) {
return super.getByKey(key);
}
/**
* lists questions within a group ordered by creation date
*
* @param questionGroupId
* @return
*/
public List<Question> listQuestionsByQuestionGroupOrderByCreatedDateTime(
Long questionGroupId) {
return listByProperty("questionGroupId", questionGroupId, "Long",
"createdDateTime", "asc");
}
/**
* lists questions within a group. If needDetails flag is true, the child objects will be loaded
* for each question. Due to processing constraints on GAE, needDetails should only be true when
* calling this method if being called from a backend or task.
*
* @param questionGroupId
* @param needDetails
* @return
*/
public TreeMap<Integer, Question> listQuestionsByQuestionGroup(
Long questionGroupId, boolean needDetails) {
return listQuestionsByQuestionGroup(questionGroupId, needDetails, true);
}
/**
* lists all the questions in a group, optionally loading details. If allowSideEffects is true,
* it will attempt to reorder any duplicated question orderings on retrieval. New users of this
* method should ALWAY call this with allowSideEffects = false
*
* @param questionGroupId
* @param needDetails
* @param allowSideEffects
* @return
*/
public TreeMap<Integer, Question> listQuestionsByQuestionGroup(
Long questionGroupId, boolean needDetails, boolean allowSideEffects) {
List<Question> qList = listByProperty("questionGroupId",
questionGroupId, "Long", "order", "asc");
TreeMap<Integer, Question> map = new TreeMap<Integer, Question>();
if (qList != null) {
for (Question q : qList) {
if (needDetails) {
q.setQuestionHelpMediaMap(helpDao.listHelpByQuestion(q
.getKey().getId()));
if (Question.Type.OPTION == q.getType()
|| Question.Type.STRENGTH == q.getType()) {
q.setQuestionOptionMap(optionDao.listOptionByQuestion(q
.getKey().getId()));
}
q.setTranslationMap(translationDao.findTranslations(
ParentType.QUESTION_TEXT, q.getKey().getId()));
// only load scoring rules for types that support
// scoring
if (Question.Type.OPTION == q.getType()
|| Question.Type.FREE_TEXT == q.getType()
|| Question.Type.NUMBER == q.getType()) {
q.setScoringRules(scoringRuleDao.listRulesByQuestion(q
.getKey().getId()));
}
}
if (q.getOrder() == null) {
q.setOrder(qList.size() + 1);
} else if (allowSideEffects) {
if (map.size() > 0 && !(q.getOrder() > map.size())) {
q.setOrder(map.size() + 1);
super.save(q);
} else if (map.size() == 0) {
super.save(q);
}
}
map.put(q.getOrder(), q);
}
}
return map;
}
/**
* finds q question by its path and order. Path is defined as the name of the
* "surveyGroupName/surveyName/QuestionGroupName"
*
* @param order
* @param path
* @return
*/
@SuppressWarnings("unchecked")
public Question getByPath(Integer order, String path) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(Question.class);
query.setFilter(" path == pathParam && order == orderParam");
query.declareParameters("String pathParam, String orderParam");
List<Question> results = (List<Question>) query.execute(path, order);
if (results != null && results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
/**
* finds a question within a group by matching on the questionText passed in
*
* @param questionGroupId
* @param questionText
* @return
*/
@SuppressWarnings("unchecked")
public Question getByQuestionGroupId(Long questionGroupId,
String questionText) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(Question.class);
query.setFilter(" questionGroupId == questionGroupIdParam && text == questionTextParam");
query.declareParameters("Long questionGroupIdParam, String questionTextParam");
List<Question> results = (List<Question>) query.execute(
questionGroupId, questionText);
if (results != null && results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
/**
* finds a question by groupId and order. If there are questions with duplicated orders, the
* first is returned.
*
* @param questionGroupId
* @param order
* @return
*/
@SuppressWarnings("unchecked")
public Question getByGroupIdAndOrder(Long questionGroupId, Integer order) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(Question.class);
query.setFilter(" questionGroupId == questionGroupIdParam && order == orderParam");
query.declareParameters("Long questionGroupIdParam, Integer orderParam");
List<Question> results = (List<Question>) query.execute(
questionGroupId, order);
if (results != null && results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
/**
* updates ONLY the order field within the question object for the questions passed in. All
* questions must exist in the datastore
*
* @param questionList
*/
public void updateQuestionOrder(List<Question> questionList) {
if (questionList != null) {
for (Question q : questionList) {
Question persistentQuestion = getByKey(q.getKey());
persistentQuestion.setOrder(q.getOrder());
// since the object is still attached, we don't need to call
// save. It will be saved on flush of the Persistent session
}
}
}
/**
* updates ONLY the order field within the question group object for the questions passed in.
* All question groups must exist in the datastore
*
* @param questionList
*/
public void updateQuestionGroupOrder(List<QuestionGroup> groupList) {
if (groupList != null) {
for (QuestionGroup q : groupList) {
QuestionGroup persistentGroup = getByKey(q.getKey(),
QuestionGroup.class);
persistentGroup.setOrder(q.getOrder());
// since the object is still attached, we don't need to call
// save. It will be saved on flush of the Persistent session
}
}
}
/**
* lists all questions that depend on the id passed in
*
* @param questionId
* @return
*/
public List<Question> listQuestionsByDependency(Long questionId) {
return listByProperty("dependentQuestionId", questionId, "Long");
}
@SuppressWarnings("unchecked")
public List<Question> listDisplayNameQuestionsBySurveyId(Long surveyId) {
PersistenceManager pm = PersistenceFilter.getManager();
javax.jdo.Query query = pm.newQuery(Question.class);
query.setFilter("surveyId == surveyIdParam && localeNameFlag == true");
query.declareParameters("Long surveyIdParam");
query.setOrdering("order asc");
List<Question> results = (List<Question>) query.execute(
surveyId);
if (results != null && results.size() > 0) {
return results;
} else {
return Collections.emptyList();
}
}
} |
package com.ezardlabs.lostsector;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.NavMesh.NavPoint.NavPointType;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Stack;
public class NavMesh {
public static NavPoint[][] navPoints;
private static int maxIndex = 0;
private static NavPoint closest;
private static boolean found = false;
enum LinkType {
WALK,
FALL,
JUMP
}
private static ArrayList<NavPoint> pointsWithAlteredIndices = new ArrayList<>();
public static class NavPoint {
public NavPointType type = NavPointType.NONE;
public final HashSet<Link> links = new HashSet<>();
public final int id;
public final Vector2 position;
private int index = 0;
static class Link {
LinkType linkType;
NavPoint target;
public Link(LinkType linkType, NavPoint target) {
this.linkType = linkType;
this.target = target;
}
}
public NavPoint(int id, Vector2 position) {
this.id = id;
this.position = position;
}
public enum NavPointType {
NONE,
PLATFORM,
LEFT_EDGE,
RIGHT_EDGE,
SOLO
}
void index(int index) {
if (found) return;
if (this.index == -1) {
this.index = index;
maxIndex = index;
closest = this;
found = true;
pointsWithAlteredIndices.add(this);
toIndex.clear();
indices.clear();
return;
}
this.index = index;
pointsWithAlteredIndices.add(this);
if (index > maxIndex) {
maxIndex = index;
closest = this;
}
for (Link l : links) {
if ((l.target.index <= 0 || l.target.index > index + 1) && !(l.linkType == LinkType.FALL && l.target.position.y < position.y) && !(l.linkType == LinkType.JUMP && l.target.position.y > position.y)) {
toIndex.addFirst(l.target);
indices.addFirst(index + 1);
}
}
}
@Override
public String toString() {
String ret = "";
for (Link l : links) {
ret += l.target.id + ", ";
}
return "NavPoint: id = " + id + ", position = " + position + ", index = " + index + ", links = " + ret;
}
}
private static ArrayDeque<NavPoint> toIndex = new ArrayDeque<>();
private static ArrayDeque<Integer> indices = new ArrayDeque<>();
public static NavPoint[] getPath(NavPoint start, NavPoint end) {
if (start == null || end == null) return null;
for (int i = 0; i < pointsWithAlteredIndices.size(); i++) {
pointsWithAlteredIndices.get(i).index = 0;
}
pointsWithAlteredIndices.clear();
end.index = -1;
maxIndex = 0;
found = false;
toIndex.clear();
indices.clear();
toIndex.add(start);
indices.add(1);
while (!toIndex.isEmpty()) {
toIndex.pop().index(indices.pop());
}
if (closest.id != end.id) {
return new NavPoint[0];
}
NavPoint[] path = new NavPoint[maxIndex];
if (maxIndex == 0) {
return path;
} else if (maxIndex == 1) {
path[0] = end;
return path;
} else {
path[maxIndex - 1] = end;
for (int i = maxIndex - 2; i >= 0; i
for (NavPoint.Link l : path[i + 1].links) {
if (l.target.index == i + 1 && !(l.target.position.y > path[i + 1].position.y && l.linkType == LinkType.FALL) && !(l.target.position.y < path[i + 1].position.y && l.linkType == LinkType.JUMP)) {
path[i] = l.target;
break;
}
}
}
return path;
}
}
private static int count = 0;
public static void init(int[][] solidityMap) {
solidityMap = fillInSolidityMap(solidityMap);
navPoints = new NavPoint[solidityMap.length][solidityMap[0].length];
for (int i = 0; i < solidityMap.length; i++) {
for (int j = 0; j < solidityMap[i].length; j++) {
if (solidityMap[i][j] == 0) solidityMap[i][j] = 1;
if (solidityMap[i][j] == 2) solidityMap[i][j] = 0;
navPoints[i][j] = new NavPoint(count++, new Vector2(i * 100, j * 100));
}
}
// Walk links
for (int y = 0; y < solidityMap[0].length; y++) {
boolean platformStarted = false;
for (int x = 0; x < solidityMap.length; x++) {
if (!platformStarted) {
if (!isCollision(solidityMap, x, y) && isCollision(solidityMap, x, y + 1) && !isCollision(solidityMap, x, y - 1)) {
navPoints[x][y].type = NavPointType.LEFT_EDGE;
platformStarted = true;
}
}
if (platformStarted) {
if (isCollision(solidityMap, x + 1, y + 1) &&
!isCollision(solidityMap, x + 1, y) &&
navPoints[x][y].type != NavPointType.LEFT_EDGE) {
navPoints[x][y].type = NavPointType.PLATFORM;
addLink(x, y, x - 1, y, LinkType.WALK);
}
if (!isCollision(solidityMap, x + 1, y + 1) || isCollision(solidityMap, x + 1, y)) {
if (navPoints[x][y].type == NavPointType.LEFT_EDGE) {
navPoints[x][y].type = NavPointType.SOLO;
} else {
navPoints[x][y].type = NavPointType.RIGHT_EDGE;
addLink(x, y, x - 1, y, LinkType.WALK);
}
platformStarted = false;
}
}
}
}
// Fall links
for (int x = 0; x < navPoints.length; x++) {
for (int y = 0; y < navPoints[x].length; y++) {
if (navPoints[x][y].type == NavPointType.RIGHT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (x + 2 < navPoints.length && !isCollision(solidityMap, x + 1, y) && !isCollision(solidityMap, x + 2, y) && !isCollision(solidityMap, x + 1, y - 1) &&
!isCollision(solidityMap, x + 2, y - 1)) {
int yTemp = y + 1;
while (yTemp < navPoints[x].length - 1 && !isCollision(solidityMap, x + 1, yTemp) && !isCollision(solidityMap, x + 2, yTemp)) {
yTemp++;
}
yTemp
if (isCollision(solidityMap, x + 2, yTemp + 1)) {
addLink(x, y, x + 2, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 4) {
addLink(x, y, x + 1, yTemp, LinkType.JUMP);
}
} else {
addLink(x, y, x + 1, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 4) {
addLink(x, y, x + 1, yTemp, LinkType.JUMP);
}
}
}
}
if (navPoints[x][y].type == NavPointType.LEFT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (x - 2 > 0 && !isCollision(solidityMap, x - 1, y) && !isCollision(solidityMap, x - 2, y) && !isCollision(solidityMap, x - 1, y - 1) && !isCollision(solidityMap, x - 2, y - 1)) {
int yTemp = y + 1;
while (yTemp < navPoints[x].length - 1 && !isCollision(solidityMap, x - 1, yTemp) && !isCollision(solidityMap, x - 2, yTemp)) {
yTemp++;
}
yTemp
if (isCollision(solidityMap, x - 2, yTemp + 1)) {
addLink(x, y, x - 2, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 4) {
addLink(x, y, x - 1, yTemp, LinkType.JUMP);
}
} else {
addLink(x, y, x - 1, yTemp, LinkType.FALL);
if (yTemp - (y + 1) < 4) {
addLink(x, y, x - 1, yTemp, LinkType.JUMP);
}
}
}
}
}
}
// Jump links
for (int x = 0; x < navPoints.length; x++) {
for (int y = 0; y < navPoints[x].length; y++) {
if (navPoints[x][y].type == NavPointType.RIGHT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (isCollision(solidityMap, x + 1, y)) {
for (int i = 1; i < 4; i++) {
if (!isCollision(solidityMap, x + 1, y - i) && !isCollision(solidityMap, x + 1, y - i - 1)) {
addLink(x, y, x + 1, y - i, LinkType.JUMP);
break;
}
}
}
}
if (navPoints[x][y].type == NavPointType.LEFT_EDGE || navPoints[x][y].type == NavPointType.SOLO) {
if (isCollision(solidityMap, x - 1, y)) {
for (int i = 1; i < 4; i++) {
if (!isCollision(solidityMap, x - 1, y - i) && !isCollision(solidityMap, x - 1, y - i - 1)) {
addLink(x, y, x - 1, y - i, LinkType.JUMP);
break;
}
}
}
}
}
}
}
private static void addLink(int x1, int y1, int x2, int y2, LinkType type) {
navPoints[x1][y1].links.add(new NavPoint.Link(type, navPoints[x2][y2]));
navPoints[x2][y2].links.add(new NavPoint.Link(type, navPoints[x1][y1]));
}
private static int[][] fillInSolidityMap(int[][] solidityMap) {
if (solidityMap == null) return null;
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{0, 0});
while (!stack.empty()) {
int[] pop = stack.pop();
int x = pop[0];
int y = pop[1];
if (solidityMap[x][y] >= 1) continue;
if (solidityMap[x][y] == 0) solidityMap[x][y] = 2;
if (x > 0) stack.push(new int[]{x - 1, y});
if (x < solidityMap.length - 2) stack.push(new int[]{x + 1, y});
if (y > 0) stack.push(new int[]{x, y - 1});
if (y < solidityMap[0].length - 2) stack.push(new int[]{x, y + 1});
}
return solidityMap;
}
private static boolean isCollision(int[][] solidity, int x, int y) {
return x >= solidity.length || x < 0 || y >= solidity[0].length || y < 0 ||
solidity[x][y] == 1;
}
} |
package com.eddysystems.eddy;
import org.jetbrains.annotations.Nullable;
import scala.NotImplementedError;
import scala.Option;
import scala.Some;
import scala.collection.JavaConversions;
import scala.collection.immutable.Map$;
import tarski.Items.*;
import tarski.Types.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.impl.source.PsiClassReferenceType;
import com.intellij.psi.*;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Converter {
private final Place place;
private final Map<PsiElement,Item> globals;
public final Map<PsiElement, Item> locals; // We will add to this
private final @NotNull Logger logger = Logger.getInstance(getClass());
Converter(Place place, Map<PsiElement, Item> globals, Map<PsiElement, Item> locals) {
this.place = place;
this.globals = globals;
this.locals = locals;
}
@Nullable Item lookup(PsiElement e) {
Item i = globals.get(e);
return i != null ? i : locals.get(e);
}
// If parent is given, use it for generics resolution. If it is null, use containing().inside() instead.
// TODO: The version without parent should probably be deleted.
Type convertType(PsiType t) {
return convertType(t,null);
}
Type convertType(PsiType t, Parent parent) {
// TODO: Handle modifiers
if (t instanceof PsiArrayType)
return new ArrayType(convertType(((PsiArrayType)t).getComponentType()));
if (t instanceof PsiWildcardType) {
// TODO: need proper wildcard expressions
PsiType bound = ((PsiWildcardType) t).getBound();
return bound != null ? convertType(bound,parent) : ObjectType$.MODULE$;
}
// Classes are not types in IntelliJ's version of the world, so we have to look up this class in envitems
if (t instanceof PsiClassType) {
PsiClass tcls = ((PsiClassType)t).resolve();
if (tcls == null) {
// ClassType cannot be resolved to a Class (probably because its class file is missing or the code is incomplete)
String name = ((PsiClassType)t).getClassName();
logger.warn("cannot resolve type " + t);
String qname = "";
boolean isfinal = false;
List<TypeArg> jargs = new SmartList<TypeArg>();
if (t instanceof PsiClassReferenceType) {
qname = ((PsiClassReferenceType)t).getReference().getQualifiedName();
if (t instanceof PsiModifierListOwner)
isfinal = ((PsiModifierListOwner) t).hasModifierProperty(PsiModifier.FINAL);
for (PsiType arg : ((PsiClassReferenceType)t).getParameters())
jargs.add((TypeArg)convertType(arg));
}
scala.collection.immutable.List<TypeArg> args = scala.collection.JavaConversions.asScalaBuffer(jargs).toList();
return new UnresolvedClassItem(name, qname.substring(qname.lastIndexOf('.')+1), args, isfinal).generic();
} else if (tcls instanceof PsiTypeParameter) {
return addTypeParam((PsiTypeParameter) tcls);
} else {
List<TypeArg> jparams = new SmartList<TypeArg>();
for (PsiType tp : ((PsiClassType)t).getParameters())
jparams.add((TypeArg) convertType(tp,parent));
scala.collection.immutable.List<TypeArg> params = scala.collection.JavaConversions.asScalaBuffer(jparams).toList();
//logger.debug("converting class " + t + " with type parameters " + params.mkString("[",",","]"));
ClassItem item = (ClassItem)addClass(tcls,false,false);
//logger.debug(" item: " + item + ": params " + item.tparams().mkString("[",",","]"));
assert params.size() == ((PsiClassType)t).getParameterCount();
if (item.arity() > 0 && params.isEmpty()) {
// This happens. For instance in java.lang.SecurityManager.getClassContext()
return item.raw();
} else if (parent == null) {
Item container = addContainer(place.containing(tcls));
return item.generic(params,((ParentItem)container).inside());
} else {
return item.generic(params,parent);
}
}
}
if (t == PsiType.BOOLEAN) return BooleanType$.MODULE$;
if (t == PsiType.INT) return IntType$.MODULE$;
if (t == PsiType.BYTE) return ByteType$.MODULE$;
if (t == PsiType.CHAR) return CharType$.MODULE$;
if (t == PsiType.FLOAT) return FloatType$.MODULE$;
if (t == PsiType.DOUBLE) return DoubleType$.MODULE$;
if (t == PsiType.LONG) return LongType$.MODULE$;
if (t == PsiType.SHORT) return ShortType$.MODULE$;
if (t == PsiType.VOID) return VoidType$.MODULE$;
throw new NotImplementedError("Unknown type: " + t.getCanonicalText() + " type " + t.getClass().getCanonicalName());
}
Item addContainer(PsiElement elem) {
{
Item i = lookup(elem);
if (i != null)
return i;
}
if (elem == null)
return tarski.Tarski.localPkg();
// local classes
if (elem instanceof PsiMethod)
return addMethod((PsiMethod) elem);
if (elem instanceof PsiClass)
return addClass((PsiClass) elem, false, false);
else if (elem instanceof PsiPackage) {
PsiPackage pkg = (PsiPackage)elem;
String qual = pkg.getQualifiedName();
Item base = tarski.Tarski.baseLookupJava(qual);
PackageItem item = base != null ? (PackageItem)base : new PackageItem(pkg.getName(), qual);
locals.put(pkg, item);
return item;
}
throw new RuntimeException("weird container "+elem);
}
static private class LazyTypeVar extends TypeVar {
private final Converter env;
private final PsiTypeParameter p;
// Lazy field
private RefType _hi;
LazyTypeVar(Converter env, PsiTypeParameter p) {
this.env = env;
this.p = p;
}
public String name() {
return p.getName();
}
public RefType lo() {
return NullType$.MODULE$;
}
public RefType hi() {
if (_hi == null) {
List<ClassType> supers = new SmartList<ClassType>();
for (PsiClassType e : p.getExtendsList().getReferencedTypes())
supers.add((ClassType)env.convertType(e));
_hi = tarski.Types.glb(JavaConversions.asScalaBuffer(supers).toList());
}
return _hi;
}
// Necessary only due to screwy Java/Scala interop
public boolean canEqual(Object x) { return this == x; }
public Some safe() { return new Some<RefType>(this); }
public TypeVar raw() { throw new NotImplementedError("Should never happen"); }
public int productArity() { throw new NotImplementedError("Should never happen"); }
public Object productElement(int i) { throw new NotImplementedError("Should never happen"); }
}
private TypeVar addTypeParam(PsiTypeParameter p) {
{
Item i = lookup(p);
if (i != null)
return (TypeVar)i;
}
// Use a maker to break recursion
TypeVar ti = new LazyTypeVar(this,p);
locals.put(p, ti);
return ti;
}
private static class LazyClass extends ClassItem {
private final Converter env;
private final PsiClass cls;
private final ParentItem _parent;
private final boolean _isFinal;
// Lazy fields
private scala.collection.immutable.List<TypeVar> _tparams;
private ClassType _base;
private scala.collection.immutable.List<RefType> _supers;
LazyClass(Converter env, PsiClass cls, ParentItem parent) {
this.env = env;
this.cls = cls;
this._parent = parent;
this._isFinal = cls.hasModifierProperty(PsiModifier.FINAL);
}
public String name() {
return cls.getName();
}
public scala.collection.immutable.List<TypeVar> tparams() {
if (_tparams == null)
_tparams = env.tparams(cls);
return _tparams;
}
public boolean isFinal() {
return _isFinal;
}
public boolean isClass() {
return !cls.isInterface();
}
public boolean isEnum() {
return cls.isEnum();
}
public ParentItem parent() {
return _parent;
}
public ClassType base() {
if (_base == null)
supers();
return _base;
}
public scala.collection.immutable.List<RefType> supers() {
if (_supers == null) {
PsiClass base = cls.getSuperClass();
ArrayList<ClassType> interfaces = new ArrayList<ClassType>();
ArrayList<RefType> all = new ArrayList<RefType>();
for (PsiClassType stype : cls.getSuperTypes()) {
ClassType sc = (ClassType)env.convertType(stype);
PsiClass stypeClass = stype.resolve();
if (base == stypeClass)
_base = sc;
all.add(sc);
}
if (_base == null) {
_base = ((ClassItem)env.addClass(base,false,false)).inside();
}
_supers = JavaConversions.asScalaBuffer(all).toList();
}
return _supers;
}
// Necessary only due to screwy Java/Scala interop
public boolean canEqual(Object x) { return this == x; }
public int productArity() { throw new NotImplementedError("Should never happen"); }
public Object productElement(int i) { throw new NotImplementedError("Should never happen"); }
}
TypeItem addClass(PsiClass cls, boolean recurse, boolean noProtected) {
{
Item i = lookup(cls);
if (i != null)
return (TypeItem)i;
}
if (cls instanceof PsiTypeParameter)
return addTypeParam((PsiTypeParameter)cls);
// Check for base classes
Item ciBase = tarski.Tarski.baseLookupJava(cls.getQualifiedName());
if (ciBase != null) {
locals.put(cls,ciBase);
return (TypeItem)ciBase;
}
// Make and add the class
final ParentItem parent = (ParentItem)addContainer(place.containing(cls));
ClassItem item = new LazyClass(this,cls,parent);
locals.put(cls, item);
// Add subthings recursively
if (recurse) {
// Force addition of type vars to the environment
item.tparams();
for (PsiField f : cls.getFields())
if (!place.isInaccessible(f,noProtected))
addField(f);
for (PsiMethod m : cls.getMethods())
if (!place.isInaccessible(m,noProtected))
addMethod(m);
for (PsiMethod m : cls.getConstructors())
if (!place.isInaccessible(m,noProtected))
addMethod(m);
for (PsiClass c : cls.getInnerClasses())
if (!place.isInaccessible(c,noProtected))
addClass(c,true,noProtected);
}
return item;
}
private scala.collection.immutable.List<TypeVar> tparams(PsiTypeParameterListOwner owner) {
List<TypeVar> jtparams = new ArrayList<TypeVar>();
for (PsiTypeParameter tp : owner.getTypeParameters())
jtparams.add(addTypeParam(tp));
return scala.collection.JavaConversions.asScalaBuffer(jtparams).toList();
}
private scala.collection.immutable.List<Type> params(PsiMethod method) {
List<Type> jparams = new SmartList<Type>();
for (PsiParameter p : method.getParameterList().getParameters())
jparams.add(convertType(p.getType()));
return scala.collection.JavaConversions.asScalaBuffer(jparams).toList();
}
private static class LazyConstructor extends ConstructorItem {
private final Converter env;
private final PsiMethod method;
private final scala.collection.immutable.List<TypeVar> _tparams;
// Lazy fields (null initially)
private ClassItem _parent;
private scala.collection.immutable.List<Type> _params;
LazyConstructor(Converter env, PsiMethod method, scala.collection.immutable.List<TypeVar> tparams) {
this.env = env;
this.method = method;
this._tparams = tparams;
}
// Core interface
public ClassItem parent() {
if (_parent == null)
_parent = (ClassItem)env.addClass(method.getContainingClass(),false,false);
return _parent;
}
public scala.collection.immutable.List<TypeVar> tparams() {
return _tparams;
}
public scala.collection.immutable.List<Type> params() {
if (_params == null)
_params = env.params(method);
return _params;
}
// Necessary only due to screwy Java/Scala interop
public boolean canEqual(Object x) { return this == x; }
public Parent simple() { throw new RuntimeException("For ConstructorItem, only inside is valid, not simple"); }
public Option<Parent> safe() { return new Some<Parent>(this); }
public scala.collection.immutable.Map<TypeVar,Option<RefType>> env() { return Map$.MODULE$.empty(); }
public int productArity() { throw new NotImplementedError("Should never happen"); }
public Object productElement(int i) { throw new NotImplementedError("Should never happen"); }
}
private static class LazyMethod extends MethodItem {
final Converter env;
final PsiMethod method;
private final scala.collection.immutable.List<TypeVar> _tparams;
private final boolean _isStatic;
// Lazy fields (null initially)
private ClassItem _parent;
private scala.collection.immutable.List<Type> _params;
private Type _retVal;
LazyMethod(Converter env, PsiMethod method, scala.collection.immutable.List<TypeVar> tparams) {
this.env = env;
this.method = method;
this._tparams = tparams;
this._isStatic = method.hasModifierProperty(PsiModifier.STATIC);
}
// Core interface
public String name() {
return method.getName();
}
public boolean isStatic() {
return _isStatic;
}
public ClassItem parent() {
if (_parent == null)
_parent = (ClassItem)env.addClass(method.getContainingClass(),false,false);
return _parent;
}
public scala.collection.immutable.List<TypeVar> tparams() {
return _tparams;
}
public scala.collection.immutable.List<Type> params() {
if (_params == null)
_params = env.params(method);
return _params;
}
public Type retVal() {
if (_retVal == null)
_retVal = env.convertType(method.getReturnType());
return _retVal;
}
// Necessary only due to screwy Java/Scala interop
public boolean canEqual(Object x) { return this == x; }
public Parent simple() { throw new RuntimeException("For ConstructorItem, only inside is valid, not simple"); }
public Option<Parent> safe() { return new Some<Parent>(this); }
public scala.collection.immutable.Map<TypeVar,Option<RefType>> env() { return Map$.MODULE$.empty(); }
public int productArity() { throw new NotImplementedError("Should never happen"); }
public Object productElement(int i) { throw new NotImplementedError("Should never happen"); }
}
CallableItem addMethod(PsiMethod method) {
{
Item i = lookup(method);
if (i != null)
return (CallableItem)i;
}
scala.collection.immutable.List<TypeVar> tparams = this.tparams(method);
ClassItem cls = (ClassItem)addClass(method.getContainingClass(),false,false);
Option<String> qual = tarski.Items.memberQualifiedName(cls,method.getName());
Item base = qual.isEmpty() ? null : tarski.Tarski.baseLookupJava(qual.get());
CallableItem item = base != null ? (CallableItem)base
: method.isConstructor() ? new LazyConstructor(this,method,tparams)
: new LazyMethod(this,method,tparams);
locals.put(method,item);
return item;
}
private static class LazyField extends FieldItem {
private final Converter env;
private final PsiField f;
private final boolean _isFinal;
// Lazy fields
private Type _inside;
LazyField(Converter env, PsiField f, boolean isFinal) {
this.env = env;
this.f = f;
this._isFinal = isFinal;
}
public String name() {
return f.getName();
}
public boolean isFinal() {
return _isFinal;
}
public Type inside() {
if (_inside == null) {
try {
_inside = env.convertType(f.getType());
} catch (Exception e) {
throw new RuntimeException("LazyField::inside failed: field "+qualifiedName().get()+": "+e.getMessage());
}
}
return _inside;
}
public ClassItem parent() {
return (ClassItem)env.addClass(f.getContainingClass(),false,false);
}
// Necessary only due to screwy Java/Scala interop
public boolean canEqual(Object x) { return this == x; }
public int productArity() { throw new NotImplementedError("Should never happen"); }
public Object productElement(int i) { throw new NotImplementedError("Should never happen"); }
}
private static class LazyStaticField extends StaticFieldItem {
private final Converter env;
private final PsiField f;
private final boolean _isFinal;
// Lazy fields
private Type _ty;
LazyStaticField(Converter env, PsiField f, boolean isFinal) {
this.env = env;
this.f = f;
this._isFinal = isFinal;
}
public String name() {
return f.getName();
}
public boolean isFinal() {
return _isFinal;
}
public Type ty() {
if (_ty == null)
_ty = env.convertType(f.getType());
return _ty;
}
public ClassItem parent() {
return (ClassItem)env.addClass(f.getContainingClass(),false,false);
}
// Necessary only due to screwy Java/Scala interop
public boolean canEqual(Object x) { return this == x; }
public int productArity() { throw new NotImplementedError("Should never happen"); }
public Object productElement(int i) { throw new NotImplementedError("Should never happen"); }
}
Value addField(PsiField f) {
{
Item i = lookup(f);
if (i != null)
return (Value)i;
}
Value v;
if (f instanceof PsiEnumConstant) {
ClassItem c = (ClassItem)addClass(f.getContainingClass(),false,false);
v = new EnumConstantItem(f.getName(),c);
} else {
boolean isFinal = f.hasModifierProperty(PsiModifier.FINAL);
v = (f.hasModifierProperty(PsiModifier.STATIC) ? new LazyStaticField(this,f,isFinal)
: new LazyField(this,f,isFinal));
}
locals.put(f,v);
return v;
}
} |
package com.namelessdev.mpdroid;
import java.util.ArrayList;
import java.util.List;
import org.a0z.mpd.MPDServerException;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.Music;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.namelessdev.mpdroid.MPDAsyncHelper.AsyncExecListener;
public class BrowseActivity extends ListActivity implements OnMenuItemClickListener, AsyncExecListener {
protected int iJobID = -1;
protected ProgressDialog pd;
public static final int MAIN = 0;
public static final int PLAYLIST = 3;
public static final int ADD = 0;
public static final int ADDNREPLACE = 1;
protected List<String> items = null;
String context;
int irAdd, irAdded;
public BrowseActivity(int rAdd, int rAdded, String pContext) {
super();
irAdd = rAdd;
irAdded = rAdded;
context = pContext;
}
@Override
protected void onStart() {
super.onStart();
MPDApplication app = (MPDApplication) getApplicationContext();
app.setActivity(this);
}
@Override
protected void onStop() {
super.onStop();
MPDApplication app = (MPDApplication) getApplicationContext();
app.unsetActivity(this);
}
public void UpdateList() {
if (pd == null) {
pd = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading));
}
MPDApplication app = (MPDApplication) getApplication();
// Loading Artists asynchronous...
app.oMPDAsyncHelper.addAsyncExecListener(this);
iJobID = app.oMPDAsyncHelper.execAsync(new Runnable() {
@Override
public void run() {
asyncUpdate();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, MAIN, 0, R.string.mainMenu).setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, PLAYLIST, 1, R.string.playlist).setIcon(R.drawable.ic_menu_pmix_playlist);
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = null;
switch (item.getItemId()) {
case MAIN:
i = new Intent(this, MainMenuActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
return true;
case PLAYLIST:
i = new Intent(this, PlaylistActivity.class);
startActivityForResult(i, PLAYLIST);
return true;
}
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(items.get((int) info.id).toString());
MenuItem addItem = menu.add(ContextMenu.NONE, ADD, 0, getResources().getString(irAdd));
addItem.setOnMenuItemClickListener(this);
MenuItem addAndReplaceItem = menu.add(ContextMenu.NONE, ADDNREPLACE, 0, R.string.addAndReplace);
addAndReplaceItem.setOnMenuItemClickListener(this);
}
protected void Add(String item) {
try {
MPDApplication app = (MPDApplication) getApplication();
ArrayList<Music> songs = new ArrayList<Music>(app.oMPDAsyncHelper.oMPD.find(context, item));
app.oMPDAsyncHelper.oMPD.getPlaylist().add(songs);
MainMenuActivity.notifyUser(String.format(getResources().getString(irAdded), item), this);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case ADDNREPLACE:
try {
MPDApplication app = (MPDApplication) getApplication();
String status = app.oMPDAsyncHelper.oMPD.getStatus().getState();
app.oMPDAsyncHelper.oMPD.stop();
app.oMPDAsyncHelper.oMPD.getPlaylist().clear();
Add(items.get((int) info.id).toString());
if (status.equals(MPDStatus.MPD_STATE_PLAYING)) {
app.oMPDAsyncHelper.oMPD.play();
}
// TODO Need to find some way of updating the main view here.
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case ADD:
Add(items.get((int) info.id).toString());
break;
}
return false;
}
protected void asyncUpdate() {
}
/**
* Update the view from the items list if items is set.
*/
public void updateFromItems() {
if (items != null) {
ListViewButtonAdapter<String> listAdapter = new ListViewButtonAdapter<String>(this, android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter);
}
}
@Override
public void asyncExecSucceeded(int jobID) {
if (iJobID == jobID) {
updateFromItems();
try {
pd.dismiss();
} catch (Exception e) {
// I know that catching everything is bad, but do you want your program to crash because it couldn't stop an already stopped
// popup window ? No.
// So, do nothing.
}
}
}
} |
package org.voovan.network;
import org.voovan.tools.buffer.ByteBufferChannel;
import org.voovan.tools.TEnv;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingDeque;
public class HeartBeat {
private byte[] ping;
private byte[] pong;
private boolean isFirstBeat = true;
private LinkedBlockingDeque<Integer> queue;
private int failedCount = 0;
/**
*
* @param ping ping
* @param pong pong
* @return
*/
private HeartBeat(String ping, String pong){
this.ping = ping.getBytes();
this.pong = pong.getBytes();
queue = new LinkedBlockingDeque<Integer>();
}
/**
*
* @return
*/
private LinkedBlockingDeque<Integer> getQueue() {
return queue;
}
/**
* ping
* @return ping
*/
public byte[] getPing() {
return ping;
}
/**
* pong
* @return pong
*/
public byte[] getPong() {
return pong;
}
/**
*
*
* @return
*/
public int getFailedCount() {
return failedCount;
}
/**
*
* @param session
* @param byteBufferChannel ByteBufferChannel
*/
public static void interceptHeartBeat(IoSession session, ByteBufferChannel byteBufferChannel){
if(session==null || byteBufferChannel==null){
return;
}
HeartBeat heartBeat = session.getHeartBeat();
if (heartBeat != null && byteBufferChannel.size() > 0) {
if (heartBeat != null) {
if (byteBufferChannel.startWith(heartBeat.getPing())) {
byteBufferChannel.shrink(0, heartBeat.getPing().length);
heartBeat.getQueue().addLast(1);
return;
}
if (byteBufferChannel.startWith(heartBeat.getPong())) {
byteBufferChannel.shrink(0, heartBeat.getPong().length);
heartBeat.getQueue().addLast(2);
return;
}
}
}
}
/**
*
* @param session
* @return true:,false:
*/
public static boolean beat(IoSession session) {
HeartBeat heartBeat = session.getHeartBeat();
boolean result = heartBeat.isFirstBeat || !heartBeat.getQueue().isEmpty();
// EventRunnerGroup
session.getSocketSelector().addChooseEvent(3, ()->{
if(!session.isConnected()){
return false;
}
if (heartBeat.isFirstBeat) {
heartBeat.isFirstBeat = false;
if (session.socketContext().getConnectModel() == ConnectModel.CLIENT) {
TEnv.sleep(session.getIdleInterval());
session.send(ByteBuffer.wrap(heartBeat.ping));
session.flush();
}
return true;
}
int waitCount = 0;
while (heartBeat.getQueue().size() == 0) {
TEnv.sleep(1);
waitCount++;
if (waitCount >= session.getIdleInterval() * 1000) {
break;
}
}
if (heartBeat.getQueue().size() > 0) {
int beatType = heartBeat.getQueue().pollFirst();
if (beatType == 1) {
session.send(ByteBuffer.wrap(heartBeat.pong));
session.flush();
heartBeat.failedCount = 0;
return true;
} else if (beatType == 2) {
session.send(ByteBuffer.wrap(heartBeat.ping));
session.flush();
heartBeat.failedCount = 0;
return true;
} else {
heartBeat.failedCount++;
return false;
}
}
heartBeat.failedCount++;
return false;
});
return result;
}
/**
* Session
* @param session
* @param ping ping
* @param pong pong
* @return
*/
public static HeartBeat attachSession(IoSession session, String ping, String pong){
HeartBeat heartBeat = null;
if(session.getHeartBeat()==null) {
heartBeat = new HeartBeat(ping, pong);
session.setHeartBeat(heartBeat);
} else{
heartBeat = session.getHeartBeat();
}
return heartBeat;
}
/**
* Session
* PING, PONG
* @param session Socket
* @param connectModel , PING ,,
* @return
*/
public static HeartBeat attachSession(IoSession session, int connectModel){
HeartBeat heartBeat = null;
if(session.getHeartBeat()==null) {
heartBeat = new HeartBeat("PING", "PONG");
session.setHeartBeat(heartBeat);
}else{
heartBeat = session.getHeartBeat();
}
return heartBeat;
}
} |
package owltools.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.coode.owlapi.obo.parser.OBOOntologyFormat;
import org.obolibrary.macro.ManchesterSyntaxTool;
import org.semanticweb.owlapi.expression.ParserException;
import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat;
import org.semanticweb.owlapi.io.OWLXMLOntologyFormat;
import org.semanticweb.owlapi.io.RDFXMLOntologyFormat;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAnnotation;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLNamedObject;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyFormat;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import owltools.gaf.inference.TaxonConstraintsEngine;
import owltools.gfx.GraphicsConfig;
import owltools.gfx.OWLGraphLayoutRenderer;
import owltools.graph.OWLGraphEdge;
import owltools.graph.OWLGraphWrapper;
import owltools.io.OWLGsonRenderer;
import owltools.io.OWLPrettyPrinter;
import owltools.io.ParserWrapper;
import owltools.mooncat.Mooncat;
import owltools.sim2.FastOwlSim;
import owltools.sim2.OwlSim;
import owltools.sim2.OwlSim.ScoreAttributeSetPair;
import owltools.sim2.SimJSONEngine;
import owltools.sim2.SimpleOwlSim;
import owltools.sim2.SimpleOwlSim.Metric;
import owltools.sim2.SimpleOwlSim.ScoreAttributePair;
import owltools.sim2.UnknownOWLClassException;
import owltools.vocab.OBOUpperVocabulary;
public class OWLHandler {
private static Logger LOG = Logger.getLogger(OWLHandler.class);
private OWLGraphWrapper graph;
private HttpServletResponse response;
private HttpServletRequest request;
private OWLPrettyPrinter owlpp;
private OWLServer owlserver;
private String format = null;
private String commandName;
private OwlSim sos;
// consider replacing with a generic result list
private Set<OWLAxiom> cachedAxioms = new HashSet<OWLAxiom>();
private Set<OWLObject> cachedObjects = new HashSet<OWLObject>();
// not yet implemented --
// for owl, edges are translated to expressions.
// axioms are added to an ontology
// expressions? temp ontology?
public enum ResultType {
AXIOM, ENTITY, EDGE, ONTOLOGY
}
public enum Param {
id, iri, label, taxid, expression,
format, direct, reflexive, target,
limit,
ontology,
classId,
individualId,
propertyId,
fillerId,
a, b, modelId, db
}
public OWLHandler(OWLServer owlserver, OWLGraphWrapper graph, HttpServletRequest request, HttpServletResponse response) throws IOException {
super();
this.owlserver = owlserver;
this.graph = graph;
this.request = request;
this.response = response;
//this.writer = response.getWriter();
this.owlpp = new OWLPrettyPrinter(graph);
}
public String getFormat() {
String fmtParam = getParam(Param.format);
if (fmtParam != null && !fmtParam.equals(""))
return fmtParam;
if (format == null)
return "txt";
return format;
}
public void setOwlSim(OwlSim sos2) {
this.sos = sos2;
}
public void setFormat(String format) {
this.format = format;
}
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
// COMMANDS
public void topCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
if (isHelp()) {
info("Basic metadata about current ontology"); // TODO - json
return;
}
headerHTML();
outputLine("<h1>OntologyID: "+this.getOWLOntology().getOntologyID()+"</h2>");
outputLine("<ul>");
for (OWLAnnotation ann : getOWLOntology().getAnnotations()) {
outputLine("<li>");
output(ann.getProperty());
outputLine("<b>"+ann.getValue().toString()+"</b>");
outputLine("</li>");
}
outputLine("</ul>");
}
public void helpCommand() throws IOException {
headerHTML();
List<String> commands = new ArrayList<String>();
outputLine("<ul>");
for (Method m : this.getClass().getMethods()) {
String mn = m.getName();
if (mn.endsWith("Command")) {
String c = mn.replace("Command", "");
commands.add(c);
outputLine("<li>"+c+"</li>");
}
}
outputLine("</ul>");
}
/**
* Params: direct, (id | expression)
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
* @throws ParserException
*/
public void getSubClassesCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, ParserException {
headerOWL();
boolean direct = getParamAsBoolean(Param.direct, false);
OWLReasoner r = getReasoner();
OWLClassExpression cls = this.resolveClassExpression();
LOG.info("finding subclasses of: "+cls+" using "+r);
int n = 0;
for (OWLClass sc : r.getSubClasses(cls, direct).getFlattened()) {
output(sc);
n++;
}
if (getParamAsBoolean(Param.reflexive, true)) {
for (OWLClass sc : r.getEquivalentClasses(cls)) {
output(sc);
}
n++;
}
LOG.info("results: "+n);
}
/**
* Params: direct, (id | expression)
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
* @throws ParserException
*/
public void getSuperClassesCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, ParserException {
headerOWL();
boolean direct = getParamAsBoolean(Param.direct, false);
OWLReasoner r = getReasoner();
OWLClassExpression cls = this.resolveClassExpression();
LOG.info("finding superclasses of: "+cls);
LOG.info("R:"+r.getSuperClasses(cls, direct));
for (OWLClass sc : r.getSuperClasses(cls, direct).getFlattened()) {
output(sc);
}
if (getParamAsBoolean(Param.reflexive, true)) {
for (OWLClass sc : r.getEquivalentClasses(cls)) {
output(sc);
}
}
}
/**
* Params: id
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
* @throws ParserException
*/
public void getAxiomsCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, ParserException {
headerOWL();
boolean direct = getParamAsBoolean(Param.direct, false);
OWLObject obj = this.resolveEntity();
LOG.info("finding axioms about: "+obj);
Set<OWLAxiom> axioms = new HashSet<OWLAxiom>();
if (obj instanceof OWLClass) {
axioms.addAll(graph.getSourceOntology().getAxioms((OWLClass)obj));
}
if (obj instanceof OWLIndividual) {
axioms.addAll(graph.getSourceOntology().getAxioms((OWLIndividual)obj));
}
if (obj instanceof OWLObjectProperty) {
axioms.addAll(graph.getSourceOntology().getAxioms((OWLObjectProperty)obj));
}
for (OWLAxiom ax : axioms) {
output(ax);
}
}
/**
* Params: direct
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
*/
public void allSubClassOfCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
headerOWL();
boolean direct = getParamAsBoolean(Param.direct, true);
OWLReasoner r = getReasoner();
for (OWLClass c : getOWLOntology().getClassesInSignature(true)) {
for (OWLClass sc : r.getSuperClasses(c, direct).getFlattened()) {
output(graph.getDataFactory().getOWLSubClassOfAxiom(c, sc));
}
}
}
public void getOutgoingEdgesCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException {
if (isHelp()) {
info("Returns paths to reachable nodes in ontology graph");
return;
}
headerOWL();
boolean isClosure = getParamAsBoolean("closure", true);
boolean isReflexive = getParamAsBoolean("reflexive", true);
OWLObject obj = this.resolveEntity();
LOG.info("finding edges from: "+obj);
for (OWLGraphEdge e : graph.getOutgoingEdges(obj,isClosure,isReflexive)) {
output(e);
}
}
/**
* information about an ontology object (class, property, individual)
*
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
*/
public void aboutCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
if (isHelp()) {
info("Returns logical relationships and metadata associated with an ontology object");
return;
}
headerOWL();
String id = this.getParam(Param.id);
OWLClass cls = graph.getOWLClassByIdentifier(id);
for (OWLAxiom axiom : getOWLOntology().getAxioms(cls)) {
output(axiom);
}
for (OWLAxiom axiom : getOWLOntology().getAnnotationAssertionAxioms(cls.getIRI())) {
output(axiom);
}
}
/**
* visualize using QuickGO graphdraw.
*
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
*/
public void qvizCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
String fmt = "png";
headerImage(fmt);
GraphicsConfig gfxCfg = new GraphicsConfig();
Set<OWLObject> objs = resolveEntityList();
OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(graph);
r.graphicsConfig = gfxCfg;
r.addObjects(objs);
r.renderImage(fmt, response.getOutputStream());
}
/**
* generates a sub-ontology consisting only of classes specified using the id param.
* If the include_ancestors param is true, then the transitive closure of the input classes is
* included. otherwise, intermediate classes are excluded and paths are filled.
*
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
* @see Mooncat#makeMinimalSubsetOntology(Set, IRI)
*/
public void makeSubsetOntologyCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
headerOWL();
Set<OWLClass> objs = resolveClassList();
Set<OWLClass> tObjs = new HashSet<OWLClass>();
if (getParamAsBoolean("include_ancestors")) {
// TODO - more more efficient
for (OWLClass obj : objs) {
for (OWLObject t : graph.getAncestorsReflexive(obj)) {
tObjs.add((OWLClass)t);
}
}
}
else {
tObjs = objs;
}
Mooncat mooncat;
mooncat = new Mooncat(graph);
OWLOntology subOnt =
mooncat.makeMinimalSubsetOntology(tObjs,
IRI.create("http://purl.obolibrary.org/obo/temporary"));
for (OWLAxiom axiom : subOnt.getAxioms()) {
output(axiom); // TODO
}
graph.getManager().removeOntology(subOnt);
}
/**
* tests which of a set of input classes (specified using id) is applicable for a set of taxa
* (specified using taxid)
*
* @throws OWLOntologyCreationException
* @throws OWLOntologyStorageException
* @throws IOException
*/
public void isClassApplicableForTaxonCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
headerOWL();
TaxonConstraintsEngine tce = new TaxonConstraintsEngine(graph);
Set<OWLClass> testClsSet = resolveClassList();
Set<OWLClass> testTaxSet = resolveClassList(Param.taxid);
for (OWLClass testTax : testTaxSet) {
Set<OWLObject> taxAncs = graph.getAncestorsReflexive(testTax);
LOG.info("Tax ancs: "+taxAncs);
for (OWLClass testCls : testClsSet) {
Set<OWLGraphEdge> edges = graph.getOutgoingEdgesClosure(testCls);
boolean isOk = tce.isClassApplicable(testCls, testTax, edges, taxAncs);
// TODO - other formats
output(testCls);
print("\t");
output(testTax);
outputLine("\t"+isOk);
}
}
}
// sim2
private OwlSim getOWLSim() throws UnknownOWLClassException {
if (owlserver.sos == null) {
LOG.info("Creating sim object"); // TODO - use factory
owlserver.sos = new FastOwlSim(graph.getSourceOntology());
owlserver.sos.createElementAttributeMapFromOntology();
}
return owlserver.sos;
}
public void getSimilarClassesCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Returns semantically similar classes using OWLSim2");
return;
}
headerOWL();
OWLClass a = this.resolveClass();
OwlSim sos = getOWLSim();
List<ScoreAttributeSetPair> saps = new ArrayList<ScoreAttributeSetPair>();
for (OWLClass b : this.getOWLOntology().getClassesInSignature()) {
double score = sos.getAttributeJaccardSimilarity(a, b);
saps.add(new ScoreAttributeSetPair(score, b) );
}
Collections.sort(saps);
int limit = 100;
int n=0;
for (ScoreAttributeSetPair sap : saps) {
output(sap.getArbitraryAttributeClass());
this.outputLine("score="+sap.score); // todo - jsonify
n++;
if (n > limit) {
break;
}
}
}
public void getSimilarIndividualsCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Returns matching individuals using OWLSim2");
return;
}
headerOWL();
OWLNamedIndividual i = (OWLNamedIndividual) this.resolveEntity();
LOG.info("i="+i);
if (i == null) {
LOG.error("Could not resolve id");
// TODO - throw
return;
}
OwlSim sos = getOWLSim();
List<ScoreAttributeSetPair> saps = new Vector<ScoreAttributeSetPair>();
for (OWLNamedIndividual j : this.getOWLOntology().getIndividualsInSignature()) {
// TODO - make configurable
ScoreAttributeSetPair match = sos.getSimilarityMaxIC(i, j);
saps.add(match);
}
Collections.sort(saps);
int limit = 100; // todo - configurable
int n=0;
for (ScoreAttributeSetPair sap : saps) {
//output(sap.attributeClass); TODO
this.outputLine("score="+sap.score); // todo - jsonify
n++;
if (n > limit) {
break;
}
}
}
public void getLowestCommonSubsumersCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Returns LCSs using sim2");
return;
}
headerOWL();
OwlSim sos = getOWLSim();
Set<OWLObject> objs = this.resolveEntityList();
if (objs.size() == 2) {
Iterator<OWLObject> oit = objs.iterator();
OWLClass a = (OWLClass) oit.next();
OWLClass b = (OWLClass) oit.next();
Set<Node<OWLClass>> lcsNodes = sos.getNamedCommonSubsumers(a, b);
for (Node<OWLClass> n : lcsNodes) {
for (OWLClass c : n.getEntities()) {
output(c);
}
}
}
else {
// TODO - throw
}
}
public void compareAttributeSetsCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Returns LCSs and their ICs for two sets of attributes (e.g. phenotypes for disease vs model) using sim2");
return;
}
headerText();
OwlSim sos = getOWLSim();
Set<OWLClass> objAs = this.resolveClassList(Param.a);
Set<OWLClass> objBs = this.resolveClassList(Param.b);
LOG.info("Comparison set A:"+objAs);
LOG.info("Comparison set B:"+objBs);
SimJSONEngine sj = new SimJSONEngine(graph,sos);
String jsonStr = sj.compareAttributeSetPair(objAs, objBs, true);
LOG.info("Finished comparison");
response.getWriter().write(jsonStr);
}
public void searchByAttributeSetCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Entities that have a similar attribute profile to the specified one, using sim2");
return;
}
headerText();
OwlSim sos = getOWLSim();
Set<OWLClass> atts = this.resolveClassList(Param.a);
SimJSONEngine sj = new SimJSONEngine(graph,sos);
String targetIdSpace = getParam(Param.target);
Integer limit = getParamAsInteger(Param.limit, 1000);
String jsonStr = sj.search(atts, targetIdSpace, true, limit);
LOG.info("Finished comparison");
response.getWriter().write(jsonStr);
}
public void getAnnotationSufficiencyScoreCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Specificity score for a set of annotations");
return;
}
headerText();
OwlSim sos = getOWLSim();
Set<OWLClass> atts = this.resolveClassList(Param.a);
SimJSONEngine sj = new SimJSONEngine(graph,sos);
String jsonStr = sj.getAnnotationSufficiencyScore(atts);
LOG.info("Finished getAnnotationSufficiencyScore");
response.getWriter().write(jsonStr);
}
public void getAttributeInformationProfileCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("Attribute Profile Information");
return;
}
headerText();
OwlSim sos = getOWLSim();
Set<OWLClass> atts = this.resolveClassList(Param.a);
SimJSONEngine sj = new SimJSONEngine(graph,sos);
String jsonStr = sj.getAttributeInformationProfile(atts);
LOG.info("Finished getAttributeInformationProfileCommand");
response.getWriter().write(jsonStr);
}
// WRITE/UPDATE OPERATIONS
@Deprecated
public void assertTypeCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("generates ClassAssertion");
return;
}
OWLOntology ont = resolveOntology(Param.ontology);
OWLClass c = resolveClass(Param.classId);
OWLIndividual i = resolveIndividual(Param.individualId);
addAxiom(ont, graph.getDataFactory().getOWLClassAssertionAxiom(c, i));
String jsonStr = "";
response.getWriter().write(jsonStr);
}
@Deprecated
public void assertFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("generates ClassAssertion");
return;
}
OWLOntology ont = resolveOntology(Param.ontology);
OWLIndividual i = resolveIndividual(Param.individualId);
OWLIndividual j = resolveIndividual(Param.fillerId);
OWLObjectProperty p = resolveObjectProperty(Param.propertyId);
addAxiom(ont, graph.getDataFactory().getOWLObjectPropertyAssertionAxiom(p, i, j));
String jsonStr = "";
response.getWriter().write(jsonStr);
}
@Deprecated
public void deleteFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("generates ClassAssertion");
return;
}
OWLOntology ont = resolveOntology(Param.ontology);
OWLIndividual i = resolveIndividual(Param.individualId);
OWLIndividual j = resolveIndividual(Param.fillerId);
OWLObjectProperty p = resolveObjectProperty(Param.propertyId);
for (OWLObjectPropertyAssertionAxiom ax : ont.getAxioms(AxiomType.OBJECT_PROPERTY_ASSERTION)) {
if (ax.getSubject().equals(i)) {
if (p == null || ax.getProperty().equals(p)) {
if (j == null || ax.getObject().equals(j)) {
removeAxiom(ont, graph.getDataFactory().getOWLObjectPropertyAssertionAxiom(p, i, j));
}
}
}
}
String jsonStr = "";
response.getWriter().write(jsonStr);
}
public void returnJSON(Object obj) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String js = gson.toJson(obj);
response.getWriter().write(js);
}
public void assertEnabledByCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("generates ClassAssertion");
return;
}
OWLOntology ont = resolveOntology(Param.ontology);
OWLIndividual i = resolveIndividual(Param.individualId);
OWLClass j = resolveClass(Param.fillerId);
OWLObjectProperty p =
OBOUpperVocabulary.GOREL_enabled_by.getObjectProperty(graph.getDataFactory());
addSomeValuesFromClassAssertion(ont, i, j, p);
String jsonStr = "";
response.getWriter().write(jsonStr);
}
public void assertOccursInCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException {
if (isHelp()) {
info("generates ClassAssertion");
return;
}
OWLOntology ont = resolveOntology(Param.ontology);
OWLIndividual i = resolveIndividual(Param.individualId);
OWLClass j = resolveClass(Param.fillerId);
OWLObjectProperty p =
OBOUpperVocabulary.BFO_occurs_in.getObjectProperty(graph.getDataFactory());
addSomeValuesFromClassAssertion(ont, i, j, p);
String jsonStr = "";
response.getWriter().write(jsonStr);
}
// END OF COMMANDS
// UTIL
private void addSomeValuesFromClassAssertion(OWLOntology ont,
OWLIndividual i, OWLClass j, OWLObjectProperty p) {
OWLDataFactory df = ont.getOWLOntologyManager().getOWLDataFactory();
OWLObjectSomeValuesFrom svf =
df.getOWLObjectSomeValuesFrom(p, j);
addAxiom(ont, df.getOWLClassAssertionAxiom(svf, i));
}
private void addAxiom(OWLOntology ont,
OWLAxiom ax) {
LOG.info("Added: " + ax);
// TODO - rollbacks
graph.getManager().addAxiom(ont, ax);
}
private void removeAxiom(OWLOntology ont,
OWLAxiom ax) {
LOG.info("Removed: " + ax);
// TODO - rollbacks
graph.getManager().removeAxiom(ont, ax);
}
private OWLObject resolveEntity() {
String id = getParam(Param.id);
if (!id.contains(":"))
id = id.replace("_", ":");
return graph.getOWLObjectByIdentifier(id);
}
private OWLClass resolveClass() {
String id = getParam(Param.id);
return graph.getOWLClassByIdentifier(id);
}
private OWLClass resolveClass(Param p) {
String id = getParam(p);
return graph.getOWLClassByIdentifier(id);
}
private OWLClass resolveClassByLabel() {
String id = getParam(Param.label);
return (OWLClass) graph.getOWLObjectByLabel(id);
}
private OWLClassExpression resolveClassExpression() throws ParserException {
if (hasParam(Param.id)) {
return resolveClass();
}
String expr = getParam(Param.expression);
ManchesterSyntaxTool parser = new ManchesterSyntaxTool(graph.getSourceOntology(), graph.getSupportOntologySet());
return parser.parseManchesterExpression(expr);
}
private OWLIndividual resolveIndividual(Param p) {
String id = getParam(p);
return graph.getOWLIndividualByIdentifier(id);
}
private OWLObjectProperty resolveObjectProperty(Param p) {
String id = getParam(p);
return graph.getOWLObjectPropertyByIdentifier(id);
}
private Set<OWLObject> resolveEntityList() {
return resolveEntityList(Param.id);
}
private Set<OWLObject> resolveEntityList(Param p) {
String[] ids = getParams(p);
Set<OWLObject> objs = new HashSet<OWLObject>();
for (String id : ids) {
// TODO - unresolvable
objs.add(graph.getOWLObjectByIdentifier(id));
}
return objs;
}
private Set<OWLClass> resolveClassList() {
return resolveClassList(Param.id);
}
private OWLOntology resolveOntology(Param p) {
String oid = getParam(p);
for (OWLOntology ont : graph.getManager().getOntologies()) {
String iri = ont.getOntologyID().getOntologyIRI().toString();
// HACK
if (iri.endsWith("/"+oid)) {
return ont;
}
}
return null;
}
private Set<OWLClass> resolveClassList(Param p) {
String[] ids = getParams(p);
Set<OWLClass> objs = new HashSet<OWLClass>();
LOG.info("Param "+p+" IDs: "+ids);
for (String id : ids) {
OWLClass c = graph.getOWLClassByIdentifier(id);
if (c == null) {
// TODO - strict mode - for now we include unresolvable classes
IRI iri = graph.getIRIByIdentifier(id);
c = graph.getDataFactory().getOWLClass(iri);
}
objs.add(c);
}
LOG.info("Num objs: "+objs.size());
return objs;
}
public void info(String msg) throws IOException {
headerHTML();
outputLine("<h2>Command: "+this.getCommandName()+"</h2>");
outputLine(msg);
}
public void headerHTML() {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
}
public void headerText() {
response.setContentType("text/plain;charset-utf-8");
response.setStatus(HttpServletResponse.SC_OK);
}
public void headerImage(String fmt) {
response.setContentType("image/"+fmt);
response.setStatus(HttpServletResponse.SC_OK);
}
public void headerOWL() {
if (isOWLOntologyFormat()) {
LOG.info("using OWL ontology header");
OWLOntologyFormat ofmt = this.getOWLOntologyFormat();
if (ofmt instanceof RDFXMLOntologyFormat) {
response.setContentType("application/rdf+xml;charset-utf-8");
}
else if (ofmt instanceof OWLXMLOntologyFormat) {
response.setContentType("application/xml;charset-utf-8");
}
else {
response.setContentType("text/plain;charset-utf-8");
}
}
else {
response.setContentType("text/plain;charset-utf-8");
}
response.setStatus(HttpServletResponse.SC_OK);
}
private void output(OWLAxiom axiom) throws IOException {
String fmt = getFormat();
if (fmt == null)
fmt = "";
if (fmt.equals("plain"))
outputLine(axiom.toString());
else if (isOWLOntologyFormat(fmt)) {
cache(axiom);
}
else if (fmt.equals("json")) {
cache(axiom);
}
else
outputLine(owlpp.render(axiom));
}
private void outputLine(String s) throws IOException {
getWriter().println(s);
}
private void print(String s) throws IOException {
getWriter().print(s);
}
private void output(OWLObject obj) throws IOException {
String fmt = getFormat();
if (fmt.equals("pretty"))
outputLine(owlpp.render(obj));
else if (fmt.equals("json")) {
//JSONPrinter jsonp = new JSONPrinter(response.getWriter());
//jsonp.render(obj);
cache(obj);
}
else if (isOWLOntologyFormat()) {
// TODO - place objects into ontology, eg as subclass of result
outputLine(obj.toString());
}
else {
// TODO - do this more generically, e.g. within owlpp
if (getParam("idstyle") != null && obj instanceof OWLNamedObject) {
if (getParam("idstyle").toLowerCase().equals("obo")) {
outputLine(graph.getIdentifier(obj));
}
else {
outputLine(obj.toString());
}
}
else
print(obj.toString());
}
}
private void output(OWLGraphEdge e) throws IOException {
if (isOWLOntologyFormat() || getFormat().equals("json")) {
// todo - json format for edge
OWLObject x = graph.edgeToTargetExpression(e);
LOG.info("EdgeToX:"+x);
output(x);
}
else {
outputLine(owlpp.render(e)); // todo - cache
}
}
/*
private void cache(OWLAxiom axiom) {
cachedAxioms.add(axiom);
}
*/
private void cache(OWLObject obj) {
cachedObjects.add(obj);
}
// when the result list is a collection of owl objects, we wait until
// we have collected everything and then generate the results such that
// the result conforms to the specified owl syntax.
// TODO - redo this. Instead generate result objects
public void printCachedObjects() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
if (getFormat().equals("json")) {
OWLGsonRenderer jsonp = new OWLGsonRenderer(response.getWriter());
if (cachedObjects.size() > 0) {
jsonp.render(cachedObjects);
}
else {
jsonp.render(cachedAxioms);
}
}
else {
// ontology format
if (cachedAxioms.size() == 0)
return;
OWLOntology tmpOnt = getTemporaryOntology();
graph.getManager().addAxioms(tmpOnt, cachedAxioms);
OWLOntologyFormat ofmt = getOWLOntologyFormat();
LOG.info("Format:"+ofmt);
ParserWrapper pw = new ParserWrapper();
//graph.getManager().saveOntology(tmpOnt, ofmt, response.getOutputStream());
pw.saveOWL(tmpOnt, ofmt, response.getOutputStream(), null);
graph.getManager().removeOntology(tmpOnt);
cachedAxioms = new HashSet<OWLAxiom>();
}
}
// always remember to remove
private OWLOntology getTemporaryOntology() throws OWLOntologyCreationException {
UUID uuid = UUID.randomUUID();
IRI iri = IRI.create("http://purl.obolibrary.org/obo/temporary/"+uuid.toString());
//OWLOntology tmpOnt = graph.getManager().getOntology(iri);
//if (iri == null)
return graph.getManager().createOntology(iri);
}
private OWLOntologyFormat getOWLOntologyFormat() {
return getOWLOntologyFormat(getFormat());
}
private OWLOntologyFormat getOWLOntologyFormat(String fmt) {
OWLOntologyFormat ofmt = null;
fmt = fmt.toLowerCase();
if (fmt.equals("rdfxml"))
ofmt = new RDFXMLOntologyFormat();
else if (fmt.equals("owl"))
ofmt = new RDFXMLOntologyFormat();
else if (fmt.equals("rdf"))
ofmt = new RDFXMLOntologyFormat();
else if (fmt.equals("owx"))
ofmt = new OWLXMLOntologyFormat();
else if (fmt.equals("owf"))
ofmt = new OWLFunctionalSyntaxOntologyFormat();
else if (fmt.equals("obo"))
ofmt = new OBOOntologyFormat();
return ofmt;
}
private boolean isOWLOntologyFormat() {
return isOWLOntologyFormat(getFormat());
}
private boolean isOWLOntologyFormat(String fmt) {
return getOWLOntologyFormat(fmt) != null;
}
private OWLReasoner getReasoner() {
String rn = getParam("reasoner");
if (rn == null) {
rn = "default";
}
return owlserver.getReasoner(rn);
}
private boolean hasParam(Param p) {
String v = request.getParameter(p.toString());
if (v == null || v.equals(""))
return false;
return true;
}
/**
* @param p
* @return the value of http parameter with key p
*/
private String getParam(Param p) {
return request.getParameter(p.toString());
}
private String getParam(String p) {
return request.getParameter(p);
}
private String[] getParams(Param p) {
return request.getParameterValues(p.toString());
}
private String[] getParams(String p) {
return request.getParameterValues(p);
}
private boolean isHelp() {
return getParamAsBoolean("help");
}
private boolean getParamAsBoolean(Param p) {
return getParamAsBoolean(p.toString(), false);
}
private boolean getParamAsBoolean(String p) {
return getParamAsBoolean(p, false);
}
private boolean getParamAsBoolean(Param p, boolean def) {
return getParamAsBoolean(p.toString(), def);
}
private boolean getParamAsBoolean(String p, boolean def) {
String r = request.getParameter(p);
if (r != null && r.toLowerCase().equals("true"))
return true;
if (r != null && r.toLowerCase().equals("false"))
return false;
else
return def;
}
private Integer getParamAsInteger(Param p, Integer def) {
String sv = request.getParameter(p.toString());
if (sv == null || sv.equals(""))
return def;
Integer v = Integer.valueOf(sv);
if (v == null) {
v = def;
}
return v;
}
private PrintWriter getWriter() throws IOException {
return response.getWriter();
}
private OWLOntology getOWLOntology() {
return graph.getSourceOntology();
}
} |
package org.dazeend.harmonium.screens;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.dazeend.harmonium.HSkin;
import org.dazeend.harmonium.Harmonium;
import org.dazeend.harmonium.Harmonium.DiscJockey;
import org.dazeend.harmonium.music.Playable;
import org.dazeend.harmonium.music.PlayableLocalTrack;
import org.dazeend.harmonium.music.PlayableTrack;
import com.tivo.hme.bananas.BScreen;
import com.tivo.hme.bananas.BText;
import com.tivo.hme.bananas.BView;
import com.tivo.hme.sdk.HmeEvent;
import com.tivo.hme.sdk.ImageResource;
import com.tivo.hme.sdk.Resource;
import com.tivo.hme.sdk.StreamResource;
public class NowPlayingScreen extends HManagedResourceScreen {
// These are the fields that might be updated
private BView albumArtView;
private BText albumNameText;
private BText albumArtistText;
private BText yearText;
private BText trackNameText;
private BText artistNameText;
private BText shuffleModeText;
private BText repeatModeText;
private BText nextTrackText;
private ProgressBar progressBar;
private StreamResource musicStream;
private BText artistNameLabelText;
/**
* @param app
*/
public NowPlayingScreen(Harmonium app, final Playable musicItem) {
super(app);
doNotFreeResourcesOnExit(); // We'll free of our own resources, using the tools HManagedResourceScreen gives us.
// Define all dimensions in terms of percentage of the screen height and width. This make it
// resolution-safe.
// constants used for screen layout
int screenWidth = app.getWidth();
int screenHeight = app.getHeight();
int safeTitleH = app.getSafeTitleHorizontal();
int safeTitleV = app.getSafeTitleVertical();
int hIndent = (int)( ( screenWidth - (2 * safeTitleH) ) * 0.01 );
int vIndent = (int)( ( screenHeight - (2 * safeTitleV) ) * 0.01 );
// Define height of each row of album info text
int albumInfoRowHeight = app.hSkin.paragraphFontSize + (app.hSkin.paragraphFontSize / 4);
// Create views for album art. Size is square, sides less of 480px or half title-safe width
// (640x480 is the maximum image size that TiVo can load.)
final int artSide = Math.min(480,(screenWidth - (2 * safeTitleH) ) / 2 );
// Define the y-coordinate for album art so that the info is verticaly centered in the screen
int albumArtViewY = ( this.getHeight() - ( artSide + (3 * albumInfoRowHeight) ) ) / 2;
this.albumArtView = new BView( this.getNormal(), safeTitleH, albumArtViewY, artSide, artSide);
// Add album info text
this.albumNameText = new BText( this.getNormal(), // parent
this.albumArtView.getX() - safeTitleH,
this.albumArtView.getY() + this.albumArtView.getHeight() + vIndent,
this.albumArtView.getWidth() + (2 * safeTitleH), // width
albumInfoRowHeight // height
);
// Set album info text properties
this.albumNameText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
this.albumNameText.setShadow(false);
this.albumNameText.setFlags(RSRC_HALIGN_CENTER);
this.albumNameText.setFont(app.hSkin.paragraphFont);
// Add album artist info text
this.albumArtistText = new BText( this.getNormal(), // parent
this.albumArtView.getX() - safeTitleH,
this.albumNameText.getY() + albumNameText.getHeight(),
this.albumArtView.getWidth() + (2 * safeTitleH), // width
albumInfoRowHeight // height
);
// Set album info text properties
this.albumArtistText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
this.albumArtistText.setShadow(false);
this.albumArtistText.setFlags(RSRC_HALIGN_CENTER);
this.albumArtistText.setFont(app.hSkin.paragraphFont);
// Add album year text
this.yearText = new BText( this.getNormal(), // parent
this.albumArtView.getX(),
this.albumArtistText.getY() + albumArtistText.getHeight(),
this.albumArtView.getWidth(), // width
albumInfoRowHeight // height
);
// Set album info text properties
this.yearText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
this.yearText.setShadow(false);
this.yearText.setFlags(RSRC_HALIGN_CENTER);
this.yearText.setFont(app.hSkin.paragraphFont);
// Define constants to make track info layout easier
// NOTE: Can't be defined with other constants, because they rely on albumArtView
int leftEdgeCoord = this.albumArtView.getX() + this.albumArtView.getWidth() + hIndent;
int textWidth = this.getWidth() - leftEdgeCoord - safeTitleH;
int rowHeight = this.albumArtView.getHeight() / 5;
// Add track title
this.trackNameText = new BText( this.getNormal(), // parent
leftEdgeCoord, // x coord relative to parent
this.albumArtView.getY(), // y coord relative to parent
textWidth, // width
rowHeight // height
);
this.trackNameText.setColor(HSkin.BAR_TEXT_COLOR);
this.trackNameText.setShadow(false);
this.trackNameText.setFlags(RSRC_HALIGN_LEFT + RSRC_VALIGN_BOTTOM + RSRC_TEXT_WRAP);
this.trackNameText.setFont(app.hSkin.barFont);
// Put in track title label
BText trackNameLabelText = new BText( this.getNormal(),
leftEdgeCoord,
this.albumArtView.getY() + rowHeight,
textWidth,
rowHeight
);
trackNameLabelText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
trackNameLabelText.setShadow(false);
trackNameLabelText.setFlags(RSRC_HALIGN_LEFT + RSRC_VALIGN_TOP);
trackNameLabelText.setFont(app.hSkin.paragraphFont);
trackNameLabelText.setValue("Title");
// Add track artist
this.artistNameText = new BText( this.getNormal(), // parent
leftEdgeCoord, // x coord relative to parent
this.albumArtView.getY() + (2 * rowHeight), // y coord relative to parent
textWidth, // width
rowHeight // height
);
this.artistNameText.setColor(HSkin.BAR_TEXT_COLOR);
this.artistNameText.setShadow(false);
this.artistNameText.setFlags(RSRC_HALIGN_LEFT + RSRC_VALIGN_BOTTOM + RSRC_TEXT_WRAP);
this.artistNameText.setFont(app.hSkin.barFont);
artistNameLabelText = new BText(this.getNormal(),
leftEdgeCoord,
this.albumArtView.getY() + (3 * rowHeight),
textWidth,
rowHeight);
artistNameLabelText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
artistNameLabelText.setShadow(false);
artistNameLabelText.setFlags(RSRC_HALIGN_LEFT + RSRC_VALIGN_TOP);
artistNameLabelText.setFont(app.hSkin.paragraphFont);
// Create Progress Bar
this.progressBar = new ProgressBar( this,
leftEdgeCoord,
this.albumArtView.getY() + (4 * rowHeight),
textWidth,
this.app.hSkin.paragraphFontSize
);
// Create footer layout variables
int footerHeight = this.app.hSkin.paragraphFontSize;
int footerTop = screenHeight - this.app.getSafeActionVertical() - footerHeight;
// Create all footer objects before initializing them.
// Some methods we call depend on their existence.
BText repeatLabelText = new BText( this.getNormal(),
safeTitleH,
footerTop,
3 * this.app.hSkin.paragraphFontSize,
footerHeight
);
this.repeatModeText = new BText( this.getNormal(),
safeTitleH + repeatLabelText.getWidth(),
footerTop,
2 * this.app.hSkin.paragraphFontSize,
footerHeight
);
BText shuffleLabelText = new BText( this.getNormal(),
this.repeatModeText.getX() + this.repeatModeText.getWidth(),
footerTop,
3 * this.app.hSkin.paragraphFontSize,
footerHeight
);
this.shuffleModeText = new BText( this.getNormal(),
shuffleLabelText.getX() + shuffleLabelText.getWidth(),
footerTop,
2 * this.app.hSkin.paragraphFontSize,
footerHeight
);
BText nextLabelText = new BText( this.getNormal(),
this.shuffleModeText.getX() + this.shuffleModeText.getWidth(),
footerTop,
2 * this.app.hSkin.paragraphFontSize,
footerHeight
);
this.nextTrackText = new BText( this.getNormal(),
nextLabelText.getX() + nextLabelText.getWidth(),
footerTop,
screenWidth - safeTitleH - ( nextLabelText.getX() + nextLabelText.getWidth() ),
footerHeight
);
// init Shuffle label
shuffleLabelText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
shuffleLabelText.setShadow(false);
shuffleLabelText.setFlags(RSRC_HALIGN_LEFT);
shuffleLabelText.setFont(app.hSkin.paragraphFont);
shuffleLabelText.setValue("Shuffle:");
// init Shuffle Mode Text
this.shuffleModeText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
this.shuffleModeText.setShadow(false);
this.shuffleModeText.setFlags(RSRC_HALIGN_LEFT);
this.shuffleModeText.setFont(app.hSkin.paragraphFont);
this.updateShuffle();
// init Repeat label
repeatLabelText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
repeatLabelText.setShadow(false);
repeatLabelText.setFlags(RSRC_HALIGN_LEFT);
repeatLabelText.setFont(app.hSkin.paragraphFont);
repeatLabelText.setValue("Repeat:");
// init Repeat Mode Text
this.repeatModeText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
this.repeatModeText.setShadow(false);
this.repeatModeText.setFlags(RSRC_HALIGN_LEFT);
this.repeatModeText.setFont(app.hSkin.paragraphFont);
this.updateRepeat();
// init next playing label
nextLabelText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
nextLabelText.setShadow(false);
nextLabelText.setFlags(RSRC_HALIGN_LEFT);
nextLabelText.setFont(app.hSkin.paragraphFont);
nextLabelText.setValue("Next:");
// init next track Text
this.nextTrackText.setColor(HSkin.PARAGRAPH_TEXT_COLOR);
this.nextTrackText.setShadow(false);
this.nextTrackText.setFlags(RSRC_HALIGN_LEFT);
this.nextTrackText.setFont(app.hSkin.paragraphFont);
this.nextTrackText.setValue( this.app.getDiscJockey().getNextTrackInfo() );
update(musicItem);
}
/**
* Update the screen to a new music item
*
* @param nowPlaying
*/
public void update(final Playable nowPlaying)
{
// turn off painting while we update the images
app.getRoot().setPainting(false);
try
{
// Update views with new info
new Thread() {
public void run() {
ImageResource albumArtImage = createManagedImage( nowPlaying, albumArtView.getWidth(), albumArtView.getHeight());
setManagedResource(albumArtView, albumArtImage, RSRC_HALIGN_CENTER + RSRC_VALIGN_CENTER + RSRC_IMAGE_BESTFIT);
flush(); // Necessay to ensure UI updates, because we're in another thread.
}
}.start();
if (nowPlaying instanceof PlayableTrack)
{
artistNameLabelText.setValue("Artist");
PlayableTrack pt = (PlayableTrack)nowPlaying;
if(pt.getDiscNumber() > 0) {
this.albumNameText.setValue(pt.getAlbumName() + " - Disc " + pt.getDiscNumber());
}
else {
this.albumNameText.setValue(pt.getAlbumName() );
}
this.albumArtistText.setValue(pt.getAlbumArtistName());
if(pt.getReleaseYear() == 0) {
this.yearText.setValue("");
}
else {
this.yearText.setValue(pt.getReleaseYear());
}
this.trackNameText.setValue(pt.getTrackName());
this.artistNameText.setValue(pt.getArtistName());
}
else
{
artistNameLabelText.setValue("");
this.albumNameText.setValue("");
this.albumArtistText.setValue("");
this.yearText.setValue("");
this.trackNameText.setValue(nowPlaying.getURI());
this.artistNameText.setValue("");
}
// indicate that we need to reset the time label on the progress bar
if(this.progressBar != null)
this.progressBar.setDurationUpdated(false);
this.nextTrackText.setValue( this.app.getDiscJockey().getNextTrackInfo() );
// update the shuffle and repeat mode indicators
this.updateShuffle();
this.updateRepeat();
}
finally
{
app.getRoot().setPainting(true);
}
}
/**
* Updates the shuffle mode indicator on the Now Playing Screen
*/
public void updateShuffle() {
if( this.app.getDiscJockey().isShuffling() ) {
this.shuffleModeText.setValue("On");
}
else {
this.shuffleModeText.setValue("Off");
}
updateNext();
}
public void updateRepeat() {
if( this.app.getDiscJockey().isRepeating() ) {
this.repeatModeText.setValue("On");
}
else {
this.repeatModeText.setValue("Off");
}
updateNext();
}
public void updateNext() {
this.nextTrackText.setValue( this.app.getDiscJockey().getNextTrackInfo() );
}
/**
* Plays an MP3.
*
* @param mp3File
*/
public boolean play(Playable playable) {
// Make sure that there is no music stream already playing
if(this.musicStream != null)
return false;
// Make sure that the file exists on disk and hasn't been deleted
if (playable instanceof PlayableLocalTrack)
{
PlayableLocalTrack plt = (PlayableLocalTrack)playable;
if( ( plt.getTrackFile() == null ) || ( !plt.getTrackFile().exists() ) )
return false;
}
// Construct the URI to send to the receiver. The receiver will
// connect back to our factory and ask for the file. The URI
// consists of:
// (our base URI) + (the Playable's URI)
String url = this.getApp().getContext().getBaseURI().toString();
try {
url += URLEncoder.encode(playable.getURI(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// MP3's are played as a streamed resource
this.musicStream = this.createStream(url, playable.getContentType(), true);
this.setResource(this.musicStream);
return true;
}
public void stopPlayback()
{
if(this.musicStream != null)
{
if (this.app.isInSimulator()) {
System.out.println("Stopping playback");
}
// Close the stream playing the MP3
this.musicStream.close();
this.musicStream.remove();
// Re-set the musicStream;
this.musicStream = null;
}
}
/**
* @return the musicStream
*/
public StreamResource getMusicStream() {
return this.musicStream;
}
public int getSecondsElapsed() {
if ( this.progressBar != null )
return this.progressBar.getSecondsElapsed();
else
return 0;
}
/**
* Restores screen and background image. This cannot be implemented in a handleExit() method
* because, we may exit this screen to the screensaver (which doesn't use the standard background).
*
*/
private void pop() {
this.app.setBackgroundImage();
this.app.pop();
}
/* (non-Javadoc)
* @see com.tivo.hme.bananas.BScreen#handleEnter(java.lang.Object, boolean)
*/
@Override
public boolean handleEnter(Object arg0, boolean arg1) {
boolean status = super.handleEnter(arg0, arg1);
// Set the background when entering the screen
// constants used for screen layout
double screenHeight = this.app.getHeight();
double screenWidth = this.app.getWidth();
double aspectRatio = screenWidth / screenHeight;
// Display the background image
if( this.app.isInSimulator() ) {
// We are in the simulator, so set a PNG background.
// Change the background based on the new aspect ratio.
if( (aspectRatio > 1.7) && (aspectRatio < 1.8) ) {
// The current aspect ratio is approximately 16:9.
// Use the high definition background meant for 720p.
String url = this.getContext().getBaseURI().toString();
try {
url += URLEncoder.encode("now_playing_720.png", "UTF-8");
}
catch(UnsupportedEncodingException e) {
}
this.app.getRoot().setResource(this.createStream(url, "image/png", true));
}
else {
// Default background is standard definition 640 x 480 (4:3)
this.app.getRoot().setResource("now_playing_sd.png");
}
}
else {
// We are running on a real TiVo, so use an MPEG background to conserve memory.
// Change the background based on the new aspect ratio.
if( (aspectRatio > 1.7) && (aspectRatio < 1.8) ) {
// The current aspect ratio is approximately 16:9.
// Use the high definition background meant for 720p.
this.app.getRoot().setResource("now_playing_720.mpg");
}
else {
// Default background is standard definition 640 x 480 (4:3)
this.app.getRoot().setResource("now_playing_sd.mpg");
}
}
return status;
}
/* (non-Javadoc)
* Handles key presses from TiVo remote control.
*/
@Override
public boolean handleKeyPress(int key, long rawcode) {
if (key == KEY_CLEAR) {
this.app.setInactive();
return true;
}
this.app.checkKeyPressToResetInactivityTimer(key);
switch(key) {
case KEY_INFO:
pop();
BrowsePlaylistScreen bps;
BScreen s = app.getCurrentScreen();
if (s instanceof BrowsePlaylistScreen) {
bps = (BrowsePlaylistScreen)s;
if(bps.isNowPlayingPlaylist()) {
bps.focusNowPlaying();
return true;
}
}
bps = new BrowsePlaylistScreen(app);
app.push(bps, TRANSITION_LEFT);
bps.focusNowPlaying();
return true;
case KEY_LEFT:
switch( this.app.getDiscJockey().getPlayRate() ) {
case NORMAL:
case PAUSE:
case STOP:
if(getBApp().getStackDepth() <= 1) {
getBApp().setActive(false);
}
else {
this.pop();
}
break;
default:
this.app.play("bonk.snd");
break;
}
return true;
case KEY_FORWARD:
this.app.play( this.app.getDiscJockey().getPlayRate().getNextFF().getSound() );
this.app.getDiscJockey().fastForward();
return true;
case KEY_REVERSE:
this.app.play( this.app.getDiscJockey().getPlayRate().getNextREW().getSound() );
this.app.getDiscJockey().rewind();
return true;
case KEY_PLAY:
this.app.getDiscJockey().playNormalSpeed();
return true;
case KEY_PAUSE:
this.app.getDiscJockey().togglePause();
return true;
case KEY_CHANNELUP:
if( ! ( this.app.getDiscJockey().isAtEndOfPlaylist() && (! this.app.getDiscJockey().isRepeating() ) ) )
{
this.app.play("pageup.snd");
this.app.getDiscJockey().playNext();
}
else {
this.app.play("bonk.snd");
}
return true;
case KEY_CHANNELDOWN:
if( getSecondsElapsed() > DiscJockey.BACK_UP_AFTER_SECONDS || !(this.app.getDiscJockey().isAtBeginningOfPlaylist() && !this.app.getDiscJockey().isRepeating()) )
{
this.app.play("pagedown.snd");
this.app.getDiscJockey().playPrevious();
}
else {
this.app.play("bonk.snd");
}
return true;
case KEY_REPLAY:
this.app.play("select.snd");
this.app.getDiscJockey().toggleRepeatMode();
return true;
case KEY_ADVANCE:
this.app.play("select.snd");
this.app.getDiscJockey().toggleShuffleMode();
return true;
}
return super.handleKeyPress(key, rawcode);
}
private void handleResourceInfoEvent(HmeEvent event)
{
HmeEvent.ResourceInfo resourceInfo = (HmeEvent.ResourceInfo) event;
if (this.musicStream != null)
System.out.println("Stream status: " + this.musicStream.getStatus());
// Check that this event is for the music stream
if( (this.musicStream != null) && (event.getID() == this.musicStream.getID() ) )
{
// Check the type of status sent
switch( resourceInfo.getStatus() )
{
case RSRC_STATUS_PLAYING:
// the current track is playing. Update the progress bar, if we know the length of the track.
if(this.progressBar != null)
{
// Set the duration label, if it hasn't already been set, and if we know what our font looks like
long duration = this.app.getDiscJockey().getNowPlaying().getDuration();
if( (! this.progressBar.isDurationUpdated() ) && (this.progressBar.fontInfo != null ) )
this.progressBar.setDuration(duration);
// Set elapsed, which updates the elapsed label and the progress bar position.
if (duration > 0)
{
String [] positionInfo = resourceInfo.getMap().get("pos").toString().split("/");
long elapsed = Long.parseLong(positionInfo[0]);
this.progressBar.setElapsed(elapsed);
}
}
break;
case RSRC_STATUS_SEEKING:
// Set elapsed, which updates the elapsed label and the progress bar position.
String [] positionInfo = resourceInfo.getMap().get("pos").toString().split("/");
long elapsed = Long.parseLong(positionInfo[0]);
double fractionComplete = this.progressBar.setElapsed(elapsed);
// Since we're using our custom duration rather than the one the Tivo sends in the event,
// trickplay doesn't automatically stop at the beginning or end of a track when fast forwarding
// or rewinding. Implement it.
double lowerLimit = 0;
double upperLimit = .95;
if(Float.parseFloat( resourceInfo.getMap().get("speed").toString() ) < 0 && fractionComplete <= lowerLimit)
{
// We are rewinding and are about to hit the beginning of the track.
// Position the track at our lower limit and drop back to NORMAL speed.
long position = (long)( this.app.getDiscJockey().getNowPlaying().getDuration() * lowerLimit);
this.musicStream.setPosition(position);
this.app.getDiscJockey().playNormalSpeed();
}
if( Float.parseFloat( resourceInfo.getMap().get("speed").toString() ) > 1 && fractionComplete >= upperLimit )
{
// We are fast forwarding and are about to hit the end of the track.
// Position the track at our upper limit and drop back to NORMAL speed.
long position = (long)( this.app.getDiscJockey().getNowPlaying().getDuration() * upperLimit);
this.musicStream.setPosition(position);
this.app.getDiscJockey().playNormalSpeed();
}
break;
case RSRC_STATUS_CLOSED:
case RSRC_STATUS_COMPLETE:
case RSRC_STATUS_ERROR:
// the current track has finished, so check if there's another track to play.
if( this.app.getDiscJockey().isAtEndOfPlaylist() && ( ! this.app.getDiscJockey().isRepeating() ) )
{
// There's not another track to play
this.app.resetInactivityTimer();
// Pop the screen saver if it is showing
if(this.app.getCurrentScreen().getClass() == ScreenSaverScreen.class)
this.pop();
// Pop this Now Playing Screen only if it is showing.
if(this.app.getCurrentScreen().equals(this))
this.pop();
}
break;
}
}
}
/* (non-Javadoc)
* Handles TiVo events
*/
@Override
public boolean handleEvent(HmeEvent event)
{
// Check to see if this event is of a type that we want to handle
if (event.getOpCode() == EVT_RSRC_INFO)
{
handleResourceInfoEvent(event);
}
return super.handleEvent(event);
}
private class ProgressBar extends BView {
private BView trackingBar;
private String elapsedLabel = "0:00";
private BText elapsedText = new BText( this, 0, 0, 0, this.getHeight() );
private BText durationText = new BText( this, this.getWidth(), 0, 0, this.getHeight() );
private Resource.FontResource font;
private HmeEvent.FontInfo fontInfo;
private boolean durationUpdated;
private long durationMS;
private long elapsedMS;
/**
* A bar that tracks the elapsed time of a stream. The height of the bar is dependent on the font sizej chosen
* for text.
*
* @param parent container for this ProgressBar
* @param x X coordinate of top-left corner of this ProgressBar
* @param y Y coordinate of top-left corner of this ProgressBar
* @param width width of this ProgressBar
* @param timeLength length of time this ProgressBar tracks in milliseconds
* @param fontSize the font to use for text in the ProgressBar
*/
public ProgressBar(NowPlayingScreen parent, int x, int y, int width, int fontSize) {
super(parent.getNormal(), x, y, width, 0, false);
// Create font. Use FONT_METRIC_BASIC flag so that we get font metrics.
this.font = (Resource.FontResource) createFont( "default.ttf", FONT_PLAIN, fontSize, FONT_METRICS_BASIC | FONT_METRICS_GLYPH);
this.elapsedText.setValue(elapsedLabel);
this.elapsedText.setFont(this.font);
this.durationText.setFont(this.font);
this.font.addHandler(this);
parent.progressBar = this;
}
/*
* (non-Javadoc)
* @see com.tivo.hme.bananas.BView#handleEvent(com.tivo.hme.sdk.HmeEvent)
*/
@Override
public boolean handleEvent(HmeEvent event) {
switch (event.getOpCode()) {
case EVT_FONT_INFO:
this.fontInfo = (HmeEvent.FontInfo) event;
// Resize the height of this ProgressBar to fit the font
this.setBounds( this.getX(), this.getY(), this.getWidth(), (int)this.fontInfo.getAscent() );
// Format the zero label
int zeroWidth = fontInfo.measureTextWidth(this.elapsedLabel);
this.elapsedText.setBounds(0, 0, zeroWidth, this.getHeight() );
// Create the tracking bar
int trackingBarHeight = (int) this.getHeight() / 2;
this.trackingBar = new BView( this,
this.elapsedText.getWidth() + (int)fontInfo.getGlyphInfo('l').getAdvance(),
(int)( (this.getHeight() - trackingBarHeight) / 2 ),
0,
trackingBarHeight
);
this.trackingBar.setResource(HSkin.NTSC_WHITE);
// Make the progress bar visible
this.setVisible(true);
return true;
}
return super.handleEvent(event);
}
/**
* Sets the position of the tracking bar
*
* @param position a double value between 0 and 1 representing the fraction of the stream that has played
*/
private boolean setPosition(double position) {
if( (position < 0) || (position > 1) ) {
return false;
}
// reset width of tracking bar based on position
this.trackingBar.setBounds( this.trackingBar.getX(),
this.trackingBar.getY(),
(int) ( ( this.getWidth() - this.elapsedText.getWidth() - this.durationText.getWidth() - ( 2 * (int)fontInfo.getGlyphInfo('l').getAdvance() ) ) * position ),
this.trackingBar.getHeight()
);
return true;
}
/**
* Sets the duration label of this ProgressBar and resizes views to fit.
*
* @param label
* @return
*/
public void setDuration(long milliseconds) {
String label = millisecondsToTimeString(milliseconds);
int labelWidth = fontInfo.measureTextWidth(label);
durationMS = milliseconds;
// Resize the width of this ProgressBar to fit the labels
if(this.getWidth() < labelWidth) {
this.setBounds( this.getX(), this.getY(), labelWidth * 2, this.getHeight() );
}
this.trackingBar.setLocation(labelWidth + (int)fontInfo.getGlyphInfo('l').getAdvance(), this.trackingBar.getY());
// Re-size the time labels and set their text
this.durationText.setBounds(this.getWidth() - labelWidth, 0, labelWidth, this.getHeight());
if (milliseconds > 0)
this.durationText.setValue(label);
else
{
this.elapsedText.setValue("");
this.durationText.setValue("");
setPosition(0);
}
this.elapsedText.setBounds(0, 0, labelWidth, this.getHeight() );
// indicate that the duration label has been set
this.durationUpdated = true;
}
public double setElapsed(long elapsedMS)
{
this.elapsedMS = elapsedMS;
this.elapsedText.setValue(millisecondsToTimeString(elapsedMS));
double fractionComplete = (double)elapsedMS / durationMS;
setPosition(fractionComplete);
return fractionComplete;
}
private String millisecondsToTimeString(long milliseconds)
{
int minutes = (int)(milliseconds / 60000);
int seconds = (int)((milliseconds % 60000) / 1000);
String secondsLabel = String.format("%02d", seconds);
return minutes + ":" + secondsLabel;
}
/**
* @return the timeUpdated
*/
public boolean isDurationUpdated() {
return durationUpdated;
}
/**
* @param timeUpdated the timeUpdated to set
*/
public void setDurationUpdated(boolean timeUpdated) {
this.durationUpdated = timeUpdated;
}
public int getSecondsElapsed() {
return (int) (elapsedMS / 1000);
}
}
} |
package org.postgresql.test.jdbc2;
import java.sql.*;
import java.util.Arrays;
import junit.framework.TestCase;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.TimeZone;
import org.postgresql.test.TestUtil;
public class UpdateableResultTest extends TestCase
{
private Connection con;
public UpdateableResultTest( String name )
{
super( name );
try
{
Class.forName("org.postgresql.Driver");
}
catch( Exception ex ){}
}
protected void setUp() throws Exception
{
con = TestUtil.openDB();
TestUtil.createTable(con, "updateable", "id int primary key, name text, notselected text, ts timestamp with time zone, intarr int[]", true);
TestUtil.createTable(con, "second", "id1 int primary key, name1 text");
TestUtil.createTable(con, "stream", "id int primary key, asi text, chr text, bin bytea");
// put some dummy data into second
Statement st2 = con.createStatement();
st2.execute( "insert into second values (1,'anyvalue' )");
st2.close();
}
protected void tearDown() throws Exception
{
TestUtil.dropTable(con, "updateable");
TestUtil.dropTable(con, "second");
TestUtil.dropTable(con, "stream");
TestUtil.closeDB(con);
}
public void testDeleteRows() throws SQLException
{
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO second values (2,'two')");
st.executeUpdate("INSERT INTO second values (3,'three')");
st.executeUpdate("INSERT INTO second values (4,'four')");
st.close();
st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
ResultSet rs = st.executeQuery( "select id1,name1 from second order by id1");
assertTrue(rs.next());
assertEquals(1, rs.getInt("id1"));
rs.deleteRow();
assertTrue(rs.isBeforeFirst());
assertTrue(rs.next());
assertTrue(rs.next());
assertEquals(3, rs.getInt("id1"));
rs.deleteRow();
assertEquals(2, rs.getInt("id1"));
rs.close();
st.close();
}
public void testCancelRowUpdates() throws Exception
{
Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
ResultSet rs = st.executeQuery( "select * from second");
// make sure we're dealing with the correct row.
rs.first();
assertEquals(1, rs.getInt(1));
assertEquals("anyvalue", rs.getString(2));
// update, cancel and make sure nothings changed.
rs.updateInt(1, 99);
rs.cancelRowUpdates();
assertEquals(1, rs.getInt(1));
assertEquals("anyvalue", rs.getString(2));
// real update
rs.updateInt(1, 999);
rs.updateRow();
assertEquals(999, rs.getInt(1));
assertEquals("anyvalue", rs.getString(2));
// scroll some and make sure the update is still there
rs.beforeFirst();
rs.next();
assertEquals(999, rs.getInt(1));
assertEquals("anyvalue", rs.getString(2));
// make sure the update got to the db and the driver isn't lying to us.
rs.close();
rs = st.executeQuery( "select * from second");
rs.first();
assertEquals(999, rs.getInt(1));
assertEquals("anyvalue", rs.getString(2));
rs.close();
st.close();
}
private void checkPositioning(ResultSet rs) throws SQLException
{
try
{
rs.getInt(1);
fail("Can't use an incorrectly positioned result set.");
}
catch (SQLException sqle)
{
}
try
{
rs.updateInt(1, 2);
fail("Can't use an incorrectly positioned result set.");
}
catch (SQLException sqle)
{
}
try
{
rs.updateRow();
fail("Can't use an incorrectly positioned result set.");
}
catch (SQLException sqle)
{
}
try
{
rs.deleteRow();
fail("Can't use an incorrectly positioned result set.");
}
catch (SQLException sqle)
{
}
}
public void testPositioning() throws SQLException
{
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id1,name1 FROM second");
checkPositioning(rs);
assertTrue(rs.next());
rs.beforeFirst();
checkPositioning(rs);
rs.afterLast();
checkPositioning(rs);
rs.beforeFirst();
assertTrue(rs.next());
assertTrue(!rs.next());
checkPositioning(rs);
rs.afterLast();
assertTrue(rs.previous());
assertTrue(!rs.previous());
checkPositioning(rs);
rs.close();
stmt.close();
}
public void testUpdateTimestamp() throws SQLException
{
TimeZone origTZ = TimeZone.getDefault();
try {
// We choose a timezone which has a partial hour portion
// Asia/Tehran is +3:30
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tehran"));
Timestamp ts = Timestamp.valueOf("2006-11-20 16:17:18");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, ts FROM updateable");
rs.moveToInsertRow();
rs.updateInt(1,1);
rs.updateTimestamp(2,ts);
rs.insertRow();
rs.first();
assertEquals(ts, rs.getTimestamp(2));
} finally {
TimeZone.setDefault(origTZ);
}
}
public void testUpdateStreams() throws SQLException, UnsupportedEncodingException
{
String string = "Hello";
byte[] bytes = new byte[]{0,'\\',(byte) 128,(byte) 255};
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, asi, chr, bin FROM stream");
rs.moveToInsertRow();
rs.updateInt(1, 1);
rs.updateAsciiStream("asi", null, 17);
rs.updateCharacterStream("chr", null, 81);
rs.updateBinaryStream("bin", null, 0);
rs.insertRow();
rs.moveToInsertRow();
rs.updateInt(1, 3);
rs.updateAsciiStream("asi", new ByteArrayInputStream(string.getBytes("US-ASCII")), 5);
rs.updateCharacterStream("chr", new StringReader(string), 5);
rs.updateBinaryStream("bin", new ByteArrayInputStream(bytes), bytes.length);
rs.insertRow();
rs.beforeFirst();
rs.next();
assertEquals(1, rs.getInt(1));
assertNull(rs.getString(2));
assertNull(rs.getString(3));
assertNull(rs.getBytes(4));
rs.updateInt("id", 2);
rs.updateAsciiStream("asi", new ByteArrayInputStream(string.getBytes("US-ASCII")), 5);
rs.updateCharacterStream("chr", new StringReader(string), 5);
rs.updateBinaryStream("bin", new ByteArrayInputStream(bytes), bytes.length);
rs.updateRow();
assertEquals(2, rs.getInt(1));
assertEquals(string, rs.getString(2));
assertEquals(string, rs.getString(3));
assertEquals(bytes, rs.getBytes(4));
rs.refreshRow();
assertEquals(2, rs.getInt(1));
assertEquals(string, rs.getString(2));
assertEquals(string, rs.getString(3));
assertEquals(bytes, rs.getBytes(4));
rs.next();
assertEquals(3, rs.getInt(1));
assertEquals(string, rs.getString(2));
assertEquals(string, rs.getString(3));
assertEquals(bytes, rs.getBytes(4));
rs.close();
stmt.close();
}
public void testZeroRowResult() throws SQLException
{
Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
ResultSet rs = st.executeQuery( "select * from updateable WHERE 0 > 1");
assertTrue(!rs.next());
rs.moveToInsertRow();
rs.moveToCurrentRow();
}
public void testUpdateable() throws SQLException
{
Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
ResultSet rs = st.executeQuery( "select * from updateable");
assertNotNull( rs );
rs.moveToInsertRow();
rs.updateInt( 1, 1 );
rs.updateString( 2, "jake" );
rs.updateString( 3, "avalue" );
rs.insertRow();
rs.first();
rs.updateInt( "id", 2 );
rs.updateString( "name", "dave" );
rs.updateRow();
assertEquals(2, rs.getInt("id"));
assertEquals("dave", rs.getString("name"));
assertEquals("avalue", rs.getString("notselected"));
rs.deleteRow();
rs.moveToInsertRow();
rs.updateInt("id", 3);
rs.updateString("name", "paul");
rs.insertRow();
try
{
rs.refreshRow();
fail("Can't refresh when on the insert row.");
}
catch (SQLException sqle)
{
}
assertEquals(3, rs.getInt("id"));
assertEquals("paul", rs.getString("name"));
assertNull(rs.getString("notselected"));
rs.close();
rs = st.executeQuery("select id1, id, name, name1 from updateable, second" );
try
{
while ( rs.next() )
{
rs.updateInt( "id", 2 );
rs.updateString( "name", "dave" );
rs.updateRow();
}
fail("should not get here, update should fail");
}
catch (SQLException ex)
{
}
rs = st.executeQuery("select oid,* from updateable");
assertTrue(rs.first());
rs.updateInt( "id", 3 );
rs.updateString( "name", "dave3");
rs.updateRow();
assertEquals(3, rs.getInt("id"));
assertEquals("dave3", rs.getString("name"));
rs.moveToInsertRow();
rs.updateInt( "id", 4 );
rs.updateString( "name", "dave4" );
rs.insertRow();
rs.updateInt("id", 5 );
rs.updateString( "name", "dave5" );
rs.insertRow();
rs.moveToCurrentRow();
assertEquals(3, rs.getInt("id"));
assertEquals("dave3", rs.getString("name"));
assertTrue( rs.next() );
assertEquals(4, rs.getInt("id"));
assertEquals("dave4", rs.getString("name"));
assertTrue( rs.next() );
assertEquals(5, rs.getInt("id"));
assertEquals("dave5", rs.getString("name"));
rs.close();
st.close();
}
public void testInsertRowIllegalMethods() throws Exception
{
Statement st = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );
ResultSet rs = st.executeQuery( "select * from updateable");
assertNotNull(rs);
rs.moveToInsertRow();
try {
rs.cancelRowUpdates();
fail("expected an exception when calling cancelRowUpdates() on the insert row");
} catch (SQLException e) {}
try {
rs.updateRow();
fail("expected an exception when calling updateRow() on the insert row");
} catch (SQLException e) {}
try {
rs.deleteRow();
fail("expected an exception when calling deleteRow() on the insert row");
} catch (SQLException e) {}
try {
rs.refreshRow();
fail("expected an exception when calling refreshRow() on the insert row");
} catch (SQLException e) {}
rs.close();
st.close();
}
public void testUpdateablePreparedStatement() throws Exception
{
// No args.
PreparedStatement st = con.prepareStatement("select * from updateable",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery();
rs.moveToInsertRow();
rs.close();
st.close();
// With args.
st = con.prepareStatement("select * from updateable where id = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st.setInt(1, 1);
rs = st.executeQuery();
rs.moveToInsertRow();
rs.close();
st.close();
}
public void testUpdateReadOnlyResultSet() throws Exception
{
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery( "select * from updateable");
try {
rs.moveToInsertRow();
fail("expected an exception when calling moveToInsertRow() on a read-only resultset");
} catch (SQLException e) {}
}
public void testBadColumnIndexes() throws Exception
{
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery( "select * from updateable");
rs.moveToInsertRow();
try {
rs.updateInt(0,1);
fail("Should have thrown an exception on bad column index.");
} catch (SQLException sqle) { }
try {
rs.updateString(1000,"hi");
fail("Should have thrown an exception on bad column index.");
} catch (SQLException sqle) { }
try {
rs.updateNull(1000);
fail("Should have thrown an exception on bad column index.");
} catch (SQLException sqle) { }
}
public void testArray() throws SQLException {
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("INSERT INTO updateable (id, intarr) VALUES (1, '{1,2,3}'::int4[])");
ResultSet rs = stmt.executeQuery("SELECT id, intarr FROM updateable");
assertTrue(rs.next());
rs.updateObject(2, rs.getArray(2));
rs.updateRow();
Array arr = rs.getArray(2);
assertEquals(Types.INTEGER, arr.getBaseType());
int intarr[] = (int[])arr.getArray();
assertEquals(3, intarr.length);
assertEquals(1, intarr[0]);
assertEquals(2, intarr[1]);
assertEquals(3, intarr[2]);
rs.close();
rs = stmt.executeQuery("SELECT id,intarr FROM updateable");
assertTrue(rs.next());
arr = rs.getArray(2);
assertEquals(Types.INTEGER, arr.getBaseType());
intarr = (int[])arr.getArray();
assertEquals(3, intarr.length);
assertEquals(1, intarr[0]);
assertEquals(2, intarr[1]);
assertEquals(3, intarr[2]);
rs.close();
stmt.close();
}
} |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import jing.chemParser.ChemParser;
public class CheckForwardAndReverseRateCoefficients {
// Assumes less than 401 species are present in the mechanism
static String[] names = new String[400];
static double[][] coeffs = new double[400][14];
static int numR = 0;
static int numP = 0;
public static void main(String args[]) {
// Temperature is assumed to have units in Kelvin
StringBuilder reverseRateCoefficients = new StringBuilder();
String temperatureString = "";
double[] T = new double [10];
for (int i=0; i<10; i++) {
double temp = (1000.0/3000.0) + ((double)i/9.0) * (1000.0/300.0 - 1000.0/3000.0);
T[i] = 1000.0 / temp;
temperatureString += Double.toString(T[i])+"\t";
}
reverseRateCoefficients.append(temperatureString+"\n");
// double[] T = {614.0,614.0,614.0,614.0,614.0,629.0,643.0,678.0,713.0,749.0,784.0,854.0,930.0,1010.0,1100.0,1250.0,1350.0,1440.0,1510.0,1570.0,1640.0,1790.0,1970.0,2030.0,2090.0,2110.0,2130.0,2170.0,2180.0,2210.0,2220.0,2220.0,2220.0,2220.0,2210.0,2210.0,2210.0,2200.0,2190.0,2180.0,2170.0,2160.0,2150.0,2150.0,2140.0,2140.0,2140.0,2140.0,2130.0,2130.0,2130.0,2120.0,2120.0,2120.0,2120.0,2110.0,2110.0,2110.0,2110.0,2110.0,2100.0,2100.0,2100.0,2090.0,2080.0,2080.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2000.0,2000.0,1990.0,1980.0,1970.0,1970.0,1960.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0};
// double[] T = {681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,682.0,683.0,684.0,687.0,693.0,703.0,712.0,730.0,749.0,767.0,786.0,823.0,860.0,897.0,934.0,1000.0,1060.0,1120.0,1170.0,1230.0,1320.0,1370.0,1410.0,1440.0,1480.0,1550.0,1660.0,1760.0,1850.0,1920.0,1960.0,2060.0,2110.0,2150.0,2200.0,2240.0,2260.0,2260.0,2250.0,2250.0,2240.0,2240.0,2230.0,2220.0,2210.0,2200.0,2190.0,2180.0,2180.0,2180.0,2180.0,2180.0,2180.0,2170.0,2170.0,2170.0,2170.0,2170.0,2170.0,2160.0,2160.0,2150.0,2150.0,2140.0,2140.0,2130.0,2130.0,2120.0,2120.0,2110.0,2110.0,2100.0,2100.0,2090.0,2090.0,2080.0,2080.0,2070.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2010.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0};
// double[] T = {2.95E+02, 2.95E+02, 2.95E+02, 2.95E+02, 6.12E+02, 9.28E+02, 1.24E+03, 1.56E+03, 1.88E+03, 2.19E+03, 2.19E+03, 2.19E+03};
// Pressure is assumed to have units in atm
// double[] Pressure = {0.03947692};
double[] Pressure = {1};
// Read in the chem.inp file
try {
FileReader fr_thermodat = new FileReader(args[0]);
BufferedReader br_thermodat = new BufferedReader(fr_thermodat);
String line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Continue reading in the file until "THERMO" is read in
boolean foundThermo = false;
while (!foundThermo) {
line = ChemParser.readMeaningfulLine(br_thermodat, true);
if (line.startsWith("THERMO")) {
foundThermo = true;
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line contains the global Tmin, Tmax, Tmid
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line should have thermo (or comments)
}
}
int counter = 0;
// Read in all information
while (line != null && !line.equals("END")) {
if (!line.startsWith("!")) {
// Thermo data for each species stored in 4 consecutive lines
String speciesName = line.substring(0,16);
StringTokenizer st_chemkinname = new StringTokenizer(speciesName);
names[counter] = st_chemkinname.nextToken().trim();
// String lowTstring = line.substring(46,56);
// double lowT = Double.parseDouble(lowTstring.trim());
// String highTstring = line.substring(56,66);
// double highT = Double.parseDouble(highTstring.trim());
// String midTstring = line.substring(66,74);
// double midT = Double.parseDouble(midTstring.trim());
// Read in the coefficients
for (int numLines=0; numLines<2; ++numLines) {
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<5; ++numcoeffs) {
coeffs[counter][5*numLines+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<4; ++numcoeffs) {
coeffs[counter][10+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
++counter;
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
// line should be END; next line should be REACTIONS
line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Determine what units Ea is in
StringTokenizer st = new StringTokenizer(line);
double R = 1.987;
while (st.hasMoreTokens()) {
String nextToken = st.nextToken().toLowerCase();
if (nextToken.equals("kcal/mol")) R = 1.987e-3;
else if (nextToken.equals("kj/mol")) R = 8.314e-3;
else if (nextToken.equals("j/mol")) R = 8.314;
}
// next line should have kinetic info
line = ChemParser.readMeaningfulLine(br_thermodat, true);
while (line != null && !line.equals("END")) {
boolean reversible = true;
if (!line.startsWith("!")&& !line.toLowerCase().contains("low") && !line.toLowerCase().contains("troe") && !line.toLowerCase().contains("dup") && !line.toLowerCase().contains("plog") && !line.contains("CHEB")) {
String rxnString = "";
String fullRxnString = line;
int[] reactsIndex = new int[3];
int[] prodsIndex = new int[3];
String shortRxnString = "";
double A = 0.0;
double n = 0.0;
double E = 0.0;
double[] logk = new double[T.length];
boolean chebyshevRate = false;
boolean rmgRate = false;
// Find all Chebyshev rate coefficients
if (line.contains("1.0E0 0.0 0.0")) {
chebyshevRate = true;
st = new StringTokenizer(line);
rxnString = st.nextToken();
shortRxnString = rxnString;
String[] reactsANDprods = rxnString.split("=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
numR = determineNumberOfSpecies(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
numP = determineNumberOfSpecies(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
line = ChemParser.readUncommentLine(br_thermodat); // TCHEB & PCHEB info
while (line.startsWith("!")) {
line = ChemParser.readUncommentLine(br_thermodat);
}
StringTokenizer st_cheb = new StringTokenizer(line,"/");
String currentToken = st_cheb.nextToken(); // TCHEB
StringTokenizer st_values = new StringTokenizer(st_cheb.nextToken());
double Tmin = Double.parseDouble(st_values.nextToken());
double Tmax = Double.parseDouble(st_values.nextToken());
double[] Ttilda = computeTtilda(T,Tmin,Tmax);
currentToken = st_cheb.nextToken(); // PCHEB
st_values = new StringTokenizer(st_cheb.nextToken());
double Pmin = Double.parseDouble(st_values.nextToken());
double Pmax = Double.parseDouble(st_values.nextToken());
double[] Ptilda = computePtilda(Pressure,Pmin,Pmax);
line = ChemParser.readUncommentLine(br_thermodat); // # of basis set info
st_cheb = new StringTokenizer(line,"/");
currentToken = st_cheb.nextToken();
st_values = new StringTokenizer(st_cheb.nextToken());
int nT = Integer.parseInt(st_values.nextToken());
int nP = Integer.parseInt(st_values.nextToken());
// Extract the coefficients
double[] coeffs = new double[nT*nP];
int coeffCounter = 0;
while (coeffCounter < nT*nP) {
line = ChemParser.readUncommentLine(br_thermodat);
String[] splitSlashes = line.split("/");
StringTokenizer st_coeffs = new StringTokenizer(splitSlashes[1]);
while (st_coeffs.hasMoreTokens()) {
coeffs[coeffCounter] = Double.parseDouble(st_coeffs.nextToken().trim());
++coeffCounter;
}
}
double[][] phiT = computephi(Ttilda,nT);
double[][] phiP = computephi(Ptilda,nP);
// Compute k(T,P)
for (int k=0; k<T.length; k++) {
for (int i=0; i<nT; i++) {
for (int j=0; j<nP; j++) {
logk[k] += coeffs[i*nP+j] * phiT[i][k] * phiP[j][0];
}
}
}
String output = "";
for (int k=0; k<T.length; k++) {
output += logk[k] + "\t";
}
// System.out.println(output + rxnString);
for (int k=0; k<T.length; k++) {
if (logk[k] > 20 && numR==1)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
else if (logk[k] > 20)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
}
else if (line.contains("(+m)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+m\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("(+M)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+M\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+m")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+m");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+M=")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+M\\=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
StringTokenizer removeComments = new StringTokenizer(sepStrings[1]);
String inputString = removeComments.nextToken();
prodsIndex = determineSpeciesIndex(inputString.substring(0,inputString.length()-2));
}
else if (line.contains("=")) {
rmgRate = true;
shortRxnString = line;
st = new StringTokenizer(line);
shortRxnString = st.nextToken();
if (shortRxnString.contains("=>")) reversible = false;
A = Double.parseDouble(st.nextToken());
n = Double.parseDouble(st.nextToken());
E = Double.parseDouble(st.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
output += logk[k] + "\t";
}
// System.out.println(output + shortRxnString);
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
if (logk[k] > 20 && numR==1)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
else if (logk[k] > 20)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
String[] reactsANDprods = shortRxnString.split("=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
}
// Calculate G_RT
if (rmgRate || chebyshevRate) {
double[] logKeq = new double[T.length];
String outputString = "";
for (int iii=0; iii<T.length; iii++) {
double H_RT = 0; double S_R = 0; int coeffsCounter = 0;
double Temperature = T[iii];
if (Temperature < 1000.0) coeffsCounter = 0;
else coeffsCounter = -7;
for (int numReacts=0; numReacts<numR; numReacts++) {
H_RT -= coeffs[reactsIndex[numReacts]][coeffsCounter+7] +
coeffs[reactsIndex[numReacts]][coeffsCounter+8]*Temperature/2 +
coeffs[reactsIndex[numReacts]][coeffsCounter+9]*Temperature*Temperature/3 +
coeffs[reactsIndex[numReacts]][coeffsCounter+10]*Temperature*Temperature*Temperature/4 +
coeffs[reactsIndex[numReacts]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/5 +
coeffs[reactsIndex[numReacts]][coeffsCounter+12]/Temperature;
S_R -= coeffs[reactsIndex[numReacts]][coeffsCounter+7]*Math.log(Temperature) +
coeffs[reactsIndex[numReacts]][coeffsCounter+8]*Temperature +
coeffs[reactsIndex[numReacts]][coeffsCounter+9]*Temperature*Temperature/2 +
coeffs[reactsIndex[numReacts]][coeffsCounter+10]*Temperature*Temperature*Temperature/3 +
coeffs[reactsIndex[numReacts]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/4 +
coeffs[reactsIndex[numReacts]][coeffsCounter+13];
}
for (int numProds=0; numProds<numP; numProds++) {
H_RT += coeffs[prodsIndex[numProds]][coeffsCounter+7] +
coeffs[prodsIndex[numProds]][coeffsCounter+8]*Temperature/2 +
coeffs[prodsIndex[numProds]][coeffsCounter+9]*Temperature*Temperature/3 +
coeffs[prodsIndex[numProds]][coeffsCounter+10]*Temperature*Temperature*Temperature/4 +
coeffs[prodsIndex[numProds]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/5 +
coeffs[prodsIndex[numProds]][coeffsCounter+12]/Temperature;
S_R += coeffs[prodsIndex[numProds]][coeffsCounter+7]*Math.log(Temperature) +
coeffs[prodsIndex[numProds]][coeffsCounter+8]*Temperature +
coeffs[prodsIndex[numProds]][coeffsCounter+9]*Temperature*Temperature/2 +
coeffs[prodsIndex[numProds]][coeffsCounter+10]*Temperature*Temperature*Temperature/3 +
coeffs[prodsIndex[numProds]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/4 +
coeffs[prodsIndex[numProds]][coeffsCounter+13];
}
logKeq[iii] = Math.log10(Math.exp(1))*(-H_RT + S_R) + (numP-numR)*Math.log10(1.0/82.06/Temperature);
if (reversible) {
if (logk[iii] - logKeq[iii] > 20 && numP==1)
System.out.format("logkr = %4.2f at T = %4.0fK for %s\n", (logk[iii]-logKeq[iii]), T[iii], fullRxnString);
else if (logk[iii] - logKeq[iii] > 20)
System.out.format("logkr = %4.2f at T = %4.0fK for %s\n", (logk[iii]-logKeq[iii]), T[iii], fullRxnString);
}
// Check if Ea is sensible
// if (rmgRate && iii==T.length-1) {
// double deltaHrxn = H_RT * R * T[iii];
// double sensible = E - deltaHrxn;
// if (sensible < 0.0)
// System.out.println("Ea - deltaHrxn = " + sensible + " for " + shortRxnString);
}
String output = "";
for (int iii=0; iii<T.length; iii++) {
output += (logk[iii] - logKeq[iii]) + "\t";
}
// System.out.println(output + shortRxnString);
reverseRateCoefficients.append(output + shortRxnString + "\n");
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
} catch (FileNotFoundException e) {
System.err.println("File was not found: " + args[0] + "\n");
}
try {
File reversek = new File("reverseRateCoefficients.txt");
FileWriter fw_rxns = new FileWriter(reversek);
fw_rxns.write(reverseRateCoefficients.toString());
fw_rxns.close();
}
catch (IOException e) {
System.out.println("Could not write reverseRateCoefficients.txt files");
System.exit(0);
}
}
public static int[] determineSpeciesIndex(String reactsORprods) {
if (reactsORprods.startsWith(">"))
reactsORprods = reactsORprods.substring(1,reactsORprods.length());
int[] speciesIndex = new int[3];
int speciesCounter = 0;
StringTokenizer st_reacts = new StringTokenizer(reactsORprods,"+");
while (st_reacts.hasMoreTokens()) {
String reactantString = st_reacts.nextToken();
boolean groupedSpecies = false;
if (reactantString.startsWith("2")) {
reactantString = reactantString.substring(1,reactantString.length());
groupedSpecies = true;
}
boolean found = false;
for (int numSpecies=0; numSpecies<names.length; numSpecies++) {
if (reactantString.equals(names[numSpecies])) {
speciesIndex[speciesCounter]=numSpecies;
++speciesCounter;
if (groupedSpecies) {
speciesIndex[speciesCounter]=numSpecies;
++speciesCounter;
}
found = true;
break;
}
}
if (!found) {
System.err.println("Could not find thermo for species: " + reactantString);
// System.exit(0);
}
}
return speciesIndex;
}
public static int determineNumberOfSpecies(String reactsORprods) {
StringTokenizer st_reacts = new StringTokenizer(reactsORprods,"+");
int numSpecies = 0;
while (st_reacts.hasMoreTokens()) {
++numSpecies;
String tempString = st_reacts.nextToken();
if (tempString.startsWith("2")) ++numSpecies;
}
return numSpecies;
}
public static double[] computeTtilda(double[] T, double Tmin, double Tmax) {
double[] Ttilda = new double[T.length];
for (int i=0; i<T.length; i++) {
if (T[i] > Tmax) T[i] = Tmax;
Ttilda[i] = (2/T[i] - 1/Tmin - 1/Tmax) / (1/Tmax - 1/Tmin);
}
return Ttilda;
}
public static double[] computePtilda(double[] P, double Pmin, double Pmax) {
double[] Ptilda = new double[P.length];
for (int i=0; i<P.length; i++) {
Ptilda[i] = (2*Math.log10(P[i]) - Math.log10(Pmin) - Math.log10(Pmax)) / (Math.log10(Pmax) - Math.log10(Pmin));
}
return Ptilda;
}
public static double[][] computephi(double[] argumentX, int maxCounter) {
if (argumentX[0] > 1.0) argumentX[0] = 1.0;
double[][] phi = new double[maxCounter][argumentX.length];
for (int j=0; j<argumentX.length; j++) {
for (int i=0; i<maxCounter; i++) {
phi[i][j] = Math.cos(i*Math.acos(argumentX[j]));
}
}
return phi;
}
} |
package edu.wustl.cab2b.server.util;
import static edu.wustl.cab2b.common.util.Constants.TYPE_DERIVED;
import edu.common.dynamicextensions.domain.DomainObjectFactory;
import edu.common.dynamicextensions.domaininterface.AbstractMetadataInterface;
import edu.common.dynamicextensions.domaininterface.AssociationInterface;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.domaininterface.RoleInterface;
import edu.common.dynamicextensions.domaininterface.TaggedValueInterface;
import edu.common.dynamicextensions.util.global.Constants;
public class TestUtil {
private static DomainObjectFactory deFactory = DomainObjectFactory.getInstance();
public static EntityInterface getEntity(String entityName, String attrName, EntityInterface parent) {
AttributeInterface a = getAttribute(attrName);
EntityInterface e1 = deFactory.createEntity();
e1.setName(entityName);
if (parent != null) {
e1.setParentEntity(parent);
markInherited(a);
}
e1.addAttribute(a);
return e1;
}
public static EntityInterface getEntity(String entityName, String attrName) {
AttributeInterface a = getAttribute(attrName);
EntityInterface e1 = getEntity(entityName);
e1.addAttribute(a);
a.setEntity(e1);
return e1;
}
public static AttributeInterface getAttribute(String entityName, long entityId, String attrName,long attrId) {
EntityInterface e = getEntity(entityName,attrName);
AttributeInterface a = e.getAttributeCollection().iterator().next();
e.setId(entityId);
a.setId(attrId);
return a;
}
public static EntityInterface getEntity(String entityName) {
EntityInterface e1 = deFactory.createEntity();
e1.setName(entityName);
return e1;
}
public static EntityInterface getEntity(String entityName, long id) {
EntityInterface e1 = deFactory.createEntity();
e1.setId(id);
e1.setName(entityName);
return e1;
}
public static EntityGroupInterface getEntityGroup(String name, long id) {
EntityGroupInterface e1 = deFactory.createEntityGroup();
e1.setId(id);
e1.setName(name);
e1.setLongName(name);
return e1;
}
public static void markInherited(AbstractMetadataInterface owner) {
TaggedValueInterface taggedValue = deFactory.createTaggedValue();
taggedValue.setKey(TYPE_DERIVED);
taggedValue.setValue(TYPE_DERIVED);
owner.addTaggedValue(taggedValue);
}
public static AssociationInterface getAssociation(String srcEntityName, String targetEntityName) {
EntityInterface src = getEntity(srcEntityName);
EntityInterface target = getEntity(targetEntityName);
AssociationInterface association = deFactory.createAssociation();
association.setName("AssociationName_" + src.getAssociationCollection().size() + 1);
association.setEntity(src);
src.addAssociation(association);
association.setSourceRole(getRole("srcRole"));
association.setTargetEntity(target);
association.setTargetRole(getRole("tgtRole"));
association.setAssociationDirection(Constants.AssociationDirection.BI_DIRECTIONAL);
return association;
}
private static RoleInterface getRole(String roleName) {
RoleInterface role = deFactory.createRole();
role.setAssociationsType(Constants.AssociationType.ASSOCIATION);
role.setName(roleName);
role.setMaximumCardinality(Constants.Cardinality.MANY);
role.setMinimumCardinality(Constants.Cardinality.MANY);
return role;
}
public static AttributeInterface getAttribute(String name) {
AttributeInterface a = deFactory.createStringAttribute();
a.setName(name);
return a;
}
public static EntityInterface getEntityWithGrp(String groupName, String entityName, String attrName) {
AttributeInterface a = getAttribute(attrName);
EntityInterface e1 = getEntity(entityName);
e1.addAttribute(a);
a.setEntity(e1);
EntityGroupInterface eg = DomainObjectFactory.getInstance().createEntityGroup();
eg.setName(groupName);
eg.addEntity(e1);
e1.addEntityGroupInterface(eg);
return e1;
}
} |
package net.fortuna.ical4j.data;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.text.ParseException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <pre>
* $Id$
*
* Created [Nov 5, 2004]
* </pre>
*
* The default implementation of a calendar parser.
* @author Ben Fortuna
*/
public class CalendarParserImpl implements CalendarParser {
private static final int WORD_CHAR_START = 32;
private static final int WORD_CHAR_END = 255;
private static final int WHITESPACE_CHAR_START = 0;
private static final int WHITESPACE_CHAR_END = 20;
private static final String UNEXPECTED_TOKEN_MESSAGE = "Expected [{0}], read [{1}]";
private Log log = LogFactory.getLog(CalendarParserImpl.class);
private final ComponentListParser componentListParser = new ComponentListParser();
private final ComponentParser componentParser = new ComponentParser();
private final PropertyListParser propertyListParser = new PropertyListParser();
private final PropertyParser propertyParser = new PropertyParser();
private final ParameterListParser paramListParser = new ParameterListParser();
private final ParameterParser paramParser = new ParameterParser();
/**
* {@inheritDoc}
*/
public final void parse(final InputStream in, final ContentHandler handler)
throws IOException, ParserException {
parse(new InputStreamReader(in), handler);
}
/**
* {@inheritDoc}
*/
public final void parse(final Reader in, final ContentHandler handler)
throws IOException, ParserException {
final StreamTokenizer tokeniser = new StreamTokenizer(in);
try {
tokeniser.resetSyntax();
tokeniser.wordChars(WORD_CHAR_START, WORD_CHAR_END);
tokeniser.whitespaceChars(WHITESPACE_CHAR_START,
WHITESPACE_CHAR_END);
tokeniser.ordinaryChar(':');
tokeniser.ordinaryChar(';');
tokeniser.ordinaryChar('=');
tokeniser.ordinaryChar('\t');
tokeniser.eolIsSignificant(true);
tokeniser.whitespaceChars(0, 0);
tokeniser.quoteChar('"');
// BEGIN:VCALENDAR
assertToken(tokeniser, in, Calendar.BEGIN);
assertToken(tokeniser, in, ':');
assertToken(tokeniser, in, Calendar.VCALENDAR, true);
assertToken(tokeniser, in, StreamTokenizer.TT_EOL);
handler.startCalendar();
// parse calendar properties..
propertyListParser.parse(tokeniser, in, handler);
// parse components..
componentListParser.parse(tokeniser, in, handler);
// END:VCALENDAR
// assertToken(tokeniser,Calendar.END);
assertToken(tokeniser, in, ':');
assertToken(tokeniser, in, Calendar.VCALENDAR, true);
handler.endCalendar();
}
catch (Exception e) {
if (e instanceof IOException) {
throw (IOException) e;
}
if (e instanceof ParserException) {
throw (ParserException) e;
}
else {
throw new ParserException(e.getMessage(), getLineNumber(tokeniser, in), e);
}
}
}
/**
* Parses an iCalendar property list from the specified stream tokeniser.
* @param tokeniser
* @throws IOException
* @throws ParseException
* @throws URISyntaxException
* @throws URISyntaxException
* @throws ParserException
*/
private class PropertyListParser {
public void parse(final StreamTokenizer tokeniser, Reader in,
final ContentHandler handler) throws IOException, ParseException,
URISyntaxException, ParserException {
assertToken(tokeniser, in, StreamTokenizer.TT_WORD);
while (/*
* !Component.BEGIN.equals(tokeniser.sval) &&
*/!Component.END.equals(tokeniser.sval)) {
// check for timezones observances or vevent/vtodo alarms..
if (Component.BEGIN.equals(tokeniser.sval)) {
componentParser.parse(tokeniser, in, handler);
}
else {
propertyParser.parse(tokeniser, in, handler);
}
absorbWhitespace(tokeniser);
// assertToken(tokeniser, StreamTokenizer.TT_WORD);
}
}
}
/**
* Parses an iCalendar property from the specified stream tokeniser.
* @param tokeniser
* @throws IOException
* @throws ParserException
* @throws URISyntaxException
* @throws ParseException
*/
private class PropertyParser {
private static final String PARSE_DEBUG_MESSAGE = "Property [{0}]";
private static final String PARSE_EXCEPTION_MESSAGE = "Property [{0}]";
private void parse(final StreamTokenizer tokeniser, Reader in,
final ContentHandler handler) throws IOException, ParserException,
URISyntaxException, ParseException {
final String name = tokeniser.sval;
// debugging..
if (log.isDebugEnabled()) {
log.debug(MessageFormat.format(PARSE_DEBUG_MESSAGE, new Object[] {name}));
}
handler.startProperty(name);
paramListParser.parse(tokeniser, in, handler);
// it appears that control tokens (ie. ':') are allowed
// after the first instance on a line is used.. as such
// we must continue appending to value until EOL is
// reached..
// assertToken(tokeniser, StreamTokenizer.TT_WORD);
// String value = tokeniser.sval;
final StringBuffer value = new StringBuffer();
// assertToken(tokeniser,StreamTokenizer.TT_EOL);
// DQUOTE is ordinary char for property value
// From sec 4.3.11 of rfc-2445:
// text = *(TSAFE-CHAR / ":" / DQUOTE / ESCAPED-CHAR)
tokeniser.ordinaryChar('"');
int nextToken = tokeniser.nextToken();
while (nextToken != StreamTokenizer.TT_EOL
&& nextToken != StreamTokenizer.TT_EOF) {
if (tokeniser.ttype == StreamTokenizer.TT_WORD) {
value.append(tokeniser.sval);
}
else {
value.append((char) tokeniser.ttype);
}
nextToken = tokeniser.nextToken();
}
// reset DQUOTE to be quote char
tokeniser.quoteChar('"');
if (nextToken == StreamTokenizer.TT_EOF) {
throw new ParserException("Unexpected end of file",
getLineNumber(tokeniser, in));
}
try {
handler.propertyValue(value.toString());
}
catch (ParseException e) {
final ParseException eNew = new ParseException("[" + name + "] "
+ e.getMessage(), e.getErrorOffset());
eNew.initCause(e);
throw eNew;
}
handler.endProperty(name);
}
}
/**
* Parses a list of iCalendar parameters by parsing the specified stream tokeniser.
* @param tokeniser
* @throws IOException
* @throws ParserException
* @throws URISyntaxException
*/
private class ParameterListParser {
public void parse(final StreamTokenizer tokeniser, Reader in,
final ContentHandler handler) throws IOException, ParserException,
URISyntaxException {
while (tokeniser.nextToken() == ';') {
paramParser.parse(tokeniser, in, handler);
}
}
}
/**
* @param tokeniser
* @param handler
* @throws IOException
* @throws ParserException
* @throws URISyntaxException
*/
private class ParameterParser {
private void parse(final StreamTokenizer tokeniser, Reader in,
final ContentHandler handler) throws IOException, ParserException,
URISyntaxException {
assertToken(tokeniser, in, StreamTokenizer.TT_WORD);
final String paramName = tokeniser.sval;
// debugging..
if (log.isDebugEnabled()) {
log.debug("Parameter [" + paramName + "]");
}
assertToken(tokeniser, in, '=');
final StringBuffer paramValue = new StringBuffer();
// preserve quote chars..
if (tokeniser.nextToken() == '"') {
paramValue.append('"');
paramValue.append(tokeniser.sval);
paramValue.append('"');
}
else if (tokeniser.sval != null) {
paramValue.append(tokeniser.sval);
}
try {
handler.parameter(paramName, paramValue.toString());
}
catch (ClassCastException cce) {
throw new ParserException("Error parsing parameter", getLineNumber(tokeniser, in), cce);
}
}
}
/**
* Parses an iCalendar component list from the specified stream tokeniser.
* @param tokeniser
* @throws IOException
* @throws ParseException
* @throws URISyntaxException
* @throws ParserException
*/
private class ComponentListParser {
private void parse(final StreamTokenizer tokeniser, Reader in,
final ContentHandler handler) throws IOException, ParseException,
URISyntaxException, ParserException {
while (Component.BEGIN.equals(tokeniser.sval)) {
componentParser.parse(tokeniser, in, handler);
absorbWhitespace(tokeniser);
// assertToken(tokeniser, StreamTokenizer.TT_WORD);
}
}
}
/**
* Parses an iCalendar component from the specified stream tokeniser.
* @param tokeniser
* @throws IOException
* @throws ParseException
* @throws URISyntaxException
* @throws ParserException
*/
private class ComponentParser {
private void parse(final StreamTokenizer tokeniser, Reader in,
final ContentHandler handler) throws IOException, ParseException,
URISyntaxException, ParserException {
assertToken(tokeniser, in, ':');
assertToken(tokeniser, in, StreamTokenizer.TT_WORD);
final String name = tokeniser.sval;
handler.startComponent(name);
assertToken(tokeniser, in, StreamTokenizer.TT_EOL);
propertyListParser.parse(tokeniser, in, handler);
/*
* // a special case for VTIMEZONE component which contains
* // sub-components..
* if (Component.VTIMEZONE.equals(name)) {
* parseComponentList(tokeniser, handler);
* }
* // VEVENT/VTODO components may optionally have embedded VALARM
* // components..
* else if ((Component.VEVENT.equals(name) || Component.VTODO.equals(name))
* && Component.BEGIN.equals(tokeniser.sval)) {
* parseComponentList(tokeniser, handler);
* }
*/
assertToken(tokeniser, in, ':');
assertToken(tokeniser, in, name);
assertToken(tokeniser, in, StreamTokenizer.TT_EOL);
handler.endComponent(name);
}
}
/**
* Asserts that the next token in the stream matches the specified token.
* @param tokeniser stream tokeniser to perform assertion on
* @param token expected token
* @throws IOException when unable to read from stream
* @throws ParserException when next token in the stream does not match the expected token
*/
private void assertToken(final StreamTokenizer tokeniser, Reader in, final int token)
throws IOException, ParserException {
if (tokeniser.nextToken() != token) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, new Object[] {
new Integer(token), new Integer(tokeniser.ttype),
}), getLineNumber(tokeniser, in));
}
if (log.isDebugEnabled()) {
log.debug("[" + token + "]");
}
}
/**
* Asserts that the next token in the stream matches the specified token. This method is case-sensitive.
* @param tokeniser
* @param token
* @throws IOException
* @throws ParserException
*/
private void assertToken(final StreamTokenizer tokeniser, Reader in, final String token)
throws IOException, ParserException {
assertToken(tokeniser, in, token, false);
}
/**
* Asserts that the next token in the stream matches the specified token.
* @param tokeniser stream tokeniser to perform assertion on
* @param token expected token
* @throws IOException when unable to read from stream
* @throws ParserException when next token in the stream does not match the expected token
*/
private void assertToken(final StreamTokenizer tokeniser, Reader in,
final String token, final boolean ignoreCase) throws IOException,
ParserException {
// ensure next token is a word token..
assertToken(tokeniser, in, StreamTokenizer.TT_WORD);
if (ignoreCase) {
if (!token.equalsIgnoreCase(tokeniser.sval)) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, new Object[] {
token, tokeniser.sval,
}), getLineNumber(tokeniser, in));
}
}
else if (!token.equals(tokeniser.sval)) {
throw new ParserException(MessageFormat.format(UNEXPECTED_TOKEN_MESSAGE, new Object[] {
token, tokeniser.sval,
}), getLineNumber(tokeniser, in));
}
if (log.isDebugEnabled()) {
log.debug("[" + token + "]");
}
}
/**
* Absorbs extraneous newlines.
* @param tokeniser
* @throws IOException
*/
private void absorbWhitespace(final StreamTokenizer tokeniser) throws IOException {
// HACK: absorb extraneous whitespace between components (KOrganizer)..
while (tokeniser.nextToken() == StreamTokenizer.TT_EOL) {
if (log.isTraceEnabled()) {
log.trace("Absorbing extra whitespace..");
}
}
if (log.isTraceEnabled()) {
log.trace("Aborting: absorbing extra whitespace complete");
}
}
/**
* @param tokeniser
* @param in
* @return
*/
private int getLineNumber(StreamTokenizer tokeniser, Reader in) {
int line = tokeniser.lineno();
if (tokeniser.ttype == StreamTokenizer.TT_EOL) {
line -= 1;
}
if (in instanceof UnfoldingReader) {
// need to take unfolded lines into account
final int unfolded = ((UnfoldingReader) in).getLinesUnfolded();
line += unfolded;
}
return line;
}
} |
package de.naoth.rc.tools;
import de.naoth.rc.RobotControl;
import de.naoth.rc.RobotControlImpl;
import de.naoth.rc.core.manager.ObjectListener;
import de.naoth.rc.core.manager.SwingCommandExecutor;
import de.naoth.rc.core.server.Command;
import de.naoth.rc.core.server.ConnectionStatusEvent;
import de.naoth.rc.core.server.ConnectionStatusListener;
import de.naoth.rc.core.server.ResponseListener;
import static de.naoth.rc.statusbar.StatusbarPluginImpl.rc;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Box;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import net.xeoh.plugins.base.Plugin;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.events.PluginLoaded;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
/**
* @author Philipp Strobel <philippstrobel@posteo.de>
*/
@PluginImplementation
public class CommandRecorder implements Plugin, ConnectionStatusListener, ObjectListener<Command>
{
@InjectPlugin
public static RobotControl robotControl;
@InjectPlugin
public static SwingCommandExecutor commandExecutor;
private static final String REC_PREFIX = "recording_";
private static final String REC_SUFFIX = ".bin";
private static final String MENU_TOOLTIP = "Not connected to robot";
private static final String MENU_REC_START = "Start Recording";
private static final String MENU_REC_STOP = "Stop Recording";
private boolean isRecording = false;
private final List<Command> log = new LinkedList<>();
private final JMenu menuMacros = new javax.swing.JMenu("Macros");
private final JMenuItem menuStartRecording = new JMenuItem(MENU_REC_START);
/**
* Gets called, when the RC plugin was loaded.
* Adds the "Macros" menu item to the RC menubar and registers itself as connection listener.
*
* @param robotControl the RC instance (JFrame)
*/
@PluginLoaded
public void loaded(RobotControl robotControl) {
rc.getMessageServer().addConnectionStatusListener(this);
menuMacros.setEnabled(false);
menuMacros.setToolTipText(MENU_TOOLTIP);
menuMacros.setHorizontalTextPosition(SwingConstants.LEADING);
menuMacros.add(menuStartRecording);
menuMacros.addSeparator();
menuStartRecording.addActionListener((ActionEvent e) -> { toggleRecording(); });
addRecordingsToMenu();
insertMacrosMenuToMenuBar();
}
/**
* Inserts the "Macros" menu item to the end of the left menubar part.
*/
private void insertMacrosMenuToMenuBar() {
JMenuBar menu = ((RobotControlImpl)robotControl).getJMenuBar();
// find the index of the 'Filler', in order to insert the menu before it
int idx = menu.getComponentCount();
for (Component component : menu.getComponents()) {
if (component instanceof Box.Filler) {
idx = menu.getComponentIndex(component);
}
}
menu.add(menuMacros, idx);
}
/**
* Searches for recoding files and adds them to the macro menu.
*/
private void addRecordingsToMenu() {
Arrays.asList((new File(robotControl.getConfigPath())).listFiles((dir, name) -> {
return name.startsWith(REC_PREFIX) && name.endsWith(REC_SUFFIX);
})).forEach((f) -> {
String name = f.getName().substring(REC_PREFIX.length(), f.getName().length() - REC_SUFFIX.length());
addMenuItem(name);
});
}
/**
* Adds a recording to the macros menu.
* Also sets the tooltip and handles the click events.
*
* @param name the recording name
*/
private void addMenuItem(String name) {
JMenuItem item = new JMenuItem(name);
item.setToolTipText("<html>Replays the recorded commands.<br>Use <i>Ctrl+Click</i> to delete this recording.</html>");
item.addActionListener((e) -> {
JMenuItem source = (JMenuItem) e.getSource();
if((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) {
// delete requested
if(JOptionPane.showConfirmDialog(
((RobotControlImpl)robotControl),
"Do you want to remove the recording '"+name+"'?",
"Remove recording",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if(recordingFileName(name).delete()) { menuMacros.remove(source); }
}
} else {
// restore dialog configuration
File f = recordingFileName(source.getText());
if(f.isFile()) {
try {
loadRecording(f);
} catch (IOException ex) {
Logger.getLogger(RobotControlImpl.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(
((RobotControlImpl)robotControl),
"The '"+source.getText()+"' recording file doesn't exists!?",
"Missing recording file",
JOptionPane.ERROR_MESSAGE);
}
}
});
menuMacros.add(item);
}
/**
* Starts or stops the recording, based on the current state (helper method).
*/
private void toggleRecording() {
if (isRecording) {
stopRecording();
} else {
startRecording();
}
}
/**
* Starts the recording.
* Registers to the message server and updates the ui.
*/
private void startRecording() {
isRecording = true;
rc.getMessageServer().addListener(this);
menuMacros.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/naoth/rc/res/media-record.png")));
menuStartRecording.setText(MENU_REC_STOP);
}
/**
* Stops the recording.
* Unregisters from the message server, updates the ui and saves the recording.
*/
private void stopRecording() {
isRecording = false;
rc.getMessageServer().removeListener(this);
menuMacros.setIcon(null);
menuStartRecording.setText(MENU_REC_START);
saveRecording();
}
/**
* Returns the File for a given recording name (helper method).
*
* @param name the name of the recording
* @return the file object pointing to the file where the recording is/should be saved
*/
private File recordingFileName(String name) {
return new File(robotControl.getConfigPath() + "/" + REC_PREFIX + name + REC_SUFFIX);
}
/**
* Actually saves the recorded commands.
* Therefore checks whether commands were recorded and ask for a name for this
* recording. The recorded commands are written as serialized java objects to the file.
*/
private void saveRecording() {
// check if something was recorded
if (log.isEmpty()) {
JOptionPane.showMessageDialog(
((RobotControlImpl)robotControl),
"No commands were recorded.",
"Nothing recorded",
JOptionPane.WARNING_MESSAGE);
return;
}
// Ask for a name for this dialog configuration
String inputName = JOptionPane.showInputDialog(
((RobotControlImpl)robotControl),
"<html>Set a name for the recorded commands<br>"
+ "<small>Only alphanumerical characters are allowed and "
+ "whitespaces are replaced with '_'.</small></html>",
"Name of recording",
JOptionPane.QUESTION_MESSAGE);
// ignore canceled inputs
if(inputName == null) { return; }
// replace whitespaces with "_" and remove all other "invalid" characters
String name = inputName.trim()
.replaceAll("[\\s+]", "_")
.replaceAll("[^A-Za-z0-9_-]", "");
// ignore empty inputs
if(name.isEmpty()) { return; }
// create record file
File file = recordingFileName(name);
// if recording name already exists - ask to overwrite
if(file.isFile() && JOptionPane.showConfirmDialog(
((RobotControlImpl)robotControl),
"This dialog layout name already exists. Overwrite?",
"Overwrite",
JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
// don't overwrite!
return;
}
// write the logged commands to the record file
try {
FileOutputStream stream = new FileOutputStream(file);
ObjectOutputStream o = new ObjectOutputStream(stream);
o.writeObject(log);
o.close();
stream.close();
// add the new recording to the macro menu
addMenuItem(name);
} catch (FileNotFoundException ex) {
Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex);
}
log.clear();
}
/**
* Loads the recorded commands from the given file.
*
* @param f
* @throws IOException
*/
private void loadRecording(File f) throws IOException {
// if not connect, do not replay commands
if (!rc.getMessageServer().isConnected()) {
return;
}
FileInputStream stream = new FileInputStream(f);
ObjectInputStream oi = new ObjectInputStream(stream);
try {
List<Command> commands = (List<Command>) oi.readObject();
for (Command command : commands) {
rc.getMessageServer().executeCommand(new ResponseListener() {
@Override
public void handleResponse(byte[] result, Command command) {
System.out.println("Successfully executed command: " + command.getName());
}
@Override
public void handleError(int code) {
System.out.println("Error during command execution, error code: " + code);
}
}, command);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(CommandRecorder.class.getName()).log(Level.SEVERE, null, ex);
}
oi.close();
stream.close();
}
/**
* Enables the macros menu.
*
* @param event
*/
@Override
public void connected(ConnectionStatusEvent event) {
menuMacros.setEnabled(true);
menuMacros.setToolTipText(null);
}
/**
* Disables the macros menu and sets the tooltip.
* @param event
*/
@Override
public void disconnected(ConnectionStatusEvent event) {
menuMacros.setEnabled(false);
menuMacros.setToolTipText(MENU_TOOLTIP);
}
/**
* Records all 'set' commands.
*
* @param cmd
*/
@Override
public void newObjectReceived(Command cmd) {
// only store the 'set' commands
if (cmd.getName().endsWith(":set") || cmd.getName().endsWith(":set_agent")) {
log.add(cmd);
Logger.getLogger(CommandRecorder.class.getName()).log(Level.INFO, "Command logged: " + cmd.getName());
}
}
/**
* Ignore any errors.
*
* @param cause
*/
@Override
public void errorOccured(String cause) { /* should never happen! */ }
} |
package samples;
import choco.kernel.common.util.tools.ArrayUtils;
import org.kohsuke.args4j.Option;
import solver.Solver;
import solver.constraints.Arithmetic;
import solver.search.strategy.selectors.values.InDomainMin;
import solver.search.strategy.selectors.variables.InputOrder;
import solver.search.strategy.strategy.Assignment;
import solver.variables.IntVar;
import solver.variables.VariableFactory;
public class StressTest2 extends AbstractProblem {
@Option(name = "-k", usage = "number of times round the loop.", required = false)
int k = 100;
@Option(name = "-n", usage = "number of iterations of change per loop .", required = false)
int n = 100;
@Option(name = "-m", usage = "m^2 propagators per change of loop.", required = false)
int m = 100;
IntVar[] x, y;
@Override
public void createSolver() {
solver = new Solver("StressTest2(" + k + "," + n + "," + m + ")");
}
@Override
public void buildModel() {
y = VariableFactory.boundedArray("y", n+1, 0, k * n, solver);
x = VariableFactory.boundedArray("x", m+1, 0, k * n, solver);
for (int i = 2; i <= n; i++) {
solver.post(new Arithmetic(y[i - 1], "-", y[i], "<=", 0, solver));
}
for (int i = 1; i <= n; i++) {
solver.post(new Arithmetic(y[0], "-", y[i], "<=", n - i + 1, solver));
}
solver.post(new Arithmetic(y[n], "-", x[0], "<=", 0, solver));
for (int i = 0; i < m; i++) {
for (int j = i + 1; j <= m; j++) {
solver.post(new Arithmetic(x[i], "-", x[j], "<=", 0, solver));
}
}
solver.post(new Arithmetic(x[m], "-", y[0], "<=", -2, solver));
}
@Override
public void configureSearch() {
IntVar[] vars = ArrayUtils.append(y, x);
solver.set(new Assignment(vars, new InputOrder(vars, solver.getEnvironment()), new InDomainMin()));
}
@Override
public void configureEngine() {
}
@Override
public void solve() {
solver.findSolution();
}
@Override
public void prettyOut() {
}
public static void main(String[] args) {
new StressTest2().execute(args);
}
} |
package org.chromium.sdk.internal.wip;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.chromium.sdk.Breakpoint;
import org.chromium.sdk.CallFrame;
import org.chromium.sdk.DebugContext;
import org.chromium.sdk.DebugContext.StepAction;
import org.chromium.sdk.ExceptionData;
import org.chromium.sdk.JavascriptVm;
import org.chromium.sdk.JsArray;
import org.chromium.sdk.JsEvaluateContext;
import org.chromium.sdk.JsFunction;
import org.chromium.sdk.JsObject;
import org.chromium.sdk.JsScope;
import org.chromium.sdk.JsValue;
import org.chromium.sdk.JsVariable;
import org.chromium.sdk.Script;
import org.chromium.sdk.SyncCallback;
import org.chromium.sdk.TextStreamPosition;
import org.chromium.sdk.internal.JsEvaluateContextBase;
import org.chromium.sdk.internal.ScriptImpl;
import org.chromium.sdk.internal.tools.v8.MethodIsBlockingException;
import org.chromium.sdk.internal.wip.WipExpressionBuilder.ValueNameBuilder;
import org.chromium.sdk.internal.wip.WipValueLoader.Getter;
import org.chromium.sdk.internal.wip.protocol.WipProtocol;
import org.chromium.sdk.internal.wip.protocol.input.debugger.CallFrameValue;
import org.chromium.sdk.internal.wip.protocol.input.debugger.EvaluateOnCallFrameData;
import org.chromium.sdk.internal.wip.protocol.input.debugger.PausedEventData;
import org.chromium.sdk.internal.wip.protocol.input.debugger.ResumedEventData;
import org.chromium.sdk.internal.wip.protocol.input.debugger.ScopeValue;
import org.chromium.sdk.internal.wip.protocol.input.runtime.EvaluateData;
import org.chromium.sdk.internal.wip.protocol.input.runtime.RemoteObjectValue;
import org.chromium.sdk.internal.wip.protocol.input.runtime.RemotePropertyValue;
import org.chromium.sdk.internal.wip.protocol.output.WipParams;
import org.chromium.sdk.internal.wip.protocol.output.WipParamsWithResponse;
import org.chromium.sdk.internal.wip.protocol.output.debugger.EvaluateOnCallFrameParams;
import org.chromium.sdk.internal.wip.protocol.output.debugger.ResumeParams;
import org.chromium.sdk.internal.wip.protocol.output.debugger.StepIntoParams;
import org.chromium.sdk.internal.wip.protocol.output.debugger.StepOutParams;
import org.chromium.sdk.internal.wip.protocol.output.debugger.StepOverParams;
import org.chromium.sdk.internal.wip.protocol.output.runtime.EvaluateParams;
import org.chromium.sdk.util.AsyncFutureRef;
import org.chromium.sdk.util.LazyConstructable;
import sun.net.www.content.audio.wav;
/**
* Builder for {@link DebugContext} that works with Wip protocol.
*/
class WipContextBuilder {
private static final Logger LOGGER = Logger.getLogger(WipContextBuilder.class.getName());
private final WipTabImpl tabImpl;
private WipDebugContextImpl currentContext = null;
WipContextBuilder(WipTabImpl tabImpl) {
this.tabImpl = tabImpl;
}
void createContext(PausedEventData data) {
if (currentContext != null) {
LOGGER.severe("Context is already created");
currentContext = null;
}
final WipDebugContextImpl context = new WipDebugContextImpl(data);
currentContext = context;
final List<Map<Long, ScriptImpl>> loadedScriptsHolder = new ArrayList<Map<Long,ScriptImpl>>(1);
tabImpl.getScriptManager().loadScriptSourcesAsync(context.getScriptIds(),
new WipScriptManager.ScriptSourceLoadCallback() {
@Override
public void done(Map<Long, ScriptImpl> loadedScripts) {
loadedScriptsHolder.add(loadedScripts);
}
},
new SyncCallback() {
@Override
public void callbackDone(RuntimeException e) {
// Invoke next step from sync callback -- even if previous step failed.
tabImpl.getCommandProcessor().runInDispatchThread(new Runnable() {
@Override
public void run() {
if (!loadedScriptsHolder.isEmpty()) {
context.setScripts(loadedScriptsHolder.get(0));
}
tabImpl.getDebugListener().getDebugEventListener().suspended(context);
}
});
}
});
}
void onResumeReportedFromRemote(ResumedEventData event) {
if (currentContext == null) {
throw new IllegalStateException();
}
WipDebugContextImpl context = currentContext;
currentContext = null;
this.tabImpl.getDebugListener().getDebugEventListener().resumed();
context.reportClosed();
}
class WipDebugContextImpl implements DebugContext {
private final WipValueLoader valueLoader = new WipValueLoader(this);
private final List<CallFrameImpl> frames;
private final ExceptionData exceptionData;
private final AtomicReference<CloseRequest> closeRequest =
new AtomicReference<CloseRequest>(null);
private final JsEvaluateContext globalContext;
public WipDebugContextImpl(PausedEventData data) {
PausedEventData.Details details = data.details();
List<CallFrameValue> frameDataList = details.callFrames();
frames = new ArrayList<CallFrameImpl>(frameDataList.size());
for (CallFrameValue frameData : frameDataList) {
frames.add(new CallFrameImpl(frameData));
}
RemoteObjectValue exceptionRemoteObject = details.exception();
if (exceptionRemoteObject == null) {
exceptionData = null;
} else {
JsValue exceptionValue =
valueLoader.getValueBuilder().wrap(exceptionRemoteObject, EXCEPTION_NAME);
exceptionData = new ExceptionDataImpl(exceptionValue);
}
globalContext = new WipEvaluateContextImpl<EvaluateData, EvaluateParams>() {
@Override protected EvaluateParams createRequestParams(String expression) {
return new EvaluateParams(expression, "watch-group", false);
}
@Override protected RemoteObjectValue getRemoteObjectValue(EvaluateData data) {
return data.result();
}
@Override protected Boolean getWasThrown(EvaluateData data) {
return data.wasThrown();
}
};
}
WipValueLoader getValueLoader() {
return valueLoader;
}
void reportClosed() {
CloseRequest request = this.closeRequest.get();
if (request != null && request.callback != null) {
request.callback.success();
}
}
Set<Long> getScriptIds() {
Set<Long> scriptIds = new HashSet<Long>();
for (CallFrameImpl frame : frames) {
Long sourceId = frame.getSourceId();
if (sourceId != null) {
scriptIds.add(sourceId);
}
}
return scriptIds;
}
void setScripts(Map<Long, ScriptImpl> loadedScripts) {
for (CallFrameImpl frame : frames) {
Long sourceId = frame.getSourceId();
if (sourceId != null) {
frame.setScript(loadedScripts.get(sourceId));
}
}
}
@Override
public State getState() {
if (exceptionData == null) {
return State.NORMAL;
} else {
return State.EXCEPTION;
}
}
@Override
public ExceptionData getExceptionData() {
return exceptionData;
}
@Override
public Collection<? extends Breakpoint> getBreakpointsHit() {
// TODO: implement.
return Collections.emptyList();
}
@Override
public List<? extends CallFrame> getCallFrames() {
return frames;
}
@Override
public void continueVm(StepAction stepAction, int stepCount,
ContinueCallback callback) {
{
boolean updated = closeRequest.compareAndSet(null, new CloseRequest(callback));
if (!updated) {
throw new IllegalStateException("Continue already requested");
}
}
WipParams params = sdkStepToProtocolStep(stepAction);
tabImpl.getCommandProcessor().send(params, null, null);
}
@Override
public JsEvaluateContext getGlobalEvaluateContext() {
return globalContext;
}
public WipTabImpl getTab() {
return tabImpl;
}
public WipCommandProcessor getCommandProcessor() {
return tabImpl.getCommandProcessor();
}
private class CloseRequest {
final ContinueCallback callback;
CloseRequest(ContinueCallback callback) {
this.callback = callback;
}
}
private class CallFrameImpl implements CallFrame {
private final String functionName;
private final String id;
private final LazyConstructable<ScopeData> scopeData;
private final TextStreamPosition streamPosition;
private final Long sourceId;
private ScriptImpl scriptImpl;
public CallFrameImpl(CallFrameValue frameData) {
functionName = frameData.functionName();
id = frameData.id();
Object sourceIDObject = frameData.location().sourceID();
sourceId = Long.parseLong(sourceIDObject.toString());
final List<ScopeValue> scopeDataList = frameData.scopeChain();
scopeData = LazyConstructable.create(new LazyConstructable.Factory<ScopeData>() {
@Override
public ScopeData construct() {
final List<JsScope> scopes = new ArrayList<JsScope>(scopeDataList.size());
ScopeValue localScopeData = null;
for (int i = 0; i < scopeDataList.size(); i++) {
ScopeValue scopeData = scopeDataList.get(i);
JsScope.Type type = WIP_TO_SDK_SCOPE_TYPE.get(scopeData.type());
if (type == null) {
type = JsScope.Type.UNKNOWN;
}
scopes.add(createScope(scopeData, type));
if (type == JsScope.Type.LOCAL) {
if (localScopeData != null) {
LOGGER.log(Level.SEVERE, "Double local scope", new Exception());
}
localScopeData = scopeData;
}
}
final JsVariable thisObject;
if (localScopeData == null) {
LOGGER.log(Level.SEVERE, "Missing local scope", new Exception());
thisObject = null;
} else {
RemoteObjectValue thisObjectData = localScopeData.getThis();
if (thisObjectData == null) {
thisObject = null;
} else {
thisObject = createSimpleNameVariable("this", thisObjectData);
}
}
return new ScopeData(scopes, thisObject);
}
});
// 0-based.
final int line = (int) frameData.location().lineNumber();
// 0-based.
// TODO: check documentation, whether it's 0-based
Long columnObject = frameData.location().columnNumber();
final int column;
if (columnObject == null) {
column = 0;
} else {
column = columnObject.intValue();
}
streamPosition = new TextStreamPosition() {
@Override public int getOffset() {
return WipBrowserImpl.throwUnsupported();
}
@Override public int getLine() {
return line;
}
@Override public int getColumn() {
return column;
}
};
}
Long getSourceId() {
return sourceId;
}
void setScript(ScriptImpl scriptImpl) {
this.scriptImpl = scriptImpl;
}
@Override
public Collection<? extends JsVariable> getVariables() {
return WipBrowserImpl.throwUnsupported();
}
@Override
public List<? extends JsScope> getVariableScopes() {
return scopeData.get().scopes;
}
@Override
public JsVariable getReceiverVariable() {
return scopeData.get().thisObject;
}
@Override
public Script getScript() {
return scriptImpl;
}
@Override
public TextStreamPosition getStatementStartPosition() {
return streamPosition;
}
@Override
public String getFunctionName() {
return functionName;
}
@Override
public JsEvaluateContext getEvaluateContext() {
return evaluateContext;
}
private JsVariable createSimpleNameVariable(final String name,
RemoteObjectValue thisObjectData) {
ValueNameBuilder valueNameBuidler = WipExpressionBuilder.createRootName(name, false);
return valueLoader.getValueBuilder().createVariable(thisObjectData, valueNameBuidler);
}
private final WipEvaluateContextImpl<?,?> evaluateContext =
new WipEvaluateContextImpl<EvaluateOnCallFrameData, EvaluateOnCallFrameParams>() {
@Override protected EvaluateOnCallFrameParams createRequestParams(String expression) {
return new EvaluateOnCallFrameParams(id, expression, "watch-group", false);
}
@Override protected RemoteObjectValue getRemoteObjectValue(EvaluateOnCallFrameData data) {
return data.result();
}
@Override protected Boolean getWasThrown(EvaluateOnCallFrameData data) {
return data.wasThrown();
}
};
}
private class ScopeData {
final List<JsScope> scopes;
final JsVariable thisObject;
ScopeData(List<JsScope> scopes, JsVariable thisObject) {
this.scopes = scopes;
this.thisObject = thisObject;
}
}
private class ExceptionDataImpl implements ExceptionData {
private final JsValue exceptionValue;
ExceptionDataImpl(JsValue exceptionValue) {
this.exceptionValue = exceptionValue;
}
@Override
public JsObject getExceptionObject() {
if (exceptionValue instanceof JsObject == false) {
return null;
}
return (JsObject) exceptionValue;
}
@Override
public JsValue getExceptionValue() {
return exceptionValue;
}
@Override
public boolean isUncaught() {
// TODO: implement.
return false;
}
@Override
public String getSourceText() {
// TODO: implement.
return null;
}
@Override
public String getExceptionMessage() {
return exceptionValue.getValueString();
}
}
@Override
public JavascriptVm getJavascriptVm() {
return tabImpl;
}
JsScope createScope(ScopeValue scopeData, JsScope.Type type) {
if (type == JsScope.Type.WITH) {
return new WithScopeImpl(scopeData);
} else {
return new ScopeImpl(scopeData, type);
}
}
private class ScopeImpl implements JsScope {
private final AsyncFutureRef<Getter<ScopeVariables>> propertiesRef =
new AsyncFutureRef<Getter<ScopeVariables>>();
private final String objectId;
private final Type type;
public ScopeImpl(ScopeValue scopeData, Type type) {
this.type = type;
if (!WipProtocol.parseHasChildren(scopeData.object().hasChildren())) {
objectId = null;
propertiesRef.initializeTrivial(EMPTY_SCOPE_VARIABLES_OPTIONAL);
} else {
objectId = scopeData.object().objectId();
}
}
@Override
public Type getType() {
return type;
}
@Override
public WithScope asWithScope() {
// TODO: implement.
return null;
}
@Override
public List<? extends JsVariable> getVariables() {
if (!propertiesRef.isInitialized()) {
WipValueLoader.LoadPostprocessor<Getter<ScopeVariables>> processor =
new WipValueLoader.LoadPostprocessor<Getter<ScopeVariables>>() {
@Override
public Getter<ScopeVariables> process(
List<? extends RemotePropertyValue> propertyList) {
final List<JsVariable> properties = new ArrayList<JsVariable>(propertyList.size());
WipValueBuilder valueBuilder = valueLoader.getValueBuilder();
for (RemotePropertyValue property : propertyList) {
final String name = property.name();
ValueNameBuilder valueNameBuilder =
WipExpressionBuilder.createRootName(name, false);
JsVariable variable =
valueBuilder.createVariable(property.value(), valueNameBuilder);
properties.add(variable);
}
final ScopeVariables scopeVariables = new ScopeVariables(properties);
return new Getter<ScopeVariables>() {
@Override
ScopeVariables get() {
return scopeVariables;
}
};
}
@Override
public Getter<ScopeVariables> getEmptyResult() {
return EMPTY_SCOPE_VARIABLES_OPTIONAL;
}
@Override
public Getter<ScopeVariables> forException(Exception exception) {
return WipValueLoader.Getter.newFailure(exception);
}
};
// This is blocking.
valueLoader.loadPropertiesAsync(objectId, processor, propertiesRef);
}
// This is blocking.
return propertiesRef.getSync().get().variables;
}
}
private class WithScopeImpl implements JsScope.WithScope {
private final JsValue jsValue;
WithScopeImpl(ScopeValue scopeData) {
jsValue = valueLoader.getValueBuilder().wrap(scopeData.object(), WITH_OBJECT_NAME);
}
@Override
public Type getType() {
return Type.WITH;
}
@Override
public WithScope asWithScope() {
return this;
}
@Override
public List<? extends JsVariable> getVariables() {
JsObject asObject = jsValue.asObject();
if (asObject == null) {
return Collections.emptyList();
}
return new ArrayList<JsVariable>(asObject.getProperties());
}
@Override
public JsValue getWithArgument() {
return jsValue;
}
}
private abstract class WipEvaluateContextImpl<DATA, PARAMS extends WipParamsWithResponse<DATA>>
extends JsEvaluateContextBase {
@Override
public DebugContext getDebugContext() {
return WipDebugContextImpl.this;
}
@Override
public void evaluateAsync(final String expression,
Map<String, String> additionalContext, final EvaluateCallback callback,
SyncCallback syncCallback) {
if (additionalContext != null) {
WipBrowserImpl.throwUnsupported();
return;
}
// TODO: set a proper value of injectedScriptIdInt.
int injectedScriptIdInt = 0;
PARAMS params = createRequestParams(expression);
JavascriptVm.GenericCallback<DATA> commandCallback;
if (callback == null) {
commandCallback = null;
} else {
commandCallback = new JavascriptVm.GenericCallback<DATA>() {
@Override
public void success(DATA data) {
RemoteObjectValue valueData = getRemoteObjectValue(data);
WipValueBuilder valueBuilder = getValueLoader().getValueBuilder();
JsVariable variable;
if (getWasThrown(data) == Boolean.TRUE) {
variable = wrapExceptionValue(valueData, valueBuilder);
} else {
ValueNameBuilder valueNameBuidler =
WipExpressionBuilder.createRootName(expression, true);
variable = valueBuilder.createVariable(valueData, valueNameBuidler);
}
callback.success(variable);
}
@Override
public void failure(Exception exception) {
callback.failure(exception.getMessage());
}
};
}
tabImpl.getCommandProcessor().send(params, commandCallback, syncCallback);
}
protected abstract PARAMS createRequestParams(String expression);
protected abstract RemoteObjectValue getRemoteObjectValue(DATA data);
protected abstract Boolean getWasThrown(DATA data);
}
}
private JsVariable wrapExceptionValue(RemoteObjectValue valueData,
WipValueBuilder valueBuilder) {
JsValue exceptionValue = valueBuilder.wrap(valueData, null);
final JsVariable property =
WipValueBuilder.createVariable(exceptionValue, EVALUATE_EXCEPTION_INNER_NAME);
JsObject wrapperValue = new JsObject() {
@Override
public void reloadHeavyValue(ReloadBiggerCallback callback,
SyncCallback syncCallback) {
WipBrowserImpl.throwUnsupported();
return;
}
@Override
public boolean isTruncated() {
return false;
}
@Override
public String getValueString() {
return "<abnormal return>";
}
@Override
public Type getType() {
return Type.TYPE_OBJECT;
}
@Override
public JsObject asObject() {
return this;
}
@Override
public String getRefId() {
return null;
}
@Override
public JsVariable getProperty(String name) {
if (name.equals(property.getName())) {
return property;
}
return null;
}
@Override
public Collection<? extends JsVariable> getProperties()
throws MethodIsBlockingException {
return Collections.singletonList(property);
}
@Override
public Collection<? extends JsVariable> getInternalProperties()
throws MethodIsBlockingException {
return Collections.emptyList();
}
@Override
public String getClassName() {
return null;
}
@Override
public JsFunction asFunction() {
return null;
}
@Override
public JsArray asArray() {
return null;
}
};
return WipValueBuilder.createVariable(wrapperValue, EVALUATE_EXCEPTION_NAME);
}
private static final Map<ScopeValue.Type, JsScope.Type> WIP_TO_SDK_SCOPE_TYPE;
static {
WIP_TO_SDK_SCOPE_TYPE = new HashMap<ScopeValue.Type, JsScope.Type>();
WIP_TO_SDK_SCOPE_TYPE.put(ScopeValue.Type.GLOBAL, JsScope.Type.GLOBAL);
WIP_TO_SDK_SCOPE_TYPE.put(ScopeValue.Type.LOCAL, JsScope.Type.LOCAL);
WIP_TO_SDK_SCOPE_TYPE.put(ScopeValue.Type.WITH, JsScope.Type.WITH);
WIP_TO_SDK_SCOPE_TYPE.put(ScopeValue.Type.CLOSURE, JsScope.Type.CLOSURE);
WIP_TO_SDK_SCOPE_TYPE.put(ScopeValue.Type.CATCH, JsScope.Type.CATCH);
assert WIP_TO_SDK_SCOPE_TYPE.size() == ScopeValue.Type.values().length;
}
// TODO: this name must be built as non-derivable.
private static final ValueNameBuilder EXCEPTION_NAME =
WipExpressionBuilder.createRootNameNoDerived("exception");
// TODO: this name must be built as non-derivable.
private static final ValueNameBuilder WITH_OBJECT_NAME =
WipExpressionBuilder.createRootNameNoDerived("<with object>");
private static final ValueNameBuilder EVALUATE_EXCEPTION_INNER_NAME =
WipExpressionBuilder.createRootNameNoDerived("<exception>");
private static final ValueNameBuilder EVALUATE_EXCEPTION_NAME =
WipExpressionBuilder.createRootNameNoDerived("<thrown exception>");
private static class ScopeVariables {
final List<JsVariable> variables;
ScopeVariables(List<JsVariable> variables) {
this.variables = variables;
}
}
private final Getter<ScopeVariables> EMPTY_SCOPE_VARIABLES_OPTIONAL =
new Getter<ScopeVariables>() {
private final ScopeVariables value =
new ScopeVariables(Collections.<JsVariable>emptyList());
@Override ScopeVariables get() {
return value;
}
};
private WipParams sdkStepToProtocolStep(StepAction stepAction) {
switch (stepAction) {
case CONTINUE:
return RESUME_PARAMS;
case IN:
return STEP_INTO_PARAMS;
case OUT:
return STEP_OUT_PARAMS;
case OVER:
return STEP_OVER_PARAMS;
default:
throw new RuntimeException();
}
}
private static final ResumeParams RESUME_PARAMS = new ResumeParams();
private static final StepIntoParams STEP_INTO_PARAMS = new StepIntoParams();
private static final StepOutParams STEP_OUT_PARAMS = new StepOutParams();
private static final StepOverParams STEP_OVER_PARAMS = new StepOverParams();
} |
package org.jasig.portal;
import java.io.*;
import java.util.*;
import java.lang.SecurityManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.AccessController;
import org.jasig.portal.channels.BaseChannel;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.XSLT;
import org.jasig.portal.utils.ResourceLoader;
import org.jasig.portal.jndi.JNDIManager;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.UPFileSpec;
import org.xml.sax.*;
import org.jasig.portal.serialize.*;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
/**
* StandaloneChannelRenderer is meant to be used as a base class for channels
* that might be rendered outside of the standard user-layout driven scheme.
* (for example CSelectSystemProfile).
* @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a>
* @version $Revision$
*/
public class StandaloneChannelRenderer extends BaseChannel {
private StylesheetSet set;
private MediaManager mediaM;
private String channelName;
private PortalControlStructures pcs;
private BrowserInfo binfo;
private boolean hasEdit = false;
private boolean hasAbout = false;
private boolean hasHelp = false;
private long timeOut; // 10 seconds is the default timeout value
private boolean dataIsSet=false;
private static final String chanID="singleton";
private static final String fs = File.separator;
private static final String relativeSSLLocation = "/org/jasig/portal/tools/ChannelServlet/ChannelServlet.ssl";
/**
* Initializes the channel and calls setStaticData() on the channel.
* @param params a hastable of channel publish/subscribe parameters (<parameter> elements
* @param channelName channel name
* @param hasHelp determines if the channel supports "help" layout event
* @param hasAbout determines if the channel supports "about" layout event
* @param hasEdit determines if the channel supports "edit" layout event
* @param timeOut channel timeout value in milliseconds
* @param person a user IPerson object
*/
public void initialize(Hashtable params,String channelName,boolean hasHelp, boolean hasAbout, boolean hasEdit, long timeOut,IPerson person) throws PortalException {
this.set = new StylesheetSet(ResourceLoader.getResourceAsURLString(this.getClass(), relativeSSLLocation));
String mediaPropsUrl = ResourceLoader.getResourceAsURLString(this.getClass(), "/properties/media.properties");
String mimePropsUrl = ResourceLoader.getResourceAsURLString(this.getClass(), "/properties/mime.properties");
String serializerPropsUrl = ResourceLoader.getResourceAsURLString(this.getClass(), "/properties/serializer.properties");
this.set.setMediaProps(mediaPropsUrl);
this.mediaM = new MediaManager(mediaPropsUrl, mimePropsUrl, serializerPropsUrl);
this.channelName=channelName;
this.hasHelp=hasHelp;
this.hasAbout=hasAbout;
this.hasEdit=hasEdit;
this.timeOut=timeOut;
this.pcs=pcs;
ChannelStaticData sd = new ChannelStaticData ();
sd.setChannelSubscribeId (chanID);
sd.setTimeout (timeOut);
sd.setParameters (params);
// get person object from UsreLayoutManager
sd.setPerson(person);
this.setStaticData(sd);
}
/**
* This request will cause setRuntimeData() method called on the channel. If this method is invoked,
* the render() method, which usually invokes setRuntimeData() method will omit the call.
* @param req http request
* @param res http response
*/
public void prepare(HttpServletRequest req) throws Exception {
if(this instanceof IPrivilegedChannel) {
((IPrivilegedChannel) this).setPortalControlStructures(pcs);
}
this.setRuntimeData(getRuntimeData(req));
dataIsSet=true;
}
/**
* This method will output channel content into the HttpServletResponse's
* out stream. Note that setRuntimeData() method is called only if there was
* no prior call to prepare() method.
* @param req http request
* @param res http response
*/
public void render(HttpServletRequest req,HttpServletResponse res) throws Throwable {
ChannelRuntimeData rd=null;
if(!dataIsSet) {
if(this instanceof IPrivilegedChannel) {
((IPrivilegedChannel) this).setPortalControlStructures(pcs);
}
rd=getRuntimeData(req);
} else {
dataIsSet=false;
}
// start rendering
ChannelRenderer cr = new ChannelRenderer (this,rd);
cr.setTimeout (timeOut);
cr.startRendering ();
// set the output mime type
res.setContentType(mediaM.getReturnMimeType(req));
// set up the serializer
BaseMarkupSerializer ser = mediaM.getSerializer(mediaM.getMedia(req), res.getWriter());
ser.asContentHandler();
// get the framing stylesheet
String xslURI = ResourceLoader.getResourceAsURLString(this.getClass(), set.getStylesheetURI(req));
try {
TransformerHandler th=XSLT.getTransformerHandler(xslURI);
th.setResult(new SAXResult(ser));
org.xml.sax.helpers.AttributesImpl atl = new org.xml.sax.helpers.AttributesImpl();
atl.addAttribute("","name","name", "CDATA", channelName);
// add other attributes: hasHelp, hasAbout, hasEdit
th.startDocument();
th.startElement("","channel","channel", atl);
ChannelSAXStreamFilter custodian = new ChannelSAXStreamFilter(th);
int out=cr.outputRendering(custodian);
if(out==cr.RENDERING_TIMED_OUT) {
throw new InternalTimeoutException("The channel has timed out");
}
th.endElement("","channel","channel");
th.endDocument();
} catch (InternalPortalException ipe) {
throw ipe.getException();
}
}
private ChannelRuntimeData getRuntimeData(HttpServletRequest req) {
// construct runtime data
this.binfo=new BrowserInfo(req);
Hashtable targetParams = new Hashtable();
UPFileSpec upfs=new UPFileSpec(req);
String channelTarget = upfs.getTargetNodeId();
LogService.instance().log(LogService.DEBUG,"StandaloneRenderer::render() : channelTarget=\""+channelTarget+"\".");
Enumeration en = req.getParameterNames();
if (en != null) {
while (en.hasMoreElements()) {
String pName= (String) en.nextElement();
Object[] val= (Object[]) req.getParameterValues(pName);
if (val == null) {
val = ((PortalSessionManager.RequestParamWrapper)req).getObjectParameterValues(pName);
}
targetParams.put (pName, val);
}
}
ChannelRuntimeData rd= new ChannelRuntimeData();
rd.setBrowserInfo(binfo);
rd.setHttpRequestMethod(pcs.getHttpServletRequest().getMethod());
if(channelTarget!=null && chanID.equals(channelTarget)) {
rd.setParameters(targetParams);
}
try {
rd.setUPFile(new UPFileSpec(PortalSessionManager.INTERNAL_TAG_VALUE,UPFileSpec.RENDER_METHOD,"servletRoot",chanID,null));
} catch (Exception e) {
LogService.instance().log(LogService.DEBUG,"StandaloneRenderer::render() : unable to generate baseActionURL. "+e);
}
return rd;
}
} |
package org.jfree.chart.renderer;
import org.jfree.data.DomainOrder;
import org.jfree.data.xy.XYDataset;
/**
* Utility methods related to the rendering process.
*
* @since 1.0.6
*/
public class RendererUtilities {
/**
* Finds the lower index of the range of live items in the specified data
* series.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param xLow the lowest x-value in the live range.
* @param xHigh the highest x-value in the live range.
*
* @return The index of the required item.
*
* @since 1.0.6
*
* @see #findLiveItemsUpperBound(XYDataset, int, double, double)
*/
public static int findLiveItemsLowerBound(XYDataset dataset, int series,
double xLow, double xHigh) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
if (xLow >= xHigh) {
throw new IllegalArgumentException("Requires xLow < xHigh.");
}
int itemCount = dataset.getItemCount(series);
if (itemCount <= 1) {
return 0;
}
if (dataset.getDomainOrder() == DomainOrder.ASCENDING) {
// for data in ascending order by x-value, we are (broadly) looking
// for the index of the highest x-value that is less than xLow
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue >= xLow) {
// special case where the lowest x-value is >= xLow
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue < xLow) {
// special case where the highest x-value is < xLow
return high;
}
while (high - low > 1) {
int mid = (low + high) / 2;
double midV = dataset.getXValue(series, mid);
if (midV >= xLow) {
high = mid;
}
else {
low = mid;
}
}
return high;
}
else if (dataset.getDomainOrder() == DomainOrder.DESCENDING) {
// when the x-values are sorted in descending order, the lower
// bound is found by calculating relative to the xHigh value
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue <= xHigh) {
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue > xHigh) {
return high;
}
while (high - low > 1) {
int mid = (low + high) / 2;
double midV = dataset.getXValue(series, mid);
if (midV > xHigh) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return high;
}
else {
// we don't know anything about the ordering of the x-values,
// but we can still skip any initial values that fall outside the
// range...
int index = 0;
// skip any items that don't need including...
double x = dataset.getXValue(series, index);
while (index < itemCount && (x < xLow || x > xHigh)) {
index++;
if (index < itemCount) {
x = dataset.getXValue(series, index);
}
}
return Math.min(Math.max(0, index), itemCount - 1);
}
}
/**
* Finds the upper index of the range of live items in the specified data
* series.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param xLow the lowest x-value in the live range.
* @param xHigh the highest x-value in the live range.
*
* @return The index of the required item.
*
* @since 1.0.6
*
* @see #findLiveItemsLowerBound(XYDataset, int, double, double)
*/
public static int findLiveItemsUpperBound(XYDataset dataset, int series,
double xLow, double xHigh) {
if (dataset == null) {
throw new IllegalArgumentException("Null 'dataset' argument.");
}
if (xLow >= xHigh) {
throw new IllegalArgumentException("Requires xLow < xHigh.");
}
int itemCount = dataset.getItemCount(series);
if (itemCount <= 1) {
return 0;
}
if (dataset.getDomainOrder() == DomainOrder.ASCENDING) {
int low = 0;
int high = itemCount - 1;
double lowValue = dataset.getXValue(series, low);
if (lowValue > xHigh) {
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue <= xHigh) {
return high;
}
int mid = (low + high) / 2;
while (high - low > 1) {
double midV = dataset.getXValue(series, mid);
if (midV <= xHigh) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return mid;
}
else if (dataset.getDomainOrder() == DomainOrder.DESCENDING) {
// when the x-values are descending, the upper bound is found by
// comparing against xLow
int low = 0;
int high = itemCount - 1;
int mid = (low + high) / 2;
double lowValue = dataset.getXValue(series, low);
if (lowValue < xLow) {
return low;
}
double highValue = dataset.getXValue(series, high);
if (highValue >= xLow) {
return high;
}
while (high - low > 1) {
double midV = dataset.getXValue(series, mid);
if (midV >= xLow) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
return mid;
}
else {
// we don't know anything about the ordering of the x-values,
// but we can still skip any trailing values that fall outside the
// range...
int index = itemCount - 1;
// skip any items that don't need including...
double x = dataset.getXValue(series, index);
while (index >= 0 && (x < xLow || x > xHigh)) {
index
if (index >= 0) {
x = dataset.getXValue(series, index);
}
}
return Math.max(index, 0);
}
}
/**
* Finds a range of item indices that is guaranteed to contain all the
* x-values from x0 to x1 (inclusive).
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param xLow the lower bound of the x-value range.
* @param xHigh the upper bound of the x-value range.
*
* @return The indices of the boundary items.
*/
public static int[] findLiveItems(XYDataset dataset, int series,
double xLow, double xHigh) {
// here we could probably be a little faster by searching for both
// indices simultaneously, but I'll look at that later if it seems
// like it matters...
int i0 = findLiveItemsLowerBound(dataset, series, xLow, xHigh);
int i1 = findLiveItemsUpperBound(dataset, series, xLow, xHigh);
if (i0 > i1) {
i0 = i1;
}
return new int[] {i0, i1};
}
} |
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.chart.util.HashUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleEdge;
import org.jfree.data.xy.XYDataset;
/**
* Line/Step item renderer for an {@link XYPlot}. This class draws lines
* between data points, only allowing horizontal or vertical lines (steps).
*/
public class XYStepRenderer extends XYLineAndShapeRenderer
implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -8918141928884796108L;
/**
* The factor (from 0.0 to 1.0) that determines the position of the
* step.
*
* @since 1.0.10.
*/
private double stepPoint = 1.0d;
/**
* Constructs a new renderer with no tooltip or URL generation.
*/
public XYStepRenderer() {
this(null, null);
}
/**
* Constructs a new renderer with the specified tool tip and URL
* generators.
*
* @param toolTipGenerator the item label generator (<code>null</code>
* permitted).
* @param urlGenerator the URL generator (<code>null</code> permitted).
*/
public XYStepRenderer(XYToolTipGenerator toolTipGenerator,
XYURLGenerator urlGenerator) {
super();
setBaseToolTipGenerator(toolTipGenerator);
setBaseURLGenerator(urlGenerator);
setBaseShapesVisible(false);
}
/**
* Returns the fraction of the domain position between two points on which
* the step is drawn. The default is 1.0d, which means the step is drawn
* at the domain position of the second`point. If the stepPoint is 0.5d the
* step is drawn at half between the two points.
*
* @return The fraction of the domain position between two points where the
* step is drawn.
*
* @see #setStepPoint(double)
*
* @since 1.0.10
*/
public double getStepPoint() {
return this.stepPoint;
}
/**
* Sets the step point and sends a {@link RendererChangeEvent} to all
* registered listeners.
*
* @param stepPoint the step point (in the range 0.0 to 1.0)
*
* @see #getStepPoint()
*
* @since 1.0.10
*/
public void setStepPoint(double stepPoint) {
if (stepPoint < 0.0d || stepPoint > 1.0d) {
throw new IllegalArgumentException(
"Requires stepPoint in [0.0;1.0]");
}
this.stepPoint = stepPoint;
fireChangeEvent();
}
/**
* Draws the visual representation of a single data item.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the area within which the data is being drawn.
* @param info collects information about the drawing.
* @param plot the plot (can be used to obtain standard color
* information etc).
* @param domainAxis the domain axis.
* @param rangeAxis the vertical axis.
* @param dataset the dataset.
* @param series the series index (zero-based).
* @param item the item index (zero-based).
* @param crosshairState crosshair information for the plot
* (<code>null</code> permitted).
* @param pass the pass index.
*/
public void drawItem(Graphics2D g2,
XYItemRendererState state,
Rectangle2D dataArea,
PlotRenderingInfo info,
XYPlot plot,
ValueAxis domainAxis,
ValueAxis rangeAxis,
XYDataset dataset,
int series,
int item,
CrosshairState crosshairState,
int pass) {
// do nothing if item is not visible
if (!getItemVisible(series, item)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
Paint seriesPaint = getItemPaint(series, item);
Stroke seriesStroke = getItemStroke(series, item);
g2.setPaint(seriesPaint);
g2.setStroke(seriesStroke);
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
double transY1 = (Double.isNaN(y1) ? Double.NaN
: rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation));
if (pass== 0 && item > 0) {
// get the previous data point...
double x0 = dataset.getXValue(series, item - 1);
double y0 = dataset.getYValue(series, item - 1);
double transX0 = domainAxis.valueToJava2D(x0, dataArea,
xAxisLocation);
double transY0 = (Double.isNaN(y0) ? Double.NaN
: rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation));
if (orientation == PlotOrientation.HORIZONTAL) {
if (transY0 == transY1) {
// this represents the situation
// for drawing a horizontal bar.
drawLine(g2, state.workingLine, transY0, transX0, transY1,
transX1);
}
else { //this handles the need to perform a 'step'.
// calculate the step point
double transXs = transX0 + (getStepPoint()
* (transX1 - transX0));
drawLine(g2, state.workingLine, transY0, transX0, transY0,
transXs);
drawLine(g2, state.workingLine, transY0, transXs, transY1,
transXs);
drawLine(g2, state.workingLine, transY1, transXs, transY1,
transX1);
}
}
else if (orientation == PlotOrientation.VERTICAL) {
if (transY0 == transY1) { // this represents the situation
// for drawing a horizontal bar.
drawLine(g2, state.workingLine, transX0, transY0, transX1,
transY1);
}
else { //this handles the need to perform a 'step'.
// calculate the step point
double transXs = transX0 + (getStepPoint()
* (transX1 - transX0));
drawLine(g2, state.workingLine, transX0, transY0, transXs,
transY0);
drawLine(g2, state.workingLine, transXs, transY0, transXs,
transY1);
drawLine(g2, state.workingLine, transXs, transY1, transX1,
transY1);
}
}
// submit this data item as a candidate for the crosshair point
int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex,
rangeAxisIndex, transX1, transY1, orientation);
// collect entity and tool tip information...
EntityCollection entities = state.getEntityCollection();
if (entities != null) {
addEntity(entities, null, dataset, series, item, transX1,
transY1);
}
}
if (pass == 1) {
// draw the item label if there is one...
if (isItemLabelVisible(series, item)) {
double xx = transX1;
double yy = transY1;
if (orientation == PlotOrientation.HORIZONTAL) {
xx = transY1;
yy = transX1;
}
drawItemLabel(g2, orientation, dataset, series, item, xx, yy,
(y1 < 0.0));
}
}
}
/**
* A utility method that draws a line but only if none of the coordinates
* are NaN values.
*
* @param g2 the graphics target.
* @param line the line object.
* @param x0 the x-coordinate for the starting point of the line.
* @param y0 the y-coordinate for the starting point of the line.
* @param x1 the x-coordinate for the ending point of the line.
* @param y1 the y-coordinate for the ending point of the line.
*/
private void drawLine(Graphics2D g2, Line2D line, double x0, double y0,
double x1, double y1) {
if (Double.isNaN(x0) || Double.isNaN(x1) || Double.isNaN(y0)
|| Double.isNaN(y1)) {
return;
}
line.setLine(x0, y0, x1, y1);
g2.draw(line);
}
/**
* Tests this renderer for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof XYLineAndShapeRenderer)) {
return false;
}
XYStepRenderer that = (XYStepRenderer) obj;
if (this.stepPoint != that.stepPoint) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
return HashUtilities.hashCode(super.hashCode(), this.stepPoint);
}
/**
* Returns a clone of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the renderer cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
} |
/*
* FileSystem class for JSyndicateFS
*/
package JSyndicateFS;
import JSyndicateFS.cache.ICache;
import JSyndicateFS.cache.TimeoutCache;
import JSyndicateFSJNI.JSyndicateFS;
import JSyndicateFSJNI.struct.JSFSConfig;
import JSyndicateFSJNI.struct.JSFSFileInfo;
import JSyndicateFSJNI.struct.JSFSStat;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author iychoi
*/
public class FileSystem implements Closeable {
public static final Log LOG = LogFactory.getLog(FileSystem.class);
private static final String FS_ROOT_PATH = "file:
private static final int DEFAULT_NEW_FILE_PERMISSION = 33204;
private static final int DEFAULT_NEW_DIR_PERMISSION = 33204;
private static FileSystem fsInstance;
private Configuration conf;
private Path workingDir;
private boolean closed = true;
private ICache<Path, FileStatus> metadataCache;
private Map<Long, FileHandle> openFileHandles = new Hashtable<Long, FileHandle>();
/*
* Construct or Get FileSystem from configuration
*/
public synchronized static FileSystem getInstance(Configuration conf) throws InstantiationException {
if(fsInstance == null) {
fsInstance = new FileSystem(conf);
} else {
LOG.info("Get FileSystem instance already created : " + conf.getUGName() + "," + conf.getVolumeName() + "," + conf.getMSUrl().toString());
}
return fsInstance;
}
/*
* Construct FileSystem from configuration
*/
protected FileSystem(Configuration conf) throws InstantiationException {
initialize(conf);
}
private void initialize(Configuration conf) throws InstantiationException {
if(conf == null)
throw new IllegalArgumentException("Can not initialize the filesystem from null configuration");
LOG.info("Initialize FileSystem : " + conf.getUGName() + "," + conf.getVolumeName() + "," + conf.getMSUrl().toString());
// set configuration unmodifiable
conf.lock();
// Convert Configuration to JSFSConfig
JSFSConfig config = conf.getJSFSConfig();
int ret = JSyndicateFSJNI.JSyndicateFS.jsyndicatefs_init(config);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new java.lang.InstantiationException("jsyndicatefs_init failed : " + errmsg);
}
this.conf = conf;
this.workingDir = getRootPath();
this.metadataCache = new TimeoutCache<Path, FileStatus>(conf.getMaxMetadataCacheSize(), conf.getCacheTimeoutSecond());
this.closed = false;
}
public Configuration getConfiguration() {
return this.conf;
}
/*
* Return the root path of the filesystem
*/
public Path getRootPath() {
return new Path(FS_ROOT_PATH);
}
/*
* Return the working directory of the filesystem
*/
public Path getWorkingDirectory() {
return this.workingDir;
}
/*
* Set the working directory of the filesystem
*/
public void setWorkingDirectory(Path path) {
if(path == null)
this.workingDir = new Path(FS_ROOT_PATH);
else
this.workingDir = path;
}
private void closeAllOpenFiles() throws PendingExceptions {
PendingExceptions pe = new PendingExceptions();
Collection<FileHandle> values = this.openFileHandles.values();
for(FileHandle handle : values) {
try {
closeFileHandle(handle);
} catch(IOException e) {
LOG.error("FileHandle close exception (Pending) : " + handle.getPath().toString());
pe.add(e);
}
}
this.openFileHandles.clear();
if(!pe.isEmpty())
throw pe;
}
/*
* Close and release all resources of the filesystem
*/
@Override
public void close() throws IOException {
if(this.closed)
throw new IOException("The filesystem is already closed");
PendingExceptions pe = new PendingExceptions();
// destroy all opened files
try {
closeAllOpenFiles();
} catch (PendingExceptions ex) {
pe.addAll(ex);
}
// destroy underlying syndicate
int ret = JSyndicateFSJNI.JSyndicateFS.jsyndicatefs_destroy();
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
LOG.error("jsyndicatefs_destroy failed : " + errmsg);
pe.add(new IOException("jsyndicatefs_destroy failed : " + errmsg));
}
this.closed = true;
// destroy all caches
this.metadataCache.clear();
if(!pe.isEmpty()) {
throw new IOException(pe.getMessage());
}
}
/*
* Return absolute path
*/
public Path getAbsolutePath(Path path) {
if(path == null)
throw new IllegalArgumentException("Can not get absolute file path from null path");
Path absolute;
if(!path.isAbsolute()) {
// start from working dir
absolute = new Path(this.workingDir, path);
} else {
absolute = path;
}
return absolute;
}
/*
* Return FileStatus from path
*/
public FileStatus getFileStatus(Path path) throws FileNotFoundException, IOException {
if(path == null)
throw new IllegalArgumentException("Can not get file status from null path");
Path absolute = getAbsolutePath(path);
// check filestatus cache
FileStatus cachedFileStatus = this.metadataCache.get(absolute);
if(cachedFileStatus != null && !cachedFileStatus.isDirty()) {
// has cache
return cachedFileStatus;
}
JSFSStat statbuf = new JSFSStat();
int ret = JSyndicateFSJNI.JSyndicateFS.jsyndicatefs_getattr(absolute.getPath(), statbuf);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_getattr failed : " + errmsg);
}
FileStatus status = new FileStatus(absolute, statbuf);
// cache filestatus
this.metadataCache.insert(absolute, status);
return status;
}
public void invalidateFileStatus(FileStatus status) {
if(status == null)
throw new IllegalArgumentException("Can not invalidate file status from null status");
// invalidate cache
this.metadataCache.invalidate(status.getPath());
status.setDirty();
}
/*
* True if the path exists
*/
public boolean exists(Path path) {
try {
if(getFileStatus(path) == null)
return false;
else
return true;
} catch (FileNotFoundException e) {
return false;
} catch (IOException ex) {
return false;
}
}
/*
* True if the path is a directory
*/
public boolean isDirectory(Path path) {
try {
return getFileStatus(path).isDirectory();
} catch (FileNotFoundException ex) {
return false;
} catch (IOException ex) {
return false;
}
}
/*
* True if the path is a regular file
*/
public boolean isFile(Path path) {
try {
return getFileStatus(path).isFile();
} catch (FileNotFoundException ex) {
return false;
} catch (IOException ex) {
return false;
}
}
/*
* Return the file handle from file status
*/
public FileHandle openFileHandle(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not open file handle from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not open file handle from dirty status");
JSFSFileInfo fileinfo = new JSFSFileInfo();
if(status.isFile()) {
int ret = JSyndicateFS.jsyndicatefs_open(status.getPath().getPath(), fileinfo);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_open failed : " + errmsg);
}
} else if(status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_opendir(status.getPath().getPath(), fileinfo);
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_opendir failed : " + errmsg);
}
} else {
throw new IOException("Can not open file handle from unknown status");
}
FileHandle filehandle = new FileHandle(this, status, fileinfo);
// add to list
if(!this.openFileHandles.containsKey(filehandle.getHandleID()))
this.openFileHandles.put(filehandle.getHandleID(), filehandle);
return filehandle;
}
/*
* Return the file handle from path
*/
public FileHandle openFileHandle(Path path) throws FileNotFoundException, IOException {
FileStatus status = getFileStatus(path);
if(status == null)
throw new FileNotFoundException("Can not find file information from the path");
return openFileHandle(status);
}
public void flushFileHandle(FileHandle filehandle) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not flush null filehandle");
if(filehandle.isDirty())
throw new IOException("Can not flush dirty file handle");
if(filehandle.isOpen()) {
int ret = JSyndicateFS.jsyndicatefs_flush(filehandle.getStatus().getPath().getPath(), filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_flush failed : " + errmsg);
}
}
}
/*
* Close file handle
*/
public void closeFileHandle(FileHandle filehandle) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not close null filehandle");
//if(filehandle.isDirty())
// throw new IOException("Can not close dirty file handle");
if(filehandle.isOpen()) {
FileStatus status = filehandle.getStatus();
if(status.isFile()) {
int ret = JSyndicateFS.jsyndicatefs_release(filehandle.getStatus().getPath().getPath(), filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_release failed : " + errmsg);
}
} else if(status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_releasedir(filehandle.getStatus().getPath().getPath(), filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_releasedir failed : " + errmsg);
}
} else {
throw new IOException("Can not close file handle from unknown status");
}
}
if(this.openFileHandles.containsKey(filehandle.getHandleID()))
this.openFileHandles.remove(filehandle.getHandleID());
// notify object is closed
filehandle.notifyClose();
}
/*
* Return input stream from file status
*/
public InputStream getFileInputStream(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not open file handle from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not open file handle from dirty status");
if(!status.isFile())
throw new IllegalArgumentException("Can not open file handle from status that is not a file");
FileHandle filehandle = openFileHandle(status);
return new FSInputStream(filehandle);
}
/*
* Return output stream frmo file status
*/
public OutputStream getFileOutputStream(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not open file handle from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not open file handle from dirty status");
if(!status.isFile())
throw new IllegalArgumentException("Can not open file handle from status that is not a file");
FileHandle filehandle = openFileHandle(status);
return new FSOutputStream(filehandle);
}
public int readFileData(FileHandle filehandle, byte[] buffer, int size, long offset) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not read from null filehandle");
if(!filehandle.isOpen())
throw new IllegalArgumentException("Can not read from closed filehandle");
if(filehandle.isDirty())
throw new IllegalArgumentException("Can not read from dirty filehandle");
if(!filehandle.getStatus().isFile())
throw new IllegalArgumentException("Can not read from filehandle that is not a file");
if(buffer == null)
throw new IllegalArgumentException("Can not read to null buffer");
if(buffer.length < size)
throw new IllegalArgumentException("Can not read to too small buffer");
if(size <= 0)
throw new IllegalArgumentException("Can not read negative size data");
if(offset < 0)
throw new IllegalArgumentException("Can not read negative offset");
int ret = JSyndicateFS.jsyndicatefs_read(filehandle.getStatus().getPath().getPath(), buffer, size, offset, filehandle.getFileInfo());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_read failed : " + errmsg);
}
return ret;
}
public void writeFileData(FileHandle filehandle, byte[] buffer, int size, long offset) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not write to null filehandle");
if(!filehandle.isOpen())
throw new IllegalArgumentException("Can not write to closed filehandle");
if(filehandle.isDirty())
throw new IllegalArgumentException("Can not write to from dirty filehandle");
if(!filehandle.getStatus().isFile())
throw new IllegalArgumentException("Can not write to filehandle that is not a file");
if(buffer == null)
throw new IllegalArgumentException("Can not write null buffer");
if(buffer.length < size)
throw new IllegalArgumentException("Can not write too small buffer");
if(size <= 0)
throw new IllegalArgumentException("Can not write negative size data");
if(offset < 0)
throw new IllegalArgumentException("Can not write negative offset");
int ret = JSyndicateFS.jsyndicatefs_write(filehandle.getStatus().getPath().getPath(), buffer, size, offset, filehandle.getFileInfo());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_write failed : " + errmsg);
}
if(ret < size) {
// pending?
throw new IOException("unexpected return : " + ret);
}
// update file size temporarily
if(filehandle.getStatus().getSize() < offset + size)
filehandle.getStatus().setSize(offset + size);
}
public String[] readDirectoryEntries(Path path) throws FileNotFoundException, IOException {
if(path == null)
throw new IllegalArgumentException("Can not read directory entries from null path");
FileHandle filehandle = openFileHandle(path);
if(filehandle == null)
throw new IOException("Can not read directory entries from null file handle");
return readDirectoryEntries(filehandle);
}
public String[] readDirectoryEntries(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not read directory entries from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not read directory entries from dirty status");
FileHandle filehandle = openFileHandle(status);
if(filehandle == null)
throw new IOException("Can not read directory entries from null file handle");
return readDirectoryEntries(filehandle);
}
public String[] readDirectoryEntries(FileHandle filehandle) throws IOException {
if(filehandle == null)
throw new IllegalArgumentException("Can not read directory entries from null filehandle");
if(filehandle.isDirty())
throw new IllegalArgumentException("Can not read directory entries from dirty filehandle");
DirFillerImpl filler = new DirFillerImpl();
if(!filehandle.getStatus().isDirectory())
throw new IllegalArgumentException("Can not read directory entries from filehandle that is not a directory");
int ret = JSyndicateFS.jsyndicatefs_readdir(filehandle.getPath().getPath(), filler, 0, filehandle.getFileInfo());
if(ret != 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_readdir failed : " + errmsg);
}
return filler.getEntryNames();
}
public void delete(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not delete from null path");
FileStatus status = getFileStatus(path);
if(status == null)
throw new IOException("Can not delete file from null file status");
delete(status);
}
public void delete(FileStatus status) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not delete file from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not delete file from dirty status");
if(status.isFile()) {
int ret = JSyndicateFS.jsyndicatefs_unlink(status.getPath().getPath());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_unlink failed : " + errmsg);
}
} else if(status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_rmdir(status.getPath().getPath());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_rmdir failed : " + errmsg);
}
} else {
throw new IOException("Can not delete file from unknown status");
}
invalidateFileStatus(status);
}
public void rename(FileStatus status, Path newpath) throws IOException {
if(status == null)
throw new IllegalArgumentException("Can not rename file from null status");
if(status.isDirty())
throw new IllegalArgumentException("Can not rename file from dirty status");
if(newpath == null)
throw new IllegalArgumentException("Can not rename file to null new name");
if(status.isFile() || status.isDirectory()) {
int ret = JSyndicateFS.jsyndicatefs_rename(status.getPath().getPath(), newpath.getPath());
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_rename failed : " + errmsg);
}
} else {
throw new IOException("Can not delete file from unknown status");
}
invalidateFileStatus(status);
}
public void mkdir(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not mkdir from null path");
int ret = JSyndicateFS.jsyndicatefs_mkdir(path.getPath(), DEFAULT_NEW_DIR_PERMISSION);
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_mkdir failed : " + errmsg);
}
}
public void mkdirs(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not mkdir from null path");
// recursive call
Path parent = path.getParent();
if(parent != null) {
if(!exists(parent)) {
// make
mkdirs(parent);
}
}
int ret = JSyndicateFS.jsyndicatefs_mkdir(path.getPath(), DEFAULT_NEW_DIR_PERMISSION);
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_mkdir failed : " + errmsg);
}
}
public boolean createNewFile(Path path) throws IOException {
Path absPath = getAbsolutePath(path);
FileStatus status = null;
try {
status = getFileStatus(absPath);
} catch(IOException ex) {}
if(status == null) {
JSFSFileInfo fi = new JSFSFileInfo();
int ret = JSyndicateFS.jsyndicatefs_create(absPath.getPath(), DEFAULT_NEW_FILE_PERMISSION, fi);
if(ret < 0) {
String errmsg = ErrorUtils.generateErrorMessage(ret);
throw new IOException("jsyndicatefs_create failed : " + errmsg);
}
return true;
} else {
return false;
}
}
private ArrayList<Path> listAllFilesRecursive(Path absPath) throws IOException {
if(absPath == null)
throw new IllegalArgumentException("Can not list files from null path");
ArrayList<Path> result = new ArrayList<Path>();
if(isFile(absPath)) {
result.add(absPath);
} else if(isDirectory(absPath)) {
// entries
String[] entries = readDirectoryEntries(absPath);
if(entries != null) {
for(String entry : entries) {
Path newEntryPath = new Path(absPath, entry);
ArrayList<Path> rec_result = listAllFilesRecursive(newEntryPath);
result.addAll(rec_result);
}
}
}
return result;
}
public Path[] listAllFiles(Path path) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not list files from null path");
Path absPath = getAbsolutePath(path);
ArrayList<Path> result = listAllFilesRecursive(absPath);
Path[] paths = new Path[result.size()];
paths = result.toArray(paths);
return paths;
}
private ArrayList<Path> listAllFilesRecursive(Path absPath, FilenameFilter filter) throws IOException {
if(absPath == null)
throw new IllegalArgumentException("Can not list files from null path");
ArrayList<Path> result = new ArrayList<Path>();
if(isFile(absPath)) {
if(filter != null) {
if(filter.accept(new File(this, absPath.getParent()), absPath.getName())) {
result.add(absPath);
}
} else {
result.add(absPath);
}
} else if(isDirectory(absPath)) {
// entries
String[] entries = readDirectoryEntries(absPath);
if(entries != null) {
for(String entry : entries) {
Path newEntryPath = new Path(absPath, entry);
if(filter != null) {
if(filter.accept(new File(this, absPath), entry)) {
ArrayList<Path> rec_result = listAllFilesRecursive(newEntryPath);
result.addAll(rec_result);
}
} else {
ArrayList<Path> rec_result = listAllFilesRecursive(newEntryPath);
result.addAll(rec_result);
}
}
}
}
return result;
}
public Path[] listAllFiles(Path path, FilenameFilter filter) throws IOException {
if(path == null)
throw new IllegalArgumentException("Can not list files from null path");
Path absPath = getAbsolutePath(path);
ArrayList<Path> result = listAllFilesRecursive(absPath, filter);
Path[] paths = new Path[result.size()];
paths = result.toArray(paths);
return paths;
}
} |
package edu.wustl.catissuecore.domain;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import edu.wustl.catissuecore.actionForm.AbstractActionForm;
import edu.wustl.catissuecore.actionForm.CreateSpecimenForm;
import edu.wustl.catissuecore.actionForm.NewSpecimenForm;
import edu.wustl.catissuecore.util.global.Validator;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.logger.Logger;
/**
* A single unit of tissue, body fluid, or derivative biological macromolecule
* that is collected or created from a Participant
* @hibernate.class table="CATISSUE_SPECIMEN"
* @hibernate.discriminator column="SPECIMEN_CLASS"
*/
public class Specimen extends AbstractDomainObject implements Serializable
{
private static final long serialVersionUID = 1234567890L;
/**
* System generated unique systemIdentifier.
*/
protected Long systemIdentifier;
/**
* Type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc.
*/
protected String type;
/**
* Is this specimen still physically available in the tissue bank?
*/
protected Boolean available;
/**
* Reference to dimensional position one of the specimen in Storage Container.
*/
protected Integer positionDimensionOne;
/**
* Reference to dimensional position two of the specimen in Storage Container.
*/
protected Integer positionDimensionTwo;
/**
* Barcode assigned to the specimen.
*/
protected String barcode;
/**
* Comments on specimen.
*/
protected String comments;
/**
* Defines whether this Specimen record can be queried (Active)
* or not queried (Inactive) by any actor.
*/
protected String activityStatus;
/**
* Parent specimen from which this specimen is derived.
*/
protected Specimen parentSpecimen;
/**
* Collection of attributes of a Specimen that renders it potentially harmful to a User.
*/
protected Collection biohazardCollection = new HashSet();
/**
* A physically discreet container that is used to store a specimen e.g. Box, Freezer etc.
*/
protected StorageContainer storageContainer = new StorageContainer();
/**
* Collection of Specimen Event Parameters associated with this specimen.
*/
protected Collection specimenEventCollection = new HashSet();
/**
* Collection of children specimens derived from this specimen.
*/
protected Collection childrenSpecimen = new HashSet();
/**
* Collection of a pre-existing, externally defined systemIdentifier associated with a specimen.
*/
protected Collection externalIdentifierCollection = new HashSet();
/**
* An event that results in the collection of one or more specimen from a participant.
*/
protected SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
/**
* The combined anatomic state and pathological diseaseclassification of a specimen.
*/
protected SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
protected transient boolean isParentChanged = false;
public Specimen()
{
}
//Constructor
public Specimen(AbstractActionForm form)
{
setAllValues(form);
}
/**
* Returns the system generated unique systemIdentifier.
* @hibernate.id name="systemIdentifier" column="IDENTIFIER" type="long" length="30"
* unsaved-value="null" generator-class="native"
* @return the system generated unique systemIdentifier.
* @see #setSystemIdentifier(Long)
* */
public Long getSystemIdentifier()
{
return systemIdentifier;
}
/**
* Sets the system generated unique systemIdentifier.
* @param systemIdentifier the system generated unique systemIdentifier.
* @see #getSystemIdentifier()
* */
public void setSystemIdentifier(Long systemIdentifier)
{
this.systemIdentifier = systemIdentifier;
}
/**
* Returns the type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc.
* @hibernate.property name="type" type="string" column="TYPE" length="50"
* @return The type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc.
* @see #setType(String)
*/
public String getType()
{
return type;
}
/**
* Sets the type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc.
* @param type The type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc.
* @see #getType()
*/
public void setType(String type)
{
this.type = type;
}
/**
* Returns true if this specimen still physically available
* in the tissue bank else returns false.
* @hibernate.property name="available" type="boolean" column="AVAILABLE"
* @return true if this specimen still physically available
* in the tissue bank else returns false.
* @see #setAvailable(Boolean)
*/
public Boolean getAvailable()
{
return available;
}
/**
* Sets true if this specimen still physically available
* in the tissue bank else returns false.
* @param available true if this specimen still physically available else false.
* @see #getAvailable()
*/
public void setAvailable(Boolean available)
{
this.available = available;
}
/**
* Returns the reference to dimensional position one of the specimen in Storage Container.
* @hibernate.property name="positionDimensionOne" type="int" column="POSITION_DIMENSION_ONE" length="30"
* @return the reference to dimensional position one of the specimen in Storage Container.
* @see #setPositionDimensionOne(Integer)
*/
public Integer getPositionDimensionOne()
{
return positionDimensionOne;
}
/**
* Sets the reference to dimensional position one of the specimen in Storage Container.
* @param positionDimensionOne the reference to dimensional position one of the specimen
* in Storage Container.
* @see #getPositionDimensionOne()
*/
public void setPositionDimensionOne(Integer positionDimensionOne)
{
this.positionDimensionOne = positionDimensionOne;
}
/**
* Returns the reference to dimensional position two of the specimen in Storage Container.
* @hibernate.property name="positionDimensionTwo" type="int" column="POSITION_DIMENSION_TWO" length="50"
* @return the reference to dimensional position two of the specimen in Storage Container.
* @see #setPositionDimensionOne(Integer)
*/
public Integer getPositionDimensionTwo()
{
return positionDimensionTwo;
}
/**
* Sets the reference to dimensional position two of the specimen in Storage Container.
* @param positionDimensionTwo the reference to dimensional position two of the specimen
* in Storage Container.
* @see #getPositionDimensionTwo()
*/
public void setPositionDimensionTwo(Integer positionDimensionTwo)
{
this.positionDimensionTwo = positionDimensionTwo;
}
/**
* Returns the barcode assigned to the specimen.
* @hibernate.property name="barcode" type="string" column="BARCODE" length="50" unique="true"
* @return the barcode assigned to the specimen.
* @see #setBarcode(String)
*/
public String getBarcode()
{
return barcode;
}
/**
* Sets the barcode assigned to the specimen.
* @param barCode the barcode assigned to the specimen.
* @see #getBarcode()
*/
public void setBarcode(String barcode)
{
this.barcode = barcode;
}
/**
* Returns the comments on the specimen.
* @hibernate.property name="comments" type="string" column="COMMENTS" length="200"
* @return the comments on the specimen.
* @see #setComments(String)
*/
public String getComments()
{
return comments;
}
/**
* Sets the comments on the specimen.
* @param comments The comments to set.
* @see #getComments()
*/
public void setComments(String comments)
{
this.comments = comments;
}
/**
* Returns whether this Specimen record can be queried (Active) or not queried (Inactive) by any actor.
* @hibernate.property name="activityStatus" type="string" column="ACTIVITY_STATUS" length="50"
* @return "Active" if this Specimen record can be queried or "Inactive" if cannot be queried.
* @see #setActivityStatus(String)
*/
public String getActivityStatus()
{
return activityStatus;
}
/**
* Sets whether this Specimen record can be queried (Active) or not queried (Inactive) by any actor.
* @param activityStatus "Active" if this Specimen record can be queried else "Inactive".
* @see #getActivityStatus()
*/
public void setActivityStatus(String activityStatus)
{
this.activityStatus = activityStatus;
}
/**
* Returns the parent specimen from which this specimen is derived.
* @hibernate.many-to-one column="PARENT_SPECIMEN_ID"
* class="edu.wustl.catissuecore.domain.Specimen" constrained="true"
* @return the parent specimen from which this specimen is derived.
* @see #setParentSpecimen(SpecimenNew)
*/
public Specimen getParentSpecimen()
{
return parentSpecimen;
}
/**
* Sets the parent specimen from which this specimen is derived.
* @param parentSpecimen the parent specimen from which this specimen is derived.
* @see #getParentSpecimen()
*/
public void setParentSpecimen(Specimen parentSpecimen)
{
this.parentSpecimen = parentSpecimen;
}
/**
* Returns the collection of attributes of a Specimen
* that renders it potentially harmful to a User.
* @hibernate.set name="biohazardCollection" table="CATISSUE_SPECIMEN_BIOHAZARD_RELATIONSHIP"
* cascade="none" inverse="false" lazy="false"
* @hibernate.collection-key column="SPECIMEN_ID"
* @hibernate.collection-many-to-many class="edu.wustl.catissuecore.domain.Biohazard" column="BIOHAZARD_ID"
* @return the collection of attributes of a Specimen
* that renders it potentially harmful to a User.
* @see #setBiohazardCollection(Set)
*/
public Collection getBiohazardCollection()
{
return biohazardCollection;
}
/**
* Sets the collection of attributes of a Specimen
* that renders it potentially harmful to a User.
* @param biohazardCollection the collection of attributes of a Specimen
* that renders it potentially harmful to a User.
* @see #getBiohazardCollection()
*/
public void setBiohazardCollection(Collection biohazardCollection)
{
this.biohazardCollection = biohazardCollection;
}
/**
* Returns the collection of Specimen Event Parameters associated with this specimen.
* @hibernate.set name="specimenEventCollection" table="CATISSUE_SPECIMEN_EVENT"
* cascade="save-update" inverse="true" lazy="false"
* @hibernate.collection-key column="SPECIMEN_ID"
* @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.SpecimenEventParameters"
* @return the collection of Specimen Event Parameters associated with this specimen.
* @see #setSpecimenEventCollection(Set)
*/
public Collection getSpecimenEventCollection()
{
return specimenEventCollection;
}
/**
* Sets the collection of Specimen Event Parameters associated with this specimen.
* @param specimenEventCollection the collection of Specimen Event Parameters
* associated with this specimen.
* @see #getSpecimenEventCollection()
*/
public void setSpecimenEventCollection(Collection specimenEventCollection)
{
this.specimenEventCollection = specimenEventCollection;
}
/**
* Returns the collection of children specimens derived from this specimen.
* @hibernate.set name="childrenSpecimen" table="CATISSUE_SPECIMEN"
* cascade="save-update" inverse="true" lazy="false"
* @hibernate.collection-key column="PARENT_SPECIMEN_ID"
* @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.Specimen"
* @return the collection of children specimens derived from this specimen.
* @see #setChildrenSpecimen(Set)
*/
public Collection getChildrenSpecimen()
{
return childrenSpecimen;
}
/**
* Sets the collection of children specimens derived from this specimen.
* @param childrenSpecimen the collection of children specimens
* derived from this specimen.
* @see #getChildrenSpecimen()
*/
public void setChildrenSpecimen(Collection childrenSpecimen)
{
this.childrenSpecimen = childrenSpecimen;
}
/**
* Returns the physically discreet container that is used to store a specimen e.g. Box, Freezer etc.
* @hibernate.many-to-one column="STORAGE_CONTAINER_IDENTIFIER"
* class="edu.wustl.catissuecore.domain.StorageContainer" constrained="true"
* @return the physically discreet container that is used to store a specimen e.g. Box, Freezer etc.
* @see #setStorageContainer(StorageContainer)
*/
public StorageContainer getStorageContainer()
{
return storageContainer;
}
/**
* Sets the physically discreet container that is used to store a specimen e.g. Box, Freezer etc.
* @param storageContainer the physically discreet container that is used to store a specimen
* e.g. Box, Freezer etc.
* @see #getStorageContainer()
*/
public void setStorageContainer(StorageContainer storageContainer)
{
this.storageContainer = storageContainer;
}
/**
* Returns the collection of a pre-existing, externally defined systemIdentifier associated with a specimen.
* @hibernate.set name="externalIdentifierCollection" table="CATISSUE_EXTERNAL_IDENTIFIER"
* cascade="save-update" inverse="true" lazy="false"
* @hibernate.collection-key column="SPECIMEN_ID"
* @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.ExternalIdentifier"
* @return the collection of a pre-existing, externally defined systemIdentifier associated with a specimen.
* @see #setExternalIdentifierCollection(Set)
*/
public Collection getExternalIdentifierCollection()
{
return externalIdentifierCollection;
}
/**
* Sets the collection of a pre-existing, externally defined systemIdentifier
* associated with a specimen.
* @param externalIdentifierCollection the collection of a pre-existing,
* externally defined systemIdentifier associated with a specimen.
* @see #getExternalIdentifierCollection()
*/
public void setExternalIdentifierCollection(Collection externalIdentifierCollection)
{
this.externalIdentifierCollection = externalIdentifierCollection;
}
/**
* Returns the event that results in the collection of one or more specimen from a participant.
* @hibernate.many-to-one column="SPECIMEN_COLLECTION_GROUP_ID"
* class="edu.wustl.catissuecore.domain.SpecimenCollectionGroup" constrained="true"
* @return the event that results in the collection of one or more specimen from a participant.
* @see #setSpecimenCollectionGroup(SpecimenCollectionGroup)
*/
public SpecimenCollectionGroup getSpecimenCollectionGroup()
{
return specimenCollectionGroup;
}
/**
* Sets the event that results in the collection of one or more specimen from a participant.
* @param specimenCollectionGroup the event that results in the collection of one or more
* specimen from a participant.
* @see #getSpecimenCollectionGroup()
*/
public void setSpecimenCollectionGroup(
SpecimenCollectionGroup specimenCollectionGroup)
{
this.specimenCollectionGroup = specimenCollectionGroup;
}
/**
* Returns the combined anatomic state and pathological diseaseclassification of a specimen.
* @hibernate.many-to-one column="SPECIMEN_CHARACTERISTICS_ID"
* class="edu.wustl.catissuecore.domain.SpecimenCharacteristics" constrained="true"
* @return the combined anatomic state and pathological diseaseclassification of a specimen.
* @see #setSpecimenCharacteristics(SpecimenCharacteristics)
*/
public SpecimenCharacteristics getSpecimenCharacteristics()
{
return specimenCharacteristics;
}
/**
* Sets the combined anatomic state and pathological diseaseclassification of a specimen.
* @param specimenCharacteristics the combined anatomic state and pathological disease
* classification of a specimen.
* @see #getSpecimenCharacteristics()
*/
public void setSpecimenCharacteristics(SpecimenCharacteristics specimenCharacteristics)
{
this.specimenCharacteristics = specimenCharacteristics;
}
public boolean isParentChanged()
{
return isParentChanged;
}
public void setParentChanged(boolean isParentChanged)
{
this.isParentChanged = isParentChanged;
}
/**
* This function Copies the data from an NewSpecimenForm object to a Specimen object.
* @param siteForm An SiteForm object containing the information about the site.
* */
public void setAllValues(AbstractActionForm abstractForm)
{
try
{
Validator validator = new Validator();
if(abstractForm instanceof NewSpecimenForm)
{
NewSpecimenForm form = (NewSpecimenForm) abstractForm;
this.activityStatus = form.getActivityStatus();
if(!validator.isEmpty(form.getBarcode()))
this.barcode = form.getBarcode();
else
this.barcode = null;
this.comments = form.getComments();
this.positionDimensionOne = new Integer(form.getPositionDimensionOne());
this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo());
this.type = form.getType();
if(form.isAddOperation())
{
this.available = new Boolean(true);
}
else
{
this.available = new Boolean(form.isAvailable());
}
//in case of edit
if(!form.isAddOperation())
{
//specimen is a new specimen
if(parentSpecimen==null)
{
String parentSpecimenId = form.getParentSpecimenId();
// specimen created from another specimen
if(parentSpecimenId!=null && !parentSpecimenId.trim().equals("") && Long.parseLong(parentSpecimenId)>0)
{
isParentChanged = true;
}
}
else//specimen created from another specimen
{
if(parentSpecimen.getSystemIdentifier().longValue()!=Long.parseLong(form.getParentSpecimenId()))
{
isParentChanged = true;
}
}
}
Logger.out.debug("isParentChanged "+isParentChanged);
if(form.isParentPresent())
{
parentSpecimen = new CellSpecimen();
parentSpecimen.setSystemIdentifier(new Long(form.getParentSpecimenId()));
this.setPositionDimensionOne(new Integer(form.getPositionDimensionOne()));
this.setPositionDimensionTwo(new Integer(form.getPositionDimensionTwo()));
}
else
{
parentSpecimen = null;
specimenCollectionGroup = new SpecimenCollectionGroup();
this.specimenCollectionGroup.setSystemIdentifier(new Long(form.getSpecimenCollectionGroupId()));
}
this.storageContainer.setSystemIdentifier(new Long(form.getStorageContainer()));
//Setting the SpecimenCharacteristics
specimenCharacteristics.pathologicalStatus = form.getPathologicalStatus();
specimenCharacteristics.tissueSide = form.getTissueSide();
specimenCharacteristics.tissueSite = form.getTissueSite();
//Getting the Map of External Identifiers
Map extMap = form.getExternalIdentifier();
MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.domain");
Collection extCollection = parser.generateData(extMap);
this.externalIdentifierCollection = extCollection;
Map bioMap = form.getBiohazard();
Logger.out.debug("PRE FIX MAP "+bioMap);
bioMap = fixMap(bioMap);
Logger.out.debug("POST FIX MAP "+bioMap);
//Getting the Map of Biohazards
parser = new MapDataParser("edu.wustl.catissuecore.domain");
Collection bioCollection = parser.generateData(bioMap);
Logger.out.debug("BIO-COL : " + bioCollection );
this.biohazardCollection = bioCollection;
}
else if(abstractForm instanceof CreateSpecimenForm)
{
CreateSpecimenForm form = (CreateSpecimenForm)abstractForm;
this.activityStatus = form.getActivityStatus();
if(!validator.isEmpty(form.getBarcode()))
this.barcode = form.getBarcode();
else
this.barcode = null;
this.comments = form.getComments();
this.positionDimensionOne = new Integer(form.getPositionDimensionOne());
this.positionDimensionTwo = new Integer(form.getPositionDimensionTwo());
this.type = form.getType();
if(form.isAddOperation())
{
this.available = new Boolean(true);
}
else
{
this.available = new Boolean(form.isAvailable());
}
this.storageContainer.setSystemIdentifier(new Long(form.getStorageContainer()));
this.parentSpecimen = new CellSpecimen();
this.parentSpecimen.setSystemIdentifier(new Long(form.getParentSpecimenId()));
//Getting the Map of External Identifiers
Map extMap = form.getExternalIdentifier();
MapDataParser parser = new MapDataParser("edu.wustl.catissuecore.domain");
Collection extCollection = parser.generateData(extMap);
this.externalIdentifierCollection = extCollection;
}
}
catch (Exception excp)
{
Logger.out.error(excp.getMessage(),excp);
}
}
protected Map fixMap(Map orgMap)
{
Map newMap = new HashMap();
Iterator it = orgMap.keySet().iterator();
while(it.hasNext())
{
String key = (String)it.next();
String value = (String)orgMap.get(key);
//Logger.out.debug("key "+key);
if(key.indexOf("persisted")==-1)
{
newMap.put(key,value);
}
}
return newMap;
}
/**
* This function returns the actual type of the specimen i.e Cell / Fluid / Molecular / Tissue.
*/
public final String getClassName()
{
String className = null;
if(this instanceof CellSpecimen)
{
className = "Cell";
}
else if(this instanceof MolecularSpecimen)
{
className = "Molecular";
}
else if(this instanceof FluidSpecimen)
{
className = "Fluid";
}
else if(this instanceof TissueSpecimen)
{
className = "Tissue";
}
return className;
}
} |
package edu.wustl.query.domain;
public class SelectedConcept
{
private String vocabName;
private String vocabVersion;
private String conceptName;
private String conceptCode;
private String medCode;
/**
*
* @return
*/
public String getVocabName()
{
return vocabName;
}
/**
*
* @param vocabName
*/
public void setVocabName(String vocabName)
{
this.vocabName = vocabName;
}
/**
*
* @return
*/
public String getVocabVersion()
{
return vocabVersion;
}
/**
*
* @param vocabVersion
*/
public void setVocabVersion(String vocabVersion)
{
this.vocabVersion = vocabVersion;
}
/**
*
* @return
*/
public String getConceptName()
{
return conceptName;
}
/**
*
* @param conceptName
*/
public void setConceptName(String conceptName)
{
this.conceptName = conceptName;
}
/**
*
* @return
*/
public String getConceptCode()
{
return conceptCode;
}
/**
*
* @param conceptCode
*/
public void setConceptCode(String conceptCode)
{
this.conceptCode = conceptCode;
}
/**
*
* @return
*/
public String getMedCode()
{
return medCode;
}
/**
*
* @param medCode
*/
public void setMedCode(String medCode)
{
this.medCode = medCode;
}
} |
package ads;
/**
*
* A simple implementation of a binary search tree.
*
* @author Andrzej Ruszczewski
*
*/
public class BinaryTree {
TreeNode root;
/**
*
* Basic insertion method which inserts into root if null, or calls the
* recursive method otherwise. This is the method that should be called to
* insert a value into the tree.
*
* @param value
* the data to insert
*
*/
public void insert(int value) {
if (root == null) {
root = new TreeNode();
root.data = value;
} else {
insertNode(value, root);
}
}
/**
*
* Recursive insertion method for inserting deeper than the root.
*
* @param value
* @param current
*
*/
private void insertNode(int value, TreeNode current) {
if (value < current.data) {
if (current.left == null) {
current.left = new TreeNode();
current.left.data = value;
} else {
insertNode(value, current.left);
}
} else {
if (current.right == null) {
current.right = new TreeNode();
current.right.data = value;
} else {
insertNode(value, current.right);
}
}
}
/**
* Checks if a given value is contained in the tree.
*
* @param value
* the value to search for in the tree
* @return True if the value is contained in the tree, false otherwise.
*/
public boolean contains(int value) {
if (findNode(value) != null) {
return true;
} else {
return false;
}
}
/**
* Main recursive search method. Deprecated. ;) Used to be used by contains
* method.
*
* @param value
* @param current
* @return
*/
private boolean containsRecursion(int value, TreeNode current) {
if (current == null) {
return false;
} else if (current.data == value) {
return true;
} else {
if (value > current.data) {
return containsRecursion(value, current.right);
} else {
return containsRecursion(value, current.left);
}
}
}
/**
* Recursively finds a reference to the node containing the given value.
*
* @param value
* Data of the node to find.
* @return A reference to the node containing the given value, null if the
* value does not exist in the tree.
*/
public TreeNode findNode(int value) {
return findNodeRecursion(value, root);
}
/**
* Main recursive logic of the findNode method.
*
* @param value
* @param current
* @return
*/
private TreeNode findNodeRecursion(int value, TreeNode current) {
if (current == null) {
return null;
} else if (current.data == value) {
return current;
} else {
if (value > current.data) {
return findNodeRecursion(value, current.right);
} else {
return findNodeRecursion(value, current.left);
}
}
}
/**
* Finds the parent node of the node containing the given value.
*
* @param value
* Parent of the node containing this value will be returned.
* @return Reference to the parent node, null if the value doesn't exist in
* the tree, or it is contained in the root node.
*/
public TreeNode findParent(int value) {
return findParentRecursion(value, root);
}
/**
* Main recursive logic for the findParent method.
*
* @param value
* @param current
* @return Reference to the parent node, null if the value doesn't exist in
* the tree, or it is contained in the root node.
*/
private TreeNode findParentRecursion(int value, TreeNode current) {
if (root.data == value) {
return null;
}
if (value < current.data) {
if (current.left == null) {
return null;
} else if (current.left.data == value) {
return current;
} else {
return findParentRecursion(value, current.left);
}
} else {
if (current.right == null) {
return null;
} else if (current.right.data == value) {
return current;
} else {
return findParentRecursion(value, current.right);
}
}
}
/**
* Removes node with the given value from the tree.
*
* @param value
* Data of the node to remove.
* @return True if the value existed and was removed, false if the value did
* not exist in the tree.
*/
public boolean remove(int value) {
TreeNode nodeToRemove = findNode(value);
if (nodeToRemove == null) {
return false;
}
TreeNode parent = findParent(value);
if (root.left == null && root.right == null) {
root = null;
} else if (nodeToRemove.left == null && nodeToRemove.right == null) {
if (value < parent.data) {
parent.left = null;
} else {
parent.right = null;
}
} else if (nodeToRemove.left == null) {
if (value < parent.data) {
parent.left = nodeToRemove.right;
} else {
parent.right = nodeToRemove.right;
}
} else if (nodeToRemove.right == null) {
if (value < parent.data) {
parent.left = nodeToRemove.left;
} else {
parent.right = nodeToRemove.left;
}
} else {
TreeNode largestValue = nodeToRemove.left;
boolean right = false;
while (largestValue.right != null) {
largestValue = largestValue.right;
right = true;
}
// bug bug bug !!!
if (right) {
findParent(largestValue.data).right = null;
} else {
findParent(largestValue.data).left = null;
}
nodeToRemove.data = largestValue.data;
}
return true;
}
/**
* Test method
*/
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.insert(42);
bt.insert(13);
bt.insert(666);
bt.insert(10);
bt.insert(11);
bt.insert(7);
bt.insert(9);
bt.insert(4);
System.out.println("1: " + bt.contains(1));
System.out.println("10: " + bt.contains(10));
System.out.println("42: " + bt.contains(42));
System.out.println("13: " + bt.contains(13));
System.out.println("11: " + bt.contains(11));
System.out.println("7: " + bt.contains(7));
System.out.println("9: " + bt.contains(9));
System.out.println("4: " + bt.contains(4));
System.out.println("666: " + bt.contains(666));
System.out.println("123456: " + bt.contains(123456));
System.out.println();
System.out.println(bt.findParent(42));
System.out.println(bt.findParent(13).data);
System.out.println(bt.findParent(10).data);
System.out.println(bt.findParent(123456));
System.out.println();
System.out.println(bt.findNode(1));
System.out.println(bt.findNode(42));
System.out.println(bt.findNode(666));
System.out.println();
// remove test
int vToRemove = 42;
System.out.println(vToRemove + ": " + bt.contains(vToRemove));
System.out.println("Removing " + vToRemove);
bt.remove(vToRemove);
System.out.println("42: " + bt.contains(42));
System.out.println("10: " + bt.contains(10));
System.out.println("13: " + bt.contains(13));
System.out.println("11: " + bt.contains(11));
System.out.println("7: " + bt.contains(7));
System.out.println("9: " + bt.contains(9));
System.out.println("4: " + bt.contains(4));
System.out.println("666: " + bt.contains(666));
System.out.println();
}
}
class TreeNode {
int data;
TreeNode left;
TreeNode right;
} |
package burai.app.project.viewer.result.graph;
import java.io.File;
import java.io.IOException;
import java.util.List;
import burai.app.project.QEFXProjectController;
import burai.app.project.viewer.result.QEFXResultButtonWrapper;
import burai.project.Project;
import burai.project.property.DosData;
import burai.project.property.ProjectDos;
import burai.project.property.ProjectEnergies;
import burai.project.property.ProjectProperty;
public class QEFXDosButton extends QEFXGraphButton<QEFXDosViewer> {
private static final String BUTTON_TITLE = "DOS";
private static final String BUTTON_FONT_COLOR = "-fx-text-fill: ivory";
private static final String BUTTON_BACKGROUND = "-fx-background-color: derive(lightslategrey, -35.0%)";
public static QEFXResultButtonWrapper<QEFXDosButton> getWrapper(QEFXProjectController projectController, Project project) {
ProjectProperty projectProperty = project == null ? null : project.getProperty();
if (projectProperty == null) {
return null;
}
ProjectEnergies projectEnergies = projectProperty.getFermiEnergies();
if (projectEnergies == null || projectEnergies.numEnergies() < 1) {
return null;
}
ProjectDos projectDos = projectProperty.getDos();
if (projectDos == null) {
return null;
}
List<DosData> dosDataList = projectDos.listDosData();
if (dosDataList == null || dosDataList.size() < 2) {
return null;
}
String dirPath = project == null ? null : project.getDirectoryPath();
String fileName = project == null ? null : (project.getPrefixName() + ".pdos_tot");
File file = null;
if (dirPath != null && fileName != null) {
file = new File(dirPath, fileName);
}
try {
if (file == null || (!file.isFile()) || (file.length() <= 0L)) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return () -> new QEFXDosButton(projectController, projectEnergies, projectDos);
}
private ProjectEnergies projectEnergies;
private ProjectDos projectDos;
private QEFXDosButton(QEFXProjectController projectController, ProjectEnergies projectEnergies, ProjectDos projectDos) {
super(projectController, BUTTON_TITLE, null);
if (projectEnergies == null) {
throw new IllegalArgumentException("projectEnergies is null.");
}
this.projectEnergies = projectEnergies;
this.projectDos = projectDos;
this.setIconStyle(BUTTON_BACKGROUND);
this.setLabelStyle(BUTTON_FONT_COLOR);
}
@Override
protected QEFXDosViewer createResultViewer() throws IOException {
if (this.projectController == null) {
return null;
}
return new QEFXDosViewer(this.projectController, this.projectEnergies, this.projectDos);
}
} |
package ca.eandb.jmist.framework.geometry;
import ca.eandb.jmist.framework.IntersectionRecorder;
import ca.eandb.jmist.framework.ShadingContext;
import ca.eandb.jmist.framework.SurfacePoint;
import ca.eandb.jmist.math.Box3;
import ca.eandb.jmist.math.Point3;
import ca.eandb.jmist.math.Ray3;
import ca.eandb.jmist.math.Sphere;
/**
* A <code>SceneElement</code> composed of a single primitive.
* @author brad
*/
public abstract class PrimitiveGeometry extends AbstractGeometry {
/**
* Ensures that the specified primitive index is valid for this
* <code>PrimitiveGeometry</code>. Since there is only one primitive, it
* must be zero.
* @param index The value to check.
* @exception IndexOutOfBoundsException if <code>index</code> is out of
* range, i.e., <code>index != 0</code>.
*/
private void validate(int index) {
if (index != 0) {
throw new IndexOutOfBoundsException();
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.geometry.AbstractGeometry#generateRandomSurfacePoint(int, ca.eandb.jmist.framework.ShadingContext)
*/
@Override
public final void generateRandomSurfacePoint(int index, ShadingContext context) {
validate(index);
generateRandomSurfacePoint(context);
}
/**
* Generates a random surface point uniformly distributed on the surface of
* this <code>PrimitiveGeometry</code> (optional operation).
* @return A random <code>SurfacePoint</code>.
*/
public void generateRandomSurfacePoint(ShadingContext context) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.geometry.AbstractGeometry#generateImportanceSampledSurfacePoint(int, ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.framework.ShadingContext)
*/
@Override
public final double generateImportanceSampledSurfacePoint(int index,
SurfacePoint x, ShadingContext context) {
validate(index);
return generateImportanceSampledSurfacePoint(0, x, context);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.SceneElement#getBoundingBox(int)
*/
@Override
public final Box3 getBoundingBox(int index) {
validate(index);
return boundingBox();
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.SceneElement#getBoundingSphere(int)
*/
@Override
public final Sphere getBoundingSphere(int index) {
validate(index);
return boundingSphere();
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.SceneElement#getNumPrimitives()
*/
@Override
public final int getNumPrimitives() {
return 1;
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.SceneElement#getSurfaceArea(int)
*/
@Override
public final double getSurfaceArea(int index) {
validate(index);
return getSurfaceArea();
}
/**
* Computes the surface area of this <code>PrimitiveGeometry</code>
* (optional operation).
* @return The surface area of this <code>PrimitiveGeometry</code>.
*/
public double getSurfaceArea() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.SceneElement#intersect(int, ca.eandb.jmist.math.Ray3, ca.eandb.jmist.framework.IntersectionRecorder)
*/
@Override
public final void intersect(int index, Ray3 ray, IntersectionRecorder recorder) {
validate(index);
intersect(ray, recorder);
}
/**
* Computes the intersections of the specified ray with this
* <code>PrimitiveGeometry</code>.
* @param ray The <code>Ray3</code> to intersect with.
* @param recorder The <code>IntersectionRecorder</code> to add the
* computed intersections to.
*/
public abstract void intersect(Ray3 ray, IntersectionRecorder recorder);
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.geometry.AbstractGeometry#intersects(int, ca.eandb.jmist.math.Ray3)
*/
@Override
public final boolean visibility(int index, Ray3 ray) {
validate(index);
return visibility(ray);
}
/**
* Determines if the specified ray intersects with this
* <code>PrimitiveGeometry</code>.
* @param ray The <code>Ray3</code> to intersect with.
* @return A value indicating if the ray intersects this
* <code>PrimitiveGeometry</code>.
*/
public boolean visibility(Ray3 ray) {
return visibility(ray, Double.POSITIVE_INFINITY);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.geometry.AbstractGeometry#intersects(int, ca.eandb.jmist.math.Ray3, double)
*/
@Override
public final boolean visibility(int index, Ray3 ray, double maximumDistance) {
validate(index);
return visibility(ray, maximumDistance);
}
/**
* Determines if the specified ray intersects with this
* <code>PrimitiveGeometry</code> within the specified distance.
* @param ray The <code>Ray3</code> to intersect with.
* @param maxim
* @return A value indicating if the ray intersects this
* <code>PrimitiveGeometry</code>.
*/
public boolean visibility(Ray3 ray, double maximumDistance) {
return super.visibility(0, ray, maximumDistance);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.geometry.AbstractGeometry#intersects(int, ca.eandb.jmist.math.Box3)
*/
@Override
public final boolean intersects(int index, Box3 box) {
validate(index);
return intersects(box);
}
/**
* Determines if the specified box intersects with the surface of this
* <code>PrimitiveGeometry</code>.
* @param box The <code>Box3</code> to check for intersection with.
* @return A value indicating if the box intersects the surface of this
* <code>PrimitiveGeometry</code>.
*/
public boolean intersects(Box3 box) {
return box.intersects(boundingBox());
}
protected final GeometryIntersection newIntersection(Ray3 ray,
double distance, boolean front) {
return super.newIntersection(ray, distance, front, 0);
}
protected final GeometryIntersection newSurfacePoint(Point3 p, boolean front) {
return super.newSurfacePoint(p, front, 0);
}
protected final GeometryIntersection newSurfacePoint(Point3 p) {
return super.newSurfacePoint(p, true, 0);
}
} |
package ca.ualberta.cs.c301f13t13.backend;
import java.util.ArrayList;
import java.util.UUID;
import android.content.Context;
public class GeneralController {
public static final int CACHED = 0;
public static final int CREATED = 1;
public static final int PUBLISHED = 2;
public static final int STORY = 0;
public static final int CHAPTER = 1;
public static final int CHOICE = 2;
public ArrayList<Story> getAllStories(int type, Context context){
StoryManager sm = new StoryManager(context);
DBHelper helper = DBHelper.getInstance(context);
ArrayList<Story> stories = new ArrayList<Story>();
ArrayList<Object> objects;
Story criteria;
switch(type) {
case CACHED:
criteria = new Story("", "", "", false);
objects = sm.retrieve(criteria, helper);
stories = Utilities.objectsToStories(objects);
break;
case CREATED:
criteria = new Story("", "", "", true);
objects = sm.retrieve(criteria, helper);
stories = Utilities.objectsToStories(objects);
break;
case PUBLISHED:
stories = sm.getPublishedStories();
break;
default:
break;
}
return stories;
}
/**
* Gets all the chapters that are in story.
*
* @param storyId
* @param context
*
* @return ArrayList<Chapter>
*/
public ArrayList<Chapter> getAllChapters(UUID storyId, Context context){
ChapterManager cm = new ChapterManager(context);
DBHelper helper = DBHelper.getInstance(context);
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
ArrayList<Object> objects;
Chapter criteria = new Chapter(storyId, "");
objects = cm.retrieve(criteria, helper);
chapters = Utilities.objectsToChapters(objects);
return chapters;
}
/**
* Gets all the choices that are in a chapter.
*
* @return
*/
public ArrayList <Choice> getAllChoices(UUID chapterId, Context context){
ChoiceManager cm = new ChoiceManager(context);
DBHelper helper = DBHelper.getInstance(context);
ArrayList<Choice> choices = new ArrayList<Choice>();
ArrayList<Object> objects;
// Choice criteria = new Choice(chapterId, "");
// objects = cm.retrieve(criteria, helper);
// choices = Utilities.objectsToChoices(objects);
return choices;
}
/**
* Adds either a story, chapter, or choice to the database.
*
* @param object
* @param helper
* @param type
* Will either be STORY(0), CHAPTER(1), CHOICE(2).
* @param context
*/
public void addObject(Object object, DBHelper helper, int type, Context context) {
switch (type) {
case STORY:
Story story = (Story) object;
StoryManager sm = new StoryManager(context);
sm.insert(story, helper);
break;
case CHAPTER:
Chapter chapter = (Chapter) object;
ChapterManager cm = new ChapterManager(context);
cm.insert(chapter, helper);
break;
case CHOICE:
Choice choice = (Choice) object;
ChoiceManager chm = new ChoiceManager(context);
chm.insert(choice, helper);
break;
}
}
/** have to figure out.... this will be used to search by keyword
*
* @return
*/
public ArrayList<Story> searchStory(String string){
//TODO everything
return null;
}
/** load all photo/illustration/choice as a chapter
*
* @return
*/
public Chapter getCompleteChapter(UUID id){
//TODO everything
return null;
}
/** load all photo/illustration/choice/chapters as a story
*
* @return
*/
public Story getCompleteStory(UUID id){
//TODO everything
return null;
}
public void updateObject(Object object, int type) {
// TODO SWITCH STATEMENT
}
} |
package org.jfree.chart.plot;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.annotations.CategoryAnnotation;
import org.jfree.chart.axis.Axis;
import org.jfree.chart.axis.AxisCollection;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.axis.AxisState;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.axis.ValueTick;
import org.jfree.chart.event.ChartChangeEventType;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.event.RendererChangeListener;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.CategoryItemRendererState;
import org.jfree.chart.util.Layer;
import org.jfree.chart.util.ObjectList;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleEdge;
import org.jfree.chart.util.RectangleInsets;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.chart.util.SortOrder;
import org.jfree.data.Range;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetUtilities;
/**
* A general plotting class that uses data from a {@link CategoryDataset} and
* renders each data item using a {@link CategoryItemRenderer}.
*/
public class CategoryPlot extends Plot implements ValueAxisPlot,
Zoomable, RendererChangeListener, Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = -3537691700434728188L;
/**
* The default visibility of the grid lines plotted against the domain
* axis.
*/
public static final boolean DEFAULT_DOMAIN_GRIDLINES_VISIBLE = false;
/**
* The default visibility of the grid lines plotted against the range
* axis.
*/
public static final boolean DEFAULT_RANGE_GRIDLINES_VISIBLE = true;
/** The default grid line stroke. */
public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[]
{2.0f, 2.0f}, 0.0f);
/** The default grid line paint. */
public static final Paint DEFAULT_GRIDLINE_PAINT = Color.WHITE;
/** The default value label font. */
public static final Font DEFAULT_VALUE_LABEL_FONT = new Font("SansSerif",
Font.PLAIN, 10);
/**
* The default crosshair visibility.
*
* @since 1.0.5
*/
public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;
/**
* The default crosshair stroke.
*
* @since 1.0.5
*/
public static final Stroke DEFAULT_CROSSHAIR_STROKE
= DEFAULT_GRIDLINE_STROKE;
/**
* The default crosshair paint.
*
* @since 1.0.5
*/
public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources
= ResourceBundle.getBundle(
"org.jfree.chart.plot.LocalizationBundle");
/** The plot orientation. */
private PlotOrientation orientation;
/** The offset between the data area and the axes. */
private RectangleInsets axisOffset;
/** Storage for the domain axes. */
private ObjectList domainAxes;
/** Storage for the domain axis locations. */
private ObjectList domainAxisLocations;
/**
* A flag that controls whether or not the shared domain axis is drawn
* (only relevant when the plot is being used as a subplot).
*/
private boolean drawSharedDomainAxis;
/** Storage for the range axes. */
private ObjectList rangeAxes;
/** Storage for the range axis locations. */
private ObjectList rangeAxisLocations;
/** Storage for the datasets. */
private ObjectList datasets;
/** Storage for keys that map datasets to domain axes. */
private ObjectList datasetToDomainAxisMap;
/** Storage for keys that map datasets to range axes. */
private ObjectList datasetToRangeAxisMap;
/** Storage for the renderers. */
private ObjectList renderers;
/** The dataset rendering order. */
private DatasetRenderingOrder renderingOrder
= DatasetRenderingOrder.REVERSE;
/**
* Controls the order in which the columns are traversed when rendering the
* data items.
*/
private SortOrder columnRenderingOrder = SortOrder.ASCENDING;
/**
* Controls the order in which the rows are traversed when rendering the
* data items.
*/
private SortOrder rowRenderingOrder = SortOrder.ASCENDING;
/**
* A flag that controls whether the grid-lines for the domain axis are
* visible.
*/
private boolean domainGridlinesVisible;
/** The position of the domain gridlines relative to the category. */
private CategoryAnchor domainGridlinePosition;
/** The stroke used to draw the domain grid-lines. */
private transient Stroke domainGridlineStroke;
/** The paint used to draw the domain grid-lines. */
private transient Paint domainGridlinePaint;
/**
* A flag that controls whether the grid-lines for the range axis are
* visible.
*/
private boolean rangeGridlinesVisible;
/** The stroke used to draw the range axis grid-lines. */
private transient Stroke rangeGridlineStroke;
/** The paint used to draw the range axis grid-lines. */
private transient Paint rangeGridlinePaint;
/** The anchor value. */
private double anchorValue;
/** A flag that controls whether or not a range crosshair is drawn. */
private boolean rangeCrosshairVisible;
/** The range crosshair value. */
private double rangeCrosshairValue;
/** The pen/brush used to draw the crosshair (if any). */
private transient Stroke rangeCrosshairStroke;
/** The color used to draw the crosshair (if any). */
private transient Paint rangeCrosshairPaint;
/**
* A flag that controls whether or not the crosshair locks onto actual
* data points.
*/
private boolean rangeCrosshairLockedOnData = true;
/** A map containing lists of markers for the domain axes. */
private Map foregroundDomainMarkers;
/** A map containing lists of markers for the domain axes. */
private Map backgroundDomainMarkers;
/** A map containing lists of markers for the range axes. */
private Map foregroundRangeMarkers;
/** A map containing lists of markers for the range axes. */
private Map backgroundRangeMarkers;
/**
* A (possibly empty) list of annotations for the plot. The list should
* be initialised in the constructor and never allowed to be
* <code>null</code>.
*/
private List annotations;
/**
* The weight for the plot (only relevant when the plot is used as a subplot
* within a combined plot).
*/
private int weight;
/** The fixed space for the domain axis. */
private AxisSpace fixedDomainAxisSpace;
/** The fixed space for the range axis. */
private AxisSpace fixedRangeAxisSpace;
/**
* An optional collection of legend items that can be returned by the
* getLegendItems() method.
*/
private LegendItemCollection fixedLegendItems;
/**
* Default constructor.
*/
public CategoryPlot() {
this(null, null, null, null);
}
/**
* Creates a new plot.
*
* @param dataset the dataset (<code>null</code> permitted).
* @param domainAxis the domain axis (<code>null</code> permitted).
* @param rangeAxis the range axis (<code>null</code> permitted).
* @param renderer the item renderer (<code>null</code> permitted).
*
*/
public CategoryPlot(CategoryDataset dataset,
CategoryAxis domainAxis,
ValueAxis rangeAxis,
CategoryItemRenderer renderer) {
super();
this.orientation = PlotOrientation.VERTICAL;
// allocate storage for dataset, axes and renderers
this.domainAxes = new ObjectList();
this.domainAxisLocations = new ObjectList();
this.rangeAxes = new ObjectList();
this.rangeAxisLocations = new ObjectList();
this.datasetToDomainAxisMap = new ObjectList();
this.datasetToRangeAxisMap = new ObjectList();
this.renderers = new ObjectList();
this.datasets = new ObjectList();
this.datasets.set(0, dataset);
if (dataset != null) {
dataset.addChangeListener(this);
}
this.axisOffset = new RectangleInsets(4.0, 4.0, 4.0, 4.0);
setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT, false);
setRangeAxisLocation(AxisLocation.TOP_OR_LEFT, false);
this.renderers.set(0, renderer);
if (renderer != null) {
renderer.setPlot(this);
renderer.addChangeListener(this);
}
this.domainAxes.set(0, domainAxis);
this.mapDatasetToDomainAxis(0, 0);
if (domainAxis != null) {
domainAxis.setPlot(this);
domainAxis.addChangeListener(this);
}
this.drawSharedDomainAxis = false;
this.rangeAxes.set(0, rangeAxis);
this.mapDatasetToRangeAxis(0, 0);
if (rangeAxis != null) {
rangeAxis.setPlot(this);
rangeAxis.addChangeListener(this);
}
configureDomainAxes();
configureRangeAxes();
this.domainGridlinesVisible = DEFAULT_DOMAIN_GRIDLINES_VISIBLE;
this.domainGridlinePosition = CategoryAnchor.MIDDLE;
this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;
this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;
this.rangeGridlinesVisible = DEFAULT_RANGE_GRIDLINES_VISIBLE;
this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;
this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;
this.foregroundDomainMarkers = new HashMap();
this.backgroundDomainMarkers = new HashMap();
this.foregroundRangeMarkers = new HashMap();
this.backgroundRangeMarkers = new HashMap();
Marker baseline = new ValueMarker(0.0, new Color(0.8f, 0.8f, 0.8f,
0.5f), new BasicStroke(1.0f), new Color(0.85f, 0.85f, 0.95f,
0.5f), new BasicStroke(1.0f), 0.6f);
addRangeMarker(baseline, Layer.BACKGROUND);
this.anchorValue = 0.0;
this.rangeCrosshairVisible = DEFAULT_CROSSHAIR_VISIBLE;
this.rangeCrosshairValue = 0.0;
this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;
this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;
this.annotations = new java.util.ArrayList();
}
/**
* Returns a string describing the type of plot.
*
* @return The type.
*/
public String getPlotType() {
return localizationResources.getString("Category_Plot");
}
/**
* Returns the orientation of the plot.
*
* @return The orientation of the plot (never <code>null</code>).
*
* @see #setOrientation(PlotOrientation)
*/
public PlotOrientation getOrientation() {
return this.orientation;
}
/**
* Sets the orientation for the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param orientation the orientation (<code>null</code> not permitted).
*
* @see #getOrientation()
*/
public void setOrientation(PlotOrientation orientation) {
if (orientation == null) {
throw new IllegalArgumentException("Null 'orientation' argument.");
}
this.orientation = orientation;
fireChangeEvent();
}
/**
* Returns the axis offset.
*
* @return The axis offset (never <code>null</code>).
*
* @see #setAxisOffset(RectangleInsets)
*/
public RectangleInsets getAxisOffset() {
return this.axisOffset;
}
/**
* Sets the axis offsets (gap between the data area and the axes) and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param offset the offset (<code>null</code> not permitted).
*
* @see #getAxisOffset()
*/
public void setAxisOffset(RectangleInsets offset) {
if (offset == null) {
throw new IllegalArgumentException("Null 'offset' argument.");
}
this.axisOffset = offset;
fireChangeEvent();
}
/**
* Returns the domain axis for the plot. If the domain axis for this plot
* is <code>null</code>, then the method will return the parent plot's
* domain axis (if there is a parent plot).
*
* @return The domain axis (<code>null</code> permitted).
*
* @see #setDomainAxis(CategoryAxis)
*/
public CategoryAxis getDomainAxis() {
return getDomainAxis(0);
}
/**
* Returns a domain axis.
*
* @param index the axis index.
*
* @return The axis (<code>null</code> possible).
*
* @see #setDomainAxis(int, CategoryAxis)
*/
public CategoryAxis getDomainAxis(int index) {
CategoryAxis result = null;
if (index < this.domainAxes.size()) {
result = (CategoryAxis) this.domainAxes.get(index);
}
if (result == null) {
Plot parent = getParent();
if (parent instanceof CategoryPlot) {
CategoryPlot cp = (CategoryPlot) parent;
result = cp.getDomainAxis(index);
}
}
return result;
}
/**
* Sets the domain axis for the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param axis the axis (<code>null</code> permitted).
*
* @see #getDomainAxis()
*/
public void setDomainAxis(CategoryAxis axis) {
setDomainAxis(0, axis);
}
/**
* Sets a domain axis and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param index the axis index.
* @param axis the axis (<code>null</code> permitted).
*
* @see #getDomainAxis(int)
*/
public void setDomainAxis(int index, CategoryAxis axis) {
setDomainAxis(index, axis, true);
}
/**
* Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param index the axis index.
* @param axis the axis (<code>null</code> permitted).
* @param notify notify listeners?
*/
public void setDomainAxis(int index, CategoryAxis axis, boolean notify) {
CategoryAxis existing = (CategoryAxis) this.domainAxes.get(index);
if (existing != null) {
existing.removeChangeListener(this);
}
if (axis != null) {
axis.setPlot(this);
}
this.domainAxes.set(index, axis);
if (axis != null) {
axis.configure();
axis.addChangeListener(this);
}
if (notify) {
fireChangeEvent();
}
}
/**
* Sets the domain axes for this plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param axes the axes (<code>null</code> not permitted).
*
* @see #setRangeAxes(ValueAxis[])
*/
public void setDomainAxes(CategoryAxis[] axes) {
for (int i = 0; i < axes.length; i++) {
setDomainAxis(i, axes[i], false);
}
fireChangeEvent();
}
/**
* Returns the index of the specified axis, or <code>-1</code> if the axis
* is not assigned to the plot.
*
* @param axis the axis (<code>null</code> not permitted).
*
* @return The axis index.
*
* @see #getDomainAxis(int)
* @see #getRangeAxisIndex(ValueAxis)
*
* @since 1.0.3
*/
public int getDomainAxisIndex(CategoryAxis axis) {
if (axis == null) {
throw new IllegalArgumentException("Null 'axis' argument.");
}
return this.domainAxes.indexOf(axis);
}
/**
* Returns the domain axis location for the primary domain axis.
*
* @return The location (never <code>null</code>).
*
* @see #getRangeAxisLocation()
*/
public AxisLocation getDomainAxisLocation() {
return getDomainAxisLocation(0);
}
/**
* Returns the location for a domain axis.
*
* @param index the axis index.
*
* @return The location.
*
* @see #setDomainAxisLocation(int, AxisLocation)
*/
public AxisLocation getDomainAxisLocation(int index) {
AxisLocation result = null;
if (index < this.domainAxisLocations.size()) {
result = (AxisLocation) this.domainAxisLocations.get(index);
}
if (result == null) {
result = AxisLocation.getOpposite(getDomainAxisLocation(0));
}
return result;
}
/**
* Sets the location of the domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param location the axis location (<code>null</code> not permitted).
*
* @see #getDomainAxisLocation()
* @see #setDomainAxisLocation(int, AxisLocation)
*/
public void setDomainAxisLocation(AxisLocation location) {
// delegate...
setDomainAxisLocation(0, location, true);
}
/**
* Sets the location of the domain axis and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param location the axis location (<code>null</code> not permitted).
* @param notify a flag that controls whether listeners are notified.
*/
public void setDomainAxisLocation(AxisLocation location, boolean notify) {
// delegate...
setDomainAxisLocation(0, location, notify);
}
/**
* Sets the location for a domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param index the axis index.
* @param location the location.
*
* @see #getDomainAxisLocation(int)
* @see #setRangeAxisLocation(int, AxisLocation)
*/
public void setDomainAxisLocation(int index, AxisLocation location) {
// delegate...
setDomainAxisLocation(index, location, true);
}
/**
* Sets the location for a domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param index the axis index.
* @param location the location.
* @param notify notify listeners?
*
* @since 1.0.5
*
* @see #getDomainAxisLocation(int)
* @see #setRangeAxisLocation(int, AxisLocation, boolean)
*/
public void setDomainAxisLocation(int index, AxisLocation location,
boolean notify) {
if (index == 0 && location == null) {
throw new IllegalArgumentException(
"Null 'location' for index 0 not permitted.");
}
this.domainAxisLocations.set(index, location);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the domain axis edge. This is derived from the axis location
* and the plot orientation.
*
* @return The edge (never <code>null</code>).
*/
public RectangleEdge getDomainAxisEdge() {
return getDomainAxisEdge(0);
}
/**
* Returns the edge for a domain axis.
*
* @param index the axis index.
*
* @return The edge (never <code>null</code>).
*/
public RectangleEdge getDomainAxisEdge(int index) {
RectangleEdge result = null;
AxisLocation location = getDomainAxisLocation(index);
if (location != null) {
result = Plot.resolveDomainAxisLocation(location, this.orientation);
}
else {
result = RectangleEdge.opposite(getDomainAxisEdge(0));
}
return result;
}
/**
* Returns the number of domain axes.
*
* @return The axis count.
*/
public int getDomainAxisCount() {
return this.domainAxes.size();
}
/**
* Clears the domain axes from the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*/
public void clearDomainAxes() {
for (int i = 0; i < this.domainAxes.size(); i++) {
CategoryAxis axis = (CategoryAxis) this.domainAxes.get(i);
if (axis != null) {
axis.removeChangeListener(this);
}
}
this.domainAxes.clear();
fireChangeEvent();
}
/**
* Configures the domain axes.
*/
public void configureDomainAxes() {
for (int i = 0; i < this.domainAxes.size(); i++) {
CategoryAxis axis = (CategoryAxis) this.domainAxes.get(i);
if (axis != null) {
axis.configure();
}
}
}
/**
* Returns the range axis for the plot. If the range axis for this plot is
* null, then the method will return the parent plot's range axis (if there
* is a parent plot).
*
* @return The range axis (possibly <code>null</code>).
*/
public ValueAxis getRangeAxis() {
return getRangeAxis(0);
}
/**
* Returns a range axis.
*
* @param index the axis index.
*
* @return The axis (<code>null</code> possible).
*/
public ValueAxis getRangeAxis(int index) {
ValueAxis result = null;
if (index < this.rangeAxes.size()) {
result = (ValueAxis) this.rangeAxes.get(index);
}
if (result == null) {
Plot parent = getParent();
if (parent instanceof CategoryPlot) {
CategoryPlot cp = (CategoryPlot) parent;
result = cp.getRangeAxis(index);
}
}
return result;
}
/**
* Sets the range axis for the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param axis the axis (<code>null</code> permitted).
*/
public void setRangeAxis(ValueAxis axis) {
setRangeAxis(0, axis);
}
/**
* Sets a range axis and sends a {@link PlotChangeEvent} to all registered
* listeners.
*
* @param index the axis index.
* @param axis the axis.
*/
public void setRangeAxis(int index, ValueAxis axis) {
setRangeAxis(index, axis, true);
}
/**
* Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param index the axis index.
* @param axis the axis.
* @param notify notify listeners?
*/
public void setRangeAxis(int index, ValueAxis axis, boolean notify) {
ValueAxis existing = (ValueAxis) this.rangeAxes.get(index);
if (existing != null) {
existing.removeChangeListener(this);
}
if (axis != null) {
axis.setPlot(this);
}
this.rangeAxes.set(index, axis);
if (axis != null) {
axis.configure();
axis.addChangeListener(this);
}
if (notify) {
fireChangeEvent();
}
}
/**
* Sets the range axes for this plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param axes the axes (<code>null</code> not permitted).
*
* @see #setDomainAxes(CategoryAxis[])
*/
public void setRangeAxes(ValueAxis[] axes) {
for (int i = 0; i < axes.length; i++) {
setRangeAxis(i, axes[i], false);
}
fireChangeEvent();
}
/**
* Returns the index of the specified axis, or <code>-1</code> if the axis
* is not assigned to the plot.
*
* @param axis the axis (<code>null</code> not permitted).
*
* @return The axis index.
*
* @see #getRangeAxis(int)
* @see #getDomainAxisIndex(CategoryAxis)
*
* @since 1.0.7
*/
public int getRangeAxisIndex(ValueAxis axis) {
if (axis == null) {
throw new IllegalArgumentException("Null 'axis' argument.");
}
int result = this.rangeAxes.indexOf(axis);
if (result < 0) { // try the parent plot
Plot parent = getParent();
if (parent instanceof CategoryPlot) {
CategoryPlot p = (CategoryPlot) parent;
result = p.getRangeAxisIndex(axis);
}
}
return result;
}
/**
* Returns the range axis location.
*
* @return The location (never <code>null</code>).
*/
public AxisLocation getRangeAxisLocation() {
return getRangeAxisLocation(0);
}
/**
* Returns the location for a range axis.
*
* @param index the axis index.
*
* @return The location.
*
* @see #setRangeAxisLocation(int, AxisLocation)
*/
public AxisLocation getRangeAxisLocation(int index) {
AxisLocation result = null;
if (index < this.rangeAxisLocations.size()) {
result = (AxisLocation) this.rangeAxisLocations.get(index);
}
if (result == null) {
result = AxisLocation.getOpposite(getRangeAxisLocation(0));
}
return result;
}
/**
* Sets the location of the range axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param location the location (<code>null</code> not permitted).
*
* @see #setRangeAxisLocation(AxisLocation, boolean)
* @see #setDomainAxisLocation(AxisLocation)
*/
public void setRangeAxisLocation(AxisLocation location) {
// defer argument checking...
setRangeAxisLocation(location, true);
}
/**
* Sets the location of the range axis and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param location the location (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #setDomainAxisLocation(AxisLocation, boolean)
*/
public void setRangeAxisLocation(AxisLocation location, boolean notify) {
setRangeAxisLocation(0, location, notify);
}
/**
* Sets the location for a range axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param index the axis index.
* @param location the location.
*
* @see #getRangeAxisLocation(int)
* @see #setRangeAxisLocation(int, AxisLocation, boolean)
*/
public void setRangeAxisLocation(int index, AxisLocation location) {
setRangeAxisLocation(index, location, true);
}
/**
* Sets the location for a range axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param index the axis index.
* @param location the location.
* @param notify notify listeners?
*
* @see #getRangeAxisLocation(int)
* @see #setDomainAxisLocation(int, AxisLocation, boolean)
*/
public void setRangeAxisLocation(int index, AxisLocation location,
boolean notify) {
if (index == 0 && location == null) {
throw new IllegalArgumentException(
"Null 'location' for index 0 not permitted.");
}
this.rangeAxisLocations.set(index, location);
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the edge where the primary range axis is located.
*
* @return The edge (never <code>null</code>).
*/
public RectangleEdge getRangeAxisEdge() {
return getRangeAxisEdge(0);
}
/**
* Returns the edge for a range axis.
*
* @param index the axis index.
*
* @return The edge.
*/
public RectangleEdge getRangeAxisEdge(int index) {
AxisLocation location = getRangeAxisLocation(index);
RectangleEdge result = Plot.resolveRangeAxisLocation(location,
this.orientation);
if (result == null) {
result = RectangleEdge.opposite(getRangeAxisEdge(0));
}
return result;
}
/**
* Returns the number of range axes.
*
* @return The axis count.
*/
public int getRangeAxisCount() {
return this.rangeAxes.size();
}
/**
* Clears the range axes from the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*/
public void clearRangeAxes() {
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.rangeAxes.get(i);
if (axis != null) {
axis.removeChangeListener(this);
}
}
this.rangeAxes.clear();
fireChangeEvent();
}
/**
* Configures the range axes.
*/
public void configureRangeAxes() {
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.rangeAxes.get(i);
if (axis != null) {
axis.configure();
}
}
}
/**
* Returns the primary dataset for the plot.
*
* @return The primary dataset (possibly <code>null</code>).
*
* @see #setDataset(CategoryDataset)
*/
public CategoryDataset getDataset() {
return getDataset(0);
}
/**
* Returns the dataset at the given index.
*
* @param index the dataset index.
*
* @return The dataset (possibly <code>null</code>).
*
* @see #setDataset(int, CategoryDataset)
*/
public CategoryDataset getDataset(int index) {
CategoryDataset result = null;
if (this.datasets.size() > index) {
result = (CategoryDataset) this.datasets.get(index);
}
return result;
}
/**
* Sets the dataset for the plot, replacing the existing dataset, if there
* is one. This method also calls the
* {@link #datasetChanged(DatasetChangeEvent)} method, which adjusts the
* axis ranges if necessary and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset()
*/
public void setDataset(CategoryDataset dataset) {
setDataset(0, dataset);
}
/**
* Sets a dataset for the plot.
*
* @param index the dataset index.
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset(int)
*/
public void setDataset(int index, CategoryDataset dataset) {
CategoryDataset existing = (CategoryDataset) this.datasets.get(index);
if (existing != null) {
existing.removeChangeListener(this);
}
this.datasets.set(index, dataset);
if (dataset != null) {
dataset.addChangeListener(this);
}
// send a dataset change event to self...
DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);
datasetChanged(event);
}
/**
* Returns the number of datasets.
*
* @return The number of datasets.
*
* @since 1.0.2
*/
public int getDatasetCount() {
return this.datasets.size();
}
/**
* Maps a dataset to a particular domain axis.
*
* @param index the dataset index (zero-based).
* @param axisIndex the axis index (zero-based).
*
* @see #getDomainAxisForDataset(int)
*/
public void mapDatasetToDomainAxis(int index, int axisIndex) {
this.datasetToDomainAxisMap.set(index, new Integer(axisIndex));
// fake a dataset change event to update axes...
datasetChanged(new DatasetChangeEvent(this, getDataset(index)));
}
/**
* Returns the domain axis for a dataset. You can change the axis for a
* dataset using the {@link #mapDatasetToDomainAxis(int, int)} method.
*
* @param index the dataset index.
*
* @return The domain axis.
*
* @see #mapDatasetToDomainAxis(int, int)
*/
public CategoryAxis getDomainAxisForDataset(int index) {
CategoryAxis result = getDomainAxis();
Integer axisIndex = (Integer) this.datasetToDomainAxisMap.get(index);
if (axisIndex != null) {
result = getDomainAxis(axisIndex.intValue());
}
return result;
}
/**
* Maps a dataset to a particular range axis.
*
* @param index the dataset index (zero-based).
* @param axisIndex the axis index (zero-based).
*
* @see #getRangeAxisForDataset(int)
*/
public void mapDatasetToRangeAxis(int index, int axisIndex) {
this.datasetToRangeAxisMap.set(index, new Integer(axisIndex));
// fake a dataset change event to update axes...
datasetChanged(new DatasetChangeEvent(this, getDataset(index)));
}
/**
* Returns the range axis for a dataset. You can change the axis for a
* dataset using the {@link #mapDatasetToRangeAxis(int, int)} method.
*
* @param index the dataset index.
*
* @return The range axis.
*
* @see #mapDatasetToRangeAxis(int, int)
*/
public ValueAxis getRangeAxisForDataset(int index) {
ValueAxis result = getRangeAxis();
Integer axisIndex = (Integer) this.datasetToRangeAxisMap.get(index);
if (axisIndex != null) {
result = getRangeAxis(axisIndex.intValue());
}
return result;
}
/**
* Returns a reference to the renderer for the plot.
*
* @return The renderer.
*
* @see #setRenderer(CategoryItemRenderer)
*/
public CategoryItemRenderer getRenderer() {
return getRenderer(0);
}
/**
* Returns the renderer at the given index.
*
* @param index the renderer index.
*
* @return The renderer (possibly <code>null</code>).
*
* @see #setRenderer(int, CategoryItemRenderer)
*/
public CategoryItemRenderer getRenderer(int index) {
CategoryItemRenderer result = null;
if (this.renderers.size() > index) {
result = (CategoryItemRenderer) this.renderers.get(index);
}
return result;
}
/**
* Sets the renderer at index 0 (sometimes referred to as the "primary"
* renderer) and sends a {@link PlotChangeEvent} to all registered
* listeners.
*
* @param renderer the renderer (<code>null</code> permitted.
*
* @see #getRenderer()
*/
public void setRenderer(CategoryItemRenderer renderer) {
setRenderer(0, renderer, true);
}
/**
* Sets the renderer at index 0 (sometimes referred to as the "primary"
* renderer) and, if requested, sends a {@link PlotChangeEvent} to all
* registered listeners.
* <p>
* You can set the renderer to <code>null</code>, but this is not
* recommended because:
* <ul>
* <li>no data will be displayed;</li>
* <li>the plot background will not be painted;</li>
* </ul>
*
* @param renderer the renderer (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getRenderer()
*/
public void setRenderer(CategoryItemRenderer renderer, boolean notify) {
setRenderer(0, renderer, notify);
}
/**
* Sets the renderer at the specified index and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the index.
* @param renderer the renderer (<code>null</code> permitted).
*
* @see #getRenderer(int)
* @see #setRenderer(int, CategoryItemRenderer, boolean)
*/
public void setRenderer(int index, CategoryItemRenderer renderer) {
setRenderer(index, renderer, true);
}
/**
* Sets a renderer. A {@link PlotChangeEvent} is sent to all registered
* listeners.
*
* @param index the index.
* @param renderer the renderer (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getRenderer(int)
*/
public void setRenderer(int index, CategoryItemRenderer renderer,
boolean notify) {
// stop listening to the existing renderer...
CategoryItemRenderer existing
= (CategoryItemRenderer) this.renderers.get(index);
if (existing != null) {
existing.removeChangeListener(this);
}
// register the new renderer...
this.renderers.set(index, renderer);
if (renderer != null) {
renderer.setPlot(this);
renderer.addChangeListener(this);
}
configureDomainAxes();
configureRangeAxes();
if (notify) {
fireChangeEvent();
}
}
/**
* Sets the renderers for this plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param renderers the renderers.
*/
public void setRenderers(CategoryItemRenderer[] renderers) {
for (int i = 0; i < renderers.length; i++) {
setRenderer(i, renderers[i], false);
}
fireChangeEvent();
}
/**
* Returns the renderer for the specified dataset. If the dataset doesn't
* belong to the plot, this method will return <code>null</code>.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The renderer (possibly <code>null</code>).
*/
public CategoryItemRenderer getRendererForDataset(CategoryDataset dataset) {
CategoryItemRenderer result = null;
for (int i = 0; i < this.datasets.size(); i++) {
if (this.datasets.get(i) == dataset) {
result = (CategoryItemRenderer) this.renderers.get(i);
break;
}
}
return result;
}
/**
* Returns the index of the specified renderer, or <code>-1</code> if the
* renderer is not assigned to this plot.
*
* @param renderer the renderer (<code>null</code> permitted).
*
* @return The renderer index.
*/
public int getIndexOf(CategoryItemRenderer renderer) {
return this.renderers.indexOf(renderer);
}
/**
* Returns the dataset rendering order.
*
* @return The order (never <code>null</code>).
*
* @see #setDatasetRenderingOrder(DatasetRenderingOrder)
*/
public DatasetRenderingOrder getDatasetRenderingOrder() {
return this.renderingOrder;
}
/**
* Sets the rendering order and sends a {@link PlotChangeEvent} to all
* registered listeners. By default, the plot renders the primary dataset
* last (so that the primary dataset overlays the secondary datasets). You
* can reverse this if you want to.
*
* @param order the rendering order (<code>null</code> not permitted).
*
* @see #getDatasetRenderingOrder()
*/
public void setDatasetRenderingOrder(DatasetRenderingOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument.");
}
this.renderingOrder = order;
fireChangeEvent();
}
/**
* Returns the order in which the columns are rendered. The default value
* is <code>SortOrder.ASCENDING</code>.
*
* @return The column rendering order (never <code>null</code).
*
* @see #setColumnRenderingOrder(SortOrder)
*/
public SortOrder getColumnRenderingOrder() {
return this.columnRenderingOrder;
}
/**
* Sets the column order in which the items in each dataset should be
* rendered and sends a {@link PlotChangeEvent} to all registered
* listeners. Note that this affects the order in which items are drawn,
* NOT their position in the chart.
*
* @param order the order (<code>null</code> not permitted).
*
* @see #getColumnRenderingOrder()
* @see #setRowRenderingOrder(SortOrder)
*/
public void setColumnRenderingOrder(SortOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument.");
}
this.columnRenderingOrder = order;
fireChangeEvent();
}
/**
* Returns the order in which the rows should be rendered. The default
* value is <code>SortOrder.ASCENDING</code>.
*
* @return The order (never <code>null</code>).
*
* @see #setRowRenderingOrder(SortOrder)
*/
public SortOrder getRowRenderingOrder() {
return this.rowRenderingOrder;
}
/**
* Sets the row order in which the items in each dataset should be
* rendered and sends a {@link PlotChangeEvent} to all registered
* listeners. Note that this affects the order in which items are drawn,
* NOT their position in the chart.
*
* @param order the order (<code>null</code> not permitted).
*
* @see #getRowRenderingOrder()
* @see #setColumnRenderingOrder(SortOrder)
*/
public void setRowRenderingOrder(SortOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument.");
}
this.rowRenderingOrder = order;
fireChangeEvent();
}
/**
* Returns the flag that controls whether the domain grid-lines are visible.
*
* @return The <code>true</code> or <code>false</code>.
*
* @see #setDomainGridlinesVisible(boolean)
*/
public boolean isDomainGridlinesVisible() {
return this.domainGridlinesVisible;
}
/**
* Sets the flag that controls whether or not grid-lines are drawn against
* the domain axis.
* <p>
* If the flag value changes, a {@link PlotChangeEvent} is sent to all
* registered listeners.
*
* @param visible the new value of the flag.
*
* @see #isDomainGridlinesVisible()
*/
public void setDomainGridlinesVisible(boolean visible) {
if (this.domainGridlinesVisible != visible) {
this.domainGridlinesVisible = visible;
fireChangeEvent();
}
}
/**
* Returns the position used for the domain gridlines.
*
* @return The gridline position (never <code>null</code>).
*
* @see #setDomainGridlinePosition(CategoryAnchor)
*/
public CategoryAnchor getDomainGridlinePosition() {
return this.domainGridlinePosition;
}
/**
* Sets the position used for the domain gridlines and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param position the position (<code>null</code> not permitted).
*
* @see #getDomainGridlinePosition()
*/
public void setDomainGridlinePosition(CategoryAnchor position) {
if (position == null) {
throw new IllegalArgumentException("Null 'position' argument.");
}
this.domainGridlinePosition = position;
fireChangeEvent();
}
/**
* Returns the stroke used to draw grid-lines against the domain axis.
*
* @return The stroke (never <code>null</code>).
*
* @see #setDomainGridlineStroke(Stroke)
*/
public Stroke getDomainGridlineStroke() {
return this.domainGridlineStroke;
}
/**
* Sets the stroke used to draw grid-lines against the domain axis and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getDomainGridlineStroke()
*/
public void setDomainGridlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' not permitted.");
}
this.domainGridlineStroke = stroke;
fireChangeEvent();
}
/**
* Returns the paint used to draw grid-lines against the domain axis.
*
* @return The paint (never <code>null</code>).
*
* @see #setDomainGridlinePaint(Paint)
*/
public Paint getDomainGridlinePaint() {
return this.domainGridlinePaint;
}
/**
* Sets the paint used to draw the grid-lines (if any) against the domain
* axis and sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDomainGridlinePaint()
*/
public void setDomainGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainGridlinePaint = paint;
fireChangeEvent();
}
/**
* Returns the flag that controls whether the range grid-lines are visible.
*
* @return The flag.
*
* @see #setRangeGridlinesVisible(boolean)
*/
public boolean isRangeGridlinesVisible() {
return this.rangeGridlinesVisible;
}
/**
* Sets the flag that controls whether or not grid-lines are drawn against
* the range axis. If the flag changes value, a {@link PlotChangeEvent} is
* sent to all registered listeners.
*
* @param visible the new value of the flag.
*
* @see #isRangeGridlinesVisible()
*/
public void setRangeGridlinesVisible(boolean visible) {
if (this.rangeGridlinesVisible != visible) {
this.rangeGridlinesVisible = visible;
fireChangeEvent();
}
}
/**
* Returns the stroke used to draw the grid-lines against the range axis.
*
* @return The stroke (never <code>null</code>).
*
* @see #setRangeGridlineStroke(Stroke)
*/
public Stroke getRangeGridlineStroke() {
return this.rangeGridlineStroke;
}
/**
* Sets the stroke used to draw the grid-lines against the range axis and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getRangeGridlineStroke()
*/
public void setRangeGridlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.rangeGridlineStroke = stroke;
fireChangeEvent();
}
/**
* Returns the paint used to draw the grid-lines against the range axis.
*
* @return The paint (never <code>null</code>).
*
* @see #setRangeGridlinePaint(Paint)
*/
public Paint getRangeGridlinePaint() {
return this.rangeGridlinePaint;
}
/**
* Sets the paint used to draw the grid lines against the range axis and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeGridlinePaint()
*/
public void setRangeGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeGridlinePaint = paint;
fireChangeEvent();
}
/**
* Returns the fixed legend items, if any.
*
* @return The legend items (possibly <code>null</code>).
*
* @see #setFixedLegendItems(LegendItemCollection)
*/
public LegendItemCollection getFixedLegendItems() {
return this.fixedLegendItems;
}
/**
* Sets the fixed legend items for the plot. Leave this set to
* <code>null</code> if you prefer the legend items to be created
* automatically.
*
* @param items the legend items (<code>null</code> permitted).
*
* @see #getFixedLegendItems()
*/
public void setFixedLegendItems(LegendItemCollection items) {
this.fixedLegendItems = items;
fireChangeEvent();
}
/**
* Returns the legend items for the plot. By default, this method creates
* a legend item for each series in each of the datasets. You can change
* this behaviour by overriding this method.
*
* @return The legend items.
*/
public LegendItemCollection getLegendItems() {
LegendItemCollection result = this.fixedLegendItems;
if (result == null) {
result = new LegendItemCollection();
// get the legend items for the datasets...
int count = this.datasets.size();
for (int datasetIndex = 0; datasetIndex < count; datasetIndex++) {
CategoryDataset dataset = getDataset(datasetIndex);
if (dataset != null) {
CategoryItemRenderer renderer = getRenderer(datasetIndex);
if (renderer != null) {
int seriesCount = dataset.getRowCount();
for (int i = 0; i < seriesCount; i++) {
LegendItem item = renderer.getLegendItem(
datasetIndex, i);
if (item != null) {
result.add(item);
}
}
}
}
}
}
return result;
}
/**
* Handles a 'click' on the plot by updating the anchor value.
*
* @param x x-coordinate of the click (in Java2D space).
* @param y y-coordinate of the click (in Java2D space).
* @param info information about the plot's dimensions.
*
*/
public void handleClick(int x, int y, PlotRenderingInfo info) {
Rectangle2D dataArea = info.getDataArea();
if (dataArea.contains(x, y)) {
// set the anchor value for the range axis...
double java2D = 0.0;
if (this.orientation == PlotOrientation.HORIZONTAL) {
java2D = x;
}
else if (this.orientation == PlotOrientation.VERTICAL) {
java2D = y;
}
RectangleEdge edge = Plot.resolveRangeAxisLocation(
getRangeAxisLocation(), this.orientation);
double value = getRangeAxis().java2DToValue(
java2D, info.getDataArea(), edge);
setAnchorValue(value);
setRangeCrosshairValue(value);
}
}
/**
* Zooms (in or out) on the plot's value axis.
* <p>
* If the value 0.0 is passed in as the zoom percent, the auto-range
* calculation for the axis is restored (which sets the range to include
* the minimum and maximum data values, thus displaying all the data).
*
* @param percent the zoom amount.
*/
public void zoom(double percent) {
if (percent > 0.0) {
double range = getRangeAxis().getRange().getLength();
double scaledRange = range * percent;
getRangeAxis().setRange(this.anchorValue - scaledRange / 2.0,
this.anchorValue + scaledRange / 2.0);
}
else {
getRangeAxis().setAutoRange(true);
}
}
/**
* Receives notification of a change to the plot's dataset.
* <P>
* The range axis bounds will be recalculated if necessary.
*
* @param event information about the event (not used here).
*/
public void datasetChanged(DatasetChangeEvent event) {
int count = this.rangeAxes.size();
for (int axisIndex = 0; axisIndex < count; axisIndex++) {
ValueAxis yAxis = getRangeAxis(axisIndex);
if (yAxis != null) {
yAxis.configure();
}
}
if (getParent() != null) {
getParent().datasetChanged(event);
}
else {
PlotChangeEvent e = new PlotChangeEvent(this);
e.setType(ChartChangeEventType.DATASET_UPDATED);
notifyListeners(e);
}
}
/**
* Receives notification of a renderer change event.
*
* @param event the event.
*/
public void rendererChanged(RendererChangeEvent event) {
Plot parent = getParent();
if (parent != null) {
if (parent instanceof RendererChangeListener) {
RendererChangeListener rcl = (RendererChangeListener) parent;
rcl.rendererChanged(event);
}
else {
// this should never happen with the existing code, but throw
// an exception in case future changes make it possible...
throw new RuntimeException(
"The renderer has changed and I don't know what to do!");
}
}
else {
configureRangeAxes();
PlotChangeEvent e = new PlotChangeEvent(this);
notifyListeners(e);
}
}
/**
* Adds a marker for display (in the foreground) against the domain axis and
* sends a {@link PlotChangeEvent} to all registered listeners. Typically a
* marker will be drawn by the renderer as a line perpendicular to the
* domain axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
*
* @see #removeDomainMarker(Marker)
*/
public void addDomainMarker(CategoryMarker marker) {
addDomainMarker(marker, Layer.FOREGROUND);
}
/**
* Adds a marker for display against the domain axis and sends a
* {@link PlotChangeEvent} to all registered listeners. Typically a marker
* will be drawn by the renderer as a line perpendicular to the domain
* axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background) (<code>null</code>
* not permitted).
*
* @see #removeDomainMarker(Marker, Layer)
*/
public void addDomainMarker(CategoryMarker marker, Layer layer) {
addDomainMarker(0, marker, layer);
}
/**
* Adds a marker for display by a particular renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to a domain axis, however this is entirely up to the renderer.
*
* @param index the renderer index.
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (<code>null</code> not permitted).
*
* @see #removeDomainMarker(int, Marker, Layer)
*/
public void addDomainMarker(int index, CategoryMarker marker, Layer layer) {
addDomainMarker(index, marker, layer, true);
}
/**
* Adds a marker for display by a particular renderer and, if requested,
* sends a {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to a domain axis, however this is entirely up to the renderer.
*
* @param index the renderer index.
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @since 1.0.10
*
* @see #removeDomainMarker(int, Marker, Layer, boolean)
*/
public void addDomainMarker(int index, CategoryMarker marker, Layer layer,
boolean notify) {
if (marker == null) {
throw new IllegalArgumentException("Null 'marker' not permitted.");
}
if (layer == null) {
throw new IllegalArgumentException("Null 'layer' not permitted.");
}
Collection markers;
if (layer == Layer.FOREGROUND) {
markers = (Collection) this.foregroundDomainMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.foregroundDomainMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
else if (layer == Layer.BACKGROUND) {
markers = (Collection) this.backgroundDomainMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.backgroundDomainMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
marker.addChangeListener(this);
if (notify) {
fireChangeEvent();
}
}
/**
* Clears all the domain markers for the plot and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @see #clearRangeMarkers()
*/
public void clearDomainMarkers() {
if (this.backgroundDomainMarkers != null) {
Set keys = this.backgroundDomainMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearDomainMarkers(key.intValue());
}
this.backgroundDomainMarkers.clear();
}
if (this.foregroundDomainMarkers != null) {
Set keys = this.foregroundDomainMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearDomainMarkers(key.intValue());
}
this.foregroundDomainMarkers.clear();
}
fireChangeEvent();
}
/**
* Returns the list of domain markers (read only) for the specified layer.
*
* @param layer the layer (foreground or background).
*
* @return The list of domain markers.
*/
public Collection getDomainMarkers(Layer layer) {
return getDomainMarkers(0, layer);
}
/**
* Returns a collection of domain markers for a particular renderer and
* layer.
*
* @param index the renderer index.
* @param layer the layer.
*
* @return A collection of markers (possibly <code>null</code>).
*/
public Collection getDomainMarkers(int index, Layer layer) {
Collection result = null;
Integer key = new Integer(index);
if (layer == Layer.FOREGROUND) {
result = (Collection) this.foregroundDomainMarkers.get(key);
}
else if (layer == Layer.BACKGROUND) {
result = (Collection) this.backgroundDomainMarkers.get(key);
}
if (result != null) {
result = Collections.unmodifiableCollection(result);
}
return result;
}
/**
* Clears all the domain markers for the specified renderer.
*
* @param index the renderer index.
*
* @see #clearRangeMarkers(int)
*/
public void clearDomainMarkers(int index) {
Integer key = new Integer(index);
if (this.backgroundDomainMarkers != null) {
Collection markers
= (Collection) this.backgroundDomainMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
if (this.foregroundDomainMarkers != null) {
Collection markers
= (Collection) this.foregroundDomainMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
fireChangeEvent();
}
/**
* Removes a marker for the domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param marker the marker.
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeDomainMarker(Marker marker) {
return removeDomainMarker(marker, Layer.FOREGROUND);
}
/**
* Removes a marker for the domain axis in the specified layer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeDomainMarker(Marker marker, Layer layer) {
return removeDomainMarker(0, marker, layer);
}
/**
* Removes a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeDomainMarker(int index, Marker marker, Layer layer) {
return removeDomainMarker(index, marker, layer, true);
}
/**
* Removes a marker for a specific dataset/renderer and, if requested,
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.10
*/
public boolean removeDomainMarker(int index, Marker marker, Layer layer,
boolean notify) {
ArrayList markers;
if (layer == Layer.FOREGROUND) {
markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(
index));
}
else {
markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(
index));
}
if (markers == null) {
return false;
}
boolean removed = markers.remove(marker);
if (removed && notify) {
fireChangeEvent();
}
return removed;
}
/**
* Adds a marker for display (in the foreground) against the range axis and
* sends a {@link PlotChangeEvent} to all registered listeners. Typically a
* marker will be drawn by the renderer as a line perpendicular to the
* range axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
*
* @see #removeRangeMarker(Marker)
*/
public void addRangeMarker(Marker marker) {
addRangeMarker(marker, Layer.FOREGROUND);
}
/**
* Adds a marker for display against the range axis and sends a
* {@link PlotChangeEvent} to all registered listeners. Typically a marker
* will be drawn by the renderer as a line perpendicular to the range axis,
* however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background) (<code>null</code>
* not permitted).
*
* @see #removeRangeMarker(Marker, Layer)
*/
public void addRangeMarker(Marker marker, Layer layer) {
addRangeMarker(0, marker, layer);
}
/**
* Adds a marker for display by a particular renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to a range axis, however this is entirely up to the renderer.
*
* @param index the renderer index.
* @param marker the marker.
* @param layer the layer.
*
* @see #removeRangeMarker(int, Marker, Layer)
*/
public void addRangeMarker(int index, Marker marker, Layer layer) {
addRangeMarker(index, marker, layer, true);
}
/**
* Adds a marker for display by a particular renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to a range axis, however this is entirely up to the renderer.
*
* @param index the renderer index.
* @param marker the marker.
* @param layer the layer.
* @param notify notify listeners?
*
* @since 1.0.10
*
* @see #removeRangeMarker(int, Marker, Layer, boolean)
*/
public void addRangeMarker(int index, Marker marker, Layer layer,
boolean notify) {
Collection markers;
if (layer == Layer.FOREGROUND) {
markers = (Collection) this.foregroundRangeMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.foregroundRangeMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
else if (layer == Layer.BACKGROUND) {
markers = (Collection) this.backgroundRangeMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.backgroundRangeMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
marker.addChangeListener(this);
if (notify) {
fireChangeEvent();
}
}
/**
* Clears all the range markers for the plot and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @see #clearDomainMarkers()
*/
public void clearRangeMarkers() {
if (this.backgroundRangeMarkers != null) {
Set keys = this.backgroundRangeMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearRangeMarkers(key.intValue());
}
this.backgroundRangeMarkers.clear();
}
if (this.foregroundRangeMarkers != null) {
Set keys = this.foregroundRangeMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearRangeMarkers(key.intValue());
}
this.foregroundRangeMarkers.clear();
}
fireChangeEvent();
}
/**
* Returns the list of range markers (read only) for the specified layer.
*
* @param layer the layer (foreground or background).
*
* @return The list of range markers.
*
* @see #getRangeMarkers(int, Layer)
*/
public Collection getRangeMarkers(Layer layer) {
return getRangeMarkers(0, layer);
}
/**
* Returns a collection of range markers for a particular renderer and
* layer.
*
* @param index the renderer index.
* @param layer the layer.
*
* @return A collection of markers (possibly <code>null</code>).
*/
public Collection getRangeMarkers(int index, Layer layer) {
Collection result = null;
Integer key = new Integer(index);
if (layer == Layer.FOREGROUND) {
result = (Collection) this.foregroundRangeMarkers.get(key);
}
else if (layer == Layer.BACKGROUND) {
result = (Collection) this.backgroundRangeMarkers.get(key);
}
if (result != null) {
result = Collections.unmodifiableCollection(result);
}
return result;
}
/**
* Clears all the range markers for the specified renderer.
*
* @param index the renderer index.
*
* @see #clearDomainMarkers(int)
*/
public void clearRangeMarkers(int index) {
Integer key = new Integer(index);
if (this.backgroundRangeMarkers != null) {
Collection markers
= (Collection) this.backgroundRangeMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
if (this.foregroundRangeMarkers != null) {
Collection markers
= (Collection) this.foregroundRangeMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
fireChangeEvent();
}
/**
* Removes a marker for the range axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param marker the marker.
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*
* @see #addRangeMarker(Marker)
*/
public boolean removeRangeMarker(Marker marker) {
return removeRangeMarker(marker, Layer.FOREGROUND);
}
/**
* Removes a marker for the range axis in the specified layer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*
* @see #addRangeMarker(Marker, Layer)
*/
public boolean removeRangeMarker(Marker marker, Layer layer) {
return removeRangeMarker(0, marker, layer);
}
/**
* Removes a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*
* @see #addRangeMarker(int, Marker, Layer)
*/
public boolean removeRangeMarker(int index, Marker marker, Layer layer) {
return removeRangeMarker(index, marker, layer, true);
}
/**
* Removes a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
* @param notify notify listeners.
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.10
*
* @see #addRangeMarker(int, Marker, Layer, boolean)
*/
public boolean removeRangeMarker(int index, Marker marker, Layer layer,
boolean notify) {
if (marker == null) {
throw new IllegalArgumentException("Null 'marker' argument.");
}
ArrayList markers;
if (layer == Layer.FOREGROUND) {
markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(
index));
}
else {
markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(
index));
}
if (markers == null) {
return false;
}
boolean removed = markers.remove(marker);
if (removed && notify) {
fireChangeEvent();
}
return removed;
}
/**
* Returns a flag indicating whether or not the range crosshair is visible.
*
* @return The flag.
*
* @see #setRangeCrosshairVisible(boolean)
*/
public boolean isRangeCrosshairVisible() {
return this.rangeCrosshairVisible;
}
/**
* Sets the flag indicating whether or not the range crosshair is visible.
*
* @param flag the new value of the flag.
*
* @see #isRangeCrosshairVisible()
*/
public void setRangeCrosshairVisible(boolean flag) {
if (this.rangeCrosshairVisible != flag) {
this.rangeCrosshairVisible = flag;
fireChangeEvent();
}
}
/**
* Returns a flag indicating whether or not the crosshair should "lock-on"
* to actual data values.
*
* @return The flag.
*
* @see #setRangeCrosshairLockedOnData(boolean)
*/
public boolean isRangeCrosshairLockedOnData() {
return this.rangeCrosshairLockedOnData;
}
/**
* Sets the flag indicating whether or not the range crosshair should
* "lock-on" to actual data values.
*
* @param flag the flag.
*
* @see #isRangeCrosshairLockedOnData()
*/
public void setRangeCrosshairLockedOnData(boolean flag) {
if (this.rangeCrosshairLockedOnData != flag) {
this.rangeCrosshairLockedOnData = flag;
fireChangeEvent();
}
}
/**
* Returns the range crosshair value.
*
* @return The value.
*
* @see #setRangeCrosshairValue(double)
*/
public double getRangeCrosshairValue() {
return this.rangeCrosshairValue;
}
/**
* Sets the domain crosshair value.
* <P>
* Registered listeners are notified that the plot has been modified, but
* only if the crosshair is visible.
*
* @param value the new value.
*
* @see #getRangeCrosshairValue()
*/
public void setRangeCrosshairValue(double value) {
setRangeCrosshairValue(value, true);
}
/**
* Sets the range crosshair value and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners (but only if the
* crosshair is visible).
*
* @param value the new value.
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getRangeCrosshairValue()
*/
public void setRangeCrosshairValue(double value, boolean notify) {
this.rangeCrosshairValue = value;
if (isRangeCrosshairVisible() && notify) {
fireChangeEvent();
}
}
/**
* Returns the pen-style (<code>Stroke</code>) used to draw the crosshair
* (if visible).
*
* @return The crosshair stroke (never <code>null</code>).
*
* @see #setRangeCrosshairStroke(Stroke)
* @see #isRangeCrosshairVisible()
* @see #getRangeCrosshairPaint()
*/
public Stroke getRangeCrosshairStroke() {
return this.rangeCrosshairStroke;
}
/**
* Sets the pen-style (<code>Stroke</code>) used to draw the range
* crosshair (if visible), and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param stroke the new crosshair stroke (<code>null</code> not
* permitted).
*
* @see #getRangeCrosshairStroke()
*/
public void setRangeCrosshairStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.rangeCrosshairStroke = stroke;
fireChangeEvent();
}
/**
* Returns the paint used to draw the range crosshair.
*
* @return The paint (never <code>null</code>).
*
* @see #setRangeCrosshairPaint(Paint)
* @see #isRangeCrosshairVisible()
* @see #getRangeCrosshairStroke()
*/
public Paint getRangeCrosshairPaint() {
return this.rangeCrosshairPaint;
}
/**
* Sets the paint used to draw the range crosshair (if visible) and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeCrosshairPaint()
*/
public void setRangeCrosshairPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeCrosshairPaint = paint;
fireChangeEvent();
}
/**
* Returns the list of annotations.
*
* @return The list of annotations (never <code>null</code>).
*/
public List getAnnotations() {
return this.annotations;
}
/**
* Adds an annotation to the plot and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param annotation the annotation (<code>null</code> not permitted).
*
* @see #removeAnnotation(CategoryAnnotation)
*/
public void addAnnotation(CategoryAnnotation annotation) {
addAnnotation(annotation, true);
}
/**
* Adds an annotation to the plot and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param annotation the annotation (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @since 1.0.10
*/
public void addAnnotation(CategoryAnnotation annotation, boolean notify) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
this.annotations.add(annotation);
if (notify) {
fireChangeEvent();
}
}
/**
* Removes an annotation from the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param annotation the annotation (<code>null</code> not permitted).
*
* @return A boolean (indicates whether or not the annotation was removed).
*
* @see #addAnnotation(CategoryAnnotation)
*/
public boolean removeAnnotation(CategoryAnnotation annotation) {
return removeAnnotation(annotation, true);
}
/**
* Removes an annotation from the plot and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param annotation the annotation (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @return A boolean (indicates whether or not the annotation was removed).
*
* @since 1.0.10
*/
public boolean removeAnnotation(CategoryAnnotation annotation,
boolean notify) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
boolean removed = this.annotations.remove(annotation);
if (removed && notify) {
fireChangeEvent();
}
return removed;
}
/**
* Clears all the annotations and sends a {@link PlotChangeEvent} to all
* registered listeners.
*/
public void clearAnnotations() {
this.annotations.clear();
fireChangeEvent();
}
/**
* Calculates the space required for the domain axis/axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param space a carrier for the result (<code>null</code> permitted).
*
* @return The required space.
*/
protected AxisSpace calculateDomainAxisSpace(Graphics2D g2,
Rectangle2D plotArea,
AxisSpace space) {
if (space == null) {
space = new AxisSpace();
}
// reserve some space for the domain axis...
if (this.fixedDomainAxisSpace != null) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
space.ensureAtLeast(
this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT);
space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),
RectangleEdge.RIGHT);
}
else if (this.orientation == PlotOrientation.VERTICAL) {
space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),
RectangleEdge.TOP);
space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),
RectangleEdge.BOTTOM);
}
}
else {
// reserve space for the primary domain axis...
RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(
getDomainAxisLocation(), this.orientation);
if (this.drawSharedDomainAxis) {
space = getDomainAxis().reserveSpace(g2, this, plotArea,
domainEdge, space);
}
// reserve space for any domain axes...
for (int i = 0; i < this.domainAxes.size(); i++) {
Axis xAxis = (Axis) this.domainAxes.get(i);
if (xAxis != null) {
RectangleEdge edge = getDomainAxisEdge(i);
space = xAxis.reserveSpace(g2, this, plotArea, edge, space);
}
}
}
return space;
}
/**
* Calculates the space required for the range axis/axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param space a carrier for the result (<code>null</code> permitted).
*
* @return The required space.
*/
protected AxisSpace calculateRangeAxisSpace(Graphics2D g2,
Rectangle2D plotArea,
AxisSpace space) {
if (space == null) {
space = new AxisSpace();
}
// reserve some space for the range axis...
if (this.fixedRangeAxisSpace != null) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),
RectangleEdge.TOP);
space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),
RectangleEdge.BOTTOM);
}
else if (this.orientation == PlotOrientation.VERTICAL) {
space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),
RectangleEdge.LEFT);
space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),
RectangleEdge.RIGHT);
}
}
else {
// reserve space for the range axes (if any)...
for (int i = 0; i < this.rangeAxes.size(); i++) {
Axis yAxis = (Axis) this.rangeAxes.get(i);
if (yAxis != null) {
RectangleEdge edge = getRangeAxisEdge(i);
space = yAxis.reserveSpace(g2, this, plotArea, edge, space);
}
}
}
return space;
}
/**
* Calculates the space required for the axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
*
* @return The space required for the axes.
*/
protected AxisSpace calculateAxisSpace(Graphics2D g2,
Rectangle2D plotArea) {
AxisSpace space = new AxisSpace();
space = calculateRangeAxisSpace(g2, plotArea, space);
space = calculateDomainAxisSpace(g2, plotArea, space);
return space;
}
/**
* Draws the plot on a Java 2D graphics device (such as the screen or a
* printer).
* <P>
* At your option, you may supply an instance of {@link PlotRenderingInfo}.
* If you do, it will be populated with information about the drawing,
* including various plot dimensions and tooltip info.
*
* @param g2 the graphics device.
* @param area the area within which the plot (including axes) should
* be drawn.
* @param anchor the anchor point (<code>null</code> permitted).
* @param parentState the state from the parent plot, if there is one.
* @param state collects info as the chart is drawn (possibly
* <code>null</code>).
*/
public void draw(Graphics2D g2, Rectangle2D area,
Point2D anchor,
PlotState parentState,
PlotRenderingInfo state) {
// if the plot area is too small, just return...
boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);
boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);
if (b1 || b2) {
return;
}
// record the plot area...
if (state == null) {
// if the incoming state is null, no information will be passed
// back to the caller - but we create a temporary state to record
// the plot area, since that is used later by the axes
state = new PlotRenderingInfo(null);
}
state.setPlotArea(area);
// adjust the drawing area for the plot insets (if any)...
RectangleInsets insets = getInsets();
insets.trim(area);
// calculate the data area...
AxisSpace space = calculateAxisSpace(g2, area);
Rectangle2D dataArea = space.shrink(area, null);
this.axisOffset.trim(dataArea);
state.setDataArea(dataArea);
// if there is a renderer, it draws the background, otherwise use the
// default background...
if (getRenderer() != null) {
getRenderer().drawBackground(g2, this, dataArea);
}
else {
drawBackground(g2, dataArea);
}
Map axisStateMap = drawAxes(g2, area, dataArea, state);
// don't let anyone draw outside the data area
Shape savedClip = g2.getClip();
g2.clip(dataArea);
drawDomainGridlines(g2, dataArea);
AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());
if (rangeAxisState == null) {
if (parentState != null) {
rangeAxisState = (AxisState) parentState.getSharedAxisStates()
.get(getRangeAxis());
}
}
if (rangeAxisState != null) {
drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());
}
// draw the markers...
for (int i = 0; i < this.renderers.size(); i++) {
drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND);
}
for (int i = 0; i < this.renderers.size(); i++) {
drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND);
}
// now render data items...
boolean foundData = false;
// set up the alpha-transparency...
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, getForegroundAlpha()));
DatasetRenderingOrder order = getDatasetRenderingOrder();
if (order == DatasetRenderingOrder.FORWARD) {
// draw background annotations
int datasetCount = this.datasets.size();
for (int i = 0; i < datasetCount; i++) {
CategoryItemRenderer r = getRenderer(i);
if (r != null) {
CategoryAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.BACKGROUND, state);
}
}
for (int i = 0; i < datasetCount; i++) {
foundData = render(g2, dataArea, i, state) || foundData;
}
// draw foreground annotations
for (int i = 0; i < datasetCount; i++) {
CategoryItemRenderer r = getRenderer(i);
if (r != null) {
CategoryAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.FOREGROUND, state);
}
}
}
else { // DatasetRenderingOrder.REVERSE
// draw background annotations
int datasetCount = this.datasets.size();
for (int i = datasetCount - 1; i >= 0; i
CategoryItemRenderer r = getRenderer(i);
if (r != null) {
CategoryAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.BACKGROUND, state);
}
}
for (int i = this.datasets.size() - 1; i >= 0; i
foundData = render(g2, dataArea, i, state) || foundData;
}
// draw foreground annotations
for (int i = datasetCount - 1; i >= 0; i
CategoryItemRenderer r = getRenderer(i);
if (r != null) {
CategoryAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.FOREGROUND, state);
}
}
}
// draw the foreground markers...
for (int i = 0; i < this.renderers.size(); i++) {
drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);
}
for (int i = 0; i < this.renderers.size(); i++) {
drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);
}
// draw the plot's annotations (if any)...
drawAnnotations(g2, dataArea, state);
g2.setClip(savedClip);
g2.setComposite(originalComposite);
if (!foundData) {
drawNoDataMessage(g2, dataArea);
}
// draw range crosshair if required...
if (isRangeCrosshairVisible()) {
// FIXME: this doesn't handle multiple range axes
drawRangeCrosshair(g2, dataArea, getOrientation(),
getRangeCrosshairValue(), getRangeAxis(),
getRangeCrosshairStroke(), getRangeCrosshairPaint());
}
// draw an outline around the plot area...
if (getRenderer() != null) {
getRenderer().drawOutline(g2, this, dataArea);
}
else {
drawOutline(g2, dataArea);
}
}
/**
* Draws the plot background (the background color and/or image).
* <P>
* This method will be called during the chart drawing process and is
* declared public so that it can be accessed by the renderers used by
* certain subclasses. You shouldn't need to call this method directly.
*
* @param g2 the graphics device.
* @param area the area within which the plot should be drawn.
*/
public void drawBackground(Graphics2D g2, Rectangle2D area) {
fillBackground(g2, area, this.orientation);
drawBackgroundImage(g2, area);
}
/**
* A utility method for drawing the plot's axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param dataArea the data area.
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return A map containing the axis states.
*/
protected Map drawAxes(Graphics2D g2,
Rectangle2D plotArea,
Rectangle2D dataArea,
PlotRenderingInfo plotState) {
AxisCollection axisCollection = new AxisCollection();
// add domain axes to lists...
for (int index = 0; index < this.domainAxes.size(); index++) {
CategoryAxis xAxis = (CategoryAxis) this.domainAxes.get(index);
if (xAxis != null) {
axisCollection.add(xAxis, getDomainAxisEdge(index));
}
}
// add range axes to lists...
for (int index = 0; index < this.rangeAxes.size(); index++) {
ValueAxis yAxis = (ValueAxis) this.rangeAxes.get(index);
if (yAxis != null) {
axisCollection.add(yAxis, getRangeAxisEdge(index));
}
}
Map axisStateMap = new HashMap();
// draw the top axes
double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(
dataArea.getHeight());
Iterator iterator = axisCollection.getAxesAtTop().iterator();
while (iterator.hasNext()) {
Axis axis = (Axis) iterator.next();
if (axis != null) {
AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.TOP, plotState);
cursor = axisState.getCursor();
axisStateMap.put(axis, axisState);
}
}
// draw the bottom axes
cursor = dataArea.getMaxY()
+ this.axisOffset.calculateBottomOutset(dataArea.getHeight());
iterator = axisCollection.getAxesAtBottom().iterator();
while (iterator.hasNext()) {
Axis axis = (Axis) iterator.next();
if (axis != null) {
AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.BOTTOM, plotState);
cursor = axisState.getCursor();
axisStateMap.put(axis, axisState);
}
}
// draw the left axes
cursor = dataArea.getMinX()
- this.axisOffset.calculateLeftOutset(dataArea.getWidth());
iterator = axisCollection.getAxesAtLeft().iterator();
while (iterator.hasNext()) {
Axis axis = (Axis) iterator.next();
if (axis != null) {
AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.LEFT, plotState);
cursor = axisState.getCursor();
axisStateMap.put(axis, axisState);
}
}
// draw the right axes
cursor = dataArea.getMaxX()
+ this.axisOffset.calculateRightOutset(dataArea.getWidth());
iterator = axisCollection.getAxesAtRight().iterator();
while (iterator.hasNext()) {
Axis axis = (Axis) iterator.next();
if (axis != null) {
AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.RIGHT, plotState);
cursor = axisState.getCursor();
axisStateMap.put(axis, axisState);
}
}
return axisStateMap;
}
/**
* Draws a representation of a dataset within the dataArea region using the
* appropriate renderer.
*
* @param g2 the graphics device.
* @param dataArea the region in which the data is to be drawn.
* @param index the dataset and renderer index.
* @param info an optional object for collection dimension information.
*
* @return A boolean that indicates whether or not real data was found.
*/
public boolean render(Graphics2D g2, Rectangle2D dataArea, int index,
PlotRenderingInfo info) {
boolean foundData = false;
CategoryDataset currentDataset = getDataset(index);
CategoryItemRenderer renderer = getRenderer(index);
CategoryAxis domainAxis = getDomainAxisForDataset(index);
ValueAxis rangeAxis = getRangeAxisForDataset(index);
boolean hasData = !DatasetUtilities.isEmptyOrNull(currentDataset);
if (hasData && renderer != null) {
foundData = true;
CategoryItemRendererState state = renderer.initialise(g2, dataArea,
this, index, info);
int columnCount = currentDataset.getColumnCount();
int rowCount = currentDataset.getRowCount();
int passCount = renderer.getPassCount();
for (int pass = 0; pass < passCount; pass++) {
if (this.columnRenderingOrder == SortOrder.ASCENDING) {
for (int column = 0; column < columnCount; column++) {
if (this.rowRenderingOrder == SortOrder.ASCENDING) {
for (int row = 0; row < rowCount; row++) {
renderer.drawItem(g2, state, dataArea, this,
domainAxis, rangeAxis, currentDataset,
row, column, pass);
}
}
else {
for (int row = rowCount - 1; row >= 0; row
renderer.drawItem(g2, state, dataArea, this,
domainAxis, rangeAxis, currentDataset,
row, column, pass);
}
}
}
}
else {
for (int column = columnCount - 1; column >= 0; column
if (this.rowRenderingOrder == SortOrder.ASCENDING) {
for (int row = 0; row < rowCount; row++) {
renderer.drawItem(g2, state, dataArea, this,
domainAxis, rangeAxis, currentDataset,
row, column, pass);
}
}
else {
for (int row = rowCount - 1; row >= 0; row
renderer.drawItem(g2, state, dataArea, this,
domainAxis, rangeAxis, currentDataset,
row, column, pass);
}
}
}
}
}
}
return foundData;
}
/**
* Draws the gridlines for the plot.
*
* @param g2 the graphics device.
* @param dataArea the area inside the axes.
*
* @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)
*/
protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea) {
// draw the domain grid lines, if any...
if (isDomainGridlinesVisible()) {
CategoryAnchor anchor = getDomainGridlinePosition();
RectangleEdge domainAxisEdge = getDomainAxisEdge();
Stroke gridStroke = getDomainGridlineStroke();
Paint gridPaint = getDomainGridlinePaint();
if ((gridStroke != null) && (gridPaint != null)) {
// iterate over the categories
CategoryDataset data = getDataset();
if (data != null) {
CategoryAxis axis = getDomainAxis();
if (axis != null) {
int columnCount = data.getColumnCount();
for (int c = 0; c < columnCount; c++) {
double xx = axis.getCategoryJava2DCoordinate(
anchor, c, columnCount, dataArea,
domainAxisEdge);
CategoryItemRenderer renderer1 = getRenderer();
if (renderer1 != null) {
renderer1.drawDomainGridline(g2, this,
dataArea, xx);
}
}
}
}
}
}
}
/**
* Draws the gridlines for the plot.
*
* @param g2 the graphics device.
* @param dataArea the area inside the axes.
* @param ticks the ticks.
*
* @see #drawDomainGridlines(Graphics2D, Rectangle2D)
*/
protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea,
List ticks) {
// draw the range grid lines, if any...
if (isRangeGridlinesVisible()) {
Stroke gridStroke = getRangeGridlineStroke();
Paint gridPaint = getRangeGridlinePaint();
if ((gridStroke != null) && (gridPaint != null)) {
ValueAxis axis = getRangeAxis();
if (axis != null) {
Iterator iterator = ticks.iterator();
while (iterator.hasNext()) {
ValueTick tick = (ValueTick) iterator.next();
CategoryItemRenderer renderer1 = getRenderer();
if (renderer1 != null) {
renderer1.drawRangeGridline(g2, this,
getRangeAxis(), dataArea, tick.getValue());
}
}
}
}
}
}
/**
* Draws the annotations.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param info the plot rendering info (<code>null</code> permitted).
*/
protected void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,
PlotRenderingInfo info) {
Iterator iterator = getAnnotations().iterator();
while (iterator.hasNext()) {
CategoryAnnotation annotation
= (CategoryAnnotation) iterator.next();
annotation.draw(g2, this, dataArea, getDomainAxis(),
getRangeAxis(), 0, info);
}
}
/**
* Draws the domain markers (if any) for an axis and layer. This method is
* typically called from within the draw() method.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param index the renderer index.
* @param layer the layer (foreground or background).
*
* @see #drawRangeMarkers(Graphics2D, Rectangle2D, int, Layer)
*/
protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,
int index, Layer layer) {
CategoryItemRenderer r = getRenderer(index);
if (r == null) {
return;
}
Collection markers = getDomainMarkers(index, layer);
CategoryAxis axis = getDomainAxisForDataset(index);
if (markers != null && axis != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
CategoryMarker marker = (CategoryMarker) iterator.next();
r.drawDomainMarker(g2, this, axis, marker, dataArea);
}
}
}
/**
* Draws the range markers (if any) for an axis and layer. This method is
* typically called from within the draw() method.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param index the renderer index.
* @param layer the layer (foreground or background).
*
* @see #drawDomainMarkers(Graphics2D, Rectangle2D, int, Layer)
*/
protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,
int index, Layer layer) {
CategoryItemRenderer r = getRenderer(index);
if (r == null) {
return;
}
Collection markers = getRangeMarkers(index, layer);
ValueAxis axis = getRangeAxisForDataset(index);
if (markers != null && axis != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker marker = (Marker) iterator.next();
r.drawRangeMarker(g2, this, axis, marker, dataArea);
}
}
}
/**
* Utility method for drawing a line perpendicular to the range axis (used
* for crosshairs).
*
* @param g2 the graphics device.
* @param dataArea the area defined by the axes.
* @param value the data value.
* @param stroke the line stroke (<code>null</code> not permitted).
* @param paint the line paint (<code>null</code> not permitted).
*/
protected void drawRangeLine(Graphics2D g2, Rectangle2D dataArea,
double value, Stroke stroke, Paint paint) {
double java2D = getRangeAxis().valueToJava2D(value, dataArea,
getRangeAxisEdge());
Line2D line = null;
if (this.orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(java2D, dataArea.getMinY(), java2D,
dataArea.getMaxY());
}
else if (this.orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(dataArea.getMinX(), java2D,
dataArea.getMaxX(), java2D);
}
g2.setStroke(stroke);
g2.setPaint(paint);
g2.draw(line);
}
/**
* Draws a range crosshair.
*
* @param g2 the graphics target.
* @param dataArea the data area.
* @param orientation the plot orientation.
* @param value the crosshair value.
* @param axis the axis against which the value is measured.
* @param stroke the stroke used to draw the crosshair line.
* @param paint the paint used to draw the crosshair line.
*
* @since 1.0.5
*/
protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,
PlotOrientation orientation, double value, ValueAxis axis,
Stroke stroke, Paint paint) {
if (!axis.getRange().contains(value)) {
return;
}
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
double xx = axis.valueToJava2D(value, dataArea,
RectangleEdge.BOTTOM);
line = new Line2D.Double(xx, dataArea.getMinY(), xx,
dataArea.getMaxY());
}
else {
double yy = axis.valueToJava2D(value, dataArea,
RectangleEdge.LEFT);
line = new Line2D.Double(dataArea.getMinX(), yy,
dataArea.getMaxX(), yy);
}
g2.setStroke(stroke);
g2.setPaint(paint);
g2.draw(line);
}
/**
* Returns the range of data values that will be plotted against the range
* axis. If the dataset is <code>null</code>, this method returns
* <code>null</code>.
*
* @param axis the axis.
*
* @return The data range.
*/
public Range getDataRange(ValueAxis axis) {
Range result = null;
List mappedDatasets = new ArrayList();
int rangeIndex = this.rangeAxes.indexOf(axis);
if (rangeIndex >= 0) {
mappedDatasets.addAll(datasetsMappedToRangeAxis(rangeIndex));
}
else if (axis == getRangeAxis()) {
mappedDatasets.addAll(datasetsMappedToRangeAxis(0));
}
// iterate through the datasets that map to the axis and get the union
// of the ranges.
Iterator iterator = mappedDatasets.iterator();
while (iterator.hasNext()) {
CategoryDataset d = (CategoryDataset) iterator.next();
CategoryItemRenderer r = getRendererForDataset(d);
if (r != null) {
result = Range.combine(result, r.findRangeBounds(d));
}
}
return result;
}
/**
* Returns a list of the datasets that are mapped to the axis with the
* specified index.
*
* @param axisIndex the axis index.
*
* @return The list (possibly empty, but never <code>null</code>).
*
* @since 1.0.3
*/
private List datasetsMappedToDomainAxis(int axisIndex) {
List result = new ArrayList();
for (int datasetIndex = 0; datasetIndex < this.datasets.size();
datasetIndex++) {
Object dataset = this.datasets.get(datasetIndex);
if (dataset != null) {
Integer m = (Integer) this.datasetToDomainAxisMap.get(
datasetIndex);
if (m == null) { // a dataset with no mapping is assigned to
// axis 0
if (axisIndex == 0) {
result.add(dataset);
}
}
else {
if (m.intValue() == axisIndex) {
result.add(dataset);
}
}
}
}
return result;
}
/**
* A utility method that returns a list of datasets that are mapped to a
* given range axis.
*
* @param index the axis index.
*
* @return A list of datasets.
*/
private List datasetsMappedToRangeAxis(int index) {
List result = new ArrayList();
for (int i = 0; i < this.datasets.size(); i++) {
Object dataset = this.datasets.get(i);
if (dataset != null) {
Integer m = (Integer) this.datasetToRangeAxisMap.get(i);
if (m == null) { // a dataset with no mapping is assigned to
// axis 0
if (index == 0) {
result.add(dataset);
}
}
else {
if (m.intValue() == index) {
result.add(dataset);
}
}
}
}
return result;
}
/**
* Returns the weight for this plot when it is used as a subplot within a
* combined plot.
*
* @return The weight.
*
* @see #setWeight(int)
*/
public int getWeight() {
return this.weight;
}
/**
* Sets the weight for the plot and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param weight the weight.
*
* @see #getWeight()
*/
public void setWeight(int weight) {
this.weight = weight;
fireChangeEvent();
}
/**
* Returns the fixed domain axis space.
*
* @return The fixed domain axis space (possibly <code>null</code>).
*
* @see #setFixedDomainAxisSpace(AxisSpace)
*/
public AxisSpace getFixedDomainAxisSpace() {
return this.fixedDomainAxisSpace;
}
/**
* Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param space the space (<code>null</code> permitted).
*
* @see #getFixedDomainAxisSpace()
*/
public void setFixedDomainAxisSpace(AxisSpace space) {
setFixedDomainAxisSpace(space, true);
}
/**
* Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param space the space (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getFixedDomainAxisSpace()
*
* @since 1.0.7
*/
public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) {
this.fixedDomainAxisSpace = space;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns the fixed range axis space.
*
* @return The fixed range axis space (possibly <code>null</code>).
*
* @see #setFixedRangeAxisSpace(AxisSpace)
*/
public AxisSpace getFixedRangeAxisSpace() {
return this.fixedRangeAxisSpace;
}
/**
* Sets the fixed range axis space and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param space the space (<code>null</code> permitted).
*
* @see #getFixedRangeAxisSpace()
*/
public void setFixedRangeAxisSpace(AxisSpace space) {
setFixedRangeAxisSpace(space, true);
}
/**
* Sets the fixed range axis space and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param space the space (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getFixedRangeAxisSpace()
*
* @since 1.0.7
*/
public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) {
this.fixedRangeAxisSpace = space;
if (notify) {
fireChangeEvent();
}
}
/**
* Returns a list of the categories in the plot's primary dataset.
*
* @return A list of the categories in the plot's primary dataset.
*
* @see #getCategoriesForAxis(CategoryAxis)
*/
public List getCategories() {
List result = null;
if (getDataset() != null) {
result = Collections.unmodifiableList(getDataset().getColumnKeys());
}
return result;
}
/**
* Returns a list of the categories that should be displayed for the
* specified axis.
*
* @param axis the axis (<code>null</code> not permitted)
*
* @return The categories.
*
* @since 1.0.3
*/
public List getCategoriesForAxis(CategoryAxis axis) {
List result = new ArrayList();
int axisIndex = this.domainAxes.indexOf(axis);
List datasets = datasetsMappedToDomainAxis(axisIndex);
Iterator iterator = datasets.iterator();
while (iterator.hasNext()) {
CategoryDataset dataset = (CategoryDataset) iterator.next();
// add the unique categories from this dataset
for (int i = 0; i < dataset.getColumnCount(); i++) {
Comparable category = dataset.getColumnKey(i);
if (!result.contains(category)) {
result.add(category);
}
}
}
return result;
}
/**
* Returns the flag that controls whether or not the shared domain axis is
* drawn for each subplot.
*
* @return A boolean.
*
* @see #setDrawSharedDomainAxis(boolean)
*/
public boolean getDrawSharedDomainAxis() {
return this.drawSharedDomainAxis;
}
/**
* Sets the flag that controls whether the shared domain axis is drawn when
* this plot is being used as a subplot.
*
* @param draw a boolean.
*
* @see #getDrawSharedDomainAxis()
*/
public void setDrawSharedDomainAxis(boolean draw) {
this.drawSharedDomainAxis = draw;
fireChangeEvent();
}
/**
* Returns <code>false</code> to indicate that the domain axes are not
* zoomable.
*
* @return A boolean.
*
* @see #isRangeZoomable()
*/
public boolean isDomainZoomable() {
return false;
}
/**
* Returns <code>true</code> to indicate that the range axes are zoomable.
*
* @return A boolean.
*
* @see #isDomainZoomable()
*/
public boolean isRangeZoomable() {
return true;
}
/**
* This method does nothing, because <code>CategoryPlot</code> doesn't
* support zooming on the domain.
*
* @param factor the zoom factor.
* @param state the plot state.
* @param source the source point (in Java2D space) for the zoom.
*/
public void zoomDomainAxes(double factor, PlotRenderingInfo state,
Point2D source) {
// can't zoom domain axis
}
/**
* This method does nothing, because <code>CategoryPlot</code> doesn't
* support zooming on the domain.
*
* @param lowerPercent the lower bound.
* @param upperPercent the upper bound.
* @param state the plot state.
* @param source the source point (in Java2D space) for the zoom.
*/
public void zoomDomainAxes(double lowerPercent, double upperPercent,
PlotRenderingInfo state, Point2D source) {
// can't zoom domain axis
}
/**
* This method does nothing, because <code>CategoryPlot</code> doesn't
* support zooming on the domain.
*
* @param factor the zoom factor.
* @param info the plot rendering info.
* @param source the source point (in Java2D space).
* @param useAnchor use source point as zoom anchor?
*
* @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)
*
* @since 1.0.7
*/
public void zoomDomainAxes(double factor, PlotRenderingInfo info,
Point2D source, boolean useAnchor) {
// can't zoom domain axis
}
/**
* Multiplies the range on the range axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param state the plot state.
* @param source the source point (in Java2D space) for the zoom.
*/
public void zoomRangeAxes(double factor, PlotRenderingInfo state,
Point2D source) {
// delegate to other method
zoomRangeAxes(factor, state, source, false);
}
/**
* Multiplies the range on the range axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info.
* @param source the source point.
* @param useAnchor a flag that controls whether or not the source point
* is used for the zoom anchor.
*
* @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)
*
* @since 1.0.7
*/
public void zoomRangeAxes(double factor, PlotRenderingInfo info,
Point2D source, boolean useAnchor) {
// perform the zoom on each range axis
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis rangeAxis = (ValueAxis) this.rangeAxes.get(i);
if (rangeAxis != null) {
if (useAnchor) {
// get the relevant source coordinate given the plot
// orientation
double sourceY = source.getY();
if (this.orientation == PlotOrientation.HORIZONTAL) {
sourceY = source.getX();
}
double anchorY = rangeAxis.java2DToValue(sourceY,
info.getDataArea(), getRangeAxisEdge());
rangeAxis.resizeRange(factor, anchorY);
}
else {
rangeAxis.resizeRange(factor);
}
}
}
}
/**
* Zooms in on the range axes.
*
* @param lowerPercent the lower bound.
* @param upperPercent the upper bound.
* @param state the plot state.
* @param source the source point (in Java2D space) for the zoom.
*/
public void zoomRangeAxes(double lowerPercent, double upperPercent,
PlotRenderingInfo state, Point2D source) {
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis rangeAxis = (ValueAxis) this.rangeAxes.get(i);
if (rangeAxis != null) {
rangeAxis.zoomRange(lowerPercent, upperPercent);
}
}
}
/**
* Returns the anchor value.
*
* @return The anchor value.
*
* @see #setAnchorValue(double)
*/
public double getAnchorValue() {
return this.anchorValue;
}
/**
* Sets the anchor value and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param value the anchor value.
*
* @see #getAnchorValue()
*/
public void setAnchorValue(double value) {
setAnchorValue(value, true);
}
/**
* Sets the anchor value and, if requested, sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param value the value.
* @param notify notify listeners?
*
* @see #getAnchorValue()
*/
public void setAnchorValue(double value, boolean notify) {
this.anchorValue = value;
if (notify) {
fireChangeEvent();
}
}
/**
* Tests the plot for equality with an arbitrary object.
*
* @param obj the object to test against (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CategoryPlot)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
CategoryPlot that = (CategoryPlot) obj;
if (this.orientation != that.orientation) {
return false;
}
if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {
return false;
}
if (!this.domainAxes.equals(that.domainAxes)) {
return false;
}
if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {
return false;
}
if (this.drawSharedDomainAxis != that.drawSharedDomainAxis) {
return false;
}
if (!this.rangeAxes.equals(that.rangeAxes)) {
return false;
}
if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {
return false;
}
if (!ObjectUtilities.equal(this.datasetToDomainAxisMap,
that.datasetToDomainAxisMap)) {
return false;
}
if (!ObjectUtilities.equal(this.datasetToRangeAxisMap,
that.datasetToRangeAxisMap)) {
return false;
}
if (!ObjectUtilities.equal(this.renderers, that.renderers)) {
return false;
}
if (this.renderingOrder != that.renderingOrder) {
return false;
}
if (this.columnRenderingOrder != that.columnRenderingOrder) {
return false;
}
if (this.rowRenderingOrder != that.rowRenderingOrder) {
return false;
}
if (this.domainGridlinesVisible != that.domainGridlinesVisible) {
return false;
}
if (this.domainGridlinePosition != that.domainGridlinePosition) {
return false;
}
if (!ObjectUtilities.equal(this.domainGridlineStroke,
that.domainGridlineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.domainGridlinePaint,
that.domainGridlinePaint)) {
return false;
}
if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {
return false;
}
if (!ObjectUtilities.equal(this.rangeGridlineStroke,
that.rangeGridlineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.rangeGridlinePaint,
that.rangeGridlinePaint)) {
return false;
}
if (this.anchorValue != that.anchorValue) {
return false;
}
if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {
return false;
}
if (this.rangeCrosshairValue != that.rangeCrosshairValue) {
return false;
}
if (!ObjectUtilities.equal(this.rangeCrosshairStroke,
that.rangeCrosshairStroke)) {
return false;
}
if (!PaintUtilities.equal(this.rangeCrosshairPaint,
that.rangeCrosshairPaint)) {
return false;
}
if (this.rangeCrosshairLockedOnData
!= that.rangeCrosshairLockedOnData) {
return false;
}
if (!ObjectUtilities.equal(this.foregroundRangeMarkers,
that.foregroundRangeMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundRangeMarkers,
that.backgroundRangeMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.annotations, that.annotations)) {
return false;
}
if (this.weight != that.weight) {
return false;
}
if (!ObjectUtilities.equal(this.fixedDomainAxisSpace,
that.fixedDomainAxisSpace)) {
return false;
}
if (!ObjectUtilities.equal(this.fixedRangeAxisSpace,
that.fixedRangeAxisSpace)) {
return false;
}
return true;
}
/**
* Returns a clone of the plot.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the cloning is not supported.
*/
public Object clone() throws CloneNotSupportedException {
CategoryPlot clone = (CategoryPlot) super.clone();
clone.domainAxes = new ObjectList();
for (int i = 0; i < this.domainAxes.size(); i++) {
CategoryAxis xAxis = (CategoryAxis) this.domainAxes.get(i);
if (xAxis != null) {
CategoryAxis clonedAxis = (CategoryAxis) xAxis.clone();
clone.setDomainAxis(i, clonedAxis);
}
}
clone.domainAxisLocations
= (ObjectList) this.domainAxisLocations.clone();
clone.rangeAxes = new ObjectList();
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis yAxis = (ValueAxis) this.rangeAxes.get(i);
if (yAxis != null) {
ValueAxis clonedAxis = (ValueAxis) yAxis.clone();
clone.setRangeAxis(i, clonedAxis);
}
}
clone.rangeAxisLocations = (ObjectList) this.rangeAxisLocations.clone();
clone.datasets = (ObjectList) this.datasets.clone();
for (int i = 0; i < clone.datasets.size(); i++) {
CategoryDataset dataset = clone.getDataset(i);
if (dataset != null) {
dataset.addChangeListener(clone);
}
}
clone.datasetToDomainAxisMap
= (ObjectList) this.datasetToDomainAxisMap.clone();
clone.datasetToRangeAxisMap
= (ObjectList) this.datasetToRangeAxisMap.clone();
clone.renderers = (ObjectList) this.renderers.clone();
if (this.fixedDomainAxisSpace != null) {
clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(
this.fixedDomainAxisSpace);
}
if (this.fixedRangeAxisSpace != null) {
clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(
this.fixedRangeAxisSpace);
}
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeStroke(this.domainGridlineStroke, stream);
SerialUtilities.writePaint(this.domainGridlinePaint, stream);
SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);
SerialUtilities.writePaint(this.rangeGridlinePaint, stream);
SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);
SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.domainGridlineStroke = SerialUtilities.readStroke(stream);
this.domainGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeGridlineStroke = SerialUtilities.readStroke(stream);
this.rangeGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);
this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);
for (int i = 0; i < this.domainAxes.size(); i++) {
CategoryAxis xAxis = (CategoryAxis) this.domainAxes.get(i);
if (xAxis != null) {
xAxis.setPlot(this);
xAxis.addChangeListener(this);
}
}
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis yAxis = (ValueAxis) this.rangeAxes.get(i);
if (yAxis != null) {
yAxis.setPlot(this);
yAxis.addChangeListener(this);
}
}
int datasetCount = this.datasets.size();
for (int i = 0; i < datasetCount; i++) {
Dataset dataset = (Dataset) this.datasets.get(i);
if (dataset != null) {
dataset.addChangeListener(this);
}
}
int rendererCount = this.renderers.size();
for (int i = 0; i < rendererCount; i++) {
CategoryItemRenderer renderer
= (CategoryItemRenderer) this.renderers.get(i);
if (renderer != null) {
renderer.addChangeListener(this);
}
}
}
} |
package com.akjava.gwt.markdowneditor.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.akjava.gwt.lib.client.GWTHTMLUtils;
import com.akjava.gwt.lib.client.LogUtils;
import com.akjava.gwt.lib.client.StorageControler;
import com.akjava.gwt.lib.client.StorageException;
import com.akjava.gwt.lib.client.TextSelection;
import com.akjava.gwt.lib.client.widget.TabInputableTextArea;
import com.akjava.lib.common.functions.StringFunctions;
import com.akjava.lib.common.predicates.StringPredicates;
import com.akjava.lib.common.tag.Tag;
import com.akjava.lib.common.utils.CSVUtils;
import com.akjava.lib.common.utils.ValuesUtils;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
public class MarkdownEditor extends SplitLayoutPanel {
public static final String KEY_SESSION="markdowneditor_session_value";//for session storage
public static final String KEY_LAST_SESSION_ID="markdowneditor_session_last_session_id";
//private static final String KEY_MARKDOWNEDITOR = "KEY_MARKDOWN_EDITOR";
private TextArea textArea;
public TextArea getTextArea() {
return textArea;
}
private CheckBox autoConvertCheck;
private HTML previewHTML;
private TextArea htmlArea;
public TextArea getHtmlArea() {
return htmlArea;
}
private ListBox titleLevelBox;
private StorageControler storageControler=new StorageControler(false);//use session
private ListBox imageListBox;
private Optional<String> syncHtmlKey=Optional.absent();
private Optional<String> syncTextKey=Optional.absent();
private TabLayoutPanel rightTabPanel;
private VerticalPanel previewPanel;
public void setSyncHtmlKey(Optional<String> syncHtmlKey) {
this.syncHtmlKey = syncHtmlKey;
}
public void setSyncTextKey(Optional<String> syncTextKey) {
this.syncTextKey = syncTextKey;
}
public MarkdownEditor(){
this(false,"","");
}
/**
*
* @param readOnly
* @param session_id
* @param defaultValue
*
* HTML integration
* @see GWTMarkdownEditor
*/
public MarkdownEditor(boolean readOnly,String session_id,String defaultValue){
createLeftPanels();
createRightPanels();
/**
* what is doing?
* try to keep value when browser back
*
* session_id is usually get from html hidden-input.
* get KEY_LAST_SESSION_ID from storage.
*
* if these are equals,it's same session and action ;get value from storage.
* last edited text always store in storage.
*
* session_id is created when edit or add button clicked manually
*
*/
if(!session_id.isEmpty()){
try {
String lastSessionId = storageControler.getValue(KEY_LAST_SESSION_ID, "");
GWT.log("gwtwiki:lastSessionId="+lastSessionId+",session_id="+session_id);
if(!session_id.equals(lastSessionId)){
//new situation
GWT.log("gwtwiki:different session id,get initial value from PEOPERTY_DEFAULT_ID");
//String data=ValueUtils.getFormValueById(PEOPERTY_DEFAULT_ID, "");
textArea.setText(defaultValue);
storageControler.setValue(KEY_SESSION,defaultValue);
storageControler.setValue(KEY_LAST_SESSION_ID, session_id);//mark used
}else{
GWT.log("gwtwiki:use last modified value");
String lastModified=storageControler.getValue(KEY_SESSION, "");
textArea.setText(lastModified);
}
} catch (StorageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
GWT.log("gwtwiki:no session id,get initial value from PEOPERTY_DEFAULT_ID");
//String data=ValueUtils.getFormValueById(PEOPERTY_DEFAULT_ID, "");
textArea.setText(defaultValue);
}
if(readOnly){
textArea.setReadOnly(readOnly);
}
doConvert();
}
public void setTotalHeightPX(int px){
this.setHeight(px+"px");
rightTabPanel.setHeight(px+"px");
// previewPanel.setHeight(px+"px");
// htmlArea.setHeight(px+"px");
textArea.setHeight((px-80)+"px");
}
private void createRightPanels() {
DockLayoutPanel rightPanel=new DockLayoutPanel(Unit.PX);
rightPanel.setSize("100%", "100%");
this.add(rightPanel);
createOptionArea(rightPanel);
rightTabPanel = new TabLayoutPanel(40,Unit.PX);
rightPanel.add(rightTabPanel);
rightTabPanel.setSize("100%","100%");
createPreviewArea(rightTabPanel);
createHtmlArea(rightTabPanel);
rightTabPanel.selectTab(0);
}
public TabLayoutPanel getRightTabPanel(){
return rightTabPanel;
}
private void createPreviewArea(TabLayoutPanel tab) {
previewPanel = new VerticalPanel();//really need?
previewPanel.setSize("100%","100%");
ScrollPanel scroll=new ScrollPanel();
scroll.setWidth("100%");
previewPanel.add(scroll);
scroll.setHeight("100%");
previewHTML = new HTML();
scroll.setWidget(previewHTML);
tab.add(previewPanel,"Preview");
}
private void createHtmlArea(TabLayoutPanel tab) {
VerticalPanel container=new VerticalPanel();
container.setSize("100%", "100%");
htmlArea = new TextArea();
htmlArea.setWidth("95%");
htmlArea.setHeight("100%");
container.add(htmlArea);
tab.add(container,"HTML");
}
private void createLeftPanels() {
DockLayoutPanel leftPanel=new DockLayoutPanel(Unit.PX);
leftPanel.setSize("100%", "100%");
this.addWest(leftPanel,560);
createToolbars(leftPanel);
createTextAreas(leftPanel);
}
private void createOptionArea(DockLayoutPanel parent) {
HorizontalPanel panel=new HorizontalPanel();
parent.addNorth(panel,40);
Button bt=new Button("Convert");
bt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
doConvert();
}
});
panel.add(bt);
autoConvertCheck = new CheckBox("auto");
autoConvertCheck.setValue(true);
panel.add(autoConvertCheck);
}
private void createTextAreas(Panel parent) {
//VerticalPanel textAreaBase=new VerticalPanel();
//textAreaBase.setSize("100%", "100%");
//parent.add(textAreaBase);
//textAreaBase.setBorderWidth(3);
textArea = new TabInputableTextArea();
parent.add(textArea);
//textArea.setText(storageControler.getValue(KEY_MARKDOWNEDITOR, ""));
textArea.setStylePrimaryName("textbg");
textArea.setWidth("98%");
textArea.setHeight("98%");
textArea.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if(event.getNativeKeyCode()==KeyCodes.KEY_ENTER){
onTextAreaUpdate();
}
else if(event.isControlKeyDown()){//copy or paste
onTextAreaUpdate();
}
else{
onTextAreaUpdate();
}
}
});
/*
* these called when focus out
textArea.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
LogUtils.log("value-changed");
}
});
textArea.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
LogUtils.log("changed");
}
});
*/
}
private void createToolbars(DockLayoutPanel parent) {
VerticalPanel panels=new VerticalPanel();
//panels.setHeight("100px");
parent.addNorth(panels,60);
HorizontalPanel button1Panel=new HorizontalPanel();
panels.add(button1Panel);
HorizontalPanel button2Panel=new HorizontalPanel();
panels.add(button2Panel);
titleLevelBox = new ListBox();
titleLevelBox.addItem("Clear");
titleLevelBox.addItem("Head 1");
titleLevelBox.addItem("Head 2");
titleLevelBox.addItem("Head 3");
titleLevelBox.addItem("Head 4");
titleLevelBox.addItem("Head 5");
titleLevelBox.addItem("Head 6");
titleLevelBox.addItem("<HEAD>");
titleLevelBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int index=titleLevelBox.getSelectedIndex();
if(index>6){
index=0;
}
titleSelected(index);
}
});
titleLevelBox.setTitle("convert pointed line to title");
titleLevelBox.setSelectedIndex(7);//default empty
button2Panel.add(titleLevelBox);
Button boldBt=new Button("Bold",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
insertBetweenSelectionText(selection,"**","**");
onTextAreaUpdate();
}
}
});
button1Panel.add(boldBt);
Button ItalicBt=new Button("Italic",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
insertBetweenSelectionText(selection,"*","*");
onTextAreaUpdate();
}
}
});
button1Panel.add(ItalicBt);
Button strikeBt=new Button("Strike",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
insertBetweenSelectionText(selection,"~~","~~");
onTextAreaUpdate();
}
}
});
strikeBt.setTitle("insert strike");
button1Panel.add(strikeBt);
Button codeBt=new Button("Code",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
if(selection.containLineBreak()){
insertBetweenSelectionText(selection,"```\n","\n```");
}else{
insertBetweenSelectionText(selection,"`","`");
}
onTextAreaUpdate();
}
}
});
codeBt.setTitle("insert code");
button1Panel.add(codeBt);
Button blockBt=new Button("Block",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
insertBetweenSelectionText(selection.getCurrentLine(),">","");
onTextAreaUpdate();
}
}
});
blockBt.setTitle("Add a Blockquote");
button1Panel.add(blockBt);
Button lineBt=new Button("Line",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
insertBetweenSelectionText(selection.getCurrentLine(),"********\n","");
onTextAreaUpdate();
}
}
});
lineBt.setTitle("Insert a Line");
button1Panel.add(lineBt);
Button LinkBt=new Button("URL",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
String url=Window.prompt("Link URL", "http:
if(url==null){//cancel
return;
}
String newText="["+selected+"]"+"("+url+")";
selection.replace(newText);
onTextAreaUpdate();
}
}
});
LinkBt.setTitle("Insert a URL");
button1Panel.add(LinkBt);
Button alinkBt=new Button("Alink",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
String url=Window.prompt("Link URL", "http:
if(url==null){//cancel
return;
}
String newText="<a href='"+url+"'>"+selected+"</a>";
selection.replace(newText);
onTextAreaUpdate();
}
}
});
alinkBt.setTitle("Insert a URL with alink");
button1Panel.add(alinkBt);
Button ImageBt=new Button("Image",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
String url=Window.prompt("Image URL", "");
if(url==null){//cancel
return;
}
String newText="!["+selected+"]"+"("+url+")";
selection.replace(newText);
onTextAreaUpdate();
}
}
});
ImageBt.setTitle("Insert a Image");
button1Panel.add(ImageBt);
Button ListBt=new Button("List",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
List<String> converted=FluentIterable
.from(Arrays.asList(selected.split("\n")))
.filter(StringPredicates.getNotEmpty())
.transform(new StringFunctions.StringToPreFixAndSuffix("- ",""))
.toList();
selection.replace(Joiner.on("\n").join(converted));
onTextAreaUpdate();
}
}
});
ListBt.setTitle("Convert to List");
button1Panel.add(ListBt);
Button tableBt=new Button("Tab2Table",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
List<List<String>> csvs=CSVUtils.csvToListList(selected, true, false);
Joiner tableJoiner=Joiner.on("|");
List<String> converted=new ArrayList<String>();
for(int i=0;i<csvs.size();i++){
List<String> csv=csvs.get(i);
converted.add(tableJoiner.join(csv));
if(i==0){//header need line
List<String> lines=new ArrayList<String>();
for(int j=0;j<csv.size();j++){
lines.add("
}
converted.add(tableJoiner.join(lines));
}
}
selection.replace(Joiner.on("\n").join(converted));
onTextAreaUpdate();
}
}
});
tableBt.setTitle("Convert Tab to table");
button2Panel.add(tableBt);
Button t2tableBt=new Button("Tab2Head",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
List<String> converted=FluentIterable
.from(Arrays.asList(selected.split("\n")))
.transform(new TabTitleFunction())
.toList();
selection.replace(Joiner.on("\n").join(converted));
onTextAreaUpdate();
}
}
});
t2tableBt.setTitle("Convert tab tree to Title");
button2Panel.add(t2tableBt);
Button tab2listBt=new Button("Tab2List",new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for(TextSelection selection:TextSelection.createTextSelection(textArea).asSet()){
String selected=selection.getSelection();
List<String> converted=FluentIterable
.from(Arrays.asList(selected.split("\n")))
.transform(new TabListFunction())
.toList();
selection.replace(Joiner.on("\n").join(converted));
onTextAreaUpdate();
}
}
});
tab2listBt.setTitle("Convert tab tree to List");
button2Panel.add(tab2listBt);
imageListBox = new ListBox();
imageListBox.addItem("");
imageListBox.addItem("16");
imageListBox.addItem("32");
imageListBox.addItem("50");
imageListBox.addItem("64");
imageListBox.addItem("100");
imageListBox.addItem("200");
imageListBox.addItem("400");
imageListBox.addItem("600");
imageListBox.addItem("800");
imageListBox.addItem("<img>");
imageListBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int width=ValuesUtils.toInt(imageListBox.getItemText(imageListBox.getSelectedIndex()),0);
imageSelected(width);
}
});
imageListBox.setTitle("insert <img> tag with width");
imageListBox.setSelectedIndex(imageListBox.getItemCount()-1);//default empty
button2Panel.add(imageListBox);
button2Panel.add(new Button("Undo", new ClickHandler() {//TODO better
@Override
public void onClick(ClickEvent event) {
int undoIndex=historyIndex-1;
if(undoIndex<0){
return;
}
String text=textHistory.get(undoIndex);
textArea.setText(text);
lastHistory=text;
historyIndex
if(historyIndex<0){
historyIndex=0;
}
onTextAreaUpdate();
}
}));
button2Panel.add(new Button("Redo", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(historyIndex<textHistory.size()){
int redoIndex=historyIndex+1;
if(redoIndex>=textHistory.size()){
return;
}
String text=textHistory.get(redoIndex);
textArea.setText(text);
lastHistory=text;
historyIndex++;
if(historyIndex>=textHistory.size()){
historyIndex=textHistory.size()-1;
}
onTextAreaUpdate();
}
}
}));
}
public void clearHistory(){
lastHistory=null;
textHistory.clear();
historyIndex=0;
}
public void addHistory(String text){
if(text.equals(lastHistory)){
return;
}
textHistory.add(text);
lastHistory=text;
//GWT.log("add history:"+text);
if(textHistory.size()>1000){
textHistory.remove(0);
}
historyIndex=textHistory.size()-1;
}
private List<String> textHistory=new ArrayList<String>();
private int historyIndex;
private String lastHistory;
protected void imageSelected(int width) {
String url=Window.prompt("Image URL", "");
if(url==null){//cancel
return;
}
Optional<TextSelection> selection= getTextSelection();
for(TextSelection textSelection:selection.asSet()){
Tag tag=new Tag("img").attr("src",url).attr("alt",textSelection.getSelection()).attr("width", ""+width).single();
textSelection.replace(tag.toString());
}
onTextAreaUpdate();
imageListBox.setSelectedIndex(imageListBox.getItemCount()-1);
}
public static class TabTitleFunction implements Function<String,String>{
@Override
public String apply(String input) {
if(input.isEmpty()){
return "";
}
String text="";
int level=1;//all text add level
for(int i=0;i<input.length();i++){
if(input.charAt(i)=='\t'){
level++;
}else{
text=input.substring(i);
break;
}
}
level=Math.min(level, 6);
return Strings.repeat("#", level)+text;
}
}
public static class TabListFunction implements Function<String,String>{
@Override
public String apply(String input) {
if(input.isEmpty()){
return "";
}
String text="";
int level=0;//all text add level
for(int i=0;i<input.length();i++){
if(input.charAt(i)=='\t'){
level++;
}else{
text=input.substring(i);
break;
}
}
//level=Math.min(level, 6);
return Strings.repeat("\t", level)+"- "+text;
}
}
private void debug(String text){
for(int i=0;i<text.length();i++){
LogUtils.log(i+":"+text.charAt(i)+","+((int)text.charAt(i)));
}
}
private static void insertBetweenSelectionText(TextSelection selection,String header,String footer){
String newText=header+selection.getSelection()+footer;
selection.replace(newText);
TextArea target=selection.getTargetTextArea();
target.setCursorPos(selection.getStart()+(header+selection.getSelection()).length());
target.setFocus(true);
}
private void titleSelected(int level){
Optional<TextSelection> selection= getTextSelection();
for(TextSelection textSelection:selection.asSet()){
LogUtils.log("select:"+textSelection.getSelection()+","+textSelection.getStart()+","+textSelection.getEnd());
TextSelection tmp1=textSelection.getCurrentLine();
LogUtils.log("current:"+tmp1.getSelection()+","+tmp1.getStart()+","+tmp1.getEnd());
TextSelection lineSelection=textSelection.getCurrentLine();
boolean startWithTitle=MarkdownPredicates.getStartWithTitleLinePredicate().apply(lineSelection.getSelection());
if(startWithTitle){
//can ignore next line
String newLine=MarkdownFunctions.getConvertTitle(level).apply(lineSelection.getSelection());
lineSelection.replace(newLine);
}else{
boolean nextLineIsTitle=false;
Optional<TextSelection> nextLine=lineSelection.getNextLine();
if(nextLine.isPresent()){
TextSelection tmp2=nextLine.get();
LogUtils.log("next:"+tmp2.getSelection()+","+tmp2.getStart()+","+tmp2.getEnd());
TextSelection nextLineSelection=nextLine.get();
nextLineIsTitle=MarkdownPredicates.getTitleLinePredicate().apply(nextLineSelection.getSelection());
}else{
LogUtils.log("no next-line");
}
String newLine=MarkdownFunctions.getConvertTitle(level).apply(lineSelection.getSelection());
if(nextLineIsTitle){
TextSelection bothSelection=new TextSelection(lineSelection.getStart(), nextLine.get().getEnd(), textArea);
bothSelection.replace(newLine);
}else{
lineSelection.replace(newLine);
}
}
}
onTextAreaUpdate();
titleLevelBox.setSelectedIndex(7);
}
public Optional<TextSelection> getTextSelection(){
return TextSelection.createTextSelection(textArea);
}
public void onTextAreaUpdate(){
addHistory(textArea.getText());//full backup
if(autoConvertCheck.getValue()){
doConvert();
}else{
}
syncOutput();//sync storage or html/text for form
}
/**
* syncOutput is integrate for standard html web-apps
*/
public void syncOutput(){//TODO async
//set values for html-form hidden
if(syncHtmlKey.isPresent()){
String html=htmlArea.getText();
GWTHTMLUtils.setValueAttributeById(syncHtmlKey.get(), html);
}
String text=textArea.getText();
if(syncTextKey.isPresent()){
GWTHTMLUtils.setValueAttributeById(syncTextKey.get(), text);
}
//store to session-storage for back-button
try {
storageControler.setValue(KEY_SESSION, textArea.getText());
} catch (StorageException e) {
e.printStackTrace();
}
}
public String getHtmlText(){
return htmlArea.getText();
}
public String getMarkdownText(){
return textArea.getText();
}
public String getHeader(){
return "";
}
public String getFooter(){
return "";
}
public void doConvert() {
String text=textArea.getText();
String html=Marked.marked(text);
htmlArea.setText(html);
previewHTML.setHTML(getHeader()+html+getFooter());
}
public HTML getPreviewHTML() {
return previewHTML;
}
} |
package com.michaldabski.filemanager.folders;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.michaldabski.filemanager.AboutActivity;
import com.michaldabski.filemanager.FileManagerApplication;
import com.michaldabski.filemanager.R;
import com.michaldabski.filemanager.clipboard.Clipboard;
import com.michaldabski.filemanager.clipboard.Clipboard.ClipboardListener;
import com.michaldabski.filemanager.clipboard.ClipboardFileAdapter;
import com.michaldabski.filemanager.favourites.FavouritesManager;
import com.michaldabski.filemanager.favourites.FavouritesManager.FavouritesListener;
import com.michaldabski.filemanager.nav_drawer.NavDrawerAdapter;
import com.michaldabski.filemanager.nav_drawer.NavDrawerAdapter.NavDrawerItem;
import com.michaldabski.utils.FontApplicator;
import com.readystatesoftware.systembartint.SystemBarTintManager;
public class FolderActivity extends Activity implements OnItemClickListener, ClipboardListener, FavouritesListener
{
public static class FolderNotOpenException extends Exception
{
}
private static final String LOG_TAG = "Main Activity";
public static final String EXTRA_DIR = FolderFragment.EXTRA_DIR;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
File lastFolder=null;
private FontApplicator fontApplicator;
private SystemBarTintManager tintManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tintManager = new SystemBarTintManager(this);
setupDrawers();
Clipboard.getInstance().addListener(this);
fontApplicator = new FontApplicator(getApplicationContext(), "Roboto_Light.ttf").applyFont(getWindow().getDecorView());
}
public FontApplicator getFontApplicator()
{
return fontApplicator;
}
@Override
protected void onDestroy()
{
Clipboard.getInstance().removeListener(this);
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getFavouritesManager().removeFavouritesListener(this);
super.onDestroy();
}
public void setLastFolder(File lastFolder)
{
this.lastFolder = lastFolder;
}
@Override
protected void onPause()
{
if (lastFolder != null)
{
FileManagerApplication application = (FileManagerApplication) getApplication();
application.getAppPreferences().setStartFolder(lastFolder).saveChanges(getApplicationContext());
Log.d(LOG_TAG, "Saved last folder "+lastFolder.toString());
}
super.onPause();
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
}
public void setActionbarVisible(boolean visible)
{
if (visible)
{
getActionBar().show();
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.accent_color);
}
else
{
getActionBar().hide();
tintManager.setStatusBarTintEnabled(false);
tintManager.setStatusBarTintResource(android.R.color.transparent);
}
}
private void setupDrawers()
{
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer)
{
boolean actionBarShown = false;;
@Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
setActionbarVisible(true);
invalidateOptionsMenu();
}
@Override
public void onDrawerClosed(View drawerView)
{
actionBarShown=false;
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0 && actionBarShown == false)
{
actionBarShown = true;
setActionbarVisible(true);
}
else if (slideOffset <= 0) actionBarShown = false;
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
// drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.END);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setupNavDrawer();
setupClipboardDrawer();
}
void setupNavDrawer()
{
FileManagerApplication application = (FileManagerApplication) getApplication();
loadFavourites(application.getFavouritesManager());
application.getFavouritesManager().addFavouritesListener(this);
// add listview header to push items below the actionbar
LayoutInflater inflater = getLayoutInflater();
ListView navListView = (ListView) findViewById(R.id.listNavigation);
View header = inflater.inflate(R.layout.list_header_actionbar_padding, navListView, false);
SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
int headerHeight = systemBarTintManager.getConfig().getPixelInsetTop(true);
header.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, headerHeight));
navListView.addHeaderView(header, null, false);
int footerHeight = systemBarTintManager.getConfig().getPixelInsetBottom();
if (footerHeight > 0)
{
View footer = inflater.inflate(R.layout.list_header_actionbar_padding, navListView, false);
footer.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, footerHeight));
navListView.addFooterView(footer, null, false);
}
}
void setupClipboardDrawer()
{
// add listview header to push items below the actionbar
LayoutInflater inflater = getLayoutInflater();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
View header = inflater.inflate(R.layout.list_header_actionbar_padding, clipboardListView, false);
SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
int headerHeight = systemBarTintManager.getConfig().getPixelInsetTop(true);
header.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, headerHeight));
clipboardListView.addHeaderView(header, null, false);
int footerHeight = systemBarTintManager.getConfig().getPixelInsetBottom();
int rightPadding = systemBarTintManager.getConfig().getPixelInsetRight();
if (footerHeight > 0)
{
View footer = inflater.inflate(R.layout.list_header_actionbar_padding, clipboardListView, false);
footer.setLayoutParams(new android.widget.AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, footerHeight));
clipboardListView.addFooterView(footer, null, false);
}
if (rightPadding > 0)
{
clipboardListView.setPadding(clipboardListView.getPaddingLeft(), clipboardListView.getPaddingTop(),
clipboardListView.getPaddingRight()+rightPadding, clipboardListView.getPaddingBottom());
}
onClipboardContentsChange(Clipboard.getInstance());
}
void loadFavourites(FavouritesManager favouritesManager)
{
ListView listNavigation = (ListView) findViewById(R.id.listNavigation);
NavDrawerAdapter navDrawerAdapter = new NavDrawerAdapter(this, new ArrayList<NavDrawerAdapter.NavDrawerItem>(favouritesManager.getFolders()));
navDrawerAdapter.setFontApplicator(fontApplicator);
listNavigation.setAdapter(navDrawerAdapter);
listNavigation.setOnItemClickListener(this);
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
if (getFragmentManager().findFragmentById(R.id.fragment) == null)
{
FolderFragment folderFragment = new FolderFragment();
if (getIntent().hasExtra(EXTRA_DIR))
{
Bundle args = new Bundle();
args.putString(FolderFragment.EXTRA_DIR, getIntent().getStringExtra(EXTRA_DIR));
folderFragment.setArguments(args);
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment, folderFragment)
.commit();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (actionBarDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId())
{
case R.id.menu_about:
startActivity(new Intent(getApplicationContext(), AboutActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFragment(Fragment fragment)
{
getFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment, fragment)
.commit();
}
public void goBack()
{
getFragmentManager().popBackStack();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
return super.onPrepareOptionsMenu(menu);
}
public FolderFragment getFolderFragment()
{
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragment);
if (fragment instanceof FolderFragment)
return (FolderFragment) fragment;
else return null;
}
public File getCurrentFolder() throws FolderNotOpenException
{
FolderFragment folderFragment = getFolderFragment();
if (folderFragment == null)
throw new FolderNotOpenException();
else return folderFragment.currentDir;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch (arg0.getId())
{
case R.id.listNavigation:
NavDrawerItem item = (NavDrawerItem) arg0.getItemAtPosition(arg2);
if (item.onClicked(this))
drawerLayout.closeDrawers();
break;
case R.id.listClipboard:
FolderFragment folderFragment = getFolderFragment();
if (folderFragment != null)
{
// TODO: paste single file
}
break;
default:
break;
}
}
public File getLastFolder()
{
return lastFolder;
}
@Override
public void onClipboardContentsChange(Clipboard clipboard)
{
invalidateOptionsMenu();
ListView clipboardListView = (ListView) findViewById(R.id.listClipboard);
if (clipboard.isEmpty() && drawerLayout != null)
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.END);
else
{
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.END);
FileManagerApplication application = (FileManagerApplication) getApplication();
if (clipboardListView != null)
{
ClipboardFileAdapter clipboardFileAdapter = new ClipboardFileAdapter(this, clipboard, application.getFileIconResolver());
clipboardFileAdapter.setFontApplicator(fontApplicator);
clipboardListView.setAdapter(clipboardFileAdapter);
}
}
}
@Override
public void onFavouritesChanged(FavouritesManager favouritesManager)
{
loadFavourites(favouritesManager);
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.workplacesystems.queuj.process;
import com.workplacesystems.queuj.ProcessBuilder;
import com.workplacesystems.queuj.process.jpa.ProcessDAO;
import com.workplacesystems.queuj.process.jpa.ProcessImpl;
import com.workplacesystems.queuj.utils.QueujException;
import com.workplacesystems.utilsj.Callback;
import java.io.Serializable;
import java.util.GregorianCalendar;
import java.util.Map;
/**
*
* @author dave
*/
public class QueujFactoryImpl extends QueujFactory<Integer> {
protected void init() {}
protected void setDefaultImplOptions0(ProcessBuilder processBuilder, Map<String, Object> implementation_options) {}
protected ProcessServer getProcessServer0(String queueOwner, Map<String, Object> server_options) {
return ProcessImplServer.newInstance(queueOwner);
}
protected QueujTransaction<Integer> getTransaction0() {
return new QueujTransaction<Integer>() {
public <T> T doTransaction(ProcessWrapper<Integer> process, Callback<T> callback, boolean doStart) {
return doTransaction(process.getQueueOwner(), process.isPersistent(), callback, doStart);
}
public <T> T doTransaction(String queueOwner, boolean persistent, Callback<T> callback, boolean doStart) {
return doTransaction(queueOwner, persistent, callback, null, doStart);
}
public <T> T doTransaction(String queueOwner, boolean persistent, Callback<T> callback, Callback<Void> commitCallback, boolean doStart) {
if (persistent)
throw new QueujException("No persistence has been enabled.");
T result = callback.action();
if (result instanceof ProcessWrapper) {
ProcessWrapper process = (ProcessWrapper)result;
((ProcessImplServer)process.getContainingServer()).commit();
}
if (commitCallback != null) {
try {
commitCallback.action();
}
catch (Exception e) {
new QueujException(e);
}
}
if (result instanceof ProcessWrapper && doStart) {
ProcessWrapper process = (ProcessWrapper)result;
if (process.rescheduleRequired(false))
process.interruptRunner();
else
process.start();
}
return result;
}
};
}
protected ProcessPersistence<ProcessEntity<Integer>,Integer> getPersistence0(String queueOwner, Map<String, Object> server_options) {
return null;
}
protected ProcessDAO getProcessDAO0() {
return null;
}
public <T> Callback<T> getAsyncCallback0(Callback<T> callback) {
return callback;
}
protected ProcessEntity<Integer> getNewProcessEntity0(String queueOwner, boolean isPersistent, Map<String, Object> server_options) {
return new ProcessImpl();
}
protected ProcessRunner getProcessRunner0(ProcessWrapper process, GregorianCalendar runTime, boolean isFailed) {
return new ProcessRunnerImpl(process, runTime, isFailed);
}
} |
package org.mskcc.portal.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mskcc.portal.network.Network;
import org.mskcc.portal.network.NetworkIO;
import org.mskcc.portal.network.NetworkUtils;
import org.mskcc.portal.network.Node;
import org.mskcc.portal.remote.GetCaseSets;
import org.mskcc.portal.remote.GetGeneticProfiles;
import org.mskcc.portal.util.GeneticProfileUtil;
import org.mskcc.portal.util.XDebug;
import org.mskcc.cgds.model.CanonicalGene;
import org.mskcc.cgds.model.CaseList;
import org.mskcc.cgds.model.ExtendedMutation;
import org.mskcc.cgds.model.GeneticProfile;
import org.mskcc.cgds.model.GeneticAlterationType;
import org.mskcc.cgds.dao.DaoMutation;
import org.mskcc.cgds.dao.DaoException;
import org.mskcc.cgds.dao.DaoGeneOptimized;
import org.mskcc.cgds.dao.DaoGeneticAlteration;
/**
* Retrieving
* @author jj
*/
public class NetworkServlet extends HttpServlet {
private static final String NODE_ATTR_IN_QUERY = "IN_QUERY";
private static final String NODE_ATTR_PERCENT_ALTERED = "PERCENT_ALTERED";
private static final String NODE_ATTR_PERCENT_MUTATED = "PERCENT_MUTATED";
private static final String NODE_ATTR_PERCENT_CNA_AMPLIFIED = "PERCENT_CNA_AMPLIFIED";
private static final String NODE_ATTR_PERCENT_CNA_GAINED = "PERCENT_CNA_GAINED";
private static final String NODE_ATTR_PERCENT_CNA_HOM_DEL = "PERCENT_CNA_HOMOZYGOUSLY_DELETED";
private static final String NODE_ATTR_PERCENT_CNA_HET_LOSS = "PERCENT_CNA_HEMIZYGOUSLY_DELETED";
private static final String NODE_ATTR_PERCENT_MRNA_WAY_UP = "PERCENT_MRNA_WAY_UP";
private static final String NODE_ATTR_PERCENT_MRNA_WAY_DOWN = "PERCENT_MRNA_WAY_DOWN";
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
this.doPost(req, res);
}
/**
* Processes Post Request.
*
* @param req HttpServletRequest Object.
* @param res HttpServletResponse Object.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
@Override
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
try {
StringBuilder messages = new StringBuilder();
XDebug xdebug = new XDebug( req );
String xd = req.getParameter("xdebug");
boolean logXDebug = xd!=null && xd.equals("1");
Map<String,Map<String,Integer>> mapQueryGeneAlterationCaseNumber
= getMapQueryGeneAlterationCaseNumber(req);
String encodedQueryAlteration = encodeQueryAlteration(mapQueryGeneAlterationCaseNumber);
if (logXDebug) {
xdebug.logMsg(this, "<a href=\""+getNetworkServletUrl(req, false,
false, false, encodedQueryAlteration)
+"\" target=\"_blank\">NetworkServlet URL</a>");
}
// Get User Defined Gene List
String geneListStr = req.getParameter(QueryBuilder.GENE_LIST);
Set<String> queryGenes = new HashSet<String>(Arrays.asList(geneListStr.toUpperCase().split(" ")));
//String geneticProfileIdSetStr = xssUtil.getCleanInput (req, QueryBuilder.GENETIC_PROFILE_IDS);
String netSrc = req.getParameter("netsrc");
Network network;
xdebug.startTimer();
if (netSrc.toUpperCase().equals("cpath2")) {
network = NetworkIO.readNetworkFromCPath2(queryGenes, true);
if (logXDebug) {
xdebug.logMsg("GetPathwayCommonsNetwork", "<a href=\""+NetworkIO.getCPath2URL(queryGenes)
+"\" target=\"_blank\">cPath2 URL</a>");
}
} else {
network = NetworkIO.readNetworkFromCGDS(queryGenes, true);
}
int nBefore = network.countNodes();
int querySize = queryGenes.size();
String netSize = req.getParameter("netsize");
boolean topologyPruned = pruneNetwork(network,netSize);
int nAfter = network.countNodes();
if (nBefore!=nAfter) {
messages.append("The network below contains ");
messages.append(nAfter);
messages.append(" nodes, including your ");
messages.append(querySize);
messages.append(" query gene");
if (querySize>1) {
messages.append("s");
}
messages.append(" and ");
messages.append(nAfter-querySize);
messages.append(" (out of ");
messages.append(nBefore-querySize);
messages.append(") neighbor genes that interact with at least two query genes.\n");
}
xdebug.stopTimer();
xdebug.logMsg(this, "Successfully retrieved networks from " + netSrc
+ ": took "+xdebug.getTimeElapsed()+"ms");
if (network.countNodes()!=0) {
// add attribute is_query to indicate if a node is in query genes
// and get the list of genes in network
xdebug.logMsg(this, "Retrieving data from CGDS...");
// get cancer study id
String cancerTypeId = req.getParameter(QueryBuilder.CANCER_STUDY_ID);
// Get case ids
Set<String> targetCaseIds = getCaseIds(req, cancerTypeId);
// Get User Selected Genetic Profiles
Set<GeneticProfile> geneticProfileSet = getGeneticProfileSet(req, cancerTypeId);
// getzScoreThreshold
double zScoreThreshold = Double.parseDouble(req.getParameter(QueryBuilder.Z_SCORE_THRESHOLD));
xdebug.startTimer();
DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();
Set<Node> queryNodes = new HashSet<Node>();
for (Node node : network.getNodes()) {
String ngnc = NetworkUtils.getSymbol(node);
if (ngnc==null) {
continue;
}
if (mapQueryGeneAlterationCaseNumber!=null) {
if (queryGenes.contains(ngnc)) {
queryNodes.add(node);
continue;
}
}
CanonicalGene canonicalGene = daoGeneOptimized.getGene(ngnc);
if (canonicalGene==null) {
continue;
}
long entrezGeneId = canonicalGene.getEntrezGeneId();
// add attributes
addCGDSDataAsNodeAttribute(node, entrezGeneId, geneticProfileSet,
targetCaseIds, zScoreThreshold);
}
xdebug.stopTimer();
xdebug.logMsg(this, "Retrived data from CGDS. Took "+xdebug.getTimeElapsed()+"ms");
if (mapQueryGeneAlterationCaseNumber!=null) {
addAttributesForQueryGenes(queryNodes, targetCaseIds.size(), mapQueryGeneAlterationCaseNumber);
}
String nLinker = req.getParameter("linkers");
if (!topologyPruned && nLinker!=null && nLinker.matches("[0-9]+")) {
String strDiffusion = req.getParameter("diffusion");
double diffusion;
try {
diffusion = Double.parseDouble(strDiffusion);
} catch (Exception ex) {
diffusion = 0.2;
}
xdebug.startTimer();
pruneNetworkByAlteration(network, diffusion, Integer.parseInt(nLinker), querySize);
nAfter = network.countNodes();
if (nBefore!=nAfter) {
messages.append("The network below contains ");
messages.append(nAfter);
messages.append(" nodes, including your ");
messages.append(querySize);
messages.append(" query gene");
if (querySize>1) {
messages.append("s");
}
messages.append(" and ");
messages.append(nAfter-querySize);
messages.append(" (out of ");
messages.append(nBefore-querySize);
messages.append(") neighbor genes.\n");
}
xdebug.stopTimer();
xdebug.logMsg(this, "Prune network. Took "+xdebug.getTimeElapsed()+"ms");
}
messages.append("Download the complete network in ");
messages.append("<a href=\"");
messages.append(getNetworkServletUrl(req, true, true, false, encodedQueryAlteration));
messages.append("\">GraphML</a> ");
messages.append("or <a href=\"");
messages.append(getNetworkServletUrl(req, true, true, true, encodedQueryAlteration));
messages.append("\">SIF</a>");
messages.append(" for import into <a href=\"http://cytoscape.org\" target=\"_blank\">Cytoscape</a>");
messages.append(" (GraphMLReader plugin is required for importing GraphML).");
}
String format = req.getParameter("format");
boolean sif = format!=null && format.equalsIgnoreCase("sif");
String download = req.getParameter("download");
if (download!=null && download.equalsIgnoreCase("on")) {
res.setContentType("application/octet-stream");
res.addHeader("content-disposition","attachment; filename=cbioportal."+(sif?"sif":"graphml"));
messages.append("In order to open this file in Cytoscape, please install GraphMLReader plugin.");
} else {
res.setContentType("text/"+(sif?"plain":"xml"));
}
NetworkIO.NodeLabelHandler nodeLabelHandler = new NetworkIO.NodeLabelHandler() {
// using HGNC gene symbol as label if available
public String getLabel(Node node) {
String symbol = NetworkUtils.getSymbol(node);
if (symbol!=null) {
return symbol;
}
Object strNames = node.getAttributes().get("PARTICIPANT_NAME");
if (strNames!=null) {
String[] names = strNames.toString().split(";",2);
if (names.length>0) {
return names[0];
}
}
return node.getId();
}
};
String graph;
if (sif) {
graph = NetworkIO.writeNetwork2Sif(network, nodeLabelHandler);
} else {
graph = NetworkIO.writeNetwork2GraphML(network,nodeLabelHandler);
}
if (logXDebug) {
writeXDebug(xdebug, res);
}
String msgoff = req.getParameter("msgoff");
if ((msgoff==null || !msgoff.equals("t")) && messages.length()>0) {
writeMsg(messages.toString(), res);
}
PrintWriter writer = res.getWriter();
writer.write(graph);
writer.flush();
} catch (DaoException e) {
//throw new ServletException (e);
writeMsg("Error loading network. Please report this to cancergenomics@cbio.mskcc.org!\n"+e.toString(), res);
res.getWriter().write("<graphml></graphml>");
}
}
private boolean pruneNetwork(Network network, String netSize) {
if ("small".equals(netSize)) {
NetworkUtils.pruneNetwork(network, new NetworkUtils.NodeSelector() {
public boolean select(Node node) {
return !isInQuery(node);
}
});
return true;
} else if ("medium".equals(netSize)) {
NetworkUtils.pruneNetwork(network, new NetworkUtils.NodeSelector() {
public boolean select(Node node) {
String inMedium = (String)node.getAttribute("IN_MEDIUM");
return inMedium==null || !inMedium.equals("true");
}
});
return true;
}
return false;
}
/**
* @param network
* @param nKeep keep the top altered
*/
private void pruneNetworkByAlteration(Network network, double diffusion, int nKeep, int nQuery) {
if (network.countNodes() <= nKeep + nQuery) {
return;
}
List<Node> nodesToRemove = getNodesToRemove(network, diffusion, nKeep);
for (Node node : nodesToRemove) {
network.removeNode(node);
}
}
/**
*
* @param network
* @param n
* @return
*/
private List<Node> getNodesToRemove(Network network, double diffusion, int n) {
final Map<Node,Double> mapDiffusion = getMapDiffusedTotalAlteredPercentage(network, diffusion);
// keep track of the top nKeep
PriorityQueue<Node> topAlteredNodes = new PriorityQueue<Node>(n,
new Comparator<Node>() {
public int compare(Node n1, Node n2) {
int ret = mapDiffusion.get(n1).compareTo(mapDiffusion.get(n2));
if (ret==0) { // if the same diffused perc, use own perc
ret = Double.compare(getTotalAlteredPercentage(n1),
getTotalAlteredPercentage(n2));
}
return ret;
}
});
List<Node> nodesToRemove = new ArrayList<Node>();
for (Node node : network.getNodes()) {
if (isInQuery(node)) {
continue;
}
if (topAlteredNodes.size()<n) {
topAlteredNodes.add(node);
} else {
if (n==0) {
nodesToRemove.add(node);
} else {
if (mapDiffusion.get(node) > mapDiffusion.get(topAlteredNodes.peek())) {
nodesToRemove.add(topAlteredNodes.poll());
topAlteredNodes.add(node);
} else {
nodesToRemove.add(node);
}
}
}
}
return nodesToRemove;
}
private boolean isInQuery(Node node) {
String inQuery = (String)node.getAttribute(NODE_ATTR_IN_QUERY);
return inQuery!=null && inQuery.equals("true");
}
private Map<Node,Double> getMapDiffusedTotalAlteredPercentage(Network network, double diffusion) {
Map<Node,Double> map = new HashMap<Node,Double>();
for (Node node : network.getNodes()) {
map.put(node, getDiffusedTotalAlteredPercentage(network,node,diffusion));
}
return map;
}
private double getDiffusedTotalAlteredPercentage(Network network, Node node, double diffusion) {
double alterPerc = getTotalAlteredPercentage(node);
if (diffusion==0) {
return alterPerc;
}
for (Node neighbor : network.getNeighbors(node)) {
double diffused = diffusion * getTotalAlteredPercentage(neighbor);
if (diffused > alterPerc) {
alterPerc = diffused;
}
}
return alterPerc;
}
private double getTotalAlteredPercentage(Node node) {
Double alterPerc = (Double)node.getAttribute(NODE_ATTR_PERCENT_ALTERED);
return alterPerc == null ? 0.0 : alterPerc;
}
private Set<String> getCaseIds(HttpServletRequest req, String cancerStudyId)
throws ServletException, DaoException {
String strCaseIds = req.getParameter(QueryBuilder.CASE_IDS);
if (strCaseIds==null || strCaseIds.length()==0) {
String caseSetId = req.getParameter(QueryBuilder.CASE_SET_ID);
// Get Case Sets for Selected Cancer Type
ArrayList<CaseList> caseSets = GetCaseSets.getCaseSets(cancerStudyId);
for (CaseList cs : caseSets) {
if (cs.getStableId().equals(caseSetId)) {
strCaseIds = cs.getCaseListAsString();
break;
}
}
}
String[] caseArray = strCaseIds.split(" ");
Set<String> targetCaseIds = new HashSet<String>(caseArray.length);
for (String caseId : caseArray) {
targetCaseIds.add(caseId);
}
return targetCaseIds;
}
private Set<GeneticProfile> getGeneticProfileSet(HttpServletRequest req, String cancerStudyId)
throws ServletException, DaoException {
Set<GeneticProfile> geneticProfileSet = new HashSet<GeneticProfile>();
ArrayList<GeneticProfile> profileList = GetGeneticProfiles.getGeneticProfiles(cancerStudyId);
for (String geneticProfileIdsStr : req.getParameterValues(QueryBuilder.GENETIC_PROFILE_IDS)) {
for (String profileId : geneticProfileIdsStr.split(" ")) {
GeneticProfile profile = GeneticProfileUtil.getProfile(profileId, profileList);
if( null != profile ){
geneticProfileSet.add(profile);
}
}
}
return geneticProfileSet;
}
private void addAttributesForQueryGenes(Set<Node> nodes, int nCases,
Map<String,Map<String,Integer>> mapQueryGeneAlterationCaseNumber) {
for (Node node : nodes) {
String symbol = NetworkUtils.getSymbol(node);
Map<String,Integer> mapAltrationCaseNumber = mapQueryGeneAlterationCaseNumber.get(symbol);
for (Map.Entry<String,Integer> entry : mapAltrationCaseNumber.entrySet()) {
node.setAttribute(mapHeatMapKeyToAttrName.get(entry.getKey()), 1.0*entry.getValue()/nCases);
}
}
}
private Map<String,Map<String,Integer>> getMapQueryGeneAlterationCaseNumber(HttpServletRequest req) {
String geneAlt = req.getParameter("query_alt");
if (geneAlt!=null) {
return decodeQueryAlteration(geneAlt);
}
String heatMap = req.getParameter("heat_map");
if (heatMap!=null) {
Map<String,Map<String,Integer>> mapQueryGeneAlterationCaseNumber
= new HashMap<String,Map<String,Integer>>();
String[] heatMapLines = heatMap.split("\r?\n");
String[] genes = heatMapLines[0].split("\t");
for (int i=1; i<genes.length; i++) {
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Any", 0);
mapQueryGeneAlterationCaseNumber.put(genes[i], map);
}
for (int i=1; i<heatMapLines.length; i++) {
String[] strs = heatMapLines[i].split("\t");
for (int j=1; j<strs.length; j++) {
Map<String,Integer> map = mapQueryGeneAlterationCaseNumber.get(genes[j]);
if (!strs[j].isEmpty()) {
map.put("Any", map.get("Any")+1);
}
for (String type : strs[j].split(";")) {
// add to specific type
Integer num = map.get(type);
if (num==null) {
map.put(type, 1);
} else {
map.put(type, num+1);
}
}
}
}
return mapQueryGeneAlterationCaseNumber;
}
return null;
}
private static final Map<String,String> mapHeatMapKeyToAttrName;
static {
mapHeatMapKeyToAttrName = new HashMap<String,String>();
mapHeatMapKeyToAttrName.put("Any", NetworkServlet.NODE_ATTR_PERCENT_ALTERED);
mapHeatMapKeyToAttrName.put("AMP", NetworkServlet.NODE_ATTR_PERCENT_CNA_AMPLIFIED);
mapHeatMapKeyToAttrName.put("GAIN", NetworkServlet.NODE_ATTR_PERCENT_CNA_GAINED);
mapHeatMapKeyToAttrName.put("HETLOSS", NetworkServlet.NODE_ATTR_PERCENT_CNA_HET_LOSS);
mapHeatMapKeyToAttrName.put("HOMDEL", NetworkServlet.NODE_ATTR_PERCENT_CNA_HOM_DEL);
mapHeatMapKeyToAttrName.put("DOWN", NetworkServlet.NODE_ATTR_PERCENT_MRNA_WAY_DOWN);
mapHeatMapKeyToAttrName.put("UP", NetworkServlet.NODE_ATTR_PERCENT_MRNA_WAY_UP);
mapHeatMapKeyToAttrName.put("MUT", NetworkServlet.NODE_ATTR_PERCENT_MUTATED);
}
private void addCGDSDataAsNodeAttribute(Node node, long entrezGeneId,
Set<GeneticProfile> profiles, Set<String> targetCaseList, double zScoreThreshold) throws DaoException {
Set<String> alteredCases = new HashSet<String>();
for (GeneticProfile profile : profiles) {
if (profile.getGeneticAlterationType() == GeneticAlterationType.MUTATION_EXTENDED) {
Set<String> cases = getMutatedCases(profile.getGeneticProfileId(),
targetCaseList, entrezGeneId);
alteredCases.addAll(cases);
node.setAttribute(NODE_ATTR_PERCENT_MUTATED, 1.0*cases.size()/targetCaseList.size());
} else if (profile.getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION) {
Map<String,Set<String>> cnaCases = getCNACases(profile.getGeneticProfileId(),
targetCaseList, entrezGeneId);
//AMP
Set<String> cases = cnaCases.get("2");
if (!cases.isEmpty()) {
alteredCases.addAll(cases);
node.setAttribute(NODE_ATTR_PERCENT_CNA_AMPLIFIED, 1.0*cases.size()/targetCaseList.size());
}
// //GAINED
// cases = cnaCases.get("1");
// if (!cases.isEmpty()) {
// alteredCases.addAll(cases);
// node.setAttribute(NODE_ATTR_PERCENT_CNA_GAINED, 1.0*cases.size()/targetCaseList.size());
// //HETLOSS
// cases = cnaCases.get("-1");
// if (!cases.isEmpty()) {
// alteredCases.addAll(cases);
// node.setAttribute(NODE_ATTR_PERCENT_CNA_HET_LOSS, 1.0*cases.size()/targetCaseList.size());
//HOMDEL
cases = cnaCases.get("-2");
if (!cases.isEmpty()) {
alteredCases.addAll(cases);
node.setAttribute(NODE_ATTR_PERCENT_CNA_HOM_DEL, 1.0*cases.size()/targetCaseList.size());
}
} else if (profile.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION) {
Set<String>[] cases = getMRnaAlteredCases(profile.getGeneticProfileId(),
targetCaseList, entrezGeneId, zScoreThreshold);
alteredCases.addAll(cases[0]);
alteredCases.addAll(cases[1]);
node.setAttribute(NODE_ATTR_PERCENT_MRNA_WAY_UP, 1.0*cases[0].size()/targetCaseList.size());
node.setAttribute(NODE_ATTR_PERCENT_MRNA_WAY_DOWN, 1.0*cases[1].size()/targetCaseList.size());
}
}
node.setAttribute(NODE_ATTR_PERCENT_ALTERED, 1.0*alteredCases.size()/targetCaseList.size());
}
/**
*
* @return mutated cases.
*/
private Set<String> getMutatedCases(int geneticProfileId, Set<String> targetCaseList,
long entrezGeneId) throws DaoException {
ArrayList <ExtendedMutation> mutationList =
DaoMutation.getInstance().getMutations(geneticProfileId, targetCaseList, entrezGeneId);
Set<String> cases = new HashSet<String>();
for (ExtendedMutation mutation : mutationList) {
cases.add(mutation.getCaseId());
}
return cases;
}
/**
*
* @param geneticProfileId
* @param targetCaseList
* @param entrezGeneId
* @return map from cna status to cases
* @throws DaoException
*/
private Map<String,Set<String>> getCNACases(int geneticProfileId, Set<String> targetCaseList,
long entrezGeneId) throws DaoException {
Map<String,String> caseMap = DaoGeneticAlteration.getInstance()
.getGeneticAlterationMap(geneticProfileId,entrezGeneId);
caseMap.keySet().retainAll(targetCaseList);
Map<String,Set<String>> res = new HashMap<String,Set<String>>();
res.put("-2", new HashSet<String>());
//res.put("-1", new HashSet<String>());
//res.put("1", new HashSet<String>());
res.put("2", new HashSet<String>());
for (Map.Entry<String,String> entry : caseMap.entrySet()) {
String cna = entry.getValue();
if (cna.equals("2")||cna.equals("-2")) {
String caseId = entry.getKey();
res.get(cna).add(caseId);
}
}
return res;
}
/**
*
* @param geneticProfileId
* @param targetCaseList
* @param entrezGeneId
* @return an array of two sets: first set contains up-regulated cases; second
* contains down-regulated cases.
* @throws DaoException
*/
private Set<String>[] getMRnaAlteredCases(int geneticProfileId, Set<String> targetCaseList,
long entrezGeneId, double zScoreThreshold) throws DaoException {
Map<String,String> caseMap = DaoGeneticAlteration.getInstance()
.getGeneticAlterationMap(geneticProfileId,entrezGeneId);
caseMap.keySet().retainAll(targetCaseList);
Set<String>[] cases = new Set[2];
cases[0] = new HashSet<String>();
cases[1] = new HashSet<String>();
for (Map.Entry<String,String> entry : caseMap.entrySet()) {
String caseId = entry.getKey();
double mrna;
try {
mrna = Double.parseDouble(entry.getValue());
} catch (Exception e) {
continue;
}
if (mrna>=zScoreThreshold) {
cases[0].add(caseId);
} else if (mrna<=-zScoreThreshold) {
cases[1].add(caseId);
}
}
return cases;
}
private Map<String,Map<String,Integer>> decodeQueryAlteration(String strQueryAlteration) {
if (strQueryAlteration==null || strQueryAlteration.isEmpty()) {
return null;
}
Map<String,Map<String,Integer>> ret = new HashMap<String,Map<String,Integer>>();
try {
String[] genes = strQueryAlteration.split(";");
for (String perGene : genes) {
int ix = perGene.indexOf(":");
String gene = perGene.substring(0, ix);
Map<String,Integer> map = new HashMap<String,Integer>();
ret.put(gene, map);
String[] alters = perGene.substring(ix+1).split(",");
for (String alter : alters) {
String[] parts = alter.split(":");
map.put(parts[0], Integer.valueOf(parts[1]));
}
}
return ret;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
private String encodeQueryAlteration(Map<String,Map<String,Integer>> queryAlteration) {
if (queryAlteration==null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,Map<String,Integer>> entry1 : queryAlteration.entrySet()) {
sb.append(entry1.getKey());
sb.append(':');
for (Map.Entry<String,Integer> entry2 : entry1.getValue().entrySet()) {
sb.append(entry2.getKey());
sb.append(':');
sb.append(entry2.getValue());
sb.append(',');
}
sb.setCharAt(sb.length()-1, ';');
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
private String getNetworkServletUrl(HttpServletRequest req, boolean complete,
boolean download, boolean sif, String strQueryAlteration) {
String geneListStr = req.getParameter(QueryBuilder.GENE_LIST);
String geneticProfileIdsStr = req.getParameter(QueryBuilder.GENETIC_PROFILE_IDS);
String cancerTypeId = req.getParameter(QueryBuilder.CANCER_STUDY_ID);
String caseSetId = req.getParameter(QueryBuilder.CASE_SET_ID);
String zscoreThreshold = req.getParameter(QueryBuilder.Z_SCORE_THRESHOLD);
String netSrc = req.getParameter("netsrc");
String netSize = req.getParameter("netsize");
String nLinker = req.getParameter("linkers");
String strDiffusion = req.getParameter("diffusion");
String ret = "network.do?"+QueryBuilder.GENE_LIST+"="+geneListStr
+"&"+QueryBuilder.GENETIC_PROFILE_IDS+"="+geneticProfileIdsStr
+"&"+QueryBuilder.CANCER_STUDY_ID+"="+cancerTypeId
+"&"+QueryBuilder.CASE_SET_ID+"="+caseSetId
+"&"+QueryBuilder.Z_SCORE_THRESHOLD+"="+zscoreThreshold
+"&netsrc="+netSrc
+"&msgoff=t";
if (strQueryAlteration!=null) {
ret += "&query_alt="+strQueryAlteration;
}
if (!complete) {
ret += "&netsize=" + netSize
+ "&linkers=" + nLinker
+"&diffusion"+strDiffusion;
}
if (download) {
ret += "&download=on";
}
if (sif) {
ret += "&format=sif";
}
return ret;
}
private void writeXDebug(XDebug xdebug, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter writer = res.getWriter();
writer.write("<!--xdebug messages begin:\n");
for (Object msg : xdebug.getDebugMessages()) {
writer.write(((org.mskcc.portal.util.XDebugMessage)msg).getMessage());
writer.write("\n");
}
writer.write("xdebug messages end
}
private void writeMsg(String msg, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter writer = res.getWriter();
writer.write("<!--messages begin:\n");
writer.write(msg);
writer.write("\nmessages end
}
} |
package net.md_5.bungee;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import lombok.Getter;
import lombok.Synchronized;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.packet.*;
public class UserConnection extends GenericConnection implements ProxiedPlayer
{
public final Packet2Handshake handshake;
final Packet1Login forgeLogin;
final List<PacketFAPluginMessage> loginMessages;
public Queue<DefinedPacket> packetQueue = new ConcurrentLinkedQueue<>();
@Getter
private final PendingConnection pendingConnection;
@Getter
private ServerConnection server;
private UpstreamBridge upBridge;
private DownstreamBridge downBridge;
// reconnect stuff
private int clientEntityId;
private int serverEntityId;
private volatile boolean reconnecting;
// ping stuff
private int trackingPingId;
private long pingTime;
@Getter
private int ping = 1000;
private final Collection<String> groups = new HashSet<>();
private final Map<String, Boolean> permissions = new HashMap<>();
private final Object permMutex = new Object();
// Hack for connect timings
private ServerInfo nextServer;
private volatile boolean clientConnected = true;
public UserConnection(Socket socket, PendingConnection pendingConnection, PacketStream stream, Packet2Handshake handshake, Packet1Login forgeLogin, List<PacketFAPluginMessage> loginMessages)
{
super( socket, stream );
this.handshake = handshake;
this.pendingConnection = pendingConnection;
this.forgeLogin = forgeLogin;
this.loginMessages = loginMessages;
name = handshake.username;
displayName = handshake.username;
Collection<String> g = ProxyServer.getInstance().getConfigurationAdapter().getGroups( name );
for ( String s : g )
{
addGroups( s );
}
}
@Override
public void setDisplayName(String name)
{
ProxyServer.getInstance().getTabListHandler().onDisconnect( this );
displayName = name;
ProxyServer.getInstance().getTabListHandler().onConnect( this );
}
@Override
public void connect(ServerInfo target)
{
nextServer = target;
}
public void connect(ServerInfo target, boolean force)
{
nextServer = null;
if ( server == null )
{
// First join
BungeeCord.getInstance().connections.put( name, this );
ProxyServer.getInstance().getTabListHandler().onConnect( this );
}
ServerConnectEvent event = new ServerConnectEvent( this, target );
BungeeCord.getInstance().getPluginManager().callEvent( event );
target = event.getTarget(); // Update in case the event changed target
ProxyServer.getInstance().getTabListHandler().onServerChange( this );
try
{
reconnecting = true;
if ( server != null )
{
stream.write( new Packet9Respawn( (byte) 1, (byte) 0, (byte) 0, (short) 256, "DEFAULT" ) );
stream.write( new Packet9Respawn( (byte) -1, (byte) 0, (byte) 0, (short) 256, "DEFAULT" ) );
}
ServerConnection newServer = ServerConnector.connect( this, target, true );
if ( server == null )
{
// Once again, first connection
clientEntityId = newServer.loginPacket.entityId;
serverEntityId = newServer.loginPacket.entityId;
stream.write( newServer.loginPacket );
stream.write( BungeeCord.getInstance().registerChannels() );
upBridge = new UpstreamBridge();
upBridge.start();
} else
{
try
{
downBridge.interrupt();
downBridge.join();
} catch ( InterruptedException ie )
{
}
server.disconnect( "Quitting" );
server.getInfo().removePlayer( this );
Packet1Login login = newServer.loginPacket;
serverEntityId = login.entityId;
stream.write( new Packet9Respawn( login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType ) );
}
// Reconnect process has finished, lets get the player moving again
reconnecting = false;
// Add to new
target.addPlayer( this );
// Start the bridges and move on
server = newServer;
downBridge = new DownstreamBridge();
downBridge.start();
} catch ( KickException ex )
{
disconnect( ex.getMessage() );
} catch ( Exception ex )
{
disconnect( "Could not connect to server - " + Util.exception( ex ) );
}
}
@Override
public synchronized void disconnect(String reason)
{
if ( clientConnected )
{
PlayerDisconnectEvent event = new PlayerDisconnectEvent( this );
ProxyServer.getInstance().getPluginManager().callEvent( event );
ProxyServer.getInstance().getTabListHandler().onDisconnect( this );
ProxyServer.getInstance().getPlayers().remove( this );
super.disconnect( reason );
if ( server != null )
{
server.getInfo().removePlayer( this );
server.disconnect( "Quitting" );
ProxyServer.getInstance().getReconnectHandler().setServer( this );
}
clientConnected = false;
}
}
@Override
public void sendMessage(String message)
{
packetQueue.add( new Packet3Chat( message ) );
}
@Override
public void sendData(String channel, byte[] data)
{
server.packetQueue.add( new PacketFAPluginMessage( channel, data ) );
}
@Override
public InetSocketAddress getAddress()
{
return (InetSocketAddress) socket.getRemoteSocketAddress();
}
@Override
@Synchronized("permMutex")
public Collection<String> getGroups()
{
return Collections.unmodifiableCollection( groups );
}
@Override
@Synchronized("permMutex")
public void addGroups(String... groups)
{
for ( String group : groups )
{
this.groups.add( group );
for ( String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions( group ) )
{
setPermission( permission, true );
}
}
}
@Override
@Synchronized("permMutex")
public void removeGroups(String... groups)
{
for ( String group : groups )
{
this.groups.remove( group );
for ( String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions( group ) )
{
setPermission( permission, false );
}
}
}
@Override
@Synchronized("permMutex")
public boolean hasPermission(String permission)
{
Boolean val = permissions.get( permission );
return ( val == null ) ? false : val;
}
@Override
@Synchronized("permMutex")
public void setPermission(String permission, boolean value)
{
permissions.put( permission, value );
}
private class UpstreamBridge extends Thread
{
public UpstreamBridge()
{
super( "Upstream Bridge - " + name );
}
@Override
public void run()
{
while ( !socket.isClosed() )
{
try
{
byte[] packet = stream.readPacket();
boolean sendPacket = true;
int id = Util.getId( packet );
switch ( id )
{
case 0x00:
if ( trackingPingId == new Packet0KeepAlive( packet ).id )
{
int newPing = (int) ( System.currentTimeMillis() - pingTime );
ProxyServer.getInstance().getTabListHandler().onPingChange( UserConnection.this, newPing );
ping = newPing;
}
break;
case 0x03:
Packet3Chat chat = new Packet3Chat( packet );
if ( chat.message.startsWith( "/" ) )
{
sendPacket = !ProxyServer.getInstance().getPluginManager().dispatchCommand( UserConnection.this, chat.message.substring( 1 ) );
} else
{
ChatEvent chatEvent = new ChatEvent( UserConnection.this, server, chat.message );
ProxyServer.getInstance().getPluginManager().callEvent( chatEvent );
sendPacket = !chatEvent.isCancelled();
}
break;
case 0xFA:
// Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage( packet );
// Might matter in the future
if ( message.tag.equals( "BungeeCord" ) )
{
continue;
}
PluginMessageEvent event = new PluginMessageEvent( UserConnection.this, server, message.tag, message.data );
ProxyServer.getInstance().getPluginManager().callEvent( event );
if ( event.isCancelled() )
{
continue;
}
break;
}
while ( !server.packetQueue.isEmpty() )
{
DefinedPacket p = server.packetQueue.poll();
if ( p != null )
{
server.stream.write( p );
}
}
EntityMap.rewrite( packet, clientEntityId, serverEntityId );
if ( sendPacket && !server.socket.isClosed() )
{
server.stream.write( packet );
}
try
{
Thread.sleep( BungeeCord.getInstance().config.getSleepTime() );
} catch ( InterruptedException ex )
{
}
} catch ( IOException ex )
{
disconnect( "Reached end of stream" );
} catch ( Exception ex )
{
disconnect( Util.exception( ex ) );
}
}
}
}
private class DownstreamBridge extends Thread
{
public DownstreamBridge()
{
super( "Downstream Bridge - " + name );
}
@Override
public void run()
{
try
{
outer:
while ( !reconnecting )
{
byte[] packet = server.stream.readPacket();
int id = Util.getId( packet );
switch ( id )
{
case 0x00:
trackingPingId = new Packet0KeepAlive( packet ).id;
pingTime = System.currentTimeMillis();
break;
case 0x03:
Packet3Chat chat = new Packet3Chat( packet );
ChatEvent chatEvent = new ChatEvent( server, UserConnection.this, chat.message );
ProxyServer.getInstance().getPluginManager().callEvent( chatEvent );
if ( chatEvent.isCancelled() )
{
continue;
}
break;
case 0xC9:
PacketC9PlayerListItem playerList = new PacketC9PlayerListItem( packet );
if ( !ProxyServer.getInstance().getTabListHandler().onListUpdate( UserConnection.this, playerList.username, playerList.online, playerList.ping ) )
{
continue;
}
break;
case 0xFA:
// Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage( packet );
DataInputStream in = new DataInputStream( new ByteArrayInputStream( message.data ) );
PluginMessageEvent event = new PluginMessageEvent( server, UserConnection.this, message.tag, message.data );
ProxyServer.getInstance().getPluginManager().callEvent( event );
if ( event.isCancelled() )
{
continue;
}
if ( message.tag.equals( "BungeeCord" ) )
{
String subChannel = in.readUTF();
if ( subChannel.equals( "Forward" ) )
{
String target = in.readUTF();
String channel = in.readUTF();
short len = in.readShort();
byte[] data = new byte[ len ];
in.readFully( data );
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( channel );
out.writeShort( data.length );
out.write( data );
if ( target.equals( "ALL" ) )
{
for ( ServerInfo server : BungeeCord.getInstance().getServers().values() )
{
server.sendData( "BungeeCord", b.toByteArray() );
}
} else
{
ServerInfo server = BungeeCord.getInstance().getServerInfo( target );
if ( server != null )
{
server.sendData( "BungeeCord", b.toByteArray() );
}
}
}
if ( subChannel.equals( "Connect" ) )
{
ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if ( server != null )
{
connect( server, true );
break outer;
}
}
if ( subChannel.equals( "IP" ) )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "IP" );
out.writeUTF( getAddress().getHostString() );
out.writeInt( getAddress().getPort() );
getServer().sendData( "BungeeCord", b.toByteArray() );
}
if ( subChannel.equals( "PlayerCount" ) )
{
ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if ( server != null )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "PlayerCount" );
out.writeUTF( server.getName() );
out.writeInt( server.getPlayers().size() );
getServer().sendData( "BungeeCord", b.toByteArray() );
}
}
if ( subChannel.equals( "PlayerList" ) )
{
ServerInfo server = ProxyServer.getInstance().getServerInfo( in.readUTF() );
if ( server != null )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "PlayerList" );
out.writeUTF( server.getName() );
StringBuilder sb = new StringBuilder();
for ( ProxiedPlayer p : server.getPlayers() )
{
sb.append( p.getName() );
sb.append( "," );
}
out.writeUTF( sb.substring( 0, sb.length() - 1 ) );
getServer().sendData( "BungeeCord", b.toByteArray() );
}
}
if ( subChannel.equals( "GetServers" ) )
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
out.writeUTF( "GetServers" );
StringBuilder sb = new StringBuilder();
for ( String server : ProxyServer.getInstance().getServers().keySet() )
{
sb.append( server );
sb.append( "," );
}
out.writeUTF( sb.substring( 0, sb.length() - 1 ) );
getServer().sendData( "BungeeCord", b.toByteArray() );
}
if ( subChannel.equals( "Message" ) )
{
ProxiedPlayer target = ProxyServer.getInstance().getPlayer( in.readUTF() );
if ( target != null )
{
target.sendMessage( in.readUTF() );
}
}
continue;
}
break;
case 0xFF:
disconnect(new PacketFFKick( packet ).message );
break outer;
}
while ( !packetQueue.isEmpty() )
{
DefinedPacket p = packetQueue.poll();
if ( p != null )
{
stream.write( p );
}
}
EntityMap.rewrite( packet, serverEntityId, clientEntityId );
stream.write( packet );
if ( nextServer != null )
{
connect( nextServer, true );
break outer;
}
}
} catch ( Exception ex )
{
disconnect( Util.exception( ex ) );
}
}
}
} |
package exm.stc.ast.descriptor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import exm.stc.ast.SwiftAST;
import exm.stc.ast.antlr.ExMParser;
import exm.stc.common.exceptions.InvalidAnnotationException;
import exm.stc.common.exceptions.TypeMismatchException;
import exm.stc.common.exceptions.UserException;
import exm.stc.common.lang.Annotations;
import exm.stc.common.lang.Types;
import exm.stc.common.lang.Types.Type;
import exm.stc.common.lang.Var;
import exm.stc.common.lang.Var.DefType;
import exm.stc.common.lang.Var.VarStorage;
import exm.stc.frontend.Context;
import exm.stc.frontend.LocalContext;
import exm.stc.frontend.TypeChecker;
public class ForeachLoop {
private static final int DEFAULT_SPLIT_DEGREE = 16;
private final SwiftAST arrayVarTree;
private final SwiftAST loopBodyTree;
private final String memberVarName;
private final String loopCountVarName;
private LocalContext loopBodyContext = null;
private Var loopCountVal = null;
private Var memberVar = null;
private final ArrayList<String> annotations;
private int unroll = 1;
private int splitDegree = DEFAULT_SPLIT_DEGREE;
public int getDesiredUnroll() {
return unroll;
}
public int getSplitDegree() {
return splitDegree;
}
public List<String> getAnnotations() {
return Collections.unmodifiableList(annotations);
}
public boolean isSyncLoop() {
return !annotations.contains(Annotations.LOOP_ASYNC);
}
public Var getMemberVar() {
return memberVar;
}
public Var getLoopCountVal() {
return loopCountVal;
}
public SwiftAST getArrayVarTree() {
return arrayVarTree;
}
public SwiftAST getBody() {
return loopBodyTree;
}
public String getMemberVarName() {
return memberVarName;
}
public String getCountVarName() {
return loopCountVarName;
}
public LocalContext getBodyContext() {
return loopBodyContext;
}
private ForeachLoop(SwiftAST arrayVarTree, SwiftAST loopBodyTree,
String memberVarName, String loopCountVarName,
ArrayList<String> annotations) {
super();
this.arrayVarTree = arrayVarTree;
this.loopBodyTree = loopBodyTree;
this.memberVarName = memberVarName;
this.loopCountVarName = loopCountVarName;
this.annotations = annotations;
}
public static ForeachLoop fromAST(Context context, SwiftAST tree)
throws UserException {
assert (tree.getType() == ExMParser.FOREACH_LOOP);
ArrayList<String> annotations = new ArrayList<String>();
// How many times to unroll loop (1 == don't unroll)
int unrollFactor = 1;
int splitDegree = DEFAULT_SPLIT_DEGREE;
int annotationCount = 0;
for (int i = tree.getChildCount() - 1; i >= 0; i
SwiftAST subtree = tree.child(i);
if (subtree.getType() == ExMParser.ANNOTATION) {
if (subtree.getChildCount() == 2) {
String key = subtree.child(0).getText();
if (key.equals(Annotations.LOOP_UNROLL)
|| key.equals(Annotations.LOOP_SPLIT_DEGREE)) {
boolean posint = false;
if (subtree.child(1).getType() == ExMParser.NUMBER) {
int val = Integer.parseInt(subtree.child(1).getText());
if (val > 0) {
posint = true;
if (key.equals(Annotations.LOOP_UNROLL)) {
unrollFactor = val;
} else {
splitDegree = val;
}
annotationCount++;
}
}
if (!posint) {
throw new InvalidAnnotationException(context, "Expected value "
+ "of " + key + " to be a positive integer");
}
} else {
throw new InvalidAnnotationException(context, key
+ " is not the name of a key-value annotation for "
+ " foreach loops");
}
} else {
assert (subtree.getChildCount() == 1);
annotations.add(subtree.child(0).getText());
annotationCount++;
}
} else {
break;
}
}
if (annotations.contains(Annotations.LOOP_NOSPLIT)) {
// Disable splitting
splitDegree = -1;
}
int childCount = tree.getChildCount() - annotationCount;
assert(childCount == 3 || childCount == 4);
SwiftAST arrayVarTree = tree.child(0);
SwiftAST loopBodyTree = tree.child(1);
SwiftAST memberVarTree = tree.child(2);
assert (memberVarTree.getType() == ExMParser.ID);
String memberVarName = memberVarTree.getText();
context.checkNotDefined(memberVarName);
String loopCountVarName;
if (childCount == 4 && tree.child(3).getType() != ExMParser.ANNOTATION) {
SwiftAST loopCountTree = tree.child(3);
assert (loopCountTree.getType() == ExMParser.ID);
loopCountVarName = loopCountTree.getText();
context.checkNotDefined(loopCountVarName);
} else {
loopCountVarName = null;
}
ForeachLoop loop = new ForeachLoop(arrayVarTree, loopBodyTree,
memberVarName, loopCountVarName, annotations);
loop.validateAnnotations(context);
loop.unroll = unrollFactor;
loop.splitDegree = splitDegree;
return loop;
}
private void validateAnnotations(Context context)
throws InvalidAnnotationException {
for (String annotation: annotations) {
if (!annotation.equals(Annotations.LOOP_SYNC) &&
!annotation.equals(Annotations.LOOP_ASYNC) &&
!annotation.equals(Annotations.LOOP_NOSPLIT)) {
throw new InvalidAnnotationException(context, "Invalid loop"
+ "annotation @" + annotation);
}
}
if (annotations.contains(Annotations.LOOP_SYNC) &&
annotations.contains(Annotations.LOOP_ASYNC)) {
throw new InvalidAnnotationException(context, "Contradictory "
+ " loop annotations");
}
}
/**
* returns true for the special case of foreach where we're iterating over a
* range bounded by integer values e.g. foreach x in [1:10] { ... } or foreach
* x, i in [f():g():h()] { ... }
*
* @return true if it is a range foreach loop
*/
public boolean iteratesOverRange() {
return arrayVarTree.getType() == ExMParser.ARRAY_RANGE;
}
public Type findArrayType(Context context)
throws UserException {
Type arrayType = TypeChecker.findSingleExprType(context, arrayVarTree);
if (!Types.isArray(arrayType) && !Types.isArrayRef(arrayType)) {
throw new TypeMismatchException(context,
"Expected array type in expression for foreach loop");
}
return arrayType;
}
/**
* Initialize the context and define the two variables: for array member and
* (optionally) for the loop count
*
* @param context
* @return
* @throws UserException
*/
public Context setupLoopBodyContext(Context context)
throws UserException {
// Set up the context for the loop body with loop variables
loopBodyContext = new LocalContext(context);
if (loopCountVarName != null) {
loopCountVal = context.createLocalValueVariable(Types.V_INT,
loopCountVarName);
} else {
loopCountVal = null;
}
Type arrayType = findArrayType(context);
memberVar = loopBodyContext.declareVariable(
Types.getArrayMemberType(arrayType), getMemberVarName(),
VarStorage.STACK, DefType.LOCAL_USER, null);
return loopBodyContext;
}
} |
package cz.zcu.kiv.mobile.logger.data.database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import cz.zcu.kiv.mobile.logger.data.database.exceptions.DatabaseException;
import cz.zcu.kiv.mobile.logger.data.database.exceptions.EntryNotFoundException;
import cz.zcu.kiv.mobile.logger.data.types.Gender;
import cz.zcu.kiv.mobile.logger.data.types.Profile;
public class ProfileTable extends ATable<ProfileTable.ProfileDataObserver> {
private static final String TAG = ProfileTable.class.getSimpleName();
public static final String TABLE_NAME = "profiles";
public static final String COLUMN_PROFILE_NAME = "profile_name";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_SURNAME = "surname";
public static final String COLUMN_BIRTH_DATE = "birth_date";
public static final String COLUMN_GENDER = "gender";
public static final String COLUMN_HEIGHT = "height";
public static final String COLUMN_ACTIVITY_LEVEL = "activity_level";
public static final String COLUMN_LIFETIME_ATHLETE = "lifetime_athlete";
public static final String COLUMN_EEGBASE_PASSWORD = "eegbase_password";
private static final String[] COLUMNS_PROFILES_ALL = new String[]{COLUMN_ID, COLUMN_PROFILE_NAME, COLUMN_EMAIL, COLUMN_NAME, COLUMN_SURNAME, COLUMN_BIRTH_DATE, COLUMN_GENDER, COLUMN_HEIGHT, COLUMN_ACTIVITY_LEVEL, COLUMN_LIFETIME_ATHLETE, COLUMN_EEGBASE_PASSWORD};
private static final String[] COLUMNS_PROFILE_NAMES = new String[]{COLUMN_ID, COLUMN_PROFILE_NAME};
private static final String WHERE_EMAIL = COLUMN_EMAIL + " = ? ";
private static final String ORDER_PROFILES_ALL_ASC = COLUMN_PROFILE_NAME + " ASC";
public ProfileTable(SQLiteOpenHelper openHelper) {
super(openHelper);
}
@Override
void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_PROFILE_NAME + " TEXT NOT NULL UNIQUE,"
+ COLUMN_EMAIL + " TEXT NULL UNIQUE,"
+ COLUMN_NAME + " TEXT NULL,"
+ COLUMN_SURNAME + " TEXT NULL,"
+ COLUMN_BIRTH_DATE + " INTEGER NOT NULL,"
+ COLUMN_GENDER + " TEXT NOT NULL,"
+ COLUMN_HEIGHT + " INTEGER NOT NULL,"
+ COLUMN_ACTIVITY_LEVEL + " INTEGER NOT NULL,"
+ COLUMN_LIFETIME_ATHLETE + " INTEGER NOT NULL,"
+ COLUMN_EEGBASE_PASSWORD + " TEXT NULL"
+ ");");
}
@Override
void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
int upgradeVersion = oldVersion;
if(upgradeVersion != currentVersion){
Log.d(TAG, "Wasn't able to upgrade the database. Wiping and rebuilding...");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public long createProfile(Profile profile) throws DatabaseException {
SQLiteDatabase db = getDatabase();
ContentValues values = getContentValues(profile);
try{
long id = db.insertOrThrow(TABLE_NAME, null, values);
profile.setId(id);
for (ProfileDataObserver o : observers) {
o.onProfileAdded(id);
}
return id;
}
catch(Exception e){
throw handleException(e);
}
}
public void updateProfile(Profile profile) throws DatabaseException {
SQLiteDatabase db = getDatabase();
long profileID = profile.getId();
ContentValues values = getContentValues(profile);
try{
db.update(TABLE_NAME, values, WHERE_ID, new String[]{String.valueOf(profileID)});
for (ProfileDataObserver o : observers) {
o.onProfileUpdated(profileID);
}
}
catch(Exception e){
throw handleException(e);
}
}
public void deleteProfile(long profileID) throws DatabaseException {
SQLiteDatabase db = getDatabase();
try{
db.delete(TABLE_NAME, WHERE_ID, new String[]{String.valueOf(profileID)});
for (ProfileDataObserver o : observers) {
o.onProfileDeleted(profileID);
}
}
catch(Exception e){
throw handleException(e);
}
}
public Cursor getProfileNames() throws DatabaseException {
SQLiteDatabase db = getDatabase();
try{
return db.query(TABLE_NAME, COLUMNS_PROFILE_NAMES, null, null, null, null, ORDER_PROFILES_ALL_ASC);
}
catch(Exception e){
throw handleException(e);
}
}
public Profile getProfile(long profileID) throws DatabaseException {
SQLiteDatabase db = getDatabase();
Cursor c = null;
try{
c = db.query(TABLE_NAME, COLUMNS_PROFILES_ALL, WHERE_ID, new String[]{String.valueOf(profileID)}, null, null, null);
if(c.getCount() == 1){
c.moveToFirst();
return readProfile(c);
}
else {
throw new EntryNotFoundException("Failed to get entry with given ID: ID=" + profileID + ", row count=" + c.getCount());
}
}
catch(Exception e){
throw handleException(e);
}
}
public Profile getProfile(String email) throws DatabaseException {
SQLiteDatabase db = getDatabase();
Cursor c = null;
try{
c = db.query(TABLE_NAME, COLUMNS_PROFILES_ALL, WHERE_EMAIL, new String[]{email}, null, null, null);
if(c.getCount() == 1) {
c.moveToFirst();
return readProfile(c);
}
else {
throw new EntryNotFoundException("Failed to get entry with given email: email=" + email + ", row count=" + c.getCount());
}
}
catch(Exception e){
throw handleException(e);
}
}
private Profile readProfile(Cursor c) {
return new Profile(
getLong(c, COLUMN_ID),
getString(c, COLUMN_PROFILE_NAME),
getString(c, COLUMN_EMAIL),
getString(c, COLUMN_NAME),
getString(c, COLUMN_SURNAME),
getCalendar(c, COLUMN_BIRTH_DATE),
Gender.fromLetter(getString(c, COLUMN_GENDER)),
getInt(c, COLUMN_HEIGHT),
getInt(c, COLUMN_ACTIVITY_LEVEL),
getBoolean(c, COLUMN_LIFETIME_ATHLETE),
getString(c, COLUMN_EEGBASE_PASSWORD));
}
private ContentValues getContentValues(Profile profile) {
ContentValues values = new ContentValues(10);
values.put(COLUMN_PROFILE_NAME, profile.getProfileName());
values.put(COLUMN_EMAIL, profile.getEmail());
values.put(COLUMN_NAME, profile.getName());
values.put(COLUMN_SURNAME, profile.getSurname());
values.put(COLUMN_BIRTH_DATE, profile.getBirthDate().getTimeInMillis());
values.put(COLUMN_GENDER, profile.getGender().getLetter());
values.put(COLUMN_HEIGHT, profile.getHeight());
values.put(COLUMN_ACTIVITY_LEVEL, profile.getActivityLevel());
values.put(COLUMN_LIFETIME_ATHLETE, profile.isLifetimeAthlete() ? VALUE_TRUE : VALUE_FALSE);
values.put(COLUMN_EEGBASE_PASSWORD, profile.getEegbasePassword());
return values;
}
public interface ProfileDataObserver {
void onProfileAdded(long id);
void onProfileUpdated(long profileID);
void onProfileDeleted(long profileID);
}
} |
package de.endrullis.idea.postfixtemplates.language;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.testFramework.LightVirtualFile;
import de.endrullis.idea.postfixtemplates.language.psi.CptFile;
import de.endrullis.idea.postfixtemplates.language.psi.CptMapping;
import de.endrullis.idea.postfixtemplates.language.psi.CptTemplate;
import de.endrullis.idea.postfixtemplates.languages.SupportedLanguages;
import de.endrullis.idea.postfixtemplates.settings.*;
import de.endrullis.idea.postfixtemplates.utils.Tuple2;
import lombok.val;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static de.endrullis.idea.postfixtemplates.utils.CollectionUtils._List;
import static de.endrullis.idea.postfixtemplates.utils.StringUtils.replace;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
@SuppressWarnings("WeakerAccess")
public class CptUtil {
public static final String PLUGIN_ID = "de.endrullis.idea.postfixtemplates";
private static String templatesPathString = null;
public static Project findProject(PsiElement element) {
PsiFile containingFile = element.getContainingFile();
if (containingFile == null) {
if (!element.isValid()) {
return null;
}
} else if (!containingFile.isValid()) {
return null;
}
return (containingFile == null ? element : containingFile).getProject();
}
public static List<CptMapping> findMappings(Project project, String key) {
List<CptMapping> result = null;
val virtualFiles = FileTypeIndex.getFiles(CptFileType.INSTANCE, GlobalSearchScope.allScope(project));
/*
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
GlobalSearchScope.allScope(project));
*/
for (VirtualFile virtualFile : virtualFiles) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
if (cptFile != null) {
CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
if (mappings != null) {
for (CptMapping mapping : mappings) {
if (key.equals(mapping.getMatchingClassName())) {
if (result == null) {
result = new ArrayList<>();
}
result.add(mapping);
}
}
}
}
}
return result != null ? result : Collections.emptyList();
}
public static List<CptMapping> findMappings(Project project) {
List<CptMapping> result = new ArrayList<>();
val virtualFiles = FileTypeIndex.getFiles(CptFileType.INSTANCE, GlobalSearchScope.allScope(project));
/*
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
GlobalSearchScope.allScope(project));
*/
for (VirtualFile virtualFile : virtualFiles) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
if (cptFile != null) {
CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
if (mappings != null) {
Collections.addAll(result, mappings);
}
}
}
return result;
}
/**
* Returns the predefined plugin templates for the given language.
*
* @param language programming language
* @return predefined plugin templates for the given language
*/
public static String getDefaultTemplates(String language) {
InputStream stream = CptUtil.class.getResourceAsStream("defaulttemplates/" + language + ".postfixTemplates");
return getContent(stream);
}
/**
* Returns the content of the given file.
*
* @param file file
* @return content of the given file
* @throws FileNotFoundException
*/
public static String getContent(@NotNull File file) throws FileNotFoundException {
return getContent(new FileInputStream(file));
}
/**
* Returns the content of the given input stream.
*
* @param stream input stream
* @return content of the given input stream
*/
private static String getContent(@NotNull InputStream stream) {
StringBuilder sb = new StringBuilder();
// convert system newlines into UNIX newlines, because IDEA works only with UNIX newlines
try (BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) {
String line;
while ((line = in.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* Returns the path of the CPT plugin settings directory.
*
* @return path of the CPT plugin settings directory
*/
public static File getPluginPath() {
File path = PluginManager.getPlugin(PluginId.getId(CptUtil.PLUGIN_ID)).getPath();
if (path.getName().endsWith(".jar")) {
path = new File(path.getParentFile(), path.getName().substring(0, path.getName().length() - 4));
}
return path;
}
/**
* Returns the path "$CPT_PLUGIN_SETTINGS/templates".
*
* @return path "$CPT_PLUGIN_SETTINGS/templates"
*/
public static File getTemplatesPath() {
return new File(getPluginPath(), "templates");
}
public static String getTemplatesPathString() {
if (templatesPathString != null) {
templatesPathString = getTemplatesPath().getAbsolutePath().replace('\\', '/');
}
return templatesPathString;
}
@Deprecated
public static void createTemplateFile(@NotNull String language, String content) {
File file = new File(CptUtil.getTemplatesPath(), language + ".postfixTemplates");
//noinspection ResultOfMethodCallIgnored
file.getParentFile().mkdirs();
try (PrintStream out = new PrintStream(file, "UTF-8")) {
out.println(content);
} catch (FileNotFoundException e) {
throw new RuntimeException(language + " template file could not copied to " + file.getAbsolutePath(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 not supported", e);
}
}
public static void moveOldTemplateFile(@NotNull String language) {
if (SupportedLanguages.supportedLanguageIds.contains(language.toLowerCase())) {
File file = new File(CptUtil.getTemplatesPath(), language + ".postfixTemplates");
if (file.exists()) {
// move file to new position
val newFile = getTemplateFile(language, "oldUserTemplates");
file.renameTo(newFile);
}
}
}
public static File getTemplateFile(@NotNull String language, @NotNull String fileName) {
val path = getTemplateDir(language);
return new File(path, fileName + ".postfixTemplates");
}
@NotNull
public static File getTemplateDir(@NotNull String language) {
final File dir = new File(getTemplatesPath(), language);
if (!dir.exists()) {
//noinspection ResultOfMethodCallIgnored
dir.mkdirs();
}
return dir;
}
@NotNull
public static File getWebTemplatesInfoFile() {
return new File(getTemplatesPath(), "webTemplateFiles.yaml");
}
public static List<File> getTemplateFiles(@NotNull String language) {
return getTemplateFiles(language, f -> f.enabled);
}
public static List<File> getEditableTemplateFiles(@NotNull String language) {
return getTemplateFiles(language, f -> f.enabled && f.url == null);
}
public static List<File> getTemplateFiles(@NotNull String language, Predicate<CptPluginSettings.VFile> fileFilter) {
if (SupportedLanguages.supportedLanguageIds.contains(language.toLowerCase())) {
// eventually move old templates file to new directory
moveOldTemplateFile(language);
val filesFromDir = getTemplateFilesFromLanguageDir(language);
val settings = CptApplicationSettings.getInstance().getPluginSettings();
val vFiles = settings.getLangName2virtualFile().getOrDefault(language, new ArrayList<>());
val allFilesFromConfig = vFiles.stream().map(f -> f.file).collect(Collectors.toSet());
val enabledFilesFromConfig = vFiles.stream().filter(fileFilter).map(f -> new File(f.file)).filter(f -> f.exists()).collect(Collectors.toList());
val remainingTemplateFilesFromDir = Arrays.stream(filesFromDir).filter(f -> !allFilesFromConfig.contains(f.getAbsolutePath()));
// templateFilesFromConfig + remainingTemplateFilesFromDir
return Stream.concat(remainingTemplateFilesFromDir, enabledFilesFromConfig.stream()).collect(Collectors.toList());
} else {
return _List();
}
}
@NotNull
public static File[] getTemplateFilesFromLanguageDir(@NotNull String language) {
final File[] files = getTemplateDir(language).listFiles(f -> f.getName().endsWith(".postfixTemplates"));
if (files == null) {
return new File[0];
}
return files;
}
@Nullable
public static CptLang getLanguageOfTemplateFile(@NotNull VirtualFile vFile) {
val name = vFile.getNameWithoutExtension();
return Optional.ofNullable(
SupportedLanguages.getCptLang(name)
).orElseGet(() -> {
return SupportedLanguages.getCptLang(getAbsoluteVirtualFile(vFile).getParent().getName());
});
}
@NotNull
public static String getPath(@NotNull VirtualFile vFile) {
return getAbsoluteVirtualFile(vFile).getPath().replace('\\', '/');
}
@NotNull
public static VirtualFile getAbsoluteVirtualFile(@NotNull VirtualFile vFile) {
if (vFile instanceof LightVirtualFile) {
vFile = ((LightVirtualFile) vFile).getOriginalFile();
}
return vFile;
}
public static void openFileInEditor(@NotNull Project project, @NotNull File file) {
VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (vFile == null) {
vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
}
assert vFile != null;
openFileInEditor(project, vFile);
}
public static void openFileInEditor(@NotNull Project project, @NotNull VirtualFile vFile) {
// open templates file in an editor
final OpenFileDescriptor openFileDescriptor = new OpenFileDescriptor(project, vFile);
openFileDescriptor.navigate(true);
//EditorFactory.getInstance().createViewer(document, project);
}
public static Project getActiveProject() {
DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult();
return DataKeys.PROJECT.getData(dataContext);
}
public static void openPluginSettings(Project project) {
ShowSettingsUtil.getInstance().showSettingsDialog(project, CptPluginConfigurable.class);
}
public static boolean isTemplateFile(@NotNull VirtualFile vFile, @NotNull String language) {
val settings = CptApplicationSettings.getInstance().getPluginSettings();
val path = getPath(vFile);
val lang = settings.getFile2langName().get(path);
return lang != null && lang.equals(language);
}
public static boolean isActiveTemplateFile(@NotNull VirtualFile vFile) {
val path = getPath(vFile);
return path.startsWith(getTemplatesPathString());
}
@Nullable
public static Tuple2<String, CptPluginSettings.VFile> getLangAndVFile(@NotNull VirtualFile vFile) {
val settings = CptApplicationSettings.getInstance().getPluginSettings();
val path = getPath(vFile);
return settings.getFile2langAndVFile().get(path);
}
public static void processTemplates(Project project, VirtualFile vFile, BiConsumer<CptTemplate, CptMapping> action) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(vFile);
if (cptFile != null) {
CptTemplate[] cptTemplates = PsiTreeUtil.getChildrenOfType(cptFile, CptTemplate.class);
if (cptTemplates != null) {
for (CptTemplate cptTemplate : cptTemplates) {
for (CptMapping mapping : cptTemplate.getMappings().getMappingList()) {
action.accept(cptTemplate, mapping);
}
}
}
}
}
private static String applyReplacements(String templatesText, boolean preFilled) {
final String[] finalTemplatesText = new String[]{templatesText};
new BufferedReader(new InputStreamReader(
CptUtil.class.getResourceAsStream("templatemapping/" + (preFilled ? "var" : "empty") + "Lambda.txt")
)).lines().filter(l -> l.contains("→")).forEach(line -> {
String[] split = line.split("→");
finalTemplatesText[0] = replace(finalTemplatesText[0], split[0].trim(), split[1].trim());
});
return finalTemplatesText[0];
}
/** Downloads/updates the web template info file. */
public static void downloadWebTemplatesInfoFile() throws IOException {
URL url = new URL("https://raw.githubusercontent.com/xylo/intellij-postfix-templates/master/templates/webTemplateFiles.yaml");
val tmpFile = File.createTempFile("idea.cpt.webtemplates", null);
val content = getContent(url.openStream());
try (BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile))) {
writer.write(content);
}
Files.move(tmpFile.toPath(), getWebTemplatesInfoFile().toPath(), REPLACE_EXISTING);
}
/**
* Downloads/updates the given web template file.
*
* @return true if the file is new
*/
public static boolean downloadWebTemplateFile(CptVirtualFile cptVirtualFile) throws IOException {
val preFilled = CptApplicationSettings.getInstance().getPluginSettings().isVarLambdaStyle();
val tmpFile = File.createTempFile("idea.cpt." + cptVirtualFile.getName(), null);
val content = applyReplacements(getContent(cptVirtualFile.getUrl().openStream()), preFilled);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile))) {
writer.write(content);
}
//Arrays.equals(Files.readAllBytes(tmpFile.toPath()), Files.readAllBytes(cptVirtualFile.getFile().toPath()));
boolean isNew = !cptVirtualFile.getFile().exists();
Files.move(tmpFile.toPath(), cptVirtualFile.getFile().toPath(), REPLACE_EXISTING);
if (cptVirtualFile.getId() != null) {
cptVirtualFile.getFile().setReadOnly();
}
return isNew;
}
public static WebTemplateFile[] loadWebTemplateFiles() {
// download the web templates file only once a day
if (!getWebTemplatesInfoFile().exists() || new Date().getTime() - getWebTemplatesInfoFile().lastModified() > 1000*60*60*24) {
try {
downloadWebTemplatesInfoFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
return WebTemplateFileLoader.load(getWebTemplatesInfoFile());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@NotNull
public static VirtualFile getVirtualFile(@NotNull PsiElement element) {
return element.getContainingFile().getViewProvider().getVirtualFile();
}
} |
package de.lmu.ifi.dbs.elki.algorithm.itemsetmining;
import gnu.trove.iterator.TLongIntIterator;
import gnu.trove.map.hash.TLongIntHashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.data.BitVector;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.data.type.VectorFieldTypeInformation;
import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.ids.DBIDIter;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.database.relation.RelationUtil;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.logging.statistics.Duration;
import de.lmu.ifi.dbs.elki.result.AprioriResult;
import de.lmu.ifi.dbs.elki.utilities.BitsUtil;
import de.lmu.ifi.dbs.elki.utilities.documentation.Description;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.documentation.Title;
import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.OneMustBeSetGlobalConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.OnlyOneIsAllowedToBeSetGlobalConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter;
/**
* Provides the APRIORI algorithm for Mining Association Rules.
* <p>
* Reference: <br>
* R. Agrawal, R. Srikant: Fast Algorithms for Mining Association Rules in Large
* Databases. <br>
* In Proc. 20th Int. Conf. on Very Large Data Bases (VLDB '94), Santiago de
* Chile, Chile 1994.
* </p>
*
* @author Arthur Zimek
* @author Erich Schubert
*
* @apiviz.has Itemset
* @apiviz.uses BitVector
*/
@Title("APRIORI: Algorithm for Mining Association Rules")
@Description("Searches for frequent itemsets")
@Reference(authors = "R. Agrawal, R. Srikant", title = "Fast Algorithms for Mining Association Rules in Large Databases", booktitle = "Proc. 20th Int. Conf. on Very Large Data Bases (VLDB '94), Santiago de Chile, Chile 1994", url = "http:
public class APRIORI extends AbstractAlgorithm<AprioriResult> {
/**
* The logger for this class.
*/
private static final Logging LOG = Logging.getLogger(APRIORI.class);
/**
* Optional parameter to specify the threshold for minimum frequency, must be
* a double greater than or equal to 0 and less than or equal to 1.
* Alternatively to parameter {@link #MINSUPP_ID}).
*/
public static final OptionID MINFREQ_ID = new OptionID("apriori.minfreq", "Threshold for minimum frequency as percentage value " + "(alternatively to parameter apriori.minsupp).");
/**
* Parameter to specify the threshold for minimum support as minimally
* required number of transactions, must be an integer equal to or greater
* than 0. Alternatively to parameter {@link #MINFREQ_ID} - setting
* {@link #MINSUPP_ID} is slightly preferable over setting {@link #MINFREQ_ID}
* in terms of efficiency.
*/
public static final OptionID MINSUPP_ID = new OptionID("apriori.minsupp", "Threshold for minimum support as minimally required number of transactions " + "(alternatively to parameter apriori.minfreq" + " - setting apriori.minsupp is slightly preferable over setting " + "apriori.minfreq in terms of efficiency).");
/**
* Holds the value of {@link #MINFREQ_ID}.
*/
private double minfreq = Double.NaN;
/**
* Holds the value of {@link #MINSUPP_ID}.
*/
private int minsupp = Integer.MIN_VALUE;
/**
* Constructor with minimum frequency.
*
* @param minfreq Minimum frequency
*/
public APRIORI(double minfreq) {
super();
this.minfreq = minfreq;
}
/**
* Constructor with minimum support.
*
* @param minsupp Minimum support
*/
public APRIORI(int minsupp) {
super();
this.minsupp = minsupp;
}
/**
* Performs the APRIORI algorithm on the given database.
*
* @param relation the Relation to process
* @return the AprioriResult learned by this APRIORI
*/
public AprioriResult run(Relation<BitVector> relation) {
DBIDs ids = relation.getDBIDs();
List<Itemset> solution = new ArrayList<>();
final int size = ids.size();
final int needed = (minfreq >= 0.) ? (int) Math.ceil(minfreq * size) : minsupp;
// TODO: we don't strictly require a vector field.
// We could work with knowing just the maximum dimensionality beforehand.
VectorFieldTypeInformation<BitVector> meta = RelationUtil.assumeVectorField(relation);
if(size > 0) {
final int dim = meta.getDimensionality();
Duration timeone = LOG.newDuration("apriori.1-items.time");
timeone.begin();
List<OneItemset> oneitems = buildFrequentOneItemsets(relation, dim, needed);
timeone.end();
LOG.statistics(timeone);
if(LOG.isVerbose()) {
StringBuilder msg = new StringBuilder();
msg.append("1-frequentItemsets (itemsets: ").append(oneitems.size())
.append(") (transactions: ").append(ids.size()).append(")");
if(LOG.isDebuggingFine()) {
debugDumpCandidates(msg, oneitems, meta);
}
msg.append('\n');
LOG.verbose(msg);
}
solution.addAll(oneitems);
if(oneitems.size() >= 2) {
Duration timetwo = LOG.newDuration("apriori.2-items.time");
timetwo.begin();
ArrayModifiableDBIDs survivors = DBIDUtil.newArray(ids.size());
List<? extends Itemset> candidates = buildFrequentTwoItemsets(oneitems, relation, dim, needed, ids, survivors);
ids = survivors; // Continue with reduced set of transactions.
timetwo.end();
LOG.statistics(timetwo);
if(LOG.isVerbose()) {
StringBuilder msg = new StringBuilder();
msg.append("2-frequentItemsets (itemsets: ").append(candidates.size())
.append(") (transactions: ").append(ids.size()).append(")");
if(LOG.isDebuggingFine()) {
debugDumpCandidates(msg, candidates, meta);
}
msg.append('\n');
LOG.verbose(msg);
}
solution.addAll(candidates);
for(int length = 3; candidates.size() >= length; length++) {
StringBuilder msg = LOG.isVerbose() ? new StringBuilder() : null;
Duration timel = LOG.newDuration("apriori." + length + "-items.time");
// Join to get the new candidates
timel.begin();
candidates = aprioriGenerate(candidates, length, dim);
if(msg != null) {
if(length > 2 && LOG.isDebuggingFinest()) {
msg.append(length).append("-candidates after pruning (").append(candidates.size()).append(")");
debugDumpCandidates(msg, candidates, meta);
}
}
survivors = DBIDUtil.newArray(ids.size());
candidates = frequentItemsets(candidates, relation, needed, ids, survivors);
ids = survivors; // Continue with reduced set of transactions.
timel.end();
LOG.statistics(timel);
if(msg != null) {
msg.append(length).append("-frequentItemsets (itemsets: ").append(candidates.size())
.append(") (transactions: ").append(ids.size()).append(")");
if(LOG.isDebuggingFine()) {
debugDumpCandidates(msg, candidates, meta);
}
LOG.verbose(msg.toString());
}
solution.addAll(candidates);
}
}
}
return new AprioriResult("APRIORI", "apriori", solution, meta);
}
/**
* Build the 1-itemsets.
*
* @param relation Data relation
* @param dim Maximum dimensionality
* @param needed Minimum support needed
* @return 1-itemsets
*/
protected List<OneItemset> buildFrequentOneItemsets(final Relation<BitVector> relation, final int dim, final int needed) {
// TODO: use TIntList and prefill appropriately to avoid knowing "dim"
// beforehand?
int[] counts = new int[dim];
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
BitVector bv = relation.get(iditer);
long[] bits = bv.getBits();
for(int i = BitsUtil.nextSetBit(bits, 0); i >= 0; i = BitsUtil.nextSetBit(bits, i + 1)) {
counts[i]++;
}
}
// Generate initial candidates of length 1.
List<OneItemset> candidates = new ArrayList<>(dim);
for(int i = 0; i < dim; i++) {
if(counts[i] >= needed) {
candidates.add(new OneItemset(i, counts[i]));
}
}
return candidates;
}
/**
* Build the 2-itemsets.
*
* @param oneitems Frequent 1-itemsets
* @param relation Data relation
* @param dim Maximum dimensionality
* @param needed Minimum support needed
* @param ids Objects to process
* @param survivors Output: objects that had at least two 1-frequent items.
* @return Frequent 2-itemsets
*/
protected List<SparseItemset> buildFrequentTwoItemsets(List<OneItemset> oneitems, final Relation<BitVector> relation, final int dim, final int needed, DBIDs ids, ArrayModifiableDBIDs survivors) {
int f1 = 0;
long[] mask = BitsUtil.zero(dim);
for(OneItemset supported : oneitems) {
BitsUtil.setI(mask, supported.item);
f1++;
}
// We quite aggressively size the map, assuming that almost each combination
// is present somewhere. If this won't fit into memory, we're likely running
// OOM somewhere later anyway!
TLongIntHashMap map = new TLongIntHashMap((f1 * (f1 - 1)) >> 1);
final long[] scratch = BitsUtil.zero(dim);
for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
long[] bv = relation.get(iditer).getBits();
for(int i = 0; i < scratch.length; i++) {
scratch[i] = (i < bv.length) ? (mask[i] & bv[i]) : 0L;
}
boolean lives = false;
for(int i = BitsUtil.nextSetBit(scratch, 0); i >= 0; i = BitsUtil.nextSetBit(scratch, i + 1)) {
for(int j = BitsUtil.nextSetBit(scratch, i + 1); j >= 0; j = BitsUtil.nextSetBit(scratch, j + 1)) {
long key = (((long) i) << 32) | j;
map.put(key, 1 + map.get(key));
lives = true;
}
}
if(lives) {
survivors.add(iditer);
}
}
// Generate candidates of length 2.
List<SparseItemset> candidates = new ArrayList<>(f1 * (int) Math.sqrt(f1));
for(TLongIntIterator iter = map.iterator(); iter.hasNext();) {
iter.advance(); // Trove style iterator - advance first.
if(iter.value() >= needed) {
int ii = (int) (iter.key() >>> 32);
int ij = (int) (iter.key() & -1L);
candidates.add(new SparseItemset(new int[] { ii, ij }, iter.value()));
}
}
// The hashmap may produce them out of order.
Collections.sort(candidates);
return candidates;
}
/**
* Returns the frequent BitSets out of the given BitSets with respect to the
* given database.
*
* @param support Support map.
* @param candidates the candidates to be evaluated
* @param relation the database to evaluate the candidates on
* @param needed Minimum support needed
* @param ids Objects to process
* @param survivors Output: objects that had at least two 1-frequent items.
* @return Itemsets with sufficient support
*/
protected List<? extends Itemset> frequentItemsets(List<? extends Itemset> candidates, Relation<BitVector> relation, int needed, DBIDs ids, ArrayModifiableDBIDs survivors) {
for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
BitVector bv = relation.get(iditer);
// TODO: exploit that the candidate set it sorted?
boolean lives = false;
for(Itemset candidate : candidates) {
if(candidate.containedIn(bv)) {
candidate.increaseSupport();
lives = true;
}
}
if(lives) {
survivors.add(iditer);
}
}
// Retain only those with minimum support:
List<Itemset> supported = new ArrayList<>(candidates.size());
for(Iterator<? extends Itemset> iter = candidates.iterator(); iter.hasNext();) {
final Itemset candidate = iter.next();
if(candidate.getSupport() >= needed) {
supported.add(candidate);
}
}
return supported;
}
/**
* Prunes a given set of candidates to keep only those BitSets where all
* subsets of bits flipping one bit are frequent already.
*
* @param supported Support map
* @param length Itemset length
* @param dim Dimensionality
* @return itemsets that cannot be pruned by apriori
*/
protected List<Itemset> aprioriGenerate(List<? extends Itemset> supported, int length, int dim) {
List<Itemset> candidateList = new ArrayList<>();
if(supported.size() <= 0) {
return candidateList;
}
Itemset ref = supported.get(0);
if(ref instanceof SparseItemset) {
// TODO: we currently never switch to DenseItemSet. This may however be
// beneficial when we have few dimensions and many candidates.
// E.g. when length > 32 and dim < 100. But this needs benchmarking!
// For length < 5 and dim > 3000, SparseItemset unsurprisingly was faster
// Scratch item to use for searching.
SparseItemset scratch = new SparseItemset(new int[length - 1]);
final int ssize = supported.size();
for(int i = 0; i < ssize; i++) {
SparseItemset ii = (SparseItemset) supported.get(i);
prefix: for(int j = i + 1; j < ssize; j++) {
SparseItemset ij = (SparseItemset) supported.get(j);
if(!ii.prefixTest(ij)) {
break prefix; // Prefix doesn't match
}
// Test subsets (re-) using scratch object
System.arraycopy(ii.indices, 1, scratch.indices, 0, length - 2);
scratch.indices[length - 2] = ij.indices[length - 2];
for(int k = length - 3; k >= 0; k
scratch.indices[k] = ii.indices[k + 1];
int pos = Collections.binarySearch(supported, scratch);
if(pos < 0) {
// Prefix was okay, but one other subset was not frequent
continue prefix;
}
}
int[] items = new int[length];
System.arraycopy(ii.indices, 0, items, 0, length - 1);
items[length - 1] = ij.indices[length - 2];
candidateList.add(new SparseItemset(items));
}
}
return candidateList;
}
if(ref instanceof DenseItemset) {
// Scratch item to use for searching.
DenseItemset scratch = new DenseItemset(BitsUtil.zero(dim), length - 1);
final int ssize = supported.size();
for(int i = 0; i < ssize; i++) {
DenseItemset ii = (DenseItemset) supported.get(i);
prefix: for(int j = i + 1; j < ssize; j++) {
DenseItemset ij = (DenseItemset) supported.get(j);
// Prefix test via "|i1 ^ i2| = 2"
System.arraycopy(ii.items, 0, scratch.items, 0, ii.items.length);
BitsUtil.xorI(scratch.items, ij.items);
if(BitsUtil.cardinality(scratch.items) != 2) {
break prefix; // No prefix match; since sorted, no more can follow!
}
// Ensure that the first difference is the last item in ii:
int first = BitsUtil.nextSetBit(scratch.items, 0);
if(BitsUtil.nextSetBit(ii.items, first + 1) > -1) {
break prefix; // Different overlap by chance?
}
BitsUtil.orI(scratch.items, ij.items);
// Test subsets.
for(int l = length, b = BitsUtil.nextSetBit(scratch.items, 0); l > 2; l--, b = BitsUtil.nextSetBit(scratch.items, b + 1)) {
BitsUtil.clearI(scratch.items, b);
int pos = Collections.binarySearch(supported, scratch);
if(pos < 0) {
continue prefix;
}
BitsUtil.setI(scratch.items, b);
}
candidateList.add(new DenseItemset(scratch.items.clone(), length));
}
}
return candidateList;
}
throw new AbortException("Unexpected itemset type " + ref.getClass());
}
/**
* Debug method: output all itemsets.
*
* @param msg Output buffer
* @param candidates Itemsets to dump
* @param meta Metadata for item labels
*/
private void debugDumpCandidates(StringBuilder msg, List<? extends Itemset> candidates, VectorFieldTypeInformation<BitVector> meta) {
msg.append(':');
for(Itemset itemset : candidates) {
msg.append(" [");
itemset.appendTo(msg, meta);
msg.append(']');
}
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return TypeUtil.array(TypeUtil.BIT_VECTOR_FIELD);
}
@Override
protected Logging getLogger() {
return LOG;
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer extends AbstractParameterizer {
/**
* Parameter for minFreq.
*/
protected Double minfreq = null;
/**
* Parameter for minSupp.
*/
protected Integer minsupp = null;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
DoubleParameter minfreqP = new DoubleParameter(MINFREQ_ID);
minfreqP.setOptional(true);
minfreqP.addConstraint(CommonConstraints.GREATER_EQUAL_ZERO_DOUBLE);
minfreqP.addConstraint(CommonConstraints.LESS_EQUAL_ONE_DOUBLE);
if(config.grab(minfreqP)) {
minfreq = minfreqP.getValue();
}
IntParameter minsuppP = new IntParameter(MINSUPP_ID);
minsuppP.setOptional(true);
minsuppP.addConstraint(CommonConstraints.GREATER_EQUAL_ZERO_INT);
if(config.grab(minsuppP)) {
minsupp = minsuppP.getValue();
}
// global parameter constraints
config.checkConstraint(new OnlyOneIsAllowedToBeSetGlobalConstraint(minfreqP, minsuppP));
config.checkConstraint(new OneMustBeSetGlobalConstraint(minfreqP, minsuppP));
}
@Override
protected APRIORI makeInstance() {
if(minfreq != null) {
return new APRIORI(minfreq);
}
if(minsupp != null) {
return new APRIORI(minsupp);
}
return null;
}
}
} |
package scala.tools.scaladoc;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import ch.epfl.lamp.util.Pair;
import scalac.Global;
import scalac.symtab.Scope;
import scalac.symtab.Scope.SymbolIterator;
import scalac.symtab.Symbol;
import scalac.symtab.Type;
import scalac.symtab.Modifiers;
import scalac.util.Debug;
import scalac.util.Name;
import scalac.util.NameTransformer;
import java.io.*;
import scalac.ast.printer.*;
import ch.epfl.lamp.util.SourceFile;
import scala.tools.scalac.ast.parser.Parser$class;
import scalac.Unit;
/**
* This class contains functions to retrieve information from a Scala
* library.
*/
public class ScalaSearch {
/////////////////// SYMBOLS TESTERS ////////////////////////////
/** Test if the given symbol is a class, a package, or an object.
*/
static boolean isContainer(Symbol sym) {
return sym.isClass() || sym.isModule() || sym.isPackage() || sym.isPackageClass();
}
/** Test if the given symbol has a lazy type.
*/
static boolean isLazy(Symbol sym) {
return
(sym.rawInfo() instanceof Type.LazyType) ||
((sym.rawInfo() instanceof Type.TypeRef) &&
(sym.rawInfo().symbol().rawInfo() instanceof Type.LazyType));
}
/** Test if the given symbol is private (without evaluating its type).
*/
static boolean isPrivate(Symbol sym) {
return (sym.flags & Modifiers.PRIVATE) != 0;
}
/** Test if the given symbol has been generated by the compiler.
*/
public static boolean isGenerated(Symbol sym) {
return
(sym.isSynthetic() && !sym.isRoot()) ||
(sym.name.indexOf('$') >= 0 &&
NameTransformer.decode(sym.name).equals(sym.name.toString())) ||
NameTransformer.decode(sym.name).endsWith("_=");
}
/** Test if the given symbol is an empty java module generated to
* contain static fields and methods of a java class.
*/
public static boolean isEmptyJavaModule(Symbol sym) {
return sym.isModule() && sym.isJava() && !(sym.isPackage() || sym.isPackageClass()) && (members(sym).length == 0);
}
/** Test if the given symbol is access method for a val.
*/
public static boolean isValMethod(Symbol sym) {
return (sym.isInitializedMethod() && (sym.flags & Modifiers.STABLE) != 0);
}
/** Test if the given symbol is relevant for the documentation.
*/
public static boolean isRelevant(Symbol sym) {
return !isGenerated(sym) && !isLazy(sym) && !isPrivate(sym) &&
!sym.isConstructor() &&
!sym.isCaseFactory() && !isEmptyJavaModule(sym);
}
//////////////////////// SCOPE ITERATOR //////////////////////////////
/** A symbol iterator that returns all alternatives of an overloaded symbol
* instead of the overloaded symbol itself (does not unload lazy symbols).
*/
public static class UnloadLazyIterator extends SymbolIterator {
private SymbolIterator iterator;
private Symbol[] alternatives;
private int index;
public UnloadLazyIterator(SymbolIterator iterator) {
this.iterator = iterator;
this.alternatives = null;
this.index = -1;
}
public boolean hasNext() {
return index >= 0 || iterator.hasNext();
}
public Symbol next() {
if (index >= 0) {
Symbol symbol = alternatives[index++];
if (index == alternatives.length) {
alternatives = null;
index = -1;
}
return symbol;
} else {
Symbol symbol = iterator.next();
if (isLazy(symbol))
return symbol;
else {
switch (symbol.type()) {
case OverloadedType(Symbol[] alts, _):
alternatives = alts;
index = 0;
return next();
default:
return symbol;
}
}
}
}
}
////////////////////////// TRAVERSER ///////////////////////////////
/** Function from Symbol to void.
*/
public static abstract class SymFun {
public abstract void apply(Symbol sym);
}
/** Apply a given function to all symbols below the given symbol
* in the symbol table.
*/
public static void foreach(Symbol sym, SymFun fun) {
if (isRelevant(sym)) {
fun.apply(sym);
Symbol[] members = members(sym);
for(int i = 0; i < members.length; i++)
foreach(members[i], fun);
}
}
/** Return all members of a container symbol.
*/
public static Symbol[] members(Symbol sym) {
if (isContainer(sym) && !isLazy(sym)) {
List memberList = new LinkedList();
SymbolIterator i =
new UnloadLazyIterator(sym.members().iterator(false));
while (i.hasNext()) {
Symbol member = i.next();
if (isRelevant(member))
memberList.add(member);
}
return (Symbol[]) memberList.toArray(new Symbol[memberList.size()]);
}
else
return new Symbol[0];
}
/** Apply a given function to all symbols below the given symbol
* in the symbol table.
*/
public static void foreach(Symbol sym, SymFun fun,
SymbolBooleanFunction isDocumented) {
if (isDocumented.apply(sym) && isRelevant(sym)) {
fun.apply(sym);
Symbol[] members = members(sym, isDocumented);
for(int i = 0; i < members.length; i++)
foreach(members[i], fun, isDocumented);
}
}
/** Return all members of a container symbol.
*/
public static Symbol[] members(Symbol sym,
SymbolBooleanFunction isDocumented) {
if (isContainer(sym) && !isLazy(sym)) {
List memberList = new LinkedList();
SymbolIterator i =
new UnloadLazyIterator(sym.members().iterator(false));
while (i.hasNext()) {
Symbol member = i.next();
if (isDocumented.apply(member) && isRelevant(sym))
memberList.add(member);
}
return (Symbol[]) memberList.toArray(new Symbol[memberList.size()]);
}
else
return new Symbol[0];
}
///////////////////////// COMPARATORS ///////////////////////////////
/**
* Use the simple name of symbols to order them.
*/
public static Comparator symAlphaOrder = new Comparator() {
public int compare(Object o1, Object o2) {
Symbol symbol1 = (Symbol) o1;
Symbol symbol2 = (Symbol) o2;
String name1 = symbol1.nameString();
String name2 = symbol2.nameString();
return name1.compareTo(name2);
}
public boolean equals(Object o) {
return false;
}
};
/**
* Use the fully qualified name of symbols to order them.
*/
public static Comparator symPathOrder = new Comparator() {
public int compare(Object o1, Object o2) {
int c = compare0(o1, o2);
return c;
}
public int compare0(Object o1, Object o2) {
LinkedList l1 = getOwners((Symbol)o1);
LinkedList l2 = getOwners((Symbol)o2);
for (int i = 0; true; i++) {
if (i == l1.size() || i == l2.size())
return l1.size() - l2.size();
Symbol s1 = (Symbol)l1.get(i);
Symbol s2 = (Symbol)l2.get(i);
if (s1 == s2) continue;
int c = s1.nameString().compareTo(s2.nameString());
if (c != 0) return c;
if (s1.isTerm() && s2.isType()) return -1;
if (s1.isType() && s2.isTerm()) return +1;
return s1.id - s2.id;
}
}
public boolean equals(Object o) {
return false;
}
public LinkedList getOwners(Symbol symbol) {
LinkedList owners = new LinkedList();
while (true) {
assert !symbol.isNone() && !symbol.isError();
owners.addFirst(symbol);
if (symbol.isRoot()) break;
if (symbol.isNone()) break;
if (symbol.isError()) break;
symbol = symbol.owner();
}
return owners;
}
};
///////////////////////// COLLECTORS ////////////////////////////
/**
* Returns the sorted list of packages from the root symbol.
*
* @param root
*/
public static Symbol[] getSortedPackageList(Symbol root, SymbolBooleanFunction isDocumented) {
final List packagesAcc = new LinkedList();
foreach(root,
new SymFun() {
public void apply(Symbol sym) {
if (sym.isPackage() || sym.isPackageClass())
packagesAcc.add(sym);
}
}, isDocumented);
Symbol[] packages = (Symbol[]) packagesAcc.toArray(new Symbol[packagesAcc.size()]);
Arrays.sort(packages, symPathOrder);
return packages;
}
public static Symbol[][] getSubContainerMembers(Symbol root, SymbolBooleanFunction isDocumented) {
final List objectsAcc = new LinkedList();
final List traitsAcc = new LinkedList();
final List classesAcc = new LinkedList();
foreach(root,
new SymFun() {
public void apply(Symbol sym) {
if (sym.isTrait() && !sym.isModuleClass())
traitsAcc.add(sym);
else if (sym.isClass() && !sym.isModuleClass())
classesAcc.add(sym);
else if (sym.isModule() && !(sym.isPackage() || sym.isPackageClass()))
objectsAcc.add(sym);
}
}, isDocumented
);
Symbol[] objects = (Symbol[]) objectsAcc.toArray(new Symbol[objectsAcc.size()]);
Symbol[] traits = (Symbol[]) traitsAcc.toArray(new Symbol[traitsAcc.size()]);
Symbol[] classes = (Symbol[]) classesAcc.toArray(new Symbol[classesAcc.size()]);
Arrays.sort(objects, symAlphaOrder);
Arrays.sort(traits, symAlphaOrder);
Arrays.sort(classes, symAlphaOrder);
return new Symbol[][]{ objects, traits, classes };
}
public static Symbol[][] splitMembers(Symbol[] syms) {
List fields = new LinkedList();
List methods = new LinkedList();
List objects = new LinkedList();
List traits = new LinkedList();
List classes = new LinkedList();
List packages = new LinkedList();
for (int i = 0; i < syms.length; i++) {
Symbol sym = syms[i];
if (sym.isTrait()) traits.add(sym);
else if (sym.isClass()) classes.add(sym);
else if (sym.isPackage() || sym.isPackageClass()) packages.add(sym);
else if (sym.isModule()) objects.add(sym);
else if (sym.isMethod() && !isValMethod(sym)) methods.add(sym);
else fields.add(sym);
}
return new Symbol[][] {
(Symbol[]) fields.toArray(new Symbol[fields.size()]),
(Symbol[]) methods.toArray(new Symbol[methods.size()]),
(Symbol[]) objects.toArray(new Symbol[objects.size()]),
(Symbol[]) traits.toArray(new Symbol[traits.size()]),
(Symbol[]) classes.toArray(new Symbol[classes.size()]),
(Symbol[]) packages.toArray(new Symbol[packages.size()])
};
}
public static void categorizeSymbols(List symbols, List fields, List modules, List types) {
Iterator i = symbols.iterator();
while (i.hasNext()) {
Symbol sym = (Symbol) i.next();
if (sym.isPackage() || sym.isPackageClass() || sym.isModule())
modules.add(sym);
else if (sym.isTerm())
fields.add(sym);
else
types.add(sym);
}
}
public static Symbol[] sortList(List symbols) {
Symbol[] array = (Symbol[]) symbols.toArray(new Symbol[symbols.size()]);
Arrays.sort(array, symAlphaOrder);
return array;
}
/////////////////// IMPLEMENTING CLASSES OR OBJECTS //////////////////////
/**
* Returns a hashtable which maps each class symbol to the list of
* its direct sub-classes or sub-modules. We also keep track of
* the exact involved type.
* Result type = Map<Symbol, List<Pair<Symbol, Type>>
*
* @param root
*/
public static Map subTemplates(Symbol root, SymbolBooleanFunction isDocumented) {
final Map subs = new HashMap();
foreach(root, new SymFun() { public void apply(Symbol sym) {
if (sym.isClass() || sym.isModule()) {
Type[] parents = sym.moduleClass().parents();
for (int i = 0; i < parents.length; i++) {
Symbol parentSymbol = parents[i].symbol();
List subList = (List) subs.get(parentSymbol);
if (subList == null) {
subList = new LinkedList();
subs.put(parentSymbol, subList);
}
subList.add(new Pair(sym, parents[i]));
}
}
}
}, isDocumented);
return subs;
}
//////////////////////// INDEX BUILDER /////////////////////////////
/**
* Returns the list of characters with the sorted list of
* members starting with a character.
* Result type = Pair<Character[], Map<Character, Symbol[]>>
*
* @param root
*/
public static Pair index(Symbol root, final SymbolBooleanFunction isDocumented) {
final Map index = new HashMap();
// collecting
foreach(root, new SymFun() { public void apply(Symbol sym) {
String name = sym.nameString();
if (name.length() > 0) {
char ch = Character.toUpperCase(name.charAt(0));
Character unicode = new Character(ch);
List symList = (List) index.get(unicode);
if (symList == null) {
symList = new LinkedList();
index.put(unicode, symList);
}
symList.add(sym);
}
}
}, isDocumented);
// sorting
Character[] chars = (Character[]) index.keySet()
.toArray(new Character[index.keySet().size()]);
Arrays.sort(chars);
for (int i = 0; i < chars.length; i++) {
Character car = chars[i];
List symList = (List) index.get(car);
Symbol[] syms = (Symbol[]) symList.toArray(new Symbol[symList.size()]);
Arrays.sort(syms, symAlphaOrder);
index.put(car, syms);
}
return new Pair(chars, index);
}
//////////////////////////// INHERITED MEMBERS //////////////////////////////
/**
* Finds all local and inherited members of a given class or
* object.
*
* @param sym
*/
public static Symbol[] collectMembers(Symbol sym) {
Type thistype = sym.thisType();
Name[] names = collectNames(thistype);
List/*<Symbol>*/ members = new LinkedList();
for (int i = 0; i < names.length; i++) {
Symbol member = thistype.lookup(names[i]);
if (member != Symbol.NONE)
members.add(member);
}
List unloadedMembers = new LinkedList();
Iterator it = members.iterator();
while (it.hasNext()) {
Symbol[] alts = ((Symbol) it.next()).alternativeSymbols();
for (int i = 0; i < alts.length; i++)
if (isRelevant(alts[i]))
unloadedMembers.add(alts[i]);
}
return (Symbol[]) unloadedMembers.toArray(new Symbol[unloadedMembers.size()]);
}
// where
protected static Name[] collectNames(Type tpe) {
List names = new LinkedList();
collectNames(tpe, names);
return (Name[]) names.toArray(new Name[names.size()]);
}
// where
protected static void collectNames(Type tpe, List/*<Name>*/ names) {
// local members
SymbolIterator it =
new UnloadLazyIterator(tpe.members().iterator(false));
while (it.hasNext()) {
Name name = ((Symbol) it.next()).name;
if (!names.contains(name))
names.add(name);
}
// inherited members
Type[] parents = tpe.parents();
for (int i = 0; i < parents.length; i++)
collectNames(parents[i], names);
}
/**
* Groups symbols with respect to their owner and sort the owners
* by name.
*
* @param syms
*/
public static Pair/*<Symbol[], Map<Symbol, Symbol[]>>*/ groupSymbols(Symbol[] syms) {
Map/*<Symbol, List>*/ groups = new HashMap();
for (int i = 0; i < syms.length; i++) {
List group = (List) groups.get(syms[i].owner());
if (group == null) {
group = new LinkedList();
groups.put(syms[i].owner(), group);
}
group.add(syms[i]);
}
Symbol[] owners =
(Symbol[]) groups.keySet().toArray(new Symbol[groups.keySet().size()]);
Arrays.sort(owners, symPathOrder);
for (int i = 0; i < owners.length; i++) {
List groupList = (List) groups.get(owners[i]);
Symbol[] group =
(Symbol[]) groupList.toArray(new Symbol[groupList.size()]);
Arrays.sort(group, symAlphaOrder);
groups.put(owners[i], group);
}
return new Pair(owners, groups);
}
//////////////////////////// OVERRIDEN SYMBOL //////////////////////////////
public static Symbol overridenBySymbol(Symbol sym) {
Type base = Type.compoundTypeWithOwner(sym.owner(),
sym.owner().info().parents(),
Scope.EMPTY);
return sym.overriddenSymbol(base);
}
////////////////////////// POST TYPECHECKING ////////////////////////
public static int queryCounter = 0;
/**
* Parse a string representing a Scala type and resolve its
* symbols. This function must be called after the typechecking
* phase. If parsing or type checking fails, return Type.NoType.
*/
public static Type typeOfString(String typeString, Global global) {
int errorNumber = global.reporter.errors();
String unitString = "trait tmp$" + queryCounter +
" extends Option[unit] { def f" + typeString + "; }";
// Rem: we use a dummy extends clause, otherwise the compiler
// complains.
queryCounter = queryCounter + 1;
InputStream in = new ByteArrayInputStream(unitString.getBytes());
SourceFile sourceFile = null;
try {
sourceFile = new SourceFile("tmp.scala", in);
} catch(IOException e) { }
Unit tmpUnit = new Unit(global, sourceFile, false);
tmpUnit.body = new Parser$class(tmpUnit).parse();
//TreePrinter treePrinter = new TextTreePrinter(System.out);
//treePrinter.print(tmpUnit);
global.PHASE.ANALYZER.phase().apply(new Unit[]{ tmpUnit });
if (global.reporter.errors() == errorNumber) {
Scope tmpScope = tmpUnit.body[0].symbol().members();
Type res = tmpScope.lookup(Name.fromString("f")).type();
return res;
}
else
return Type.NoType;
}
}
//////////////////////////// DOCUMENTED SYMBOLS //////////////////////////////
/** Compute documented symbols. */
public class DocSyms {
Set syms;
DocSyms(Global global, Symbol[] packages) {
syms = new HashSet();
for(int i = 0; i < packages.length; i++) {
Symbol pack = packages[i];
// add all sub-members.
ScalaSearch.foreach(pack,
new ScalaSearch.SymFun() {
public void apply(Symbol sym) {
syms.add(sym);
}
}
);
// add all super packages.
if (!pack.isRoot()) {
Symbol owner = pack.owner();
while (!owner.isRoot()) {
syms.add(owner.module());
owner = owner.owner();
}
}
}
}
public boolean contains(Symbol sym) {
boolean res = false;
if (sym.isParameter())
res = contains(sym.classOwner());
else
res = sym.isRoot() || (syms.contains(sym) || (sym.isModuleClass() && syms.contains(sym.module())));
return res;
}
}
public abstract class SymbolBooleanFunction {
public abstract boolean apply(Symbol sym);
} |
package dr.evomodel.coalescent;
import dr.evolution.coalescent.IntervalList;
import dr.evolution.coalescent.Intervals;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Forms a base class for a number of coalescent likelihood calculators.
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: CoalescentLikelihood.java,v 1.43 2006/07/28 11:27:32 rambaut Exp $
*/
public abstract class AbstractCoalescentLikelihood extends AbstractModel implements Likelihood, Units {
// PUBLIC STUFF
public AbstractCoalescentLikelihood(
String name,
Tree tree,
TaxonList includeSubtree,
List<TaxonList> excludeSubtrees) throws Tree.MissingTaxonException {
super(name);
this.tree = tree;
if (includeSubtree != null) {
includedLeafSet = Tree.Utils.getLeavesForTaxa(tree, includeSubtree);
} else {
includedLeafSet = null;
}
if (excludeSubtrees != null) {
excludedLeafSets = new Set[excludeSubtrees.size()];
for (int i = 0; i < excludeSubtrees.size(); i++) {
excludedLeafSets[i] = Tree.Utils.getLeavesForTaxa(tree, excludeSubtrees.get(i));
}
} else {
excludedLeafSets = new Set[0];
}
if (tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
intervals = new Intervals(tree.getNodeCount());
storedIntervals = new Intervals(tree.getNodeCount());
eventsKnown = false;
addStatistic(new DeltaStatistic());
likelihoodKnown = false;
}
// ModelListener IMPLEMENTATION
protected final void handleModelChangedEvent(Model model, Object object, int index) {
if (model == tree) {
// treeModel has changed so recalculate the intervals
eventsKnown = false;
}
likelihoodKnown = false;
}
// ParameterListener IMPLEMENTATION
protected void handleParameterChangedEvent(Parameter parameter, int index, Parameter.ChangeType type) {
} // No parameters to respond to
// Model IMPLEMENTATION
/**
* Stores the precalculated state: in this case the intervals
*/
protected final void storeState() {
// copy the intervals into the storedIntervals
storedIntervals.copyIntervals(intervals);
storedEventsKnown = eventsKnown;
storedLikelihoodKnown = likelihoodKnown;
storedLogLikelihood = logLikelihood;
}
/**
* Restores the precalculated state: that is the intervals of the tree.
*/
protected final void restoreState() {
// swap the intervals back
Intervals tmp = storedIntervals;
storedIntervals = intervals;
intervals = tmp;
eventsKnown = storedEventsKnown;
likelihoodKnown = storedLikelihoodKnown;
logLikelihood = storedLogLikelihood;
}
protected final void acceptState() {
} // nothing to do
// Likelihood IMPLEMENTATION
public final Model getModel() {
return this;
}
public final double getLogLikelihood() {
if (!eventsKnown) {
setupIntervals();
likelihoodKnown = false;
}
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
public final void makeDirty() {
likelihoodKnown = false;
eventsKnown = false;
}
/**
* Calculates the log likelihood of this set of coalescent intervals,
* given a demographic model.
*/
public abstract double calculateLogLikelihood();
/**
* @returns the node ref of the MRCA of this coalescent prior in the given tree.
*/
protected NodeRef getIncludedMRCA(Tree tree) {
if (includedLeafSet != null) {
return Tree.Utils.getCommonAncestorNode(tree, includedLeafSet);
} else {
return tree.getRoot();
}
}
/**
* @returns an array of noderefs that represent the MRCAs of subtrees to exclude from coalescent prior.
* May return null if no subtrees should be excluded.
*/
protected Set<NodeRef> getExcludedMRCAs(Tree tree) {
if (excludedLeafSets.length == 0) return null;
Set<NodeRef> excludeNodesBelow = new HashSet<NodeRef>();
for (int i = 0; i < excludedLeafSets.length; i++) {
excludeNodesBelow.add(Tree.Utils.getCommonAncestorNode(tree, excludedLeafSets[i]));
}
return excludeNodesBelow;
}
public Tree getTree() {
return tree;
}
public IntervalList getIntervals() {
return intervals;
}
/**
* Recalculates all the intervals from the tree model.
*/
protected final void setupIntervals() {
intervals.resetEvents();
collectTimes(tree, getIncludedMRCA(tree), getExcludedMRCAs(tree), intervals);
// force a calculation of the intervals...
intervals.getIntervalCount();
eventsKnown = true;
}
/**
* extract coalescent times and tip information into ArrayList times from tree.
*
* @param tree the tree
* @param node the node to start from
* @param intervals the intervals object to store the events
*/
private void collectTimes(Tree tree, NodeRef node, Set<NodeRef> excludeNodesBelow, Intervals intervals) {
intervals.addCoalescentEvent(tree.getNodeHeight(node));
for (int i = 0; i < tree.getChildCount(node); i++) {
NodeRef child = tree.getChild(node, i);
// check if this subtree is included in the coalescent density
boolean include = true;
if (excludeNodesBelow != null && excludeNodesBelow.contains(child)) {
include = false;
}
if (!include || tree.isExternal(child)) {
intervals.addSampleEvent(tree.getNodeHeight(child));
} else {
collectTimes(tree, child, excludeNodesBelow, intervals);
}
}
}
// Loggable IMPLEMENTATION
/**
* @return the log columns.
*/
public final dr.inference.loggers.LogColumn[] getColumns() {
return new dr.inference.loggers.LogColumn[]{
new LikelihoodColumn(getId())
};
}
private final class LikelihoodColumn extends dr.inference.loggers.NumberColumn {
public LikelihoodColumn(String label) {
super(label);
}
public double getDoubleValue() {
return getLogLikelihood();
}
}
public String toString() {
return Double.toString(logLikelihood);
}
// Inner classes
public class DeltaStatistic extends Statistic.Abstract {
public DeltaStatistic() {
super("delta");
}
public int getDimension() {
return 1;
}
public double getStatisticValue(int i) {
throw new RuntimeException("Not implemented");
// return IntervalList.Utils.getDelta(intervals);
}
}
// Private and protected stuff
/**
* The tree.
*/
private Tree tree = null;
private final Set<String> includedLeafSet;
private final Set[] excludedLeafSets;
/**
* The intervals.
*/
private Intervals intervals = null;
/**
* The stored values for intervals.
*/
private Intervals storedIntervals = null;
private boolean eventsKnown = false;
private boolean storedEventsKnown = false;
private double logLikelihood;
private double storedLogLikelihood;
private boolean likelihoodKnown = false;
private boolean storedLikelihoodKnown = false;
} |
// $Header: /cvsshare/content/cvsroot/cdecurate/src/gov/nih/nci/cadsr/cdecurate/tool/NCICurationServlet.java,v 1.59 2008-12-29 16:18:59 veerlah Exp $
// $Name: not supported by cvs2svn $
package gov.nih.nci.cadsr.cdecurate.tool;
// import files
import gov.nih.nci.cadsr.cdecurate.database.SQLHelper;
import gov.nih.nci.cadsr.cdecurate.util.ClockTime;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import gov.nih.nci.cadsr.cdecurate.util.HelpURL;
import org.apache.log4j.Logger;
/**
* The NCICurationServlet is the main servlet for communicating between the client and the server.
* <P>
*
* @author Joe Zhou, Sumana Hegde, Tom Phillips, Jesse McKean
* @version 3.0
*/
/**
* @author shegde
*/
public class NCICurationServlet extends HttpServlet
{
private static final long serialVersionUID = 8538064617183797182L;
public static Properties m_settings;
public static String _dataSourceName = null;
public static String _authenticateDSName = null;
public static String _userName = null;
public static String _password = null;
public static final Logger logger = Logger.getLogger(NCICurationServlet.class.getName());
/**
* To initialize global variables and load the Oracle driver.
*
* @param config
* The ServletConfig object that has the server configuration
* @throws ServletException
* Any exception that occurs during initialization
*/
public void init(ServletConfig config) throws ServletException
{
if (false)
{
// For development debug only.
Enumeration attrs = config.getServletContext().getAttributeNames();
while (attrs.hasMoreElements())
{
String name = (String) attrs.nextElement();
Object obj = config.getServletContext().getAttribute(name);
logger.debug(name + " = " + obj.toString());
}
}
logger.info(" ");
logger.info("Starting " + this.getClass().getName());
logger.info(" ");
super.init(config);
try
{
// Get the properties settings
// Placeholder data for AC creation coming from CRT
getProperties();
}
catch (Exception ee)
{
logger.fatal("Servlet-init : Unable to start curation tool : " + ee.toString(), ee);
}
// call the method to make oracle connection **database connection class requires lot of changes everywhere;
// leave it right now */
this.initOracleConnect();
}
/**
* initilize the oracle connect
*/
private void initOracleConnect()
{
try
{
logger.info("initOracleConnect - accessing data source pool");
_dataSourceName = "java:/" + getServletConfig().getInitParameter("jbossDataSource");
_authenticateDSName="java:/" + getServletConfig().getInitParameter("jbossAuthenticate");
_userName= getServletConfig().getInitParameter("username");
_password = getServletConfig().getInitParameter("password");
// Test connnection
Connection con = null;
Statement stmt = null;
ResultSet rset = null;
boolean connected =false;
CurationServlet curser = new CurationServlet();
try
{
con = curser.getConnFromDS();
stmt = con.createStatement();
rset = stmt.executeQuery("Select sysdate from dual");
if (rset.next())
{
rset.getString(1);
connected =true;
}
else
throw (new Exception("DBPool connection test failed."));
if(connected)
{
String helpURL = curser.getHelpURL(con);
HelpURL.setCurationToolHelpURL(helpURL);
}
}
catch (Exception e)
{
logger.fatal("Could not open database connection.", e);
}
finally{
SQLHelper.closeResultSet(rset);
SQLHelper.closeStatement(stmt);
SQLHelper.closeConnection(con);
}
}
catch (Exception e)
{
logger.fatal("initOracleConnect - Some other error", e);
}
}
/**
* The service method services all requests to this servlet.
*
* @param req
* The HttpServletRequest object that contains the request
* @param res
* The HttpServletResponse object that contains the response
*/
public void service(HttpServletRequest req, HttpServletResponse res)
{
ClockTime clock = new ClockTime();
try
{
String reqType = req.getParameter("reqType");
HttpSession session = req.getSession();
String menuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION);
if (menuAction != null) {
}else if(!(reqType.equals("homePage"))) {
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/");
rd.forward(req, res);
return;
}
// add the forwarding to request to session (to go after login)
String forwardReq = (String)session.getAttribute("forwardReq");
if (forwardReq == null || !forwardReq.equals("login"))
session.setAttribute("forwardReq", reqType);
ACRequestTypes acrt = null;
CurationServlet curObj = null;
try {
acrt = ACRequestTypes.valueOf(reqType);
if (acrt != null)
{
String className = acrt.getClassName();
curObj = (CurationServlet) Class.forName(className).newInstance();
curObj.init(req, res, this.getServletContext());
curObj.get_m_conn();
curObj.execute(acrt);
}
} catch (RuntimeException e) {
//logger.info(e.toString(), e);
}
finally
{
if (curObj != null)
curObj.destroy();
}
if (acrt == null)
{
CurationServlet curser = new CurationServlet(req, res, this.getServletContext());
curser.service();
}
}
catch (Exception e)
{
logger.error("Service error : " + e.toString(), e);
}
logger.debug("service response time " + clock.toStringLifeTime());
}
/**
* The getProperties method sets up some default properties and then looks for the NCICuration.properties file to override the defaults. Called from 'init'
* method.
*/
private void getProperties()
{
Properties defaultProperties;
InputStream input;
// Set the defaults first
defaultProperties = new Properties();
defaultProperties.put("DEDefinition", "Please provide definition.");
defaultProperties.put("VDDefinition", "Please provide definition.");
defaultProperties.put("DataType", "CHARACTER");
defaultProperties.put("MaxLength", "200");
// Now read the properties file for any changes
m_settings = new Properties(defaultProperties);
try
{
input = NCICurationServlet.class.getResourceAsStream("NCICuration.properties");
m_settings.load(input);
}
catch (Exception e)
{
// System.err.println("ERROR - Got exception reading properties " + e);
logger.error("Servlet-getProperties : " + e.hashCode() + " : " + e.toString(), e);
}
}
/**
* Get Servlet information
*
* @return java.lang.String
*/
public String getServletInfo()
{
return "gov.nih.nci.cadsr.cdecurate.tool.NCICuration Information";
}
/**
* The destroy method closes a connection pool to db.
*/
public void destroy()
{
logger.info(" ");
logger.info("Stopping " + this.getClass().getName());
logger.info(" ");
}
} |
/**
*
* $Id: XenograftManagerImpl.java,v 1.29 2006-05-22 18:14:36 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.28 2006/05/22 15:02:27 pandyas
* Fixed Xenograft so organ is reused/created each time
*
* Revision 1.27 2006/05/19 18:50:37 pandyas
* defect #225 - Add clearOrgan functionality to Xenograft screen
*
* Revision 1.26 2006/05/19 16:39:43 pandyas
* Defect #249 - add other to species on the Xenograft screen
*
* Revision 1.25 2006/04/20 18:11:30 pandyas
* Cleaned up Species or Strain save of Other in DB
*
* Revision 1.24 2006/04/19 17:38:26 pandyas
* Removed TODO text
*
* Revision 1.23 2006/04/17 19:11:05 pandyas
* caMod 2.1 OM changes
*
* Revision 1.22 2005/12/12 17:33:37 georgeda
* Defect #265, store host/origin species in correct places
*
* Revision 1.21 2005/12/01 13:43:36 georgeda
* Defect #226, reuse Taxon objects and do not delete them from Database
*
* Revision 1.20 2005/11/28 22:54:11 pandyas
* Defect #186: Added organ/tissue to Xenograft page, modified search page to display multiple Xenografts with headers, modified XenograftManagerImpl so it does not create or save an organ object if not organ is selected
*
* Revision 1.19 2005/11/28 13:46:53 georgeda
* Defect #207, handle nulls for pages w/ uncontrolled vocab
*
* Revision 1.18 2005/11/16 15:31:05 georgeda
* Defect #41. Clean up of email functionality
*
* Revision 1.17 2005/11/14 14:19:37 georgeda
* Cleanup
*
* Revision 1.16 2005/11/11 16:27:44 pandyas
* added javadocs
*
*
*/
package gov.nih.nci.camod.service.impl;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.Organ;
import gov.nih.nci.camod.domain.Strain;
import gov.nih.nci.camod.domain.Xenograft;
import gov.nih.nci.camod.service.XenograftManager;
import gov.nih.nci.camod.util.MailUtil;
import gov.nih.nci.camod.webapp.form.XenograftData;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.TreeMap;
/**
* @author rajputs
*/
public class XenograftManagerImpl extends BaseManager implements XenograftManager
{
/**
* Get all Xenograft objects
*
*
* @return the matching Xenograft objects, or null if not found.
*
* @exception Exception
* when anything goes wrong.
*/
public List getAll() throws Exception
{
log.trace("In XenograftManagerImpl.getAll");
return super.getAll(Xenograft.class);
}
/**
* Get a specific Xenograft by id
*
* @param id
* the unique id for a Xenograft
*
* @return the matching Xenograft object, or null if not found.
*
* @exception Exception
* when anything goes wrong.
*/
public Xenograft get(String id) throws Exception
{
log.trace("In XenograftManagerImpl.get");
return (Xenograft) super.get(id, Xenograft.class);
}
public void save(Xenograft xenograft) throws Exception
{
log.trace("In XenograftManagerImpl.save");
super.save(xenograft);
}
public void remove(String id,
AnimalModel inAnimalModel) throws Exception
{
log.trace("In XenograftManagerImpl.remove");
inAnimalModel.getXenograftCollection().remove(get(id));
super.save(inAnimalModel);
}
public Xenograft create(XenograftData inXenograftData,
AnimalModel inAnimalModel) throws Exception
{
log.trace("<XenograftManagerImpl> Entering XenograftManagerImpl.create");
Xenograft theXenograft = new Xenograft();
populateSpeciesStrain(inXenograftData, theXenograft, inAnimalModel);
populateOrgan(inXenograftData, theXenograft);
populateXenograft(inXenograftData, theXenograft, inAnimalModel);
log.info("<XenograftManagerImpl> Exiting XenograftManagerImpl.create");
return theXenograft;
}
public void update(XenograftData inXenograftData,
Xenograft inXenograft,
AnimalModel inAnimalModel) throws Exception
{
log.info("Entering XenograftManagerImpl.update XenograftId: " + inXenograft.getId());
// Populate w/ the new values and save
populateSpeciesStrain(inXenograftData, inXenograft, inAnimalModel);
populateOrgan(inXenograftData, inXenograft);
populateXenograft(inXenograftData, inXenograft, inAnimalModel);
save(inXenograft);
log.info("Exiting XenograftManagerImpl.update");
}
private void populateXenograft(XenograftData inXenograftData,
Xenograft inXenograft,
AnimalModel inAnimalModel) throws Exception
{
log.info("Entering XenograftManagerImpl.populateXenograft");
/* Set xenograftName */
inXenograft.setXenograftName(inXenograftData.getXenograftName());
/* Set other adminstrative site or selected adminstrative site */
// save directly in administrativeSite column of table
if (inXenograftData.getAdministrativeSite().equals(Constants.Dropdowns.OTHER_OPTION))
{
// Do not save other in the DB
inXenograft.setAdminSiteUnctrlVocab(inXenograftData.getOtherAdministrativeSite());
// Send e-mail for other administrativeSite
sendEmail(inAnimalModel, inXenograftData.getOtherAdministrativeSite(), "AdministrativeSite");
}
else
{
inXenograft.setAdministrativeSite(inXenograftData.getAdministrativeSite());
}
inXenograft.setGeneticManipulation(inXenograftData.getGeneticManipulation());
inXenograft.setModificationDescription(inXenograftData.getModificationDescription());
inXenograft.setParentalCellLineName(inXenograftData.getParentalCellLineName());
inXenograft.setAtccNumber(inXenograftData.getAtccNumber());
inXenograft.setCellAmount(inXenograftData.getCellAmount());
inXenograft.setGrowthPeriod(inXenograftData.getGrowthPeriod());
// anytime the graft type is "other"
if (inXenograftData.getGraftType().equals(Constants.Dropdowns.OTHER_OPTION))
{
// Set Graft type
inXenograft.setGraftType(null);
inXenograft.setGraftTypeUnctrlVocab(inXenograftData.getOtherGraftType());
// Send e-mail for other Graft Type
sendEmail(inAnimalModel, inXenograftData.getOtherGraftType(), "GraftType");
}
// anytime graft type is not other set uncontrolled vocab to null
// (covers editing)
else
{
inXenograft.setGraftType(inXenograftData.getGraftType());
inXenograft.setGraftTypeUnctrlVocab(null);
}
log.info("Exiting XenograftManagerImpl.populateXenograft");
}
private void populateSpeciesStrain(XenograftData inXenograftData,
Xenograft inXenograft,
AnimalModel inAnimalModel) throws Exception
{
// Use Species to create strain
Strain theStrain = StrainManagerSingleton.instance().getOrCreate(inXenograftData.getDonorEthinicityStrain(),
inXenograftData.getOtherDonorEthinicityStrain(),
inXenograftData.getDonorScientificName(),
inXenograftData.getOtherDonorScientificName());
// other option selected for species - send e-mail
if (inXenograftData.getDonorScientificName().equals(Constants.Dropdowns.OTHER_OPTION))
{
// Send e-mail for other donor species
sendEmail(inAnimalModel, inXenograftData.getOtherDonorScientificName(), "Donor Species");
}
// other option selected for strain - send e-mail
if (inXenograftData.getDonorEthinicityStrain().equals(Constants.Dropdowns.OTHER_OPTION))
{
// Send e-mail for other donor species
sendEmail(inAnimalModel, inXenograftData.getOtherDonorEthinicityStrain(), "Donor Strain");
}
log.info("\n <populateSpeciesStrain> theSpecies is NOT other: ");
inXenograft.setStrain(theStrain);
}
private void populateOrgan(XenograftData inXenograftData,
Xenograft inXenograft) throws Exception
{
// reuse/create Organ by matching concept code
Organ theOrgan = OrganManagerSingleton.instance().getOrCreate(inXenograftData.getOrganTissueCode(),
inXenograftData.getOrganTissueName());
/*
* Add a Organ to AnimalModel with correct IDs, conceptCode, only if
* organ is selected by user - no need to check for existing organ in 2.1
*/
if (inXenograftData.getOrganTissueCode() != null && inXenograftData.getOrganTissueCode().length() > 0)
{
inXenograft.setOrgan(theOrgan);
}
//blank out organ, clear button functionality during editing
else
{
log.info("Setting object to null - clear organ: ");
inXenograft.setOrgan(null);
}
}
private void sendEmail(AnimalModel inAnimalModel,
String theUncontrolledVocab,
String inType)
{
// Get the e-mail resource
ResourceBundle theBundle = ResourceBundle.getBundle("camod");
// Iterate through all the reciepts in the config file
String recipients = theBundle.getString(Constants.BundleKeys.NEW_UNCONTROLLED_VOCAB_NOTIFY_KEY);
StringTokenizer st = new StringTokenizer(recipients, ",");
String inRecipients[] = new String[st.countTokens()];
for (int i = 0; i < inRecipients.length; i++)
{
inRecipients[i] = st.nextToken();
}
String inSubject = theBundle.getString(Constants.BundleKeys.NEW_UNCONTROLLED_VOCAB_SUBJECT_KEY);
String inFrom = inAnimalModel.getSubmitter().getEmailAddress();
// gather message keys and variable values to build the e-mail
String[] messageKeys = { Constants.Admin.NONCONTROLLED_VOCABULARY };
Map<String, Object> values = new TreeMap<String, Object>();
values.put("type", inType);
values.put("value", theUncontrolledVocab);
values.put("submitter", inAnimalModel.getSubmitter());
values.put("model", inAnimalModel.getModelDescriptor());
values.put("modelstate", inAnimalModel.getState());
// Send the email
try
{
MailUtil.sendMail(inRecipients, inSubject, "", inFrom, messageKeys, values);
}
catch (Exception e)
{
log.error("Caught exception sending mail: ", e);
e.printStackTrace();
}
}
} |
// XSL : not found (java.io.FileNotFoundException: (Bad file descriptor))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl
package gov.nih.nci.nautilus.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionError;
import org.apache.struts.util.LabelValueBean;
import java.util.*;
import java.util.regex .*;
import java.lang.reflect.*;
import java.io.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import gov.nih.nci.nautilus.constants.NautilusConstants;
import gov.nih.nci.nautilus.criteria.*;
import gov.nih.nci.nautilus.de.*;
import gov.nih.nci.nautilus.query.QueryCollection;
public class GeneExpressionForm extends BaseForm {
// Variables
private String[] pathwayName;
/** geneList property */
private String geneList;
/** goClassification property */
private String goClassification;
/** goCellularComp property */
private String goCellularComp;
/** goMolecularFunction property */
private String goMolecularFunction;
/** goBiologicalProcess property */
private String goBiologicalProcess;
/** tumorGrade property */
private String tumorGrade;
/** region property */
private String region;
/** foldChangeValueDown property */
private String foldChangeValueDown = "2";
/** cytobandRegion property */
private String cytobandRegion;
/** cloneId property */
private String cloneId;
/** pathways property */
private String pathways;
/** tumorType property */
private String tumorType;
/** arrayPlatform property */
private String arrayPlatform;
/** cloneListFile property */
private String cloneListFile;
/** cloneListSpecify property */
private String cloneListSpecify;
/** basePairEnd property */
private String basePairEnd;
/** chrosomeNumber property */
private String chrosomeNumber;
/** regulationStatus property */
private String regulationStatus;
/** foldChangeValueUnchangeFrom property */
private String foldChangeValueUnchangeFrom = "0.8";
/** foldChangeValueUnchangeTo property */
private String foldChangeValueUnchangeTo = "1.2";
/** foldChangeValueUp property */
private String foldChangeValueUp = "2";
/** geneType property */
private String geneType;
/** foldChangeValueUDUp property */
private String foldChangeValueUDUp;
/** resultView property */
private String resultView;
/** geneFile property */
private String geneFile;
/** foldChangeValueUDDown property */
private String foldChangeValueUDDown = "2";
/** geneGroup property */
private String geneGroup;
/** cloneList property */
private String cloneList;
/** queryName property */
private String queryName;
/** basePairStart property */
private String basePairStart;
// Collections used for Lookup values.
//private ArrayList diseaseType;// moved this to the upperclass:
// BaseForm.java
//private ArrayList geneTypeColl;// move this to the upperclass:
// BaseForm.java
private ArrayList cloneTypeColl;
private ArrayList arrayPlatformTypeColl;
private DiseaseOrGradeCriteria diseaseOrGradeCriteria;
private GeneIDCriteria geneCriteria;
private FoldChangeCriteria foldChangeCriteria;
private RegionCriteria regionCriteria;
private CloneOrProbeIDCriteria cloneOrProbeIDCriteria;
private GeneOntologyCriteria geneOntologyCriteria;
private PathwayCriteria pathwayCriteria;
private ArrayPlatformCriteria arrayPlatformCriteria;
// UntranslatedRegionCriteria: for both 5' and 3', "included" is used as
// default,
// on the jsp, it may be commented out for now
private UntranslatedRegionCriteria untranslatedRegionCriteria;
// Hashmap to store Domain elements
private HashMap diseaseDomainMap;
private HashMap geneDomainMap;
private HashMap foldUpDomainMap;
private HashMap foldDownDomainMap;
private HashMap regionDomainMap;
private HashMap cloneDomainMap;
private HashMap geneOntologyDomainMap;
private HashMap pathwayDomainMap;
private HashMap arrayPlatformDomainMap;
private HttpServletRequest thisRequest;
private QueryCollection queryCollection;
private static Logger logger = Logger.getLogger(NautilusConstants.LOGGER);
public GeneExpressionForm() {
// Create Lookups for Gene Expression screens
super();
setGeneExpressionLookup();
}
/**
* Method validate
*
* @param ActionMapping
* mapping
* @param HttpServletRequest
* request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
// Query Name cannot be blank
if ((queryName == null || queryName.length() < 1))
errors.add("queryName", new ActionError(
"gov.nih.nci.nautilus.struts.form.queryname.no.error"));
// Chromosomal region validations
if (this.getChrosomeNumber().trim().length() > 0) {
if (this.getRegion().trim().length() < 1)
errors.add("chrosomeNumber", new ActionError(
"gov.nih.nci.nautilus.struts.form.region.no.error"));
else {
if (this.getRegion().trim().equalsIgnoreCase("cytoband")) {
if (this.getCytobandRegion().trim().length() < 1)
errors
.add(
"cytobandRegion",
new ActionError(
"gov.nih.nci.nautilus.struts.form.cytobandregion.no.error"));
}
if (this.getRegion().trim()
.equalsIgnoreCase("basePairPosition")) {
if ((this.getBasePairStart().trim().length() < 1)
|| (this.getBasePairEnd().trim().length() < 1)) {
errors
.add(
"basePairEnd",
new ActionError(
"gov.nih.nci.nautilus.struts.form.basePair.no.error"));
} else {
if (!isBasePairValid(this.getBasePairStart(), this
.getBasePairEnd()))
errors
.add(
"basePairEnd",
new ActionError(
"gov.nih.nci.nautilus.struts.form.basePair.incorrect.error"));
}
}
}
}
if (this.getGoClassification() != null) {
if (this.getGoMolecularFunction() == null
&& this.getGoCellularComp() == null
&& this.getGoBiologicalProcess() == null) {
errors
.add(
"Gene Ontology (GO) Classifications",
new ActionError(
"error:gov.nih.nci.nautilus.struts.form.geneOntology.functions.required"));
}
}
// Validate minimum criteria's for GE Query
if (this.getQueryName() != null && this.getQueryName().length() >= 1) {
if ((this.getGeneGroup() == null || this.getGeneGroup().trim().length() < 1) &&
(this.getCloneId() == null || this.getCloneId().trim().length() < 1) &&
(this.getChrosomeNumber() == null || this.getChrosomeNumber().trim().length() < 1) &&
(this.getGoClassification() == null || this.getGoClassification().trim().length() < 1) &&
(this.getPathways() == null || this.getPathways().trim().length() < 1)) {
errors
.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"gov.nih.nci.nautilus.struts.form.ge.minimum.error"));
}
}
if (this.getGeneGroup() != null && this.getGeneGroup().trim().length() >= 1){
if (this.getGeneList().trim().length() < 1 && this.getGeneFile().trim().length() < 1){
errors
.add(
"geneGroup",
new ActionError(
"gov.nih.nci.nautilus.struts.form.geneGroup.no.error"));
}
}
if (this.getCloneId() != null && this.getCloneId().trim().length() >= 1){
if (this.getCloneListSpecify().trim().length() < 1 && this.getCloneListFile().trim().length() < 1){
errors
.add(
"cloneId",
new ActionError(
"gov.nih.nci.nautilus.struts.form.cloneid.no.error"));
}
}
if (errors.isEmpty()) {
createDiseaseCriteriaObject();
createGeneCriteriaObject();
createFoldChangeCriteriaObject();
createRegionCriteriaObject();
createCloneOrProbeCriteriaObject();
createGeneOntologyCriteriaObject();
createPathwayCriteriaObject();
createArrayPlatformCriteriaObject();
}
return errors;
}
private void createDiseaseCriteriaObject() {
//look thorugh the diseaseDomainMap to extract out the domain elements
// and create respective Criteria Objects
Set keys = diseaseDomainMap.keySet();
Iterator iter = keys.iterator();
while (iter.hasNext()) {
Object key = iter.next();
try {
String strDiseaseDomainClass = (String) diseaseDomainMap
.get(key);//use key to get value
Constructor[] diseaseConstructors = Class.forName(
strDiseaseDomainClass).getConstructors();
Object[] parameterObjects = { key };
DiseaseNameDE diseaseNameDEObj = (DiseaseNameDE) diseaseConstructors[0]
.newInstance(parameterObjects);
diseaseOrGradeCriteria.setDisease(diseaseNameDEObj);
} catch (Exception ex) {
logger.error("Error in createDiseaseCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createDiseaseCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createGeneCriteriaObject() {
// Loop thru the HashMap, extract the Domain elements and create
// respective Criteria Objects
Set keys = geneDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + geneDomainMap.get(key));
try {
String strgeneDomainClass = (String) geneDomainMap.get(key);
Constructor[] geneConstructors = Class.forName(
strgeneDomainClass).getConstructors();
Object[] parameterObjects = { key };
GeneIdentifierDE geneSymbolDEObj = (GeneIdentifierDE) geneConstructors[0]
.newInstance(parameterObjects);
geneCriteria.setGeneIdentifier(geneSymbolDEObj);
logger.debug("Gene Domain Element Value==> "
+ geneSymbolDEObj.getValueObject());
} catch (Exception ex) {
logger.debug("Error in createGeneCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createGeneCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createFoldChangeCriteriaObject() {
// For Fold Change Up
Set keys = foldUpDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + foldUpDomainMap.get(key));
try {
String strFoldDomainClass = (String) foldUpDomainMap.get(key);
Constructor[] foldConstructors = Class.forName(
strFoldDomainClass).getConstructors();
Object[] parameterObjects = { Float.valueOf((String) key) };
ExprFoldChangeDE foldChangeDEObj = (ExprFoldChangeDE) foldConstructors[0]
.newInstance(parameterObjects);
foldChangeCriteria.setFoldChangeObject(foldChangeDEObj);
logger.debug("Fold Change Domain Element Value is ==>"
+ foldChangeDEObj.getValueObject());
} catch (Exception ex) {
logger.error("Error in createFoldChangeCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createFoldChangeCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
// For Fold Change Down
keys = foldDownDomainMap.keySet();
i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + foldDownDomainMap.get(key));
try {
String strFoldDomainClass = (String) foldDownDomainMap.get(key);
Constructor[] foldConstructors = Class.forName(
strFoldDomainClass).getConstructors();
Object[] parameterObjects = { Float.valueOf((String) key) };
ExprFoldChangeDE foldChangeDEObj = (ExprFoldChangeDE) foldConstructors[0]
.newInstance(parameterObjects);
foldChangeCriteria.setFoldChangeObject(foldChangeDEObj);
logger.debug("Fold Change Domain Element Value is ==>"
+ foldChangeDEObj.getValueObject());
} catch (Exception ex) {
logger.error("Error in createFoldChangeCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createFoldChangeCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createRegionCriteriaObject() {
Set keys = regionDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + regionDomainMap.get(key));
try {
String strRegionDomainClass = (String) regionDomainMap.get(key);
Constructor[] regionConstructors = Class.forName(
strRegionDomainClass).getConstructors();
if (strRegionDomainClass.endsWith("CytobandDE")) {
Object[] parameterObjects = { (String) key };
CytobandDE cytobandDEObj = (CytobandDE) regionConstructors[0]
.newInstance(parameterObjects);
regionCriteria.setCytoband(cytobandDEObj);
logger.debug("Test Cytoband Criteria"
+ regionCriteria.getCytoband().getValue());
}
if (strRegionDomainClass.endsWith("ChromosomeNumberDE")) {
Object[] parameterObjects = { (String) key };
ChromosomeNumberDE chromosomeDEObj = (ChromosomeNumberDE) regionConstructors[0]
.newInstance(parameterObjects);
regionCriteria.setChromNumber(chromosomeDEObj);
logger.debug("Test Chromosome Criteria "
+ regionCriteria.getChromNumber().getValue());
}
if (strRegionDomainClass.endsWith("StartPosition")) {
Object[] parameterObjects = { Integer.valueOf((String) key) };
BasePairPositionDE.StartPosition baseStartDEObj = (BasePairPositionDE.StartPosition) regionConstructors[0]
.newInstance(parameterObjects);
regionCriteria.setStart(baseStartDEObj);
logger.debug("Test Start Criteria"
+ regionCriteria.getStart().getValue());
}
if (strRegionDomainClass.endsWith("EndPosition")) {
Object[] parameterObjects = { Integer.valueOf((String) key) };
BasePairPositionDE.EndPosition baseEndDEObj = (BasePairPositionDE.EndPosition) regionConstructors[0]
.newInstance(parameterObjects);
regionCriteria.setEnd(baseEndDEObj);
logger.debug("Test End Criteria"
+ regionCriteria.getEnd().getValue());
}
} catch (Exception ex) {
logger.error("Error in createRegionCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createRegionCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createCloneOrProbeCriteriaObject() {
// Loop thru the cloneDomainMap HashMap, extract the Domain elements and
// create respective Criteria Objects
Set keys = cloneDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + cloneDomainMap.get(key));
try {
String strCloneDomainClass = (String) cloneDomainMap.get(key);
Constructor[] cloneConstructors = Class.forName(
strCloneDomainClass).getConstructors();
Object[] parameterObjects = { key };
CloneIdentifierDE cloneIdentfierDEObj = (CloneIdentifierDE) cloneConstructors[0]
.newInstance(parameterObjects);
cloneOrProbeIDCriteria.setCloneIdentifier(cloneIdentfierDEObj);
logger.debug("Clone Domain Element Value==> "
+ cloneIdentfierDEObj.getValueObject());
} catch (Exception ex) {
logger.error("Error in createGeneCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createGeneCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createGeneOntologyCriteriaObject() {
// Loop thru the geneOntologyDomainMap HashMap, extract the Domain
// elements and create respective Criteria Objects
Set keys = geneOntologyDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + geneOntologyDomainMap.get(key));
try {
String strGeneOntologyDomainClass = (String) geneOntologyDomainMap
.get(key);
Constructor[] geneOntologyConstructors = Class.forName(
strGeneOntologyDomainClass).getConstructors();
Object[] parameterObjects = { key };
GeneOntologyDE geneOntologyDEObj = (GeneOntologyDE) geneOntologyConstructors[0]
.newInstance(parameterObjects);
geneOntologyCriteria.setGOIdentifier(geneOntologyDEObj);
logger.debug("GO Domain Element Value==> "
+ geneOntologyDEObj.getValueObject());
} catch (Exception ex) {
logger.error("Error in createGeneOntologyCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createGeneOntologyCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createPathwayCriteriaObject() {
// Loop thru the pathwayDomainMap HashMap, extract the Domain elements
// and create respective Criteria Objects
Set keys = pathwayDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + pathwayDomainMap.get(key));
try {
String strPathwayDomainClass = (String) pathwayDomainMap
.get(key);
logger.debug("strPathwayDomainClass is for pathway:"
+ strPathwayDomainClass
+ strPathwayDomainClass.length());
Constructor[] pathwayConstructors = Class.forName(
strPathwayDomainClass).getConstructors();
Object[] parameterObjects = { key };
PathwayDE pathwayDEObj = (PathwayDE) pathwayConstructors[0]
.newInstance(parameterObjects);
pathwayCriteria.setPathwayName(pathwayDEObj);
logger.debug("GO Domain Element Value==> "
+ pathwayDEObj.getValueObject());
} catch (Exception ex) {
logger.error("Error in createGeneCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createGeneCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
private void createArrayPlatformCriteriaObject() {
// Loop thru the pathwayDomainMap HashMap, extract the Domain elements
// and create respective Criteria Objects
Set keys = arrayPlatformDomainMap.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
logger.debug(key + "=>" + arrayPlatformDomainMap.get(key));
try {
String strArrayPlatformDomainClass = (String) arrayPlatformDomainMap
.get(key);
Constructor[] arrayPlatformConstructors = Class.forName(
strArrayPlatformDomainClass).getConstructors();
Object[] parameterObjects = { key };
ArrayPlatformDE arrayPlatformDEObj = (ArrayPlatformDE) arrayPlatformConstructors[0]
.newInstance(parameterObjects);
arrayPlatformCriteria.setPlatform(arrayPlatformDEObj);
logger.debug("GO Domain Element Value==> "
+ arrayPlatformDEObj.getValueObject());
} catch (Exception ex) {
logger.error("Error in createArrayPlatformCriteriaObject "
+ ex.getMessage());
ex.printStackTrace();
} catch (LinkageError le) {
logger.error("Linkage Error in createArrayPlatformCriteriaObject "
+ le.getMessage());
le.printStackTrace();
}
}
}
public void setGeneExpressionLookup() {
//diseaseType = new ArrayList();// moved to the upper class:
// BaseForm.java
//geneTypeColl = new ArrayList();// moved to the upper class:
// BaseForm.java
cloneTypeColl = new ArrayList();
arrayPlatformTypeColl = new ArrayList();
// These are hardcoded but will come from DB
/*
* *moved to the upperclass:: BaseForm.java
*
* diseaseType.add( new LabelValueBean( "Astrocytic", "astro" ) );
* diseaseType.add( new LabelValueBean( "Oligodendroglial", "oligo" ) );
* diseaseType.add( new LabelValueBean( "Ependymal cell", "Ependymal
* cell" ) ); diseaseType.add( new LabelValueBean( "Mixed gliomas",
* "Mixed gliomas" ) ); diseaseType.add( new LabelValueBean(
* "Neuroepithelial", "Neuroepithelial" ) ); diseaseType.add( new
* LabelValueBean( "Choroid Plexus", "Choroid Plexus" ) );
* diseaseType.add( new LabelValueBean( "Neuronal and mixed
* neuronal-glial", "neuronal-glial" ) ); diseaseType.add( new
* LabelValueBean( "Pineal Parenchyma", "Pineal Parenchyma" ));
* diseaseType.add( new LabelValueBean( "Embryonal", "Embryonal" ));
* diseaseType.add( new LabelValueBean( "Glioblastoma", "Glioblastoma"
* ));
*/
//geneTypeColl.add( new LabelValueBean( "All Genes", "allgenes" )
// );//moved to the upperclass:: BaseForm.java
//geneTypeColl.add( new LabelValueBean( "Name/Symbol", "genesymbol" )
// );//moved to the upperclass:: BaseForm.java
//geneTypeColl.add( new LabelValueBean( "Locus Link Id", "genelocus" )
// );//moved to the upperclass:: BaseForm.java
//geneTypeColl.add( new LabelValueBean( "GenBank AccNo.", "genbankno" )
// );//moved to the upperclass:: BaseForm.java
cloneTypeColl.add(new LabelValueBean("IMAGE Id", "imageId"));
//cloneTypeColl.add( new LabelValueBean( "BAC Id", "BACId" ) );
cloneTypeColl.add(new LabelValueBean("Probe Set Id", "probeSetId"));
arrayPlatformTypeColl.add(new LabelValueBean("all", "all"));
arrayPlatformTypeColl.add(new LabelValueBean("Oligo (Affymetrix)",
"Oligo (Affymetrix)"));
arrayPlatformTypeColl.add(new LabelValueBean("cDNA", "cDNA"));
}
/**
* Method reset. Reset all properties to their default values.
*
* @param ActionMapping
* mapping used to select this instance.
* @param HttpServletRequest
* request The servlet request we are processing.
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
pathwayName = new String[0];
geneList = "";
goBiologicalProcess = "";
tumorGrade = "";
region = "";
foldChangeValueDown = "2";
cytobandRegion = "";
cloneId = "";
pathways = "";
tumorType = "";
arrayPlatform = "";
cloneListFile = "";
goCellularComp = "";
goMolecularFunction = "";
cloneListSpecify = "";
goClassification = "";
basePairEnd = "";
chrosomeNumber = "";
regulationStatus = "";
foldChangeValueUnchangeFrom = "0.8";
foldChangeValueUnchangeTo = "1.2";
foldChangeValueUp = "2";
geneType = "";
foldChangeValueUDUp = "2";
resultView = "";
geneFile = "";
foldChangeValueUDDown = "2";
geneGroup = "";
cloneList = "";
queryName = "";
basePairStart = "";
//Set the Request Object
this.thisRequest = request;
diseaseDomainMap = new HashMap();
geneDomainMap = new HashMap();
foldUpDomainMap = new HashMap();
foldDownDomainMap = new HashMap();
regionDomainMap = new HashMap();
cloneDomainMap = new HashMap();
geneOntologyDomainMap = new HashMap();
pathwayDomainMap = new HashMap();
arrayPlatformDomainMap = new HashMap();
diseaseOrGradeCriteria = new DiseaseOrGradeCriteria();
geneCriteria = new GeneIDCriteria();
foldChangeCriteria = new FoldChangeCriteria();
regionCriteria = new RegionCriteria();
cloneOrProbeIDCriteria = new CloneOrProbeIDCriteria();
geneOntologyCriteria = new GeneOntologyCriteria();
pathwayCriteria = new PathwayCriteria();
arrayPlatformCriteria = new ArrayPlatformCriteria();
//arrayPlatformCriteria = new ArrayPlatformCriteria();
}
/**
* Returns the geneList.
*
* @return String
*/
public String getGeneList() {
return geneList;
}
/**
* Set the geneList.
*
* @param geneList
* The geneList to set
*/
public void setGeneList(String geneList) {
this.geneList = geneList;
String thisGeneType = this.thisRequest.getParameter("geneType");
String thisGeneGroup = this.thisRequest.getParameter("geneGroup");
if ((thisGeneGroup != null)
&& thisGeneGroup.equalsIgnoreCase("Specify")
&& (thisGeneType.length() > 0) && (this.geneList.length() > 0)) {
String[] splitValue = this.geneList.split("\\x2C");
for (int i = 0; i < splitValue.length; i++) {
if (thisGeneType.equalsIgnoreCase("genesymbol")) {
geneDomainMap.put(splitValue[i],
GeneIdentifierDE.GeneSymbol.class.getName());
} else if (thisGeneType.equalsIgnoreCase("genelocus")) {
geneDomainMap.put(splitValue[i],
GeneIdentifierDE.LocusLink.class.getName());
} else if (thisGeneType.equalsIgnoreCase("genbankno")) {
geneDomainMap.put(splitValue[i],
GeneIdentifierDE.GenBankAccessionNumber.class
.getName());
} else if (thisGeneType.equalsIgnoreCase("allgenes")) {
geneDomainMap.put(splitValue[i],
GeneIdentifierDE.GeneSymbol.class.getName());
}
}
}
// Set for all genes
/*
* if (thisGeneGroup != null &&
* thisGeneGroup.equalsIgnoreCase("Specify") &&
* (thisGeneType.equalsIgnoreCase("allgenes"))){
* geneDomainMap.put("allgenes",
* GeneIdentifierDE.GeneSymbol.class.getName()); }
*/
}
/**
* Returns the geneFile.
*
* @return String
*/
public String getGeneFile() {
return geneFile;
}
/**
* Set the geneFile.
*
* @param geneFile
* The geneFile to set
*/
public void setGeneFile(String geneFile) {
this.geneFile = geneFile;
String thisGeneType = this.thisRequest.getParameter("geneType");
String thisGeneGroup = this.thisRequest.getParameter("geneGroup");
System.out.println("this.geneFile before:"+this.geneFile);
//Pattern.compile("\\").matcher(this.geneFile).replaceAll(File.separator);
this.geneFile = this.geneFile.replaceAll("\"",File.separator);
System.out.println("this.geneFile :"+this.geneFile);
System.out.println("thisGeneType :"+thisGeneType);
System.out.println("thisGeneGroup8888888888888 :"+thisGeneGroup);
if ((thisGeneGroup != null) && thisGeneGroup.equalsIgnoreCase("Upload")
&& (thisGeneType.length() > 0) && (this.geneFile.length() > 0)) {
File geneListFile = new File(this.geneFile);
String line = null;
try {
FileReader editfr = new FileReader(geneListFile);
BufferedReader inFile = new BufferedReader(editfr);
line = inFile.readLine();
int i = 0;
while (line != null && line.length() > 0) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (thisGeneType.equalsIgnoreCase("genesymbol")) {
geneDomainMap
.put(token,
GeneIdentifierDE.GeneSymbol.class
.getName());
} else if (thisGeneType.equalsIgnoreCase("genelocus")) {
geneDomainMap.put(token,
GeneIdentifierDE.LocusLink.class.getName());
} else if (thisGeneType.equalsIgnoreCase("genbankno")) {
geneDomainMap
.put(
token,
GeneIdentifierDE.GenBankAccessionNumber.class
.getName());
} else if (thisGeneType.equalsIgnoreCase("allgenes")) {
geneDomainMap
.put(token,
GeneIdentifierDE.GeneSymbol.class
.getName());
}
}
line = inFile.readLine();
}// end of while
inFile.close();
} catch (IOException ex) {
logger.error("Errors when uploading gene file:"
+ ex.getMessage());
}
}
}
public GeneIDCriteria getGeneIDCriteria() {
return this.geneCriteria;
}
public FoldChangeCriteria getFoldChangeCriteria() {
return this.foldChangeCriteria;
}
public RegionCriteria getRegionCriteria() {
return this.regionCriteria;
}
public DiseaseOrGradeCriteria getDiseaseOrGradeCriteria() {
return this.diseaseOrGradeCriteria;
}
public CloneOrProbeIDCriteria getCloneOrProbeIDCriteria() {
return this.cloneOrProbeIDCriteria;
}
public GeneOntologyCriteria getGeneOntologyCriteria() {
return this.geneOntologyCriteria;
}
public PathwayCriteria getPathwayCriteria() {
return this.pathwayCriteria;
}
public ArrayPlatformCriteria getArrayPlatformCriteria() {
return this.arrayPlatformCriteria;
}
/**
* Returns the goBiologicalProcess.
*
* @return String
*/
public String getGoBiologicalProcess() {
return goBiologicalProcess;
}
/**
* Set the goBiologicalProcess.
*
* @param goBiologicalProcess
* The goBiologicalProcess to set
*/
public void setGoBiologicalProcess(String goBiologicalProcess) {
this.goBiologicalProcess = goBiologicalProcess;
}
/**
* Returns the tumorGrade.
*
* @return String
*/
public String getTumorGrade() {
return tumorGrade;
}
/**
* Set the tumorGrade.
*
* @param tumorGrade
* The tumorGrade to set
*/
public void setTumorGrade(String tumorGrade) {
this.tumorGrade = tumorGrade;
}
/**
* Returns the region.
*
* @return String
*/
public String getRegion() {
return region;
}
/**
* Set the region.
*
* @param region
* The region to set
*/
public void setRegion(String region) {
this.region = region;
}
/**
* Returns the foldChangeValueDown.
*
* @return String
*/
public String getFoldChangeValueDown() {
return foldChangeValueDown;
}
/**
* Set the foldChangeValueDown.
*
* @param foldChangeValueDown
* The foldChangeValueDown to set
*/
public void setFoldChangeValueDown(String foldChangeValueDown) {
this.foldChangeValueDown = foldChangeValueDown;
String thisRegulationStatus = this.thisRequest
.getParameter("regulationStatus");
if (thisRegulationStatus != null
&& thisRegulationStatus.equalsIgnoreCase("down")
&& (this.foldChangeValueDown.length() > 0))
foldDownDomainMap.put(this.foldChangeValueDown,
ExprFoldChangeDE.DownRegulation.class.getName());
}
/**
* Returns the cytobandRegion.
*
* @return String
*/
public String getCytobandRegion() {
return cytobandRegion;
}
/**
* Set the cytobandRegion.
*
* @param cytobandRegion
* The cytobandRegion to set
*/
public void setCytobandRegion(String cytobandRegion) {
this.cytobandRegion = cytobandRegion;
String thisRegion = this.thisRequest.getParameter("region");
String thisChrNumber = this.thisRequest.getParameter("chrosomeNumber");
if (thisChrNumber != null && thisChrNumber.trim().length() > 0) {
if (thisRegion != null && thisRegion.equalsIgnoreCase("cytoband")
&& this.cytobandRegion.trim().length() > 0) {
regionDomainMap.put(this.cytobandRegion, CytobandDE.class
.getName());
}
}
}
/**
* Returns the cloneId.
*
* @return String
*/
public String getCloneId() {
return cloneId;
}
/**
* Set the cloneId.
*
* @param cloneId
* The cloneId to set
*/
public void setCloneId(String cloneId) {
this.cloneId = cloneId;
}
/**
* Returns the pathways.
*
* @return String
*/
public String getPathways() {
return pathways;
}
/**
* Set the pathways.
*
* @param pathways
* The pathways to set
*/
public void setPathways(String pathways) {
logger.debug("pathways.length:" + pathways.length());
if (pathways != null) {
this.pathways = pathways.trim();
logger.debug("pathways.length after:"
+ this.pathways.length());
String pathwaySelect = (String) thisRequest
.getParameter("pathways");
if (pathwaySelect != null && !pathwaySelect.equals("")) {
pathwayDomainMap.put(this.pathways, PathwayDE.class.getName());
}
}
}
/**
* Returns the tumorType.
*
* @return String
*/
public String getTumorType() {
return tumorType;
}
/**
* Set the tumorType.
*
* @param tumorType
* The tumorType to set
*/
public void setTumorType(String tumorType) {
this.tumorType = tumorType;
if (this.tumorType.equalsIgnoreCase("ALL")) {
ArrayList allDiseases = this.getDiseaseType();
for (Iterator diseaseIter = allDiseases.iterator(); diseaseIter
.hasNext();) {
LabelValueBean thisLabelBean = (LabelValueBean) diseaseIter
.next();
String thisDiseaseType = thisLabelBean.getValue();
// stuff this in our DomainMap for later use !!
if (!thisDiseaseType.equalsIgnoreCase("ALL")) {
diseaseDomainMap.put(thisDiseaseType, DiseaseNameDE.class
.getName());
}
}
} else {
diseaseDomainMap.put(this.tumorType, DiseaseNameDE.class.getName());
}
}
/**
* Returns the arrayPlatform.
*
* @return String
*/
public String getArrayPlatform() {
return arrayPlatform;
}
/**
* Set the arrayPlatform.
*
* @param arrayPlatform
* The arrayPlatform to set
*/
public void setArrayPlatform(String arrayPlatform) {
this.arrayPlatform = arrayPlatform;
arrayPlatformDomainMap.put(this.arrayPlatform, ArrayPlatformDE.class
.getName());
}
/**
* Returns the goCellularComp.
*
* @return String
*/
public String getGoCellularComp() {
return goCellularComp;
}
/**
* Set the goCellularComp.
*
* @param goCellularComp
* The goCellularComp to set
*/
public void setGoCellularComp(String goCellularComp) {
this.goCellularComp = goCellularComp;
}
/**
* Returns the goMolecularFunction.
*
* @return String
*/
public String getGoMolecularFunction() {
return goMolecularFunction;
}
/**
* Set the goMolecularFunction.
*
* @param goMolecularFunction
* The goMolecularFunction to set
*/
public void setGoMolecularFunction(String goMolecularFunction) {
this.goMolecularFunction = goMolecularFunction;
}
/**
* Returns the cloneListSpecify.
*
* @return String
*/
public String getCloneListSpecify() {
return cloneListSpecify;
}
/**
* Set the cloneListSpecify.
*
* @param cloneListSpecify
* The cloneListSpecify to set
*/
public void setCloneListSpecify(String cloneListSpecify) {
this.cloneListSpecify = cloneListSpecify;
// this is to check if the radio button is selected for the clone
// category
String thisCloneId = (String) thisRequest.getParameter("cloneId");
// this is to check the type of the clone
String thisCloneList = (String) thisRequest.getParameter("cloneList");
if (thisCloneId != null && thisCloneList != null
&& !thisCloneList.equals("")) {
if (this.cloneListSpecify != null && !cloneListSpecify.equals("")) {
String[] cloneStr = cloneListSpecify.split("\\x2C");
for (int i = 0; i < cloneStr.length; i++) {
if (thisCloneList.equalsIgnoreCase("imageId")) {
cloneDomainMap.put(cloneStr[i],
CloneIdentifierDE.IMAGEClone.class.getName());
} else if (thisCloneList.equalsIgnoreCase("BACId")) {
cloneDomainMap.put(cloneStr[i],
CloneIdentifierDE.BACClone.class.getName());
} else if (thisCloneList.equalsIgnoreCase("probeSetId")) {
cloneDomainMap.put(cloneStr[i],
CloneIdentifierDE.ProbesetID.class.getName());
}
} // end of for loop
}// end of if(this.cloneListSpecify != null &&
// !cloneListSpecify.equals("")){
}
}
/**
* Returns the cloneListFile.
*
* @return String
*/
public String getCloneListFile() {
return cloneListFile;
}
/**
* Set the cloneListFile.
*
* @param cloneListFile
* The cloneListFile to set
*/
public void setCloneListFile(String cloneListFile) {
this.cloneListFile = cloneListFile;
// this is to check if the radio button is selected for the clone
// category
String thisCloneId = (String) thisRequest.getParameter("cloneId");
// this is to check the type of the clone
String thisCloneList = (String) thisRequest.getParameter("cloneList");
if ((thisCloneId != null) && thisCloneId.equalsIgnoreCase("Upload")
&& (thisCloneList.length() > 0)
&& (this.cloneListFile.length() > 0)) {
File cloneFile = new File(this.cloneListFile);
String line = null;
try {
FileReader editfr = new FileReader(cloneFile);
BufferedReader inFile = new BufferedReader(editfr);
line = inFile.readLine();
int i = 0;
while (line != null && line.length() > 0) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (thisCloneList.equalsIgnoreCase("imageId")) {
cloneDomainMap.put(token,
CloneIdentifierDE.IMAGEClone.class
.getName());
} else if (thisCloneList.equalsIgnoreCase("BACId")) {
cloneDomainMap.put(token,
CloneIdentifierDE.BACClone.class.getName());
} else if (thisCloneList.equalsIgnoreCase("probeSetId")) {
cloneDomainMap.put(token,
CloneIdentifierDE.ProbesetID.class
.getName());
}
}
line = inFile.readLine();
}// end of while
inFile.close();
} catch (IOException ex) {
logger.error("Errors when uploading gene file:"
+ ex.getMessage());
}
}
}
/**
* Returns the goClassification.
*
* @return String
*/
public String getGoClassification() {
return goClassification;
}
/**
* Set the goClassification.
*
* @param goClassification
* The goClassification to set
*/
public void setGoClassification(String goClassification) {
this.goClassification = goClassification;
String goSelect = (String) thisRequest.getParameter("goClassification");
if (goSelect != null && !goSelect.equals("")) {
geneOntologyDomainMap.put(this.goClassification,
GeneOntologyDE.class.getName());
}
}
/**
* Returns the basePairEnd.
*
* @return String
*/
public String getBasePairEnd() {
return basePairEnd;
}
/**
* Set the basePairEnd.
*
* @param basePairEnd
* The basePairEnd to set
*/
public void setBasePairEnd(String basePairEnd) {
this.basePairEnd = basePairEnd;
String thisRegion = this.thisRequest.getParameter("region");
String thisChrNumber = this.thisRequest.getParameter("chrosomeNumber");
String thisBasePairStart = this.thisRequest
.getParameter("basePairStart");
if (thisChrNumber != null && thisChrNumber.trim().length() > 0) {
if (thisRegion != null && thisBasePairStart != null
&& this.basePairEnd != null) {
if ((thisRegion.equalsIgnoreCase("basePairPosition"))
&& (thisBasePairStart.trim().length() > 0)
&& (this.basePairEnd.trim().length() > 0)) {
regionDomainMap.put(this.basePairEnd,
BasePairPositionDE.EndPosition.class.getName());
}
}
}
}
/**
* Returns the chrosomeNumber.
*
* @return String
*/
public String getChrosomeNumber() {
return chrosomeNumber;
}
/**
* Set the chrosomeNumber.
*
* @param chrosomeNumber
* The chrosomeNumber to set
*/
public void setChrosomeNumber(String chrosomeNumber) {
this.chrosomeNumber = chrosomeNumber;
if (chrosomeNumber != null && chrosomeNumber.length() > 0) {
regionDomainMap.put(this.chrosomeNumber, ChromosomeNumberDE.class
.getName());
}
}
/**
* Returns the regulationStatus.
*
* @return String
*/
public String getRegulationStatus() {
return regulationStatus;
}
/**
* Set the regulationStatus.
*
* @param regulationStatus
* The regulationStatus to set
*/
public void setRegulationStatus(String regulationStatus) {
this.regulationStatus = regulationStatus;
}
/**
* Returns the foldChangeValueUnchange.
*
* @return String
*/
public String getFoldChangeValueUnchangeFrom() {
return foldChangeValueUnchangeFrom;
}
/**
* Set the foldChangeValueUnchange.
*
* @param foldChangeValueUnchange
* The foldChangeValueUnchange to set
*/
public void setFoldChangeValueUnchangeFrom(
String foldChangeValueUnchangeFrom) {
this.foldChangeValueUnchangeFrom = foldChangeValueUnchangeFrom;
String thisRegulationStatus = this.thisRequest
.getParameter("regulationStatus");
if (thisRegulationStatus != null
&& thisRegulationStatus.equalsIgnoreCase("unchange")
&& (this.foldChangeValueUnchangeFrom.length() > 0))
foldDownDomainMap.put(this.foldChangeValueUnchangeFrom,
ExprFoldChangeDE.UnChangedRegulationDownLimit.class
.getName());
}
/**
* Returns the foldChangeValueUp.
*
* @return String
*/
/**
* Returns the foldChangeValueUnchange.
*
* @return String
*/
public String getFoldChangeValueUnchangeTo() {
return foldChangeValueUnchangeTo;
}
/**
* Set the foldChangeValueUnchange.
*
* @param foldChangeValueUnchange
* The foldChangeValueUnchange to set
*/
public void setFoldChangeValueUnchangeTo(String foldChangeValueUnchangeTo) {
this.foldChangeValueUnchangeTo = foldChangeValueUnchangeTo;
String thisRegulationStatus = this.thisRequest
.getParameter("regulationStatus");
if (thisRegulationStatus != null
&& thisRegulationStatus.equalsIgnoreCase("unchange")
&& (this.foldChangeValueUnchangeTo.length() > 0)) {
foldUpDomainMap.put(this.foldChangeValueUnchangeTo,
ExprFoldChangeDE.UnChangedRegulationUpperLimit.class
.getName());
}
}
/**
* Returns the foldChangeValueUp.
*
* @return String
*/
public String getFoldChangeValueUp() {
return foldChangeValueUp;
}
/**
* Set the foldChangeValueUp.
*
* @param foldChangeValueUp
* The foldChangeValueUp to set
*/
public void setFoldChangeValueUp(String foldChangeValueUp) {
this.foldChangeValueUp = foldChangeValueUp;
logger.debug("I am in the setFoldChangeValueUp() method");
String thisRegulationStatus = this.thisRequest
.getParameter("regulationStatus");
if (thisRegulationStatus != null
&& thisRegulationStatus.equalsIgnoreCase("up")
&& (this.foldChangeValueUp.length() > 0))
foldUpDomainMap.put(this.foldChangeValueUp,
ExprFoldChangeDE.UpRegulation.class.getName());
}
/**
* Returns the geneType.
*
* @return String
*/
public String getGeneType() {
return geneType;
}
/**
* Set the geneType.
*
* @param geneType
* The geneType to set
*/
public void setGeneType(String geneType) {
this.geneType = geneType;
}
/**
* Returns the foldChangeValueUDUp.
*
* @return String
*/
public String getFoldChangeValueUDUp() {
return foldChangeValueUDUp;
}
/**
* Set the foldChangeValueUDUp.
*
* @param foldChangeValueUDUp
* The foldChangeValueUDUp to set
*/
public void setFoldChangeValueUDUp(String foldChangeValueUDUp) {
this.foldChangeValueUDUp = foldChangeValueUDUp;
String thisRegulationStatus = this.thisRequest
.getParameter("regulationStatus");
logger.debug("I am in the setFoldChangeValueUDUp() thisRegulationStatus:"
+ thisRegulationStatus);
if (thisRegulationStatus != null
&& thisRegulationStatus.equalsIgnoreCase("updown")
&& (this.foldChangeValueUDUp.length() > 0)) {
foldUpDomainMap.put(this.foldChangeValueUDUp,
ExprFoldChangeDE.UpRegulation.class.getName());
logger.debug("foldDomainMap size in the setFoldChangeValueUDUp() method:"
+ foldUpDomainMap.size());
}
}
/**
* Returns the foldChangeValueUDDown.
*
* @return String
*/
public String getFoldChangeValueUDDown() {
return foldChangeValueUDDown;
}
/**
* Set the foldChangeValueUDDown.
*
* @param foldChangeValueUDDown
* The foldChangeValueUDDown to set
*/
public void setFoldChangeValueUDDown(String foldChangeValueUDDown) {
this.foldChangeValueUDDown = foldChangeValueUDDown;
String thisRegulationStatus = this.thisRequest
.getParameter("regulationStatus");
logger.debug("I am in the setFoldChangeValueUDDown() methid: "
+ thisRegulationStatus);
if (thisRegulationStatus != null
&& thisRegulationStatus.equalsIgnoreCase("updown")
&& (this.foldChangeValueUDDown.length() > 0))
foldDownDomainMap.put(this.foldChangeValueUDDown,
ExprFoldChangeDE.DownRegulation.class.getName());
logger.debug("foldDomainMap size in the setFoldChangeValueUDDown() method:"
+ foldDownDomainMap.size());
}
/**
* Returns the resultView.
*
* @return String
*/
public String getResultView() {
return resultView;
}
/**
* Set the resultView.
*
* @param resultView
* The resultView to set
*/
public void setResultView(String resultView) {
this.resultView = resultView;
}
/**
* Returns the geneGroup.
*
* @return String
*/
public String getGeneGroup() {
return geneGroup;
}
/**
* Set the geneGroup.
*
* @param geneGroup
* The geneGroup to set
*/
public void setGeneGroup(String geneGroup) {
this.geneGroup = geneGroup;
}
/**
* Returns the cloneList.
*
* @return String
*/
public String getCloneList() {
return cloneList;
}
/**
* Set the cloneList.
*
* @param cloneList
* The cloneList to set
*/
public void setCloneList(String cloneList) {
this.cloneList = cloneList;
}
/**
* Returns the queryName.
*
* @return String
*/
public String getQueryName() {
return queryName;
}
/**
* Set the queryName.
*
* @param queryName
* The queryName to set
*/
public void setQueryName(String queryName) {
this.queryName = queryName;
}
/**
* Returns the basePairStart.
*
* @return String
*/
public String getBasePairStart() {
return basePairStart;
}
/**
* Set the basePairStart.
*
* @param basePairStart
* The basePairStart to set
*/
public void setBasePairStart(String basePairStart) {
this.basePairStart = basePairStart;
String thisRegion = this.thisRequest.getParameter("region");
String thisChrNumber = this.thisRequest.getParameter("chrosomeNumber");
String thisBasePairEnd = this.thisRequest.getParameter("basePairEnd");
if (thisChrNumber != null && thisChrNumber.trim().length() > 0) {
if (thisRegion != null && this.basePairStart != null
&& thisBasePairEnd != null) {
if ((thisRegion.equalsIgnoreCase("basePairPosition"))
&& (thisBasePairEnd.trim().length() > 0)
&& (this.basePairStart.trim().length() > 0)) {
regionDomainMap.put(this.basePairStart,
BasePairPositionDE.StartPosition.class.getName());
}
}
}
}
public ArrayList getCloneTypeColl() {
return cloneTypeColl;
}
public void setQueryCollection(QueryCollection queryCollection) {
this.queryCollection = queryCollection;
}
public QueryCollection getQueryCollection() {
return this.queryCollection;
}
public String[] getPathwayName() {
return pathwayName;
}
public void setPathwayName(String[] pathwayName) {
this.pathwayName = pathwayName;
}
} |
package gov.nih.nci.rembrandt.web.xml;
import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonResult;
import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonResultEntry;
import gov.nih.nci.caintegrator.dto.de.GeneIdentifierDE.GeneSymbol;
import gov.nih.nci.caintegrator.service.findings.ClassComparisonFinding;
import gov.nih.nci.caintegrator.service.findings.Finding;
import gov.nih.nci.rembrandt.queryservice.resultset.DimensionalViewContainer;
import gov.nih.nci.rembrandt.queryservice.resultset.Resultant;
import gov.nih.nci.rembrandt.queryservice.resultset.ResultsContainer;
import gov.nih.nci.rembrandt.queryservice.resultset.annotation.GeneExprAnnotationService;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.GeneExprSingleViewResultsContainer;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.GeneResultset;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.ReporterResultset;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.SampleFoldChangeValuesResultset;
import gov.nih.nci.rembrandt.queryservice.resultset.gene.ViewByGroupResultset;
import gov.nih.nci.rembrandt.web.helper.FilterHelper;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @author LandyR
* Feb 8, 2005
*
*/
public class ClassComparisonReport{
public ClassComparisonReport() {
//super();
}
/* (non-Javadoc)
* @see gov.nih.nci.nautilus.ui.report.ReportGenerator#getTemplate(gov.nih.nci.nautilus.resultset.Resultant, java.lang.String)
*/
public static Document getReportXML(Finding finding, Map filterMapParams) {
DecimalFormat resultFormat = new DecimalFormat("0.0000");
/*
* this is for filtering, we will want a p-value filter for CC
*/
ArrayList filter_string = new ArrayList(); // hashmap of genes | reporters | cytobands
String filter_type = "show"; // show | hide
String filter_element = "none"; // none | gene | reporter | cytoband
if(filterMapParams.containsKey("filter_string") && filterMapParams.get("filter_string") != null)
filter_string = (ArrayList) filterMapParams.get("filter_string");
if(filterMapParams.containsKey("filter_type") && filterMapParams.get("filter_type") != null)
filter_type = (String) filterMapParams.get("filter_type");
if(filterMapParams.containsKey("filter_element") && filterMapParams.get("filter_element") != null)
filter_element = (String) filterMapParams.get("filter_element");
String defaultV = "
String delim = " | ";
Document document = DocumentHelper.createDocument();
Element report = document.addElement( "Report" );
Element cell = null;
Element data = null;
Element dataRow = null;
//add the atts
report.addAttribute("reportType", "Class Comparison");
//fudge these for now
report.addAttribute("groupBy", "none");
String queryName = "none";
queryName = finding.getTaskId();
//set the queryName to be unique for session/cache access
report.addAttribute("queryName", queryName);
report.addAttribute("sessionId", "the session id");
report.addAttribute("creationTime", "right now");
StringBuffer sb = new StringBuffer();
int recordCount = 0;
int totalSamples = 0;
//TODO: instance of
ClassComparisonFinding ccf = (ClassComparisonFinding) finding;
if(ccf != null) {
Element headerRow = report.addElement("Row").addAttribute("name", "headerRow");
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("Reporter");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("Group Avg");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
String isAdj = ccf.arePvaluesAdjusted() ? " (Adjusted) " : "";
data = cell.addElement("Data").addAttribute("type", "header").addText("P-Value"+isAdj);
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("Fold Change");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "header").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("Gene Symbol");
data = null;
cell = null;
//starting annotations...leave these here for now, as we may want them
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GenBank Acc");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("Locus link");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("GO Id");
data = null;
cell = null;
cell = headerRow.addElement("Cell").addAttribute("type", "header").addAttribute("class", "csv").addAttribute("group", "header");
data = cell.addElement("Data").addAttribute("type", "header").addText("Pathways");
data = null;
cell = null;
/* done with the headerRow and SampleRow Elements, time to add data rows */
Map<String,ReporterResultset> reporterResultsetMap = null;
reporterResultsetMap = ccf.getReporterAnnotationsMap();
List<ClassComparisonResultEntry> classComparisonResultEntrys = ccf.getResultEntries();
List<String> reporterIds = new ArrayList<String>();
for (ClassComparisonResultEntry classComparisonResultEntry: classComparisonResultEntrys){
if(classComparisonResultEntry.getReporterId() != null){
reporterIds.add(classComparisonResultEntry.getReporterId());
}
}
if(reporterResultsetMap == null) {
try {
reporterResultsetMap = GeneExprAnnotationService.getAnnotationsMapForReporters(reporterIds);
}
catch(Exception e){}
}
for(ClassComparisonResultEntry ccre : ccf.getResultEntries()) {
dataRow = report.addElement("Row").addAttribute("name", "dataRow");
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "reporter").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(ccre.getReporterId());
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(resultFormat.format(ccre.getMeanGrp1()) + " / " + resultFormat.format(ccre.getMeanGrp2()));
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
//String pv = (ccre.getPvalue() == null) ? String.valueOf(ccre.getPvalue()) : "N/A";
data = cell.addElement("Data").addAttribute("type", "header").addText(String.valueOf(resultFormat.format(ccre.getPvalue())));
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "data").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(String.valueOf(resultFormat.format(ccre.getFoldChange())));
data = null;
cell = null;
//get the gene symbols for this reporter
//ccre.getReporterId()
String genes = defaultV;
//start annotations
String accIds = defaultV;
String llink = defaultV;
String go = defaultV;
String pw = defaultV;
if(reporterResultsetMap != null && reporterIds != null){
//int count = 0;
String reporterId = ccre.getReporterId();
ReporterResultset reporterResultset = reporterResultsetMap.get(reporterId);
Collection<String> geneSymbols = (Collection<String>)reporterResultset.getAssiciatedGeneSymbols();
if(geneSymbols != null){
genes = StringUtils.join(geneSymbols.toArray(), delim);
}
Collection<String> genBank_AccIDS = (Collection<String>)reporterResultset.getAssiciatedGenBankAccessionNos();
if(genBank_AccIDS != null){
accIds = StringUtils.join(genBank_AccIDS.toArray(), delim);
}
Collection<String> locusLinkIDs = (Collection<String>)reporterResultset.getAssiciatedLocusLinkIDs();
if(locusLinkIDs != null){
llink = StringUtils.join(locusLinkIDs.toArray(), delim);
}
Collection<String> goIds = (Collection<String>)reporterResultset.getAssociatedGOIds();
if(goIds != null){
go = StringUtils.join(goIds.toArray(), delim);
}
Collection<String> pathways = (Collection<String>)reporterResultset.getAssociatedPathways();
if(pathways != null){
pw = StringUtils.join(pathways.toArray(), delim);
}
}
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "gene").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(genes);
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(accIds);
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(llink);
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(go);
data = null;
cell = null;
cell = dataRow.addElement("Cell").addAttribute("type", "data").addAttribute("class", "csv").addAttribute("group", "data");
data = cell.addElement("Data").addAttribute("type", "header").addText(pw);
data = null;
cell = null;
}
}
else {
//TODO: handle this error
sb.append("<br><Br>Class Comparison is empty<br>");
}
return document;
}
} |
package org.rstudio.studio.client.projects;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.SerializedCommand;
import org.rstudio.core.client.SerializedCommandQueue;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.core.client.widget.MessageDialog;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.core.client.widget.ProgressOperationWithInput;
import org.rstudio.studio.client.application.ApplicationQuit;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.FileDialogs;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.console.ConsoleProcess;
import org.rstudio.studio.client.common.console.ProcessExitEvent;
import org.rstudio.studio.client.common.vcs.GitServerOperations;
import org.rstudio.studio.client.common.vcs.VCSConstants;
import org.rstudio.studio.client.common.vcs.VcsCloneOptions;
import org.rstudio.studio.client.packrat.model.PackratServerOperations;
import org.rstudio.studio.client.projects.events.OpenProjectErrorEvent;
import org.rstudio.studio.client.projects.events.OpenProjectErrorHandler;
import org.rstudio.studio.client.projects.events.OpenProjectFileEvent;
import org.rstudio.studio.client.projects.events.OpenProjectFileHandler;
import org.rstudio.studio.client.projects.events.SwitchToProjectEvent;
import org.rstudio.studio.client.projects.events.SwitchToProjectHandler;
import org.rstudio.studio.client.projects.model.NewProjectContext;
import org.rstudio.studio.client.projects.model.NewProjectInput;
import org.rstudio.studio.client.projects.model.NewProjectResult;
import org.rstudio.studio.client.projects.model.ProjectsServerOperations;
import org.rstudio.studio.client.projects.model.RProjectOptions;
import org.rstudio.studio.client.projects.ui.newproject.NewProjectWizard;
import org.rstudio.studio.client.projects.ui.prefs.ProjectPreferencesDialog;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.server.remote.RResult;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.events.SessionInitEvent;
import org.rstudio.studio.client.workbench.events.SessionInitHandler;
import org.rstudio.studio.client.workbench.model.RemoteFileSystemContext;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.SessionInfo;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.views.vcs.common.ConsoleProgressDialog;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Command;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
@Singleton
public class Projects implements OpenProjectFileHandler,
SwitchToProjectHandler,
OpenProjectErrorHandler
{
public interface Binder extends CommandBinder<Commands, Projects> {}
@Inject
public Projects(GlobalDisplay globalDisplay,
final Session session,
Provider<ProjectMRUList> pMRUList,
FileDialogs fileDialogs,
RemoteFileSystemContext fsContext,
ApplicationQuit applicationQuit,
ProjectsServerOperations projServer,
PackratServerOperations packratServer,
GitServerOperations gitServer,
EventBus eventBus,
Binder binder,
final Commands commands,
Provider<ProjectPreferencesDialog> pPrefDialog,
Provider<UIPrefs> pUIPrefs)
{
globalDisplay_ = globalDisplay;
pMRUList_ = pMRUList;
applicationQuit_ = applicationQuit;
projServer_ = projServer;
packratServer_ = packratServer;
gitServer_ = gitServer;
fileDialogs_ = fileDialogs;
fsContext_ = fsContext;
session_ = session;
pPrefDialog_ = pPrefDialog;
pUIPrefs_ = pUIPrefs;
binder.bind(commands, this);
eventBus.addHandler(OpenProjectErrorEvent.TYPE, this);
eventBus.addHandler(SwitchToProjectEvent.TYPE, this);
eventBus.addHandler(OpenProjectFileEvent.TYPE, this);
eventBus.addHandler(SessionInitEvent.TYPE, new SessionInitHandler() {
public void onSessionInit(SessionInitEvent sie)
{
SessionInfo sessionInfo = session.getSessionInfo();
// ensure mru is initialized
ProjectMRUList mruList = pMRUList_.get();
// enable/disable commands
String activeProjectFile = sessionInfo.getActiveProjectFile();
boolean hasProject = activeProjectFile != null;
commands.closeProject().setEnabled(hasProject);
commands.projectOptions().setEnabled(hasProject);
if (!hasProject)
{
commands.setWorkingDirToProjectDir().remove();
commands.showDiagnosticsProject().remove();
}
// remove version control commands if necessary
if (!sessionInfo.isVcsEnabled())
{
commands.activateVcs().remove();
commands.vcsCommit().remove();
commands.vcsShowHistory().remove();
commands.vcsPull().remove();
commands.vcsPush().remove();
commands.vcsCleanup().remove();
}
else
{
commands.activateVcs().setMenuLabel(
"Show _" + sessionInfo.getVcsName());
// customize for svn if necessary
if (sessionInfo.getVcsName().equals(VCSConstants.SVN_ID))
{
commands.vcsPush().remove();
commands.vcsPull().setButtonLabel("Update");
commands.vcsPull().setMenuLabel("_Update");
}
// customize for git if necessary
if (sessionInfo.getVcsName().equals(VCSConstants.GIT_ID))
{
commands.vcsCleanup().remove();
}
}
// disable the open project in new window if necessary
if (!sessionInfo.getMultiSession())
commands.openProjectInNewWindow().remove();
// maintain mru
if (hasProject)
mruList.add(activeProjectFile);
}
});
}
@Handler
public void onClearRecentProjects()
{
// Clear the contents of the most rencently used list of projects
pMRUList_.get().clear();
}
@Handler
public void onNewProject()
{
// first resolve the quit context (potentially saving edited documents
// and determining whether to save the R environment on exit)
applicationQuit_.prepareForQuit("Save Current Workspace",
new ApplicationQuit.QuitContext() {
@Override
public void onReadyToQuit(final boolean saveChanges)
{
projServer_.getNewProjectContext(
new SimpleRequestCallback<NewProjectContext>() {
@Override
public void onResponseReceived(NewProjectContext context)
{
NewProjectWizard wiz = new NewProjectWizard(
session_.getSessionInfo(),
pUIPrefs_.get(),
new NewProjectInput(
FileSystemItem.createDir(
pUIPrefs_.get().defaultProjectLocation().getValue()),
context
),
new ProgressOperationWithInput<NewProjectResult>() {
@Override
public void execute(NewProjectResult newProject,
ProgressIndicator indicator)
{
indicator.onCompleted();
createNewProject(newProject, saveChanges);
}
});
wiz.showModal();
}
});
}
});
}
private void createNewProject(final NewProjectResult newProject,
final boolean saveChanges)
{
// This gets a little crazy. We have several pieces of asynchronous logic
// that each may or may not need to be executed, depending on the type
// of project being created and on whether the previous pieces of logic
// succeed. Plus we have this ProgressIndicator that needs to be fed
// properly.
final ProgressIndicator indicator = globalDisplay_.getProgressIndicator(
"Error Creating Project");
// Here's the command queue that will hold the various operations.
final SerializedCommandQueue createProjectCmds =
new SerializedCommandQueue();
// WARNING: When calling addCommand, BE SURE TO PASS FALSE as the second
// argument, to delay running of the commands until they are all
// scheduled.
// First, attempt to update the default project location pref
createProjectCmds.addCommand(new SerializedCommand()
{
@Override
public void onExecute(final Command continuation)
{
UIPrefs uiPrefs = pUIPrefs_.get();
// update default project location pref if necessary
if ((newProject.getNewDefaultProjectLocation() != null) ||
(newProject.getCreateGitRepo() !=
uiPrefs.newProjGitInit().getValue()))
{
indicator.onProgress("Saving defaults...");
if (newProject.getNewDefaultProjectLocation() != null)
{
uiPrefs.defaultProjectLocation().setGlobalValue(
newProject.getNewDefaultProjectLocation());
}
if (newProject.getCreateGitRepo() !=
uiPrefs.newProjGitInit().getValue())
{
uiPrefs.newProjGitInit().setGlobalValue(
newProject.getCreateGitRepo());
}
if (newProject.getUsePackrat() !=
uiPrefs.newProjUsePackrat().getValue())
{
uiPrefs.newProjUsePackrat().setGlobalValue(
newProject.getUsePackrat());
}
// call the server -- in all cases continue on with
// creating the project (swallow errors updating the pref)
projServer_.setUiPrefs(
session_.getSessionInfo().getUiPrefs(),
new VoidServerRequestCallback(indicator) {
@Override
public void onResponseReceived(Void response)
{
continuation.execute();
}
@Override
public void onError(ServerError error)
{
super.onError(error);
continuation.execute();
}
});
}
else
{
continuation.execute();
}
}
}, false);
// Next, if necessary, clone a repo
if (newProject.getVcsCloneOptions() != null)
{
createProjectCmds.addCommand(new SerializedCommand()
{
@Override
public void onExecute(final Command continuation)
{
VcsCloneOptions cloneOptions = newProject.getVcsCloneOptions();
if (cloneOptions.getVcsName().equals((VCSConstants.GIT_ID)))
indicator.onProgress("Cloning Git repository...");
else
indicator.onProgress("Checking out SVN repository...");
gitServer_.vcsClone(
cloneOptions,
new ServerRequestCallback<ConsoleProcess>() {
@Override
public void onResponseReceived(ConsoleProcess proc)
{
final ConsoleProgressDialog consoleProgressDialog =
new ConsoleProgressDialog(proc, gitServer_);
consoleProgressDialog.showModal();
proc.addProcessExitHandler(new ProcessExitEvent.Handler()
{
@Override
public void onProcessExit(ProcessExitEvent event)
{
if (event.getExitCode() == 0)
{
consoleProgressDialog.hide();
continuation.execute();
}
else
{
indicator.onCompleted();
}
}
});
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
indicator.onError(error.getUserMessage());
}
});
}
}, false);
}
// Next, create the project itself -- depending on the type, this
// could involve creating an R package, or Shiny application, and so on.
createProjectCmds.addCommand(new SerializedCommand()
{
@Override
public void onExecute(final Command continuation)
{
// Validate the package name if we're creating a package
if (newProject.getNewPackageOptions() != null)
{
final String packageName =
newProject.getNewPackageOptions().getPackageName();
if (!PACKAGE_NAME_PATTERN.test(packageName))
{
indicator.onError(
"Invalid package name '" + packageName + "': " +
"package names must start with a letter, and contain " +
"only letters and numbers."
);
return;
}
}
indicator.onProgress("Creating project...");
if (newProject.getNewPackageOptions() == null)
{
projServer_.createProject(
newProject.getProjectFile(),
newProject.getNewPackageOptions(),
newProject.getNewShinyAppOptions(),
new VoidServerRequestCallback(indicator)
{
@Override
public void onSuccess()
{
continuation.execute();
}
});
}
else
{
String projectFile = newProject.getProjectFile();
String packageDirectory = projectFile.substring(0,
projectFile.lastIndexOf('/'));
projServer_.packageSkeleton(
newProject.getNewPackageOptions().getPackageName(),
packageDirectory,
newProject.getNewPackageOptions().getCodeFiles(),
newProject.getNewPackageOptions().getUsingRcpp(),
new ServerRequestCallback<RResult<Void>>()
{
@Override
public void onResponseReceived(RResult<Void> response)
{
if (response.failed())
indicator.onError(response.errorMessage());
else
continuation.execute();
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
indicator.onError(error.getUserMessage());
}
});
}
}
}, false);
// Next, initialize a git repo if requested
if (newProject.getCreateGitRepo())
{
createProjectCmds.addCommand(new SerializedCommand()
{
@Override
public void onExecute(final Command continuation)
{
indicator.onProgress("Initializing git repository...");
String projDir = FileSystemItem.createFile(
newProject.getProjectFile()).getParentPathString();
gitServer_.gitInitRepo(
projDir,
new VoidServerRequestCallback(indicator)
{
@Override
public void onSuccess()
{
continuation.execute();
}
@Override
public void onFailure()
{
continuation.execute();
}
});
}
}, false);
}
// Generate a new packrat project
if (newProject.getUsePackrat()) {
createProjectCmds.addCommand(new SerializedCommand()
{
@Override
public void onExecute(final Command continuation) {
indicator.onProgress("Initializing packrat project...");
String projDir = FileSystemItem.createFile(
newProject.getProjectFile()
).getParentPathString();
packratServer_.packratBootstrap(
projDir,
false,
new VoidServerRequestCallback(indicator) {
@Override
public void onSuccess()
{
continuation.execute();
}
});
}
}, false);
}
if (newProject.getOpenInNewWindow())
{
createProjectCmds.addCommand(new SerializedCommand() {
@Override
public void onExecute(final Command continuation)
{
FileSystemItem project = FileSystemItem.createFile(
newProject.getProjectFile());
if (Desktop.isDesktop())
{
Desktop.getFrame().openProjectInNewWindow(project.getPath());
continuation.execute();
}
else
{
indicator.onProgress("Preparing to open project...");
serverOpenProjectInNewWindow(project, continuation);
}
}
}, false);
}
// If we get here, dismiss the progress indicator
createProjectCmds.addCommand(new SerializedCommand()
{
@Override
public void onExecute(Command continuation)
{
indicator.onCompleted();
if (!newProject.getOpenInNewWindow())
{
applicationQuit_.performQuit(
saveChanges,
newProject.getProjectFile());
}
continuation.execute();
}
}, false);
// Now set it all in motion!
createProjectCmds.run();
}
@Handler
public void onOpenProject()
{
// first resolve the quit context (potentially saving edited documents
// and determining whether to save the R environment on exit)
applicationQuit_.prepareForQuit("Switch Projects",
new ApplicationQuit.QuitContext() {
public void onReadyToQuit(final boolean saveChanges)
{
showOpenProjectDialog(
new ProgressOperationWithInput<FileSystemItem>()
{
@Override
public void execute(final FileSystemItem input,
ProgressIndicator indicator)
{
indicator.onCompleted();
if (input == null)
return;
// perform quit
applicationQuit_.performQuit(saveChanges, input.getPath());
}
});
}
});
}
@Handler
public void onOpenProjectInNewWindow()
{
showOpenProjectDialog(
new ProgressOperationWithInput<FileSystemItem>()
{
@Override
public void execute(final FileSystemItem input,
ProgressIndicator indicator)
{
indicator.onCompleted();
if (input == null)
return;
// call the desktop to open the project (since it is
// a conventional foreground gui application it has
// less chance of running afowl of desktop app creation
// & activation restrictions)
if (Desktop.isDesktop())
Desktop.getFrame().openProjectInNewWindow(input.getPath());
else
serverOpenProjectInNewWindow(input, null);
}
});
}
@Handler
public void onCloseProject()
{
// first resolve the quit context (potentially saving edited documents
// and determining whether to save the R environment on exit)
applicationQuit_.prepareForQuit("Close Project",
new ApplicationQuit.QuitContext() {
public void onReadyToQuit(final boolean saveChanges)
{
applicationQuit_.performQuit(saveChanges, NONE);
}});
}
@Handler
public void onProjectOptions()
{
showProjectOptions(ProjectPreferencesDialog.GENERAL);
}
@Handler
public void onProjectSweaveOptions()
{
showProjectOptions(ProjectPreferencesDialog.SWEAVE);
}
@Handler
public void onBuildToolsProjectSetup()
{
// check whether there is a project active
if (!hasActiveProject())
{
globalDisplay_.showMessage(
MessageDialog.INFO,
"No Active Project",
"Build tools can only be configured from within an " +
"RStudio project.");
}
else
{
showProjectOptions(ProjectPreferencesDialog.BUILD);
}
}
@Handler
public void onVersionControlProjectSetup()
{
// check whether there is a project active
if (!hasActiveProject())
{
globalDisplay_.showMessage(
MessageDialog.INFO,
"No Active Project",
"Version control features can only be accessed from within an " +
"RStudio project. Note that if you have an existing directory " +
"under version control you can associate an RStudio project " +
"with that directory using the New Project dialog.");
}
else
{
showProjectOptions(ProjectPreferencesDialog.VCS);
}
}
@Handler
public void onPackratBootstrap()
{
showProjectOptions(ProjectPreferencesDialog.PACKRAT);
}
@Handler
public void onPackratOptions()
{
showProjectOptions(ProjectPreferencesDialog.PACKRAT);
}
private void showProjectOptions(final int initialPane)
{
final ProgressIndicator indicator = globalDisplay_.getProgressIndicator(
"Error Reading Options");
indicator.onProgress("Reading options...");
projServer_.readProjectOptions(new SimpleRequestCallback<RProjectOptions>() {
@Override
public void onResponseReceived(RProjectOptions options)
{
indicator.onCompleted();
ProjectPreferencesDialog dlg = pPrefDialog_.get();
dlg.initialize(options);
dlg.activatePane(initialPane);
dlg.showModal();
}});
}
@Override
public void onOpenProjectFile(final OpenProjectFileEvent event)
{
// project options for current project
FileSystemItem projFile = event.getFile();
if (projFile.getPath().equals(
session_.getSessionInfo().getActiveProjectFile()))
{
onProjectOptions();
return;
}
// prompt to confirm
String projectPath = projFile.getParentPathString();
globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_QUESTION,
"Confirm Open Project",
"Do you want to open the project " + projectPath + "?",
new Operation()
{
public void execute()
{
switchToProject(event.getFile().getPath());
}
},
true);
}
@Override
public void onSwitchToProject(final SwitchToProjectEvent event)
{
switchToProject(event.getProject());
}
@Override
public void onOpenProjectError(OpenProjectErrorEvent event)
{
// show error dialog
String msg = "Project '" + event.getProject() + "' " +
"could not be opened: " + event.getMessage();
globalDisplay_.showErrorMessage("Error Opening Project", msg);
// remove from mru list
pMRUList_.get().remove(event.getProject());
}
private boolean hasActiveProject()
{
return session_.getSessionInfo().getActiveProjectFile() != null;
}
private void switchToProject(final String projectFilePath)
{
applicationQuit_.prepareForQuit("Switch Projects",
new ApplicationQuit.QuitContext() {
public void onReadyToQuit(final boolean saveChanges)
{
applicationQuit_.performQuit(saveChanges, projectFilePath);
}});
}
private void showOpenProjectDialog(
ProgressOperationWithInput<FileSystemItem> onCompleted)
{
// choose project file
fileDialogs_.openFile(
"Open Project",
fsContext_,
FileSystemItem.createDir(
pUIPrefs_.get().defaultProjectLocation().getValue()),
"R Projects (*.Rproj)",
onCompleted);
}
@Handler
public void onShowDiagnosticsProject()
{
final ProgressIndicator indicator = globalDisplay_.getProgressIndicator("Lint");
indicator.onProgress("Analyzing project sources...");
projServer_.analyzeProject(new ServerRequestCallback<Void>()
{
@Override
public void onResponseReceived(Void response)
{
indicator.onCompleted();
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
indicator.onCompleted();
}
});
}
private void serverOpenProjectInNewWindow(FileSystemItem project,
final Command onSuccess)
{
projServer_.getProjectUrl(
GWT.getHostPageBaseURL(),
project.getParentPathString(),
new SimpleRequestCallback<String>() {
@Override
public void onResponseReceived(String url)
{
if (onSuccess != null)
onSuccess.execute();
globalDisplay_.openWindow(url);
}
});
}
private final Provider<ProjectMRUList> pMRUList_;
private final ApplicationQuit applicationQuit_;
private final ProjectsServerOperations projServer_;
private final PackratServerOperations packratServer_;
private final GitServerOperations gitServer_;
private final FileDialogs fileDialogs_;
private final RemoteFileSystemContext fsContext_;
private final GlobalDisplay globalDisplay_;
private final Session session_;
private final Provider<ProjectPreferencesDialog> pPrefDialog_;
private final Provider<UIPrefs> pUIPrefs_;
public static final String NONE = "none";
public static final Pattern PACKAGE_NAME_PATTERN =
Pattern.create("^[a-zA-Z][a-zA-Z0-9.]*$", "");
} |
package it.feio.android.omninotes.async;
import it.feio.android.omninotes.OmniNotes;
import it.feio.android.omninotes.R;
import it.feio.android.omninotes.models.Attachment;
import it.feio.android.omninotes.utils.BitmapDecoder;
import it.feio.android.omninotes.utils.Constants;
import it.feio.android.omninotes.utils.StorageManager;
import java.io.FileNotFoundException;
import java.lang.ref.WeakReference;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.widget.ImageView;
public class ThumbnailLoaderTask extends
AsyncTask<Attachment, Void, Bitmap> {
private final int FADE_IN_TIME = 190;
private final Activity mActivity;
private final WeakReference<ImageView> imageViewReference;
private int width = 100;
private int height = 100;
public ThumbnailLoaderTask(Activity activity, ImageView imageView,
int thumbnailSize) {
this.mActivity = activity;
imageViewReference = new WeakReference<ImageView>(imageView);
width = thumbnailSize;
height = thumbnailSize;
}
@Override
protected Bitmap doInBackground(Attachment... params) {
Bitmap bmp = null;
Attachment mAttachment = params[0];
String path = mAttachment.getUri().getPath();
// Creating a key based on path and thumbnail size to re-use the same
// AsyncTask both for list and detail
String cacheKey = path + width;
// Requesting from Application an instance of the cache
OmniNotes app = ((OmniNotes) mActivity.getApplication());
// Video
if (Constants.MIME_TYPE_VIDEO.equals(mAttachment.getMime_type())) {
// Tries to retrieve full path from ContentResolver if is a new
// video
path = StorageManager.getRealPathFromURI(mActivity,
mAttachment.getUri());
// .. or directly from local directory otherwise
if (path == null) {
path = mAttachment.getUri().getPath();
}
// Fetch from cache if possible
bmp = app.getBitmapFromMemCache(cacheKey);
// Otherwise creates thumbnail
if (bmp == null) {
bmp = ThumbnailUtils.createVideoThumbnail(path,
Thumbnails.MINI_KIND);
bmp = createVideoThumbnail(bmp);
app.addBitmapToCache(cacheKey, bmp);
}
// Image
} else if (Constants.MIME_TYPE_IMAGE.equals(mAttachment.getMime_type())) {
try {
// Fetch from cache if possible
bmp = app.getBitmapFromMemCache(cacheKey);
// Otherwise creates thumbnail
if (bmp == null) {
try {
bmp = checkIfBroken(BitmapDecoder.decodeSampledFromUri(
mActivity, mAttachment.getUri(), width, height));
// cache.addBitmap(path, bmp);
app.addBitmapToCache(cacheKey, bmp);
} catch (FileNotFoundException e) {
Log.e(Constants.TAG,
"Error getting bitmap for thumbnail " + path);
}
}
} catch (NullPointerException e) {
bmp = checkIfBroken(null);
// cache.addBitmap(cacheKey, bmp);
app.addBitmapToCache(cacheKey, bmp);
}
// Audio
} else if (Constants.MIME_TYPE_AUDIO.equals(mAttachment.getMime_type())) {
// Fetch from cache if possible
bmp = app.getBitmapFromMemCache(cacheKey);
// Otherwise creates thumbnail
if (bmp == null) {
bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeResource(
mActivity.getResources(), R.drawable.play), width, height);
bmp = BitmapDecoder.drawTextToBitmap(mActivity, bmp, mAttachment
.getUri().getLastPathSegment(), null, -10, 10, mActivity
.getResources().getColor(R.color.text_gray));
app.addBitmapToCache(cacheKey, bmp);
}
}
return bmp;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// if (imageViewReference != null && bitmap != null) {
// final ImageView imageView = imageViewReference.get();
// if (imageView != null) {
// imageView.setImageBitmap(bitmap);
fadeInImage(bitmap);
}
/**
* Draws a watermark on ImageView to highlight videos
*
* @param bmp
* @param overlay
* @return
*/
public Bitmap createVideoThumbnail(Bitmap video) {
Bitmap mark = ThumbnailUtils.extractThumbnail(
BitmapFactory.decodeResource(mActivity.getResources(),
R.drawable.play_white), width, height);
Bitmap thumbnail = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(thumbnail);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(checkIfBroken(video), 0, 0, null);
canvas.drawBitmap(mark, 0, 0, null);
return thumbnail;
}
private Bitmap checkIfBroken(Bitmap bmp) {
// In case no thumbnail can be extracted from video
if (bmp == null) {
bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeResource(
mActivity.getResources(), R.drawable.attachment_broken),
width, height);
}
return bmp;
}
private void fadeInImage(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
// Transition drawable with a transparent drwabale and the final
// bitmap
final TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(Color.TRANSPARENT),
new BitmapDrawable(mActivity.getResources(), bitmap) });
// Set background to loading bitmap
// imageView.setBackgroundDrawable(
// new BitmapDrawable(mLoadingBitmap));
imageView.setImageDrawable(td);
td.startTransition(FADE_IN_TIME);
}
}
}
} |
package com.sarality.app.view.nav;
import android.app.Activity;
import android.view.View;
import com.sarality.app.view.action.BaseViewAction;
import com.sarality.app.view.action.TriggerType;
import com.sarality.app.view.action.ViewActionTrigger;
import com.sarality.app.view.action.ViewDetail;
/**
* Action to finish an Activity
*
* @author sunayna@ (Sunayna Uberoy)
*/
public class FinishActivityAction extends BaseViewAction {
private final Activity activity;
/**
* Constructor.
*
* @param viewId Id of view that triggers the action.
* @param triggerType Type of event that triggers the action.
* @param Activity that needs to be finished
*/
public FinishActivityAction(int viewId, TriggerType triggerType, Activity activity) {
super(viewId, triggerType);
this.activity = activity;
}
@Override
public boolean doAction(View view, ViewActionTrigger actionDetail, ViewDetail viewDetail) {
activity.finish();
return true;
}
} |
package io.compgen.ngsutils.vcf.annotate;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.DataFormatException;
import io.compgen.common.IterUtils;
import io.compgen.common.StringUtils;
import io.compgen.ngsutils.tabix.TabixFile;
import io.compgen.ngsutils.vcf.VCFAnnotationDef;
import io.compgen.ngsutils.vcf.VCFAttributeException;
import io.compgen.ngsutils.vcf.VCFAttributeValue;
import io.compgen.ngsutils.vcf.VCFHeader;
import io.compgen.ngsutils.vcf.VCFParseException;
import io.compgen.ngsutils.vcf.VCFRecord;
public class VCFAnnotation extends AbstractBasicAnnotator {
private static Map<String, TabixFile> cache = new HashMap<String, TabixFile>();
final protected String name;
final protected String filename;
final protected TabixFile vcfTabix;
final protected String infoVal;
final protected boolean exactMatch;
final protected boolean passingOnly;
public VCFAnnotation(String name, String filename, String infoVal, boolean exact, boolean passing) throws IOException {
this.name = name;
this.filename = filename;
this.infoVal = infoVal;
if (name.equals("@ID")) {
this.exactMatch = true;
} else {
this.exactMatch = exact;
}
this.passingOnly = passing;
this.vcfTabix = getTabixFile(filename);
}
public VCFAnnotation(String name, String filename, String infoVal) throws IOException {
this(name, filename, infoVal, false, false);
}
private static TabixFile getTabixFile(String filename) throws IOException {
if (!cache.containsKey(filename)) {
cache.put(filename, new TabixFile(filename));
}
return cache.get(filename);
}
@Override
public void setHeaderInner(VCFHeader header) throws VCFAnnotatorException {
try {
if (name.equals("@ID")) {
return;
}
String extra = "";
if (passingOnly && exactMatch) {
extra = " (passing, exact match)";
} else if (passingOnly) {
extra = " (passing)";
} else if (exactMatch) {
extra = " (exact match)";
}
if (infoVal == null) {
header.addInfo(VCFAnnotationDef.info(name, "0", "Flag", "Present in VCF file"+extra, filename, null, null, null));
} else {
header.addInfo(VCFAnnotationDef.info(name, "1", "String", infoVal+" from VCF file"+extra, filename, null, null, null));
}
} catch (VCFParseException e) {
throw new VCFAnnotatorException(e);
}
}
@Override
public void close() throws VCFAnnotatorException {
try {
vcfTabix.close();
} catch (IOException e) {
throw new VCFAnnotatorException(e);
}
}
@Override
public void annotate(VCFRecord record) throws VCFAnnotatorException {
String chrom;
int pos;
try {
chrom = getChrom(record);
pos = getPos(record);
} catch (VCFAnnotatorMissingAltException e) {
return;
}
// System.err.println("Query: " + chrom+":"+pos);
try {
// String records = ; // zero-based query
// if (records == null) {
// return;
List<String> vals = new ArrayList<String>();
for (String line: IterUtils.wrap(vcfTabix.query(chrom, pos-1))) {
VCFRecord bgzfRec = VCFRecord.parseLine(line);
// System.err.println("Record: " + bgzfRec.getChrom()+":"+bgzfRec.getPos());
if (bgzfRec.getPos() != record.getPos()) {
// System.err.println("Wrong pos?" + record.getPos() + " vs " + bgzfRec.getPos());
// exact pos matches only...
// don't check chrom to avoid potential chrZ/Z mismatches
// the tabix query handles this.
continue;
}
if (passingOnly && bgzfRec.isFiltered()) {
// System.err.println("Filter fail: " + StringUtils.join(",", bgzfRec.getFilters()));
continue;
}
boolean match = !exactMatch;
if (exactMatch) {
if (bgzfRec.getAlt()!=null) {
for (String a1: bgzfRec.getAlt()) {
for (String a2: record.getAlt()) {
if (a1.equals(a2)) {
match = true;
}
}
}
}
}
if (match) {
if (name.equals("@ID")) {
record.setDbSNPID(bgzfRec.getDbSNPID());
// @ID returns right away
return;
} else if (infoVal == null) { // just add a flag
// System.err.println("Flagged: " + name);
record.getInfo().put(name, VCFAttributeValue.EMPTY);
// flags return right away
return;
} else {
if (bgzfRec.getInfo().get(infoVal)!=null) {
String val = bgzfRec.getInfo().get(infoVal).asString(null);
if (val != null && !val.equals("")) {
vals.add(val);
}
}
}
// } else {
// System.err.println("Alt match fail: " + record.getAlt() + " vs " + bgzfRec.getAlt());
}
}
// it's possible for there to be multiple lines for a position, so we need to loop them all
if (vals.size() > 0) {
record.getInfo().put(name, new VCFAttributeValue(StringUtils.join(",", vals)));
}
} catch (VCFAttributeException | VCFParseException | IOException | DataFormatException e) {
throw new VCFAnnotatorException(e);
}
}
} |
package org.apache.commons.pool.impl;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.commons.collections.CursorableLinkedList;
import org.apache.commons.pool.BaseObjectPool;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
public class GenericObjectPool extends BaseObjectPool implements ObjectPool {
/**
* A "when exhausted action" type indicating that when the pool is
* exhausted (i.e., the maximum number of active objects has
* been reached), the {@link #borrowObject}
* method should fail, throwing a {@link NoSuchElementException}.
* @see #WHEN_EXHAUSTED_BLOCK
* @see #WHEN_EXHAUSTED_GROW
* @see #setWhenExhaustedAction
*/
public static final byte WHEN_EXHAUSTED_FAIL = 0;
/**
* A "when exhausted action" type indicating that when the pool
* is exhausted (i.e., the maximum number
* of active objects has been reached), the {@link #borrowObject}
* method should block until a new object is available, or the
* {@link #getMaxWait maximum wait time} has been reached.
* @see #WHEN_EXHAUSTED_FAIL
* @see #WHEN_EXHAUSTED_GROW
* @see #setMaxWait
* @see #getMaxWait
* @see #setWhenExhaustedAction
*/
public static final byte WHEN_EXHAUSTED_BLOCK = 1;
/**
* A "when exhausted action" type indicating that when the pool is
* exhausted (i.e., the maximum number
* of active objects has been reached), the {@link #borrowObject}
* method should simply create a new object anyway.
* @see #WHEN_EXHAUSTED_FAIL
* @see #WHEN_EXHAUSTED_GROW
* @see #setWhenExhaustedAction
*/
public static final byte WHEN_EXHAUSTED_GROW = 2;
/**
* The default cap on the number of "sleeping" instances in the pool.
* @see #getMaxIdle
* @see #setMaxIdle
*/
public static final int DEFAULT_MAX_IDLE = 8;
/**
* The default cap on the total number of active instances from the pool.
* @see #getMaxActive
*/
public static final int DEFAULT_MAX_ACTIVE = 8;
/**
* The default "when exhausted action" for the pool.
* @see #WHEN_EXHAUSTED_BLOCK
* @see #WHEN_EXHAUSTED_FAIL
* @see #WHEN_EXHAUSTED_GROW
* @see #setWhenExhaustedAction
*/
public static final byte DEFAULT_WHEN_EXHAUSTED_ACTION = WHEN_EXHAUSTED_BLOCK;
/**
* The default maximum amount of time (in millis) the
* {@link #borrowObject} method should block before throwing
* an exception when the pool is exhausted and the
* {@link #getWhenExhaustedAction "when exhausted" action} is
* {@link #WHEN_EXHAUSTED_BLOCK}.
* @see #getMaxWait
* @see #setMaxWait
*/
public static final long DEFAULT_MAX_WAIT = -1L;
/**
* The default "test on borrow" value.
* @see #getTestOnBorrow
* @see #setTestOnBorrow
*/
public static final boolean DEFAULT_TEST_ON_BORROW = false;
/**
* The default "test on return" value.
* @see #getTestOnReturn
* @see #setTestOnReturn
*/
public static final boolean DEFAULT_TEST_ON_RETURN = false;
/**
* The default "test while idle" value.
* @see #getTestWhileIdle
* @see #setTestWhileIdle
* @see #getTimeBetweenEvictionRunsMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public static final boolean DEFAULT_TEST_WHILE_IDLE = false;
/**
* The default "time between eviction runs" value.
* @see #getTimeBetweenEvictionRunsMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
/**
* The default number of objects to examine per run in the
* idle object evictor.
* @see #getNumTestsPerEvictionRun
* @see #setNumTestsPerEvictionRun
* @see #getTimeBetweenEvictionRunsMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3;
/**
* The default value for {@link #getMinEvictableIdleTimeMillis}.
* @see #getMinEvictableIdleTimeMillis
* @see #setMinEvictableIdleTimeMillis
*/
public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
/**
* Create a new <tt>GenericObjectPool</tt>.
*/
public GenericObjectPool() {
this(null,DEFAULT_MAX_ACTIVE,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
*/
public GenericObjectPool(PoolableObjectFactory factory) {
this(factory,DEFAULT_MAX_ACTIVE,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param config a non-<tt>null</tt> {@link GenericObjectPool.Config} describing my configuration
*/
public GenericObjectPool(PoolableObjectFactory factory, GenericObjectPool.Config config) {
this(factory,config.maxActive,config.whenExhaustedAction,config.maxWait,config.maxIdle,config.testOnBorrow,config.testOnReturn,config.timeBetweenEvictionRunsMillis,config.numTestsPerEvictionRun,config.minEvictableIdleTimeMillis,config.testWhileIdle);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
*/
public GenericObjectPool(PoolableObjectFactory factory, int maxActive) {
this(factory,maxActive,DEFAULT_WHEN_EXHAUSTED_ACTION,DEFAULT_MAX_WAIT,DEFAULT_MAX_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
* @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
* @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
*/
public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait) {
this(factory,maxActive,whenExhaustedAction,maxWait,DEFAULT_MAX_IDLE,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
* @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
* @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
* @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
* @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
*/
public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, boolean testOnBorrow, boolean testOnReturn) {
this(factory,maxActive,whenExhaustedAction,maxWait,DEFAULT_MAX_IDLE,testOnBorrow,testOnReturn,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
* @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
* @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
* @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
*/
public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle) {
this(factory,maxActive,whenExhaustedAction,maxWait,maxIdle,DEFAULT_TEST_ON_BORROW,DEFAULT_TEST_ON_RETURN,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
* @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #getWhenExhaustedAction})
* @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #getMaxWait})
* @param maxIdle the maximum number of idle objects in my pool (see {@link #getMaxIdle})
* @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #getTestOnBorrow})
* @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #getTestOnReturn})
*/
public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) {
this(factory,maxActive,whenExhaustedAction,maxWait,maxIdle,testOnBorrow,testOnReturn,DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,DEFAULT_NUM_TESTS_PER_EVICTION_RUN,DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,DEFAULT_TEST_WHILE_IDLE);
}
/**
* Create a new <tt>GenericObjectPool</tt> using the specified values.
* @param factory the (possibly <tt>null</tt>)PoolableObjectFactory to use to create, validate and destroy objects
* @param maxActive the maximum number of objects that can be borrowed from me at one time (see {@link #setMaxActive})
* @param whenExhaustedAction the action to take when the pool is exhausted (see {@link #setWhenExhaustedAction})
* @param maxWait the maximum amount of time to wait for an idle object when the pool is exhausted an and <i>whenExhaustedAction</i> is {@link #WHEN_EXHAUSTED_BLOCK} (otherwise ignored) (see {@link #setMaxWait})
* @param maxIdle the maximum number of idle objects in my pool (see {@link #setMaxIdle})
* @param testOnBorrow whether or not to validate objects before they are returned by the {@link #borrowObject} method (see {@link #setTestOnBorrow})
* @param testOnReturn whether or not to validate objects after they are returned to the {@link #returnObject} method (see {@link #setTestOnReturn})
* @param timeBetweenEvictionRunsMillis the amount of time (in milliseconds) to sleep between examining idle objects for eviction (see {@link #setTimeBetweenEvictionRunsMillis})
* @param numTestsPerEvictionRun the number of idle objects to examine per run within the idle object eviction thread (if any) (see {@link #setNumTestsPerEvictionRun})
* @param minEvictableIdleTimeMillis the minimum number of milliseconds an object can sit idle in the pool before it is eligable for evcition (see {@link #setMinEvictableIdleTimeMillis})
* @param testWhileIdle whether or not to validate objects in the idle object eviction thread, if any (see {@link #setTestWhileIdle})
*/
public GenericObjectPool(PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle) {
_factory = factory;
_maxActive = maxActive;
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_BLOCK:
case WHEN_EXHAUSTED_FAIL:
case WHEN_EXHAUSTED_GROW:
_whenExhaustedAction = whenExhaustedAction;
break;
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
}
_maxWait = maxWait;
_maxIdle = maxIdle;
_testOnBorrow = testOnBorrow;
_testOnReturn = testOnReturn;
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
_numTestsPerEvictionRun = numTestsPerEvictionRun;
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
_testWhileIdle = testWhileIdle;
_pool = new CursorableLinkedList();
startEvictor(_timeBetweenEvictionRunsMillis);
}
/**
* Returns the cap on the total number of active instances from my pool.
* @return the cap on the total number of active instances from my pool.
* @see #setMaxActive
*/
public int getMaxActive() {
return _maxActive;
}
/**
* Sets the cap on the total number of active instances from my pool.
* @param maxActive The cap on the total number of active instances from my pool.
* Use a negative value for an infinite number of instances.
* @see #getMaxActive
*/
public void setMaxActive(int maxActive) {
_maxActive = maxActive;
synchronized(this) {
notifyAll();
}
}
/**
* Returns the action to take when the {@link #borrowObject} method
* is invoked when the pool is exhausted (the maximum number
* of "active" objects has been reached).
*
* @return one of {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL} or {@link #WHEN_EXHAUSTED_GROW}
* @see #setWhenExhaustedAction
*/
public byte getWhenExhaustedAction() {
return _whenExhaustedAction;
}
/**
* Sets the action to take when the {@link #borrowObject} method
* is invoked when the pool is exhausted (the maximum number
* of "active" objects has been reached).
*
* @param whenExhaustedAction the action code, which must be one of
* {@link #WHEN_EXHAUSTED_BLOCK}, {@link #WHEN_EXHAUSTED_FAIL},
* or {@link #WHEN_EXHAUSTED_GROW}
* @see #getWhenExhaustedAction
*/
public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) {
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_BLOCK:
case WHEN_EXHAUSTED_FAIL:
case WHEN_EXHAUSTED_GROW:
_whenExhaustedAction = whenExhaustedAction;
notifyAll();
break;
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
}
}
/**
* Returns the maximum amount of time (in milliseconds) the
* {@link #borrowObject} method should block before throwing
* an exception when the pool is exhausted and the
* {@link #setWhenExhaustedAction "when exhausted" action} is
* {@link #WHEN_EXHAUSTED_BLOCK}.
*
* When less than 0, the {@link #borrowObject} method
* may block indefinitely.
*
* @see #setMaxWait
* @see #setWhenExhaustedAction
* @see #WHEN_EXHAUSTED_BLOCK
*/
public synchronized long getMaxWait() {
return _maxWait;
}
/**
* Sets the maximum amount of time (in milliseconds) the
* {@link #borrowObject} method should block before throwing
* an exception when the pool is exhausted and the
* {@link #setWhenExhaustedAction "when exhausted" action} is
* {@link #WHEN_EXHAUSTED_BLOCK}.
*
* When less than 0, the {@link #borrowObject} method
* may block indefinitely.
*
* @see #getMaxWait
* @see #setWhenExhaustedAction
* @see #WHEN_EXHAUSTED_BLOCK
*/
public synchronized void setMaxWait(long maxWait) {
_maxWait = maxWait;
}
/**
* Returns the cap on the number of "idle" instances in the pool.
* @return the cap on the number of "idle" instances in the pool.
* @see #setMaxIdle
*/
public int getMaxIdle() {
return _maxIdle;
}
/**
* Sets the cap on the number of "idle" instances in the pool.
* @param maxIdle The cap on the number of "idle" instances in the pool.
* Use a negative value to indicate an unlimited number
* of idle instances.
* @see #getMaxIdle
*/
public void setMaxIdle(int maxIdle) {
_maxIdle = maxIdle;
synchronized(this) {
notifyAll();
}
}
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* before being returned by the {@link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #setTestOnBorrow
*/
public boolean getTestOnBorrow() {
return _testOnBorrow;
}
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* before being returned by the {@link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #getTestOnBorrow
*/
public void setTestOnBorrow(boolean testOnBorrow) {
_testOnBorrow = testOnBorrow;
}
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {@link #returnObject}.
*
* @see #setTestOnReturn
*/
public boolean getTestOnReturn() {
return _testOnReturn;
}
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {@link #returnObject}.
*
* @see #getTestOnReturn
*/
public void setTestOnReturn(boolean testOnReturn) {
_testOnReturn = testOnReturn;
}
/**
* Returns the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #setTimeBetweenEvictionRunsMillis
*/
public synchronized long getTimeBetweenEvictionRunsMillis() {
return _timeBetweenEvictionRunsMillis;
}
/**
* Sets the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #getTimeBetweenEvictionRunsMillis
*/
public synchronized void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
startEvictor(_timeBetweenEvictionRunsMillis);
}
/**
* Returns the number of objects to examine during each run of the
* idle object evictor thread (if any).
*
* @see #setNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getNumTestsPerEvictionRun() {
return _numTestsPerEvictionRun;
}
/**
* Sets the number of objects to examine during each run of the
* idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
* idle objects will be tested per run.
*
* @see #getNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
_numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* Returns the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
*
* @see #setMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public synchronized long getMinEvictableIdleTimeMillis() {
return _minEvictableIdleTimeMillis;
}
/**
* Sets the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
* When non-positive, no objects will be evicted from the pool
* due to idle time alone.
*
* @see #getMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public synchronized void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #setTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public boolean getTestWhileIdle() {
return _testWhileIdle;
}
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #getTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setTestWhileIdle(boolean testWhileIdle) {
_testWhileIdle = testWhileIdle;
}
/**
* Sets my configuration.
* @see GenericObjectPool.Config
*/
public synchronized void setConfig(GenericObjectPool.Config conf) {
setMaxIdle(conf.maxIdle);
setMaxActive(conf.maxActive);
setMaxWait(conf.maxWait);
setWhenExhaustedAction(conf.whenExhaustedAction);
setTestOnBorrow(conf.testOnBorrow);
setTestOnReturn(conf.testOnReturn);
setTestWhileIdle(conf.testWhileIdle);
setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun);
setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
notifyAll();
}
public Object borrowObject() throws Exception {
long starttime = System.currentTimeMillis();
boolean newlyCreated = false;
for(;;) {
ObjectTimestampPair pair = null;
synchronized(this) {
assertOpen();
// if there are any sleeping, just grab one of those
try {
pair = (ObjectTimestampPair)(_pool.removeFirst());
} catch(NoSuchElementException e) {
; /* ignored */
}
// otherwise
if(null == pair) {
// check if we can create one
// (note we know that the num sleeping is 0, else we wouldn't be here)
if(_maxActive <= 0 || _numActive < _maxActive) {
// allow new object to be created
} else {
// the pool is exhausted
switch(_whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
throw new NoSuchElementException();
case WHEN_EXHAUSTED_BLOCK:
try {
if(_maxWait <= 0) {
wait();
} else {
wait(_maxWait);
}
} catch(InterruptedException e) {
// ignored
}
if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized.");
}
}
}
_numActive++;
} // end synchronized
// create new object when needed
if(null == pair) {
try {
Object obj = _factory.makeObject();
pair = new ObjectTimestampPair(obj);
newlyCreated = true;
}
catch (Exception e) {
// object cannot be created
synchronized(this) {
_numActive
notifyAll();
}
throw e;
}
}
// activate & validate the object
try {
_factory.activateObject(pair.value);
if(_testOnBorrow && !_factory.validateObject(pair.value)) {
throw new Exception("validateObject failed");
}
return pair.value;
}
catch (Exception e) {
// object cannot be activated or is invalid
synchronized(this) {
_numActive
notifyAll();
}
try {
_factory.destroyObject(pair.value);
}
catch (Exception e2) {
// cannot destroy broken object
}
if(newlyCreated) {
throw new NoSuchElementException("Could not create a validated object");
}
else {
continue; // keep looping
}
}
}
}
public synchronized void invalidateObject(Object obj) throws Exception {
assertOpen();
_numActive
_factory.destroyObject(obj);
notifyAll(); // _numActive has changed
}
public synchronized void clear() {
assertOpen();
for(Iterator it = _pool.iterator(); it.hasNext(); ) {
try {
_factory.destroyObject(((ObjectTimestampPair)(it.next())).value);
} catch(Exception e) {
// ignore error, keep destroying the rest
}
it.remove();
}
_pool.clear();
notifyAll(); // num sleeping has changed
}
public int getNumActive() {
assertOpen();
return _numActive;
}
public int getNumIdle() {
assertOpen();
return _pool.size();
}
public void returnObject(Object obj) throws Exception {
assertOpen();
boolean success = true;
if(_testOnReturn && !(_factory.validateObject(obj))) {
success = false;
} else {
try {
_factory.passivateObject(obj);
} catch(Exception e) {
success = false;
}
}
boolean shouldDestroy = !success;
synchronized(this) {
_numActive
if((_maxIdle >= 0) && (_pool.size() >= _maxIdle)) {
shouldDestroy = true;
} else if(success) {
_pool.addFirst(new ObjectTimestampPair(obj));
}
notifyAll(); // _numActive has changed
}
if(shouldDestroy) {
try {
_factory.destroyObject(obj);
} catch(Exception e) {
// ignored
}
}
}
synchronized public void close() throws Exception {
clear();
_pool = null;
_factory = null;
if(null != _evictionCursor) {
_evictionCursor.close();
_evictionCursor = null;
}
startEvictor(-1L);
super.close();
}
synchronized public void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
assertOpen();
if(0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
clear();
_factory = factory;
}
}
public synchronized void evict() throws Exception {
assertOpen();
if(!_pool.isEmpty()) {
if(null == _evictionCursor) {
_evictionCursor = (_pool.cursor(_pool.size()));
} else if(!_evictionCursor.hasPrevious()) {
_evictionCursor.close();
_evictionCursor = (_pool.cursor(_pool.size()));
}
for(int i=0,m=getNumTests();i<m;i++) {
if(!_evictionCursor.hasPrevious()) {
_evictionCursor.close();
_evictionCursor = (_pool.cursor(_pool.size()));
} else {
boolean removeObject = false;
ObjectTimestampPair pair = (ObjectTimestampPair)(_evictionCursor.previous());
if(_minEvictableIdleTimeMillis > 0 &&
System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) {
removeObject = true;
} else if(_testWhileIdle) {
boolean active = false;
try {
_factory.activateObject(pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_evictionCursor.remove();
_factory.destroyObject(pair.value);
} catch(Exception e) {
; // ignored
}
}
}
}
}
}
/**
* Create an object, and place it into the pool.
* addObject() is useful for "pre-loading" a pool with idle objects.
*/
public void addObject() throws Exception {
Object obj = _factory.makeObject();
synchronized(this) {
_numActive++; // A little slimy - must do this because returnObject decrements it.
this.returnObject(obj);
}
}
/**
* Start the eviction thread or service, or when
* <i>delay</i> is non-positive, stop it
* if it is already running.
*/
protected synchronized void startEvictor(long delay) {
if(null != _evictor) {
_evictor.cancel();
_evictor = null;
}
if(delay > 0) {
_evictor = new Evictor(delay);
Thread t = new Thread(_evictor);
t.setDaemon(true);
t.start();
}
}
synchronized String debugInfo() {
StringBuffer buf = new StringBuffer();
buf.append("Active: ").append(getNumActive()).append("\n");
buf.append("Idle: ").append(getNumIdle()).append("\n");
buf.append("Idle Objects:\n");
Iterator it = _pool.iterator();
long time = System.currentTimeMillis();
while(it.hasNext()) {
ObjectTimestampPair pair = (ObjectTimestampPair)(it.next());
buf.append("\t").append(pair.value).append("\t").append(time - pair.tstamp).append("\n");
}
return buf.toString();
}
private int getNumTests() {
if(_numTestsPerEvictionRun >= 0) {
return _numTestsPerEvictionRun;
} else {
return(int)(Math.ceil((double)_pool.size()/Math.abs((double)_numTestsPerEvictionRun)));
}
}
/**
* A simple "struct" encapsulating an object instance and a timestamp.
*/
class ObjectTimestampPair {
Object value;
long tstamp;
ObjectTimestampPair(Object val) {
this(val,System.currentTimeMillis());
}
ObjectTimestampPair(Object val, long time) {
value = val;
tstamp = time;
}
}
/**
* The idle object evictor thread.
* @see #setTimeBetweenEvictionRunsMillis
*/
class Evictor implements Runnable {
private boolean _cancelled = false;
private long _delay = 0L;
public Evictor(long delay) {
_delay = delay;
}
void cancel() {
_cancelled = true;
}
public void run() {
while(!_cancelled) {
try {
Thread.sleep(_delay);
} catch(Exception e) {
// ignored
}
try {
evict();
} catch(Exception e) {
// ignored
}
}
synchronized(GenericObjectPool.this) {
if(null != _evictionCursor) {
_evictionCursor.close();
_evictionCursor = null;
}
}
}
}
/**
* A simple "struct" encapsulating the
* configuration information for a {@link GenericObjectPool}.
* @see GenericObjectPool#GenericObjectPool(org.apache.commons.pool.PoolableObjectFactory,org.apache.commons.pool.impl.GenericObjectPool.Config)
* @see GenericObjectPool#setConfig
*/
public static class Config {
public int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
public int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
public long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT;
public byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
public boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
public boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
public boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
public long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
public int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
public long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
}
/**
* The cap on the number of idle instances in the pool.
* @see #setMaxIdle
* @see #getMaxIdle
*/
private int _maxIdle = DEFAULT_MAX_IDLE;
/**
* The cap on the total number of active instances from the pool.
* @see #setMaxActive
* @see #getMaxActive
*/
private int _maxActive = DEFAULT_MAX_ACTIVE;
/**
* The maximum amount of time (in millis) the
* {@link #borrowObject} method should block before throwing
* an exception when the pool is exhausted and the
* {@link #getWhenExhaustedAction "when exhausted" action} is
* {@link #WHEN_EXHAUSTED_BLOCK}.
*
* When less than 0, the {@link #borrowObject} method
* may block indefinitely.
*
* @see #setMaxWait
* @see #getMaxWait
* @see #WHEN_EXHAUSTED_BLOCK
* @see #setWhenExhaustedAction
* @see #getWhenExhaustedAction
*/
private long _maxWait = DEFAULT_MAX_WAIT;
/**
* The action to take when the {@link #borrowObject} method
* is invoked when the pool is exhausted (the maximum number
* of "active" objects has been reached).
*
* @see #WHEN_EXHAUSTED_BLOCK
* @see #WHEN_EXHAUSTED_FAIL
* @see #WHEN_EXHAUSTED_GROW
* @see #DEFAULT_WHEN_EXHAUSTED_ACTION
* @see #setWhenExhaustedAction
* @see #getWhenExhaustedAction
*/
private byte _whenExhaustedAction = DEFAULT_WHEN_EXHAUSTED_ACTION;
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* before being returned by the {@link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #setTestOnBorrow
* @see #getTestOnBorrow
*/
private boolean _testOnBorrow = DEFAULT_TEST_ON_BORROW;
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {@link #returnObject}.
*
* @see #getTestOnReturn
* @see #setTestOnReturn
*/
private boolean _testOnReturn = DEFAULT_TEST_ON_RETURN;
/**
* When <tt>true</tt>, objects will be
* {@link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #setTestWhileIdle
* @see #getTestWhileIdle
* @see #getTimeBetweenEvictionRunsMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
private boolean _testWhileIdle = DEFAULT_TEST_WHILE_IDLE;
/**
* The number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #setTimeBetweenEvictionRunsMillis
* @see #getTimeBetweenEvictionRunsMillis
*/
private long _timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
/**
* The number of objects to examine during each run of the
* idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <tt>ceil({@link #getNumIdle})/abs({@link #getNumTestsPerEvictionRun})</tt>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
* idle objects will be tested per run.
*
* @see #setNumTestsPerEvictionRun
* @see #getNumTestsPerEvictionRun
* @see #getTimeBetweenEvictionRunsMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
private int _numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
/**
* The minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
* When non-positive, no objects will be evicted from the pool
* due to idle time alone.
*
* @see #setMinEvictableIdleTimeMillis
* @see #getMinEvictableIdleTimeMillis
* @see #getTimeBetweenEvictionRunsMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
private long _minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
/** My pool. */
private CursorableLinkedList _pool = null;
/** My {@link PoolableObjectFactory}. */
private PoolableObjectFactory _factory = null;
/**
* The number of objects {@link #borrowObject} borrowed
* from the pool, but not yet returned.
*/
private int _numActive = 0;
/**
* My idle object eviction thread, if any.
*/
private Evictor _evictor = null;
private CursorableLinkedList.Cursor _evictionCursor = null;
} |
package org.jivesoftware.openfire.pubsub;
import org.dom4j.Element;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import java.util.*;
/**
* A NodeAffiliate keeps information about the affiliation of an entity with a node. Possible
* affiliations are: owner, publisher, none or outcast. All except for outcast affiliations
* may have a {@link NodeSubscription} with the node.
*
* @author Matt Tucker
*/
public class NodeAffiliate {
private JID jid;
private Node node;
private Affiliation affiliation;
NodeAffiliate(Node node, JID jid) {
this.node = node;
this.jid = jid;
}
public Node getNode() {
return node;
}
public JID getJID() {
return jid;
}
public Affiliation getAffiliation() {
return affiliation;
}
void setAffiliation(Affiliation affiliation) {
this.affiliation = affiliation;
}
/**
* Returns the list of subscriptions of the affiliate in the node.
*
* @return the list of subscriptions of the affiliate in the node.
*/
public Collection<NodeSubscription> getSubscriptions() {
return node.getSubscriptions(jid);
}
/**
* Sends an event notification for the published items to the affiliate. The event
* notification may contain zero, one or many published items based on the items
* included in the original publication. If the affiliate has many subscriptions and
* many items were published then the affiliate will get a notification for each set
* of items that affected the same subscriptions.
*
* @param notification the message to sent to the subscribers. The message will be completed
* with the items to include in each notification.
* @param event the event Element included in the notification message. Passed as an
* optimization to avoid future look ups.
* @param leafNode the leaf node where the items where published.
* @param publishedItems the list of items that were published. Could be an empty list.
*/
void sendPublishedNotifications(Message notification, Element event, LeafNode leafNode,
List<PublishedItem> publishedItems) {
if (!publishedItems.isEmpty()) {
Map<List<NodeSubscription>, List<PublishedItem>> itemsBySubs =
getItemsBySubscriptions(leafNode, publishedItems);
// Send one notification for published items that affect the same subscriptions
for (List<NodeSubscription> nodeSubscriptions : itemsBySubs.keySet()) {
// Add items information
Element items = event.addElement("items");
items.addAttribute("node", getNode().getNodeID());
for (PublishedItem publishedItem : itemsBySubs.get(nodeSubscriptions)) {
// FIXME: This was added for compatibility with PEP supporting clients.
// Alternate solution needed when XEP-0163 version > 1.0 is released.
// If the node ID looks like a JID, replace it with the published item's node ID.
if (getNode().getNodeID().indexOf("@") >= 0) {
items.addAttribute("node", publishedItem.getNode().getNodeID());
}
// Add item information to the event notification
Element item = items.addElement("item");
if (leafNode.isItemRequired()) {
item.addAttribute("id", publishedItem.getID());
}
if (leafNode.isPayloadDelivered()) {
item.add(publishedItem.getPayload().createCopy());
}
// Add leaf leafNode information if affiliated leafNode and node
// where the item was published are different
if (leafNode != getNode()) {
item.addAttribute("node", leafNode.getNodeID());
}
}
// Send the event notification
sendEventNotification(notification, nodeSubscriptions);
// Remove the added items information
event.remove(items);
}
}
else {
// Filter affiliate subscriptions and only use approved and configured ones
List<NodeSubscription> affectedSubscriptions = new ArrayList<NodeSubscription>();
for (NodeSubscription subscription : getSubscriptions()) {
if (subscription.canSendPublicationEvent(leafNode, null)) {
affectedSubscriptions.add(subscription);
}
}
// Add item information to the event notification
Element items = event.addElement("items");
items.addAttribute("node", leafNode.getNodeID());
// Send the event notification
sendEventNotification(notification, affectedSubscriptions);
// Remove the added items information
event.remove(items);
}
}
/**
* Sends an event notification to the affiliate for the deleted items. The event
* notification may contain one or many published items based on the items included
* in the original publication. If the affiliate has many subscriptions and many
* items were deleted then the affiliate will get a notification for each set
* of items that affected the same subscriptions.
*
* @param notification the message to sent to the subscribers. The message will be completed
* with the items to include in each notification.
* @param event the event Element included in the notification message. Passed as an
* optimization to avoid future look ups.
* @param leafNode the leaf node where the items where deleted from.
* @param publishedItems the list of items that were deleted.
*/
void sendDeletionNotifications(Message notification, Element event, LeafNode leafNode,
List<PublishedItem> publishedItems) {
if (!publishedItems.isEmpty()) {
Map<List<NodeSubscription>, List<PublishedItem>> itemsBySubs =
getItemsBySubscriptions(leafNode, publishedItems);
// Send one notification for published items that affect the same subscriptions
for (List<NodeSubscription> nodeSubscriptions : itemsBySubs.keySet()) {
// Add items information
Element items = event.addElement("items");
items.addAttribute("node", leafNode.getNodeID());
for (PublishedItem publishedItem : itemsBySubs.get(nodeSubscriptions)) {
// Add retract information to the event notification
Element item = items.addElement("retract");
if (leafNode.isItemRequired()) {
item.addAttribute("id", publishedItem.getID());
}
}
// Send the event notification
sendEventNotification(notification, nodeSubscriptions);
// Remove the added items information
event.remove(items);
}
}
}
/**
* Sends an event notification to each affected subscription of the affiliate. If the owner
* has many subscriptions from the same full JID then a single notification is going to be
* sent including a detail of the subscription IDs for which the notification is being sent.<p>
*
* Event notifications may include notifications of new published items or of items that
* were deleted.<p>
*
* The original publication to the node may or may not contain a {@link PublishedItem}. The
* subscriptions of the affiliation will be filtered based on the published item (if one was
* specified), the subscription status and originating node.
*
* @param notification the message to send containing the event notification.
* @param notifySubscriptions list of subscriptions that were affected and are going to be
* included in the notification message. The list should not be empty.
*/
private void sendEventNotification(Message notification,
List<NodeSubscription> notifySubscriptions) {
if (node.isMultipleSubscriptionsEnabled()) {
// Group subscriptions with the same subscriber JID
Map<JID, Collection<String>> groupedSubs = new HashMap<JID, Collection<String>>();
for (NodeSubscription subscription : notifySubscriptions) {
Collection<String> subIDs = groupedSubs.get(subscription.getJID());
if (subIDs == null) {
subIDs = new ArrayList<String>();
groupedSubs.put(subscription.getJID(), subIDs);
}
subIDs.add(subscription.getID());
}
// Send an event notification to each subscriber with a different JID
for (JID subscriberJID : groupedSubs.keySet()) {
// Get ID of affected subscriptions
Collection<String> subIDs = groupedSubs.get(subscriberJID);
// Send the notification to the subscriber
node.sendEventNotification(subscriberJID, notification, subIDs);
}
}
else {
// Affiliate should have at most one subscription so send the notification to
// the subscriber
if (!notifySubscriptions.isEmpty()) {
NodeSubscription subscription = notifySubscriptions.get(0);
node.sendEventNotification(subscription.getJID(), notification, null);
}
}
}
private Map<List<NodeSubscription>, List<PublishedItem>> getItemsBySubscriptions(
LeafNode leafNode, List<PublishedItem> publishedItems) {
// Identify which subscriptions can receive each item
Map<PublishedItem, List<NodeSubscription>> subsByItem =
new HashMap<PublishedItem, List<NodeSubscription>>();
// Filter affiliate subscriptions and only use approved and configured ones
Collection<NodeSubscription> subscriptions = getSubscriptions();
for (PublishedItem publishedItem : publishedItems) {
for (NodeSubscription subscription : subscriptions) {
if (subscription.canSendPublicationEvent(leafNode, publishedItem)) {
List<NodeSubscription> nodeSubscriptions = subsByItem.get(publishedItem);
if (nodeSubscriptions == null) {
nodeSubscriptions = new ArrayList<NodeSubscription>();
subsByItem.put(publishedItem, nodeSubscriptions);
}
nodeSubscriptions.add(subscription);
}
}
}
// Identify which items should be sent together to the same subscriptions
Map<List<NodeSubscription>, List<PublishedItem>> itemsBySubs =
new HashMap<List<NodeSubscription>, List<PublishedItem>>();
List<PublishedItem> affectedSubscriptions;
for (PublishedItem publishedItem : subsByItem.keySet()) {
affectedSubscriptions = itemsBySubs.get(subsByItem.get(publishedItem));
if (affectedSubscriptions == null) {
List<PublishedItem> items = new ArrayList<PublishedItem>(publishedItems.size());
items.add(publishedItem);
itemsBySubs.put(subsByItem.get(publishedItem), items);
}
else {
affectedSubscriptions.add(publishedItem);
}
}
return itemsBySubs;
}
public String toString() {
return super.toString() + " - JID: " + getJID() + " - Affiliation: " +
getAffiliation().name();
}
public static enum Affiliation {
/**
* An owner can publish, delete and purge items as well as configure and delete the node.
*/
owner,
/**
* A publisher can subscribe and publish items to the node.
*/
publisher,
/**
* A user with no affiliation can susbcribe to the node.
*/
none,
/**
* Outcast users are not allowed to subscribe to the node.
*/
outcast
}
} |
package org.jivesoftware.sparkimpl.profile;
import org.jivesoftware.resource.Res;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.URLFileSystem;
import org.jivesoftware.spark.util.log.Log;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JDialog;
import java.awt.Color;
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
/**
* UI to view/edit avatar.
*/
public class AvatarPanel extends JPanel implements ActionListener {
private JLabel avatar;
private byte[] bytes;
private File avatarFile;
final JButton browseButton = new JButton();
final JButton clearButton = new JButton();
private FileDialog fileChooser;
private Dialog dlg;
/**
* Default Constructor
*/
public AvatarPanel() {
setLayout(new GridBagLayout());
final JLabel photo = new JLabel("Avatar:");
avatar = new JLabel();
add(photo, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(avatar, new GridBagConstraints(1, 0, 1, 2, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(browseButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(clearButton, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
browseButton.addActionListener(this);
// Add ResourceUtils
ResourceUtils.resButton(browseButton, Res.getString("button.browse"));
ResourceUtils.resButton(clearButton, Res.getString("button.clear"));
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
avatar.setIcon(null);
bytes = null;
avatarFile = null;
avatar.setBorder(null);
}
});
avatar.setText(Res.getString("message.no.avatar.found"));
GraphicUtils.makeSameSize(browseButton, clearButton);
}
/**
* Sets if the Avatar can be edited.
*
* @param editable true if edtiable.
*/
public void setEditable(boolean editable) {
browseButton.setVisible(editable);
clearButton.setVisible(editable);
}
/**
* Sets the displayable icon with the users avatar.
*
* @param icon the icon.
*/
public void setAvatar(ImageIcon icon) {
avatar.setBorder(BorderFactory.createBevelBorder(0, Color.white, Color.lightGray));
avatar.setIcon(new ImageIcon(icon.getImage().getScaledInstance(-1, 48, Image.SCALE_SMOOTH)));
avatar.setText("");
}
/**
* Sets the avatar bytes.
*
* @param bytes the bytes.
*/
public void setAvatarBytes(byte[] bytes) {
this.bytes = bytes;
}
/**
* Returns the avatars bytes.
*
* @return the bytes.
*/
public byte[] getAvatarBytes() {
return bytes;
}
/**
* Returns the Icon representation of the Avatar.
*
* @return
*/
public Icon getAvatar() {
return avatar.getIcon();
}
/**
* Returns the image file to use as the avatar.
*
* @return
*/
public File getAvatarFile() {
return avatarFile;
}
public void actionPerformed(ActionEvent e) {
// init file chooser (if not already done)
initFileChooser();
fileChooser.show();
if (fileChooser.getDirectory() != null && fileChooser.getFile() != null) {
File file = new File(fileChooser.getDirectory(), fileChooser.getFile());
String suffix = URLFileSystem.getSuffix(file);
if (suffix.toLowerCase().equals(".jpeg") ||
suffix.toLowerCase().equals(".gif") ||
suffix.toLowerCase().equals(".jpg") ||
suffix.toLowerCase().equals(".png")) {
changeAvatar(file, this);
}
else {k
JOptionPane.showMessageDialog(this, "Please choose a valid image file.", Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
}
}
}
private void changeAvatar(final File selectedFile, final Component parent) {
SwingWorker worker = new SwingWorker() {
public Object construct() {
try {
ImageIcon imageOnDisk = new ImageIcon(selectedFile.getCanonicalPath());
Image avatarImage = imageOnDisk.getImage();
if (avatarImage.getHeight(null) > 96 || avatarImage.getWidth(null) > 96) {
avatarImage = avatarImage.getScaledInstance(-1, 64, Image.SCALE_SMOOTH);
}
return avatarImage;
}
catch (IOException ex) {
Log.error(ex);
}
return null;
}
public void finished() {
Image avatarImage = (Image)get();
// Check size.
long length = GraphicUtils.getBytesFromImage(avatarImage).length * 8;
long k = 8192;
long actualSize = (length / k) + 1;
if (actualSize > 16) {
// Do not allow
JOptionPane.showMessageDialog(parent, Res.getString("message.image.too.large"));
return;
}
setAvatar(new ImageIcon(avatarImage));
avatarFile = selectedFile;
}
};
worker.start();
}
public class ImageFilter implements FilenameFilter {
public final String jpeg = "jpeg";
public final String jpg = "jpg";
public final String gif = "gif";
public final String png = "png";
//Accept all directories and all gif, jpg, tiff, or png files.
public boolean accept(File f, String string) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null) {
if (
extension.equals(gif) ||
extension.equals(jpeg) ||
extension.equals(jpg) ||
extension.equals(png)
) {
return true;
}
else {
return false;
}
}
return false;
}
/*
* Get the extension of a file.
*/
public String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}
//The description of this filter
public String getDescription() {
return "*.JPEG, *.GIF, *.PNG";
}
}
public void allowEditing(boolean allowEditing) {
Component[] comps = getComponents();
final int no = comps != null ? comps.length : 0;
for (int i = 0; i < no; i++) {
Component comp = comps[i];
if (comp instanceof JTextField) {
((JTextField)comp).setEditable(allowEditing);
}
}
}
public void initFileChooser() {
if (fileChooser == null) {
fileChooser = new FileDialog(dlg, "Choose Avatar", FileDialog.LOAD);
fileChooser.setFilenameFilter(new ImageFilter());
}
}
public void setParentDialog(Dialog dialog){
this.dlg = dialog;
}
} |
package org.neo4j.impl.batchinsert;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.NeoService;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.NotFoundException;
import org.neo4j.api.core.NotInTransactionException;
import org.neo4j.api.core.Relationship;
import org.neo4j.api.core.RelationshipType;
import org.neo4j.api.core.ReturnableEvaluator;
import org.neo4j.api.core.StopEvaluator;
import org.neo4j.api.core.Transaction;
import org.neo4j.api.core.Traverser;
import org.neo4j.api.core.Traverser.Order;
import org.neo4j.impl.cache.LruCache;
import org.neo4j.impl.nioneo.store.InvalidRecordException;
class NeoServiceBatchImpl implements NeoService
{
final BatchInserterImpl batchInserter;
private final LruCache<Long,NodeBatchImpl> nodes =
new LruCache<Long,NodeBatchImpl>( "NodeCache", 10000, null )
{
@Override
public void elementCleaned( NodeBatchImpl node )
{
Map<String,Object> properties = node.getProperties();
if ( properties != null )
{
batchInserter.setNodeProperties( node.getId(), properties );
}
}
};
private final LruCache<Long,RelationshipBatchImpl> rels =
new LruCache<Long,RelationshipBatchImpl>( "RelCache", 100000, null )
{
@Override
public void elementCleaned( RelationshipBatchImpl rel )
{
Map<String,Object> properties = rel.getProperties();
if ( properties != null )
{
batchInserter.setRelationshipProperties( rel.getId(),
properties );
}
}
};
NeoServiceBatchImpl( BatchInserterImpl batchInserter )
{
this.batchInserter = batchInserter;
}
BatchInserterImpl getBatchInserter()
{
return batchInserter;
}
public Transaction beginTx()
{
return new FakeTransaction();
}
public Node createNode()
{
long id = batchInserter.createNode( null );
NodeBatchImpl node = new NodeBatchImpl( id, this, emptyProps() );
nodes.put( id, node );
return node;
}
static Map<String,Object> emptyProps()
{
return new HashMap<String,Object>();
}
public boolean enableRemoteShell()
{
return false;
}
public boolean enableRemoteShell( Map<String,Serializable> initialProperties )
{
return false;
}
public Iterable<Node> getAllNodes()
{
throw new UnsupportedOperationException( "Batch inserter mode" );
}
public Node getNodeById( long id )
{
NodeBatchImpl node = nodes.get( id );
if ( node == null )
{
try
{
node = new NodeBatchImpl( id, this,
batchInserter.getNodeProperties( id ) );
nodes.put( id, node );
}
catch ( InvalidRecordException e )
{
throw new NotFoundException( e );
}
}
return node;
}
public Node getReferenceNode()
{
return getNodeById( 0 );
}
public Relationship getRelationshipById( long id )
{
RelationshipBatchImpl rel = rels.get( id );
if ( rel == null )
{
try
{
SimpleRelationship simpleRel =
batchInserter.getRelationshipById( id );
Map<String,Object> props =
batchInserter.getRelationshipProperties( id );
rel = new RelationshipBatchImpl( simpleRel, this, props );
rels.put( id, rel );
}
catch ( InvalidRecordException e )
{
throw new NotFoundException( e );
}
}
return rel;
}
public Iterable<RelationshipType> getRelationshipTypes()
{
throw new UnsupportedOperationException( "Batch inserter mode" );
}
public void shutdown()
{
batchInserter.shutdown();
}
static class FakeTransaction implements Transaction
{
public void failure()
{
throw new NotInTransactionException( "Batch insert mode, " +
"failure is not an option." );
}
public void finish()
{
}
public void success()
{
}
}
private static class NodeBatchImpl implements Node
{
private final NeoServiceBatchImpl neoService;
private final long id;
private final Map<String,Object> properties;
NodeBatchImpl( long id, NeoServiceBatchImpl neoService,
Map<String,Object> properties )
{
this.id = id;
this.neoService = neoService;
this.properties = properties;
}
public Relationship createRelationshipTo( Node otherNode,
RelationshipType type )
{
long relId = neoService.getBatchInserter().createRelationship( id,
otherNode.getId(), type, null );
RelationshipBatchImpl rel = new RelationshipBatchImpl(
new SimpleRelationship( (int)relId, (int) id,
(int) otherNode.getId(), type ), neoService, emptyProps() );
neoService.addRelationshipToCache( relId, rel );
return rel;
}
Map<String,Object> getProperties()
{
return properties;
}
public void delete()
{
throw new UnsupportedOperationException();
}
public long getId()
{
return id;
}
private RelIterator newRelIterator( Direction dir,
RelationshipType[] types )
{
Iterable<Long> relIds =
neoService.getBatchInserter().getRelationshipIds( id );
return new RelIterator( neoService, relIds, id, dir, types );
}
public Iterable<Relationship> getRelationships()
{
return newRelIterator( Direction.BOTH, null );
}
public Iterable<Relationship> getRelationships(
RelationshipType... types )
{
return newRelIterator( Direction.BOTH, types );
}
public Iterable<Relationship> getRelationships( Direction dir )
{
return newRelIterator( dir, null );
}
public Iterable<Relationship> getRelationships( RelationshipType type,
Direction dir )
{
return newRelIterator( dir, new RelationshipType[] { type } );
}
public Relationship getSingleRelationship( RelationshipType type,
Direction dir )
{
Iterator<Relationship> relItr =
newRelIterator( dir, new RelationshipType[] { type } );
if ( relItr.hasNext() )
{
Relationship rel = relItr.next();
if ( relItr.hasNext() )
{
throw new NotFoundException( "More than one relationship[" +
type + ", " + dir + "] found for " + this );
}
return rel;
}
return null;
}
public boolean hasRelationship()
{
Iterator<Relationship> relItr =
newRelIterator( Direction.BOTH, null );
return relItr.hasNext();
}
public boolean hasRelationship( RelationshipType... types )
{
Iterator<Relationship> relItr =
newRelIterator( Direction.BOTH, types );
return relItr.hasNext();
}
public boolean hasRelationship( Direction dir )
{
Iterator<Relationship> relItr =
newRelIterator( dir, null );
return relItr.hasNext();
}
public boolean hasRelationship( RelationshipType type, Direction dir )
{
Iterator<Relationship> relItr =
newRelIterator( dir, new RelationshipType[] { type } );
return relItr.hasNext();
}
public Traverser traverse( Order traversalOrder,
StopEvaluator stopEvaluator,
ReturnableEvaluator returnableEvaluator,
RelationshipType relationshipType, Direction direction )
{
throw new UnsupportedOperationException( "Batch inserter mode" );
}
public Traverser traverse( Order traversalOrder,
StopEvaluator stopEvaluator,
ReturnableEvaluator returnableEvaluator,
RelationshipType firstRelationshipType, Direction firstDirection,
RelationshipType secondRelationshipType, Direction secondDirection )
{
throw new UnsupportedOperationException( "Batch inserter mode" );
}
public Traverser traverse( Order traversalOrder,
StopEvaluator stopEvaluator,
ReturnableEvaluator returnableEvaluator,
Object... relationshipTypesAndDirections )
{
throw new UnsupportedOperationException( "Batch inserter mode" );
}
public Object getProperty( String key )
{
Object val = properties.get( key );
if ( val == null )
{
throw new NotFoundException( key );
}
return val;
}
public Object getProperty( String key, Object defaultValue )
{
Object val = properties.get( key );
if ( val == null )
{
return defaultValue;
}
return val;
}
public Iterable<String> getPropertyKeys()
{
return properties.keySet();
}
public Iterable<Object> getPropertyValues()
{
return properties.values();
}
public boolean hasProperty( String key )
{
return properties.containsKey( key );
}
public Object removeProperty( String key )
{
Object val = properties.remove( key );
if ( val == null )
{
throw new NotFoundException( "Property " + key );
}
return val;
}
public void setProperty( String key, Object value )
{
properties.put( key, value );
}
public boolean equals( Object o )
{
if ( !(o instanceof Node) )
{
return false;
}
return this.getId() == ((Node) o).getId();
}
public int hashCode()
{
return (int) id;
}
}
private static class RelationshipBatchImpl implements Relationship
{
private final SimpleRelationship rel;
private final NeoServiceBatchImpl neoService;
private final Map<String,Object> properties;
RelationshipBatchImpl( SimpleRelationship rel,
NeoServiceBatchImpl neoService, Map<String,Object> properties )
{
this.rel = rel;
this.neoService = neoService;
this.properties = properties;
}
Map<String,Object> getProperties()
{
return properties;
}
public void delete()
{
throw new UnsupportedOperationException( "Batch inserter mode" );
}
public Node getEndNode()
{
return neoService.getNodeById( rel.getEndNode() );
}
public long getId()
{
return rel.getId();
}
public Node[] getNodes()
{
return new Node[] { getStartNode(), getEndNode() };
}
public Node getOtherNode( Node node )
{
Node startNode = getStartNode();
Node endNode = getEndNode();
if ( node.equals( endNode ) )
{
return startNode;
}
if ( node.equals( startNode ) )
{
return endNode;
}
throw new IllegalArgumentException( "" + node );
}
public Node getStartNode()
{
return neoService.getNodeById( rel.getStartNode() );
}
public RelationshipType getType()
{
return rel.getType();
}
public boolean isType( RelationshipType type )
{
return rel.getType().equals( type );
}
public Object getProperty( String key )
{
Object val = properties.get( key );
if ( val == null )
{
throw new NotFoundException( key );
}
return val;
}
public Object getProperty( String key, Object defaultValue )
{
Object val = properties.get( key );
if ( val == null )
{
return defaultValue;
}
return val;
}
public Iterable<String> getPropertyKeys()
{
return properties.keySet();
}
public Iterable<Object> getPropertyValues()
{
return properties.values();
}
public boolean hasProperty( String key )
{
return properties.containsKey( key );
}
public Object removeProperty( String key )
{
Object val = properties.remove( key );
if ( val == null )
{
throw new NotFoundException( "Property " + key );
}
return val;
}
public void setProperty( String key, Object value )
{
properties.put( key, value );
}
public boolean equals( Object o )
{
if ( !(o instanceof Relationship) )
{
return false;
}
return this.getId() == ((Relationship) o).getId();
}
public int hashCode()
{
return (int) rel.getId();
}
}
void addRelationshipToCache( long id, RelationshipBatchImpl rel )
{
rels.put( id, rel );
}
static class RelIterator implements
Iterable<Relationship>, Iterator<Relationship>
{
private final NeoServiceBatchImpl neoService;
private final Iterable<Long> relIds;
private final Iterator<Long> relItr;
private final long nodeId;
private final Direction dir;
private final RelationshipType[] types;
private Relationship nextElement;
RelIterator( NeoServiceBatchImpl neoService, Iterable<Long> relIds,
long nodeId, Direction dir, RelationshipType[] types )
{
this.neoService = neoService;
this.relIds = relIds;
this.relItr = relIds.iterator();
this.nodeId = nodeId;
this.dir = dir;
this.types = types;
}
public Iterator<Relationship> iterator()
{
return new RelIterator( neoService, relIds, nodeId, dir, types );
}
public boolean hasNext()
{
getNextElement();
if ( nextElement != null )
{
return true;
}
return false;
}
public Relationship next()
{
getNextElement();
if ( nextElement != null )
{
Relationship returnVal = nextElement;
nextElement = null;
return returnVal;
}
throw new NoSuchElementException();
}
private void getNextElement()
{
while ( nextElement == null && relItr.hasNext() )
{
Relationship possibleRel =
neoService.getRelationshipById( relItr.next() );
if ( dir == Direction.OUTGOING &&
possibleRel.getEndNode().getId() == nodeId )
{
continue;
}
if ( dir == Direction.INCOMING &&
possibleRel.getStartNode().getId() == nodeId )
{
continue;
}
if ( types != null )
{
for ( RelationshipType type : types )
{
if ( type.name().equals(
possibleRel.getType().name() ) )
{
nextElement = possibleRel;
break;
}
}
}
else
{
nextElement = possibleRel;
}
}
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
void clearCaches()
{
nodes.clear();
rels.clear();
}
} |
package org.orbeon.oxf.xforms;
import org.apache.commons.pool.ObjectPool;
import org.dom4j.Document;
import org.dom4j.Element;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.util.NetUtils;
import org.orbeon.oxf.xforms.action.XFormsActionInterpreter;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsValueControl;
import org.orbeon.oxf.xforms.control.XFormsSingleNodeControl;
import org.orbeon.oxf.xforms.control.controls.XFormsOutputControl;
import org.orbeon.oxf.xforms.control.controls.XFormsUploadControl;
import org.orbeon.oxf.xforms.control.controls.XXFormsDialogControl;
import org.orbeon.oxf.xforms.event.*;
import org.orbeon.oxf.xforms.event.events.*;
import org.orbeon.oxf.xforms.processor.XFormsServer;
import org.orbeon.oxf.xforms.state.XFormsState;
import org.orbeon.oxf.xforms.processor.XFormsURIResolver;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.saxon.om.NodeInfo;
import java.io.IOException;
import java.util.*;
/**
* Represents an XForms containing document.
*
* The containing document includes:
*
* o XForms models (including multiple instances)
* o XForms controls
* o Event handlers hierarchy
*/
public class XFormsContainingDocument implements XFormsEventTarget, XFormsEventHandlerContainer {
public static final String CONTAINING_DOCUMENT_PSEUDO_ID = "$containing-document$";
// Global XForms function library
private static XFormsFunctionLibrary functionLibrary = new XFormsFunctionLibrary();
// Object pool this object must be returned to, if any
private ObjectPool sourceObjectPool;
// URI resolver
private XFormsURIResolver uriResolver;
// Whether this document is currently being initialized
private boolean isInitializing;
// A document contains models and controls
private XFormsStaticState xformsStaticState;
private List models = new ArrayList();
private Map modelsMap = new HashMap();
private XFormsControls xformsControls;
// Client state
private boolean dirtySinceLastRequest;
private XFormsModelSubmission activeSubmission;
private boolean gotSubmission;
private List messagesToRun;
private List loadsToRun;
private List scriptsToRun;
private String focusEffectiveControlId;
private String helpEffectiveControlId;
private XFormsActionInterpreter actionInterpreter;
// Global flag used during initialization only
private boolean mustPerformInitializationFirstRefresh;
// Legacy information
private String legacyContainerType;
private String legacyContainerNamespace;
// Event information
private static final Map ignoredXFormsOutputExternalEvents = new HashMap();
private static final Map allowedXFormsOutputExternalEvents = new HashMap();
private static final Map allowedXFormsUploadExternalEvents = new HashMap();
private static final Map allowedExternalEvents = new HashMap();
private static final Map allowedXFormsSubmissionExternalEvents = new HashMap();
private static final Map allowedXFormsContainingDocumentExternalEvents = new HashMap();
private static final Map allowedXXFormsDialogExternalEvents = new HashMap();
static {
// External events ignored on xforms:output
ignoredXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_DOM_FOCUS_IN, "");
ignoredXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_DOM_FOCUS_OUT, "");
// External events allowed on xforms:output
allowedXFormsOutputExternalEvents.putAll(ignoredXFormsOutputExternalEvents);
allowedXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_HELP, "");
// External events allowed on xforms:upload
allowedXFormsUploadExternalEvents.putAll(allowedXFormsOutputExternalEvents);
allowedXFormsUploadExternalEvents.put(XFormsEvents.XFORMS_SELECT, "");
allowedXFormsUploadExternalEvents.put(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE, "");
// External events allowed on other controls
allowedExternalEvents.putAll(allowedXFormsOutputExternalEvents);
allowedExternalEvents.put(XFormsEvents.XFORMS_DOM_ACTIVATE, "");
allowedExternalEvents.put(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE, "");
// External events allowed on xforms:submission
allowedXFormsSubmissionExternalEvents.put(XFormsEvents.XXFORMS_SUBMIT, "");
// External events allowed on containing document
allowedXFormsContainingDocumentExternalEvents.put(XFormsEvents.XXFORMS_LOAD, "");
// External events allowed on xxforms:dialog
allowedXXFormsDialogExternalEvents.put(XFormsEvents.XXFORMS_DIALOG_CLOSE, "");
}
// For testing only
private static int testAjaxToggleValue = 0;
/**
* Return the global function library.
*/
public static XFormsFunctionLibrary getFunctionLibrary() {
return functionLibrary;
}
/**
* Create an XFormsContainingDocument from an XFormsEngineStaticState object.
*
* @param pipelineContext current pipeline context
* @param xformsStaticState XFormsEngineStaticState
* @param uriResolver optional URIResolver for loading instances during initialization (and possibly more, such as schemas and "GET" submissions upon initialization)
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsStaticState xformsStaticState,
XFormsURIResolver uriResolver) {
XFormsServer.logger.debug("XForms - creating new ContainingDocument (static state object provided).");
// Remember static state
this.xformsStaticState = xformsStaticState;
// Remember URI resolver for initialization
this.uriResolver = uriResolver;
this.isInitializing = true;
// Initialize the containing document
try {
initialize(pipelineContext);
} catch (Exception e) {
throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "initializing XForms containing document"));
}
// Clear URI resolver, since it is of no use after initialization, and it may keep dangerous references (PipelineContext)
this.uriResolver = null;
this.isInitializing = false;
}
/**
* Create an XFormsContainingDocument from an XFormsState object.
*
* @param pipelineContext current pipeline context
* @param xformsState XFormsState containing static and dynamic state
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsState xformsState) {
XFormsServer.logger.debug("XForms - creating new ContainingDocument (static state object not provided).");
// Create static state object
// TODO: Handle caching of XFormsStaticState object
xformsStaticState = new XFormsStaticState(pipelineContext, xformsState.getStaticState());
// Restore the containing document's dynamic state
final String encodedDynamicState = xformsState.getDynamicState();
try {
if (encodedDynamicState == null || encodedDynamicState.equals("")) {
// Just for tests, we allow the dynamic state to be empty
initialize(pipelineContext);
xformsControls.evaluateAllControlsIfNeeded(pipelineContext);
} else {
// Regular case
restoreDynamicState(pipelineContext, encodedDynamicState);
}
} catch (Exception e) {
throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "re-initializing XForms containing document"));
}
}
/**
* Legacy constructor for XForms Classic.
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsModel xformsModel) {
this.models = Collections.singletonList(xformsModel);
this.xformsControls = new XFormsControls(this, null, null);
if (xformsModel.getEffectiveId() != null)
modelsMap.put(xformsModel.getEffectiveId(), xformsModel);
xformsModel.setContainingDocument(this);
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
this.legacyContainerType = externalContext.getRequest().getContainerType();
this.legacyContainerNamespace = externalContext.getRequest().getContainerNamespace();
initialize(pipelineContext);
}
public void setSourceObjectPool(ObjectPool sourceObjectPool) {
this.sourceObjectPool = sourceObjectPool;
}
public ObjectPool getSourceObjectPool() {
return sourceObjectPool;
}
public XFormsURIResolver getURIResolver() {
return uriResolver;
}
public boolean isInitializing() {
return isInitializing;
}
/**
* Return model with the specified id, null if not found. If the id is the empty string, return
* the default model, i.e. the first model.
*/
public XFormsModel getModel(String modelId) {
return (XFormsModel) ("".equals(modelId) ? models.get(0) : modelsMap.get(modelId));
}
/**
* Get a list of all the models in this document.
*/
public List getModels() {
return models;
}
/**
* Return the XForms controls.
*/
public XFormsControls getXFormsControls() {
return xformsControls;
}
/**
* Whether the document is dirty since the last request.
*
* @return whether the document is dirty since the last request
*/
public boolean isDirtySinceLastRequest() {
return dirtySinceLastRequest || xformsControls == null || xformsControls.isDirtySinceLastRequest();
}
public void markCleanSinceLastRequest() {
this.dirtySinceLastRequest = false;
}
public void markDirtySinceLastRequest() {
this.dirtySinceLastRequest = true;
}
/**
* Return the XFormsEngineStaticState.
*/
public XFormsStaticState getStaticState() {
return xformsStaticState;
}
/**
* Return a map of script id -> script text.
*/
public Map getScripts() {
return (xformsStaticState == null) ? null : xformsStaticState.getScripts();
}
/**
* Return the document base URI.
*/
public String getBaseURI() {
return (xformsStaticState == null) ? null : xformsStaticState.getBaseURI();
}
/**
* Return the container type that generate the XForms page, either "servlet" or "portlet".
*/
public String getContainerType() {
return (xformsStaticState == null) ? legacyContainerType : xformsStaticState.getContainerType();
}
/**
* Return the container namespace that generate the XForms page. Always "" for servlets.
*/
public String getContainerNamespace() {
return (xformsStaticState == null) ? legacyContainerNamespace : xformsStaticState.getContainerNamespace();
}
/**
* Return external-events configuration attribute.
*/
private Map getExternalEventsMap() {
return (xformsStaticState == null) ? null : xformsStaticState.getExternalEventsMap();
}
/**
* Return whether an external event name is explicitly allowed by the configuration.
*
* @param eventName event name to check
* @return true if allowed, false otherwise
*/
private boolean isExplicitlyAllowedExternalEvent(String eventName) {
return !XFormsEventFactory.isBuiltInEvent(eventName) && getExternalEventsMap() != null && getExternalEventsMap().get(eventName) != null;
}
/**
* Get object with the id specified.
*/
public Object getObjectById(PipelineContext pipelineContext, String id) {
// Search in models
for (Iterator i = models.iterator(); i.hasNext();) {
XFormsModel model = (XFormsModel) i.next();
final Object resultObject = model.getObjectByid(pipelineContext, id);
if (resultObject != null)
return resultObject;
}
// Search in controls
{
final Object resultObject = xformsControls.getObjectById(id);
if (resultObject != null)
return resultObject;
}
// Check containing document
if (id.equals(getEffectiveId()))
return this;
return null;
}
/**
* Find the instance containing the specified node, in any model.
*
* @param nodeInfo node contained in an instance
* @return instance containing the node
*/
public XFormsInstance getInstanceForNode(NodeInfo nodeInfo) {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
final XFormsInstance currentInstance = currentModel.getInstanceForNode(nodeInfo);
if (currentInstance != null)
return currentInstance;
}
// This should not happen if the node is currently in an instance!
return null;
}
/**
* Find the instance with the specified id, searching in any model.
*
* @param instanceId id of the instance to find
* @return instance containing the node
*/
public XFormsInstance findInstance(String instanceId) {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
final XFormsInstance currentInstance = currentModel.getInstance(instanceId);
if (currentInstance != null)
return currentInstance;
}
return null;
}
/**
* Return the active submission if any or null.
*/
public XFormsModelSubmission getClientActiveSubmission() {
return activeSubmission;
}
/**
* Clear current client state.
*/
private void clearClientState() {
this.activeSubmission = null;
this.gotSubmission = false;
this.messagesToRun = null;
this.loadsToRun = null;
this.scriptsToRun = null;
this.focusEffectiveControlId = null;
this.helpEffectiveControlId = null;
}
/**
* Set the active submission.
*
* This can be called with a non-null value at most once.
*/
public void setClientActiveSubmission(XFormsModelSubmission activeSubmission) {
if (this.activeSubmission != null)
throw new ValidationException("There is already an active submission.", activeSubmission.getLocationData());
if (loadsToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData());
if (messagesToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData());
if (scriptsToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData());
if (focusEffectiveControlId != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData());
if (helpEffectiveControlId != null)
throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData());
this.activeSubmission = activeSubmission;
}
public boolean isGotSubmission() {
return gotSubmission;
}
public void setGotSubmission(boolean gotSubmission) {
this.gotSubmission = gotSubmission;
}
/**
* Add an XForms message to send to the client.
*/
public void addMessageToRun(String message, String level) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData());
if (messagesToRun == null)
messagesToRun = new ArrayList();
messagesToRun.add(new Message(message, level));
}
/**
* Return the list of messages to send to the client, null if none.
*/
public List getMessagesToRun() {
return messagesToRun;
}
public static class Message {
private String message;
private String level;
public Message(String message, String level) {
this.message = message;
this.level = level;
}
public String getMessage() {
return message;
}
public String getLevel() {
return level;
}
}
public void addScriptToRun(String scriptId, String eventTargetId, String eventHandlerContainerId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData());
if (scriptsToRun == null)
scriptsToRun = new ArrayList();
scriptsToRun.add(new Script(XFormsUtils.scriptIdToScriptName(scriptId), eventTargetId, eventHandlerContainerId));
}
public static class Script {
private String functionName;
private String eventTargetId;
private String eventHandlerContainerId;
public Script(String functionName, String eventTargetId, String eventHandlerContainerId) {
this.functionName = functionName;
this.eventTargetId = eventTargetId;
this.eventHandlerContainerId = eventHandlerContainerId;
}
public String getFunctionName() {
return functionName;
}
public String getEventTargetId() {
return eventTargetId;
}
public String getEventHandlerContainerId() {
return eventHandlerContainerId;
}
}
public List getScriptsToRun() {
return scriptsToRun;
}
/**
* Add an XForms load to send to the client.
*/
public void addLoadToRun(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData());
if (loadsToRun == null)
loadsToRun = new ArrayList();
loadsToRun.add(new Load(resource, target, urlType, isReplace, isPortletLoad, isShowProgress));
}
/**
* Return the list of messages to send to the client, null if none.
*/
public List getLoadsToRun() {
return loadsToRun;
}
public static class Load {
private String resource;
private String target;
private String urlType;
private boolean isReplace;
private boolean isPortletLoad;
private boolean isShowProgress;
public Load(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) {
this.resource = resource;
this.target = target;
this.urlType = urlType;
this.isReplace = isReplace;
this.isPortletLoad = isPortletLoad;
this.isShowProgress = isShowProgress;
}
public String getResource() {
return resource;
}
public String getTarget() {
return target;
}
public String getUrlType() {
return urlType;
}
public boolean isReplace() {
return isReplace;
}
public boolean isPortletLoad() {
return isPortletLoad;
}
public boolean isShowProgress() {
return isShowProgress;
}
}
/**
* Tell the client that focus must be changed to the given effective control id.
*
* This can be called several times, but only the last controld id is remembered.
*
* @param effectiveControlId
*/
public void setClientFocusEffectiveControlId(String effectiveControlId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData());
this.focusEffectiveControlId = effectiveControlId;
}
/**
* Return the effective control id of the control to set the focus to, or null.
*/
public String getClientFocusEffectiveControlId(PipelineContext pipelineContext) {
if (focusEffectiveControlId == null)
return null;
final XFormsControl xformsControl = (XFormsControl) getObjectById(pipelineContext, focusEffectiveControlId);
// It doesn't make sense to tell the client to set the focus to an element that is non-relevant or readonly
if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) {
final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl;
if (xformsSingleNodeControl.isRelevant() && !xformsSingleNodeControl.isReadonly())
return focusEffectiveControlId;
else
return null;
} else {
return null;
}
}
/**
* Tell the client that help must be shown for the given effective control id.
*
* This can be called several times, but only the last controld id is remembered.
*
* @param effectiveControlId
*/
public void setClientHelpEffectiveControlId(String effectiveControlId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData());
this.helpEffectiveControlId = effectiveControlId;
}
/**
* Return the effective control id of the control to help for, or null.
*/
public String getClientHelpEffectiveControlId(PipelineContext pipelineContext) {
if (helpEffectiveControlId == null)
return null;
final XFormsControl xformsControl = (XFormsControl) getObjectById(pipelineContext, helpEffectiveControlId);
// It doesn't make sense to tell the client to show help for an element that is non-relevant, but we allow readonly
if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) {
final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl;
if (xformsSingleNodeControl.isRelevant())
return helpEffectiveControlId;
else
return null;
} else {
return null;
}
}
/**
* Execute an external event on element with id targetElementId and event eventName.
*/
public void executeExternalEvent(PipelineContext pipelineContext, String eventName, String controlId, String otherControlId, String contextString, Element filesElement) {
// Get event target object
final XFormsEventTarget eventTarget;
{
final Object eventTargetObject = getObjectById(pipelineContext, controlId);
if (!(eventTargetObject instanceof XFormsEventTarget)) {
if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) {
throw new ValidationException("Event target id '" + controlId + "' is not an XFormsEventTarget.", getLocationData());
} else {
if (XFormsServer.logger.isDebugEnabled()) {
XFormsServer.logger.debug("XForms - ignoring client event with invalid control id: " + controlId);
}
return;
}
}
eventTarget = (XFormsEventTarget) eventTargetObject;
}
// Don't allow for events on non-relevant, readonly or xforms:output controls (we accept focus events on
// xforms:output though).
// This is also a security measures that also ensures that somebody is not able to change values in an instance
// by hacking external events.
if (eventTarget instanceof XFormsControl) {
// Target is a control
if (eventTarget instanceof XXFormsDialogControl) {
// Target is a dialog
// Check for implicitly allowed events
if (allowedXXFormsDialogExternalEvents.get(eventName) == null) {
return;
}
} else {
// Target is a regular control
// Only single-node controls accept events from the client
if (!(eventTarget instanceof XFormsSingleNodeControl)) {
return;
}
final XFormsSingleNodeControl xformsControl = (XFormsSingleNodeControl) eventTarget;
if (!xformsControl.isRelevant() || (xformsControl.isReadonly() && !(xformsControl instanceof XFormsOutputControl))) {
// Controls accept event only if they are relevant and not readonly, except for xforms:output which may be readonly
return;
}
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed: check for implicitly allowed events
if (xformsControl instanceof XFormsOutputControl) {
if (allowedXFormsOutputExternalEvents.get(eventName) == null) {
return;
}
} else if (xformsControl instanceof XFormsUploadControl) {
if (allowedXFormsUploadExternalEvents.get(eventName) == null) {
return;
}
} else {
if (allowedExternalEvents.get(eventName) == null) {
return;
}
}
}
}
} else if (eventTarget instanceof XFormsModelSubmission) {
// Target is a submission
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed: check for implicitly allowed events
if (allowedXFormsSubmissionExternalEvents.get(eventName) == null) {
return;
}
}
} else if (eventTarget instanceof XFormsContainingDocument) {
// Target is the containing document
// Check for implicitly allowed events
if (allowedXFormsContainingDocumentExternalEvents.get(eventName) == null) {
return;
}
} else {
// Target is not a control
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed
return;
}
}
// Get other event target
final XFormsEventTarget otherEventTarget;
{
final Object otherEventTargetObject = (otherControlId == null) ? null : getObjectById(pipelineContext, otherControlId);
if (otherEventTargetObject == null) {
otherEventTarget = null;
} else if (!(otherEventTargetObject instanceof XFormsEventTarget)) {
if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) {
throw new ValidationException("Other event target id '" + otherControlId + "' is not an XFormsEventTarget.", getLocationData());
} else {
if (XFormsServer.logger.isDebugEnabled()) {
XFormsServer.logger.debug("XForms - ignoring client event with invalid second control id: " + otherControlId);
}
return;
}
} else {
otherEventTarget = (XFormsEventTarget) otherEventTargetObject;
}
}
// Handle repeat focus. Don't dispatch event on DOMFocusOut however.
if (controlId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1 && !XFormsEvents.XFORMS_DOM_FOCUS_OUT.equals(eventName)) {
// The event target is in a repeated structure, so make sure it gets repeat focus
dispatchEvent(pipelineContext, new XXFormsRepeatFocusEvent(eventTarget));
}
// Don't actually dispatch event to xforms:output (but repeat focus may have been dispatched)
if (eventTarget instanceof XFormsOutputControl && ignoredXFormsOutputExternalEvents.equals(eventName)) {
return;
// NOTE: We always receive DOMFocusIn from the client on xforms:output. Would it make sense to turn this
// into a DOMActivate if the control is not read-only?
// final XFormsOutputControl xformsOutputControl = (XFormsOutputControl) eventTarget;
// if (xformsOutputControl.isReadonly()) ...
}
// Create event
if (XFormsProperties.isAjaxTest()) {
if (eventName.equals(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE)) {
if ("category-select1".equals(controlId)) {
if (testAjaxToggleValue == 0) {
testAjaxToggleValue = 1;
contextString = "supplier";
} else {
testAjaxToggleValue = 0;
contextString = "customer";
}
} else if (("xforms-element-287" + XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1 + "1").equals(controlId)) {
contextString = "value" + System.currentTimeMillis();
}
}
}
final XFormsEvent xformsEvent = XFormsEventFactory.createEvent(eventName, eventTarget, otherEventTarget, true, true, true, contextString, null, null, filesElement);
// Interpret event
if (xformsEvent instanceof XXFormsValueChangeWithFocusChangeEvent) {
// 4.6.7 Sequence: Value Change
// What we want to do here is set the value on the initial controls state, as the value
// has already been changed on the client. This means that this event(s) must be the
// first to come!
final XXFormsValueChangeWithFocusChangeEvent concreteEvent = (XXFormsValueChangeWithFocusChangeEvent) xformsEvent;
// 1. xforms-recalculate
// 2. xforms-revalidate
// 3. xforms-refresh performs reevaluation of UI binding expressions then dispatches
// these events according to value changes, model item property changes and validity
// changes
// [n] xforms-value-changed, [n] xforms-valid or xforms-invalid, [n] xforms-enabled or
// xforms-disabled, [n] xforms-optional or xforms-required, [n] xforms-readonly or
// xforms-readwrite, [n] xforms-out-of-range or xforms-in-range
final String targetControlEffectiveId;
{
// Set current context to control
final XFormsValueControl valueXFormsControl = (XFormsValueControl) concreteEvent.getTargetObject();
targetControlEffectiveId = valueXFormsControl.getEffectiveId();
// Notify the control of the value change
final String eventValue = concreteEvent.getNewValue();
valueXFormsControl.setExternalValue(pipelineContext, eventValue, null);
}
{
// NOTE: Recalculate and revalidate are done with the automatic deferred updates
// Handle focus change DOMFocusOut / DOMFocusIn
if (concreteEvent.getOtherTargetObject() != null) {
final XFormsControl sourceXFormsControl = (XFormsControl) getObjectById(pipelineContext, targetControlEffectiveId);
final XFormsControl otherTargetXFormsControl
= (XFormsControl) getObjectById(pipelineContext,
((XFormsControl) concreteEvent.getOtherTargetObject()).getEffectiveId());
// We have a focus change (otherwise, the focus is assumed to remain the same)
if (sourceXFormsControl != null)
dispatchEvent(pipelineContext, new XFormsDOMFocusOutEvent(sourceXFormsControl));
if (otherTargetXFormsControl != null)
dispatchEvent(pipelineContext, new XFormsDOMFocusInEvent(otherTargetXFormsControl));
}
// NOTE: Refresh is done with the automatic deferred updates
}
} else {
// Dispatch any other allowed event
dispatchEvent(pipelineContext, xformsEvent);
}
}
/**
* Prepare the ContainingDocumentg for a sequence of external events.
*/
public void prepareForExternalEventsSequence(PipelineContext pipelineContext) {
// Clear containing document state
clearClientState();
// Initialize controls
xformsControls.initialize(pipelineContext);
}
public void startOutermostActionHandler() {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
currentModel.startOutermostActionHandler();
}
}
public void endOutermostActionHandler(PipelineContext pipelineContext) {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
currentModel.endOutermostActionHandler(pipelineContext);
}
}
public XFormsEventHandlerContainer getParentContainer(XFormsContainingDocument containingDocument) {
return null;
}
public List getEventHandlers(XFormsContainingDocument containingDocument) {
return null;
}
public String getEffectiveId() {
return CONTAINING_DOCUMENT_PSEUDO_ID;
}
public LocationData getLocationData() {
return (xformsStaticState != null) ? xformsStaticState.getLocationData() : null;
}
public void performDefaultAction(PipelineContext pipelineContext, XFormsEvent event) {
final String eventName = event.getEventName();
if (XFormsEvents.XXFORMS_LOAD.equals(eventName)) {
// Internal load event
final XXFormsLoadEvent xxformsLoadEvent = (XXFormsLoadEvent) event;
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
try {
final String resource = xxformsLoadEvent.getResource();
final String pathInfo;
final Map parameters;
final int qmIndex = resource.indexOf('?');
if (qmIndex != -1) {
pathInfo = resource.substring(0, qmIndex);
parameters = NetUtils.decodeQueryString(resource.substring(qmIndex + 1), false);
} else {
pathInfo = resource;
parameters = null;
}
externalContext.getResponse().sendRedirect(pathInfo, parameters, false, false);
} catch (IOException e) {
throw new ValidationException(e, getLocationData());
}
}
}
/**
* Main event dispatching entry.
*/
public void dispatchEvent(PipelineContext pipelineContext, XFormsEvent event) {
if (XFormsServer.logger.isDebugEnabled()) {
XFormsServer.logger.debug("XForms - dispatching event: " + getEventLogSpaces() + event.getEventName() + " - " + event.getTargetObject().getEffectiveId() + " - at " + event.getLocationData());
}
final XFormsEventTarget targetObject = event.getTargetObject();
try {
if (targetObject == null)
throw new ValidationException("Target object null for event: " + event.getEventName(), getLocationData());
// Find all event handler containers
final List containers = new ArrayList();
{
XFormsEventHandlerContainer container
= (targetObject instanceof XFormsEventHandlerContainer) ? (XFormsEventHandlerContainer) targetObject : targetObject.getParentContainer(this);
while (container != null) {
containers.add(container);
container = container.getParentContainer(this);
}
}
boolean propagate = true;
boolean performDefaultAction = true;
// Go from root to leaf
Collections.reverse(containers);
// Capture phase
for (Iterator i = containers.iterator(); i.hasNext();) {
final XFormsEventHandlerContainer container = (XFormsEventHandlerContainer) i.next();
final List eventHandlers = container.getEventHandlers(this);
if (eventHandlers != null) {
if (container != targetObject) {
// Event listeners on the target which are in capture mode are not called
for (Iterator j = eventHandlers.iterator(); j.hasNext();) {
final XFormsEventHandler eventHandlerImpl = (XFormsEventHandler) j.next();
if (!eventHandlerImpl.isPhase() && eventHandlerImpl.getEventName().equals(event.getEventName())) {
// Capture phase match
startHandleEvent(event);
try {
eventHandlerImpl.handleEvent(pipelineContext, event);
} finally {
endHandleEvent();
}
propagate &= eventHandlerImpl.isPropagate();
performDefaultAction &= eventHandlerImpl.isDefaultAction();
}
}
// Cancel propagation if requested and if authorized by event
if (!propagate && event.isCancelable())
break;
}
}
}
// Go from leaf to root
Collections.reverse(containers);
// Bubbling phase
if (propagate && event.isBubbles()) {
for (Iterator i = containers.iterator(); i.hasNext();) {
final XFormsEventHandlerContainer container = (XFormsEventHandlerContainer) i.next();
final List eventHandlers = container.getEventHandlers(this);
if (eventHandlers != null) {
for (Iterator j = eventHandlers.iterator(); j.hasNext();) {
final XFormsEventHandler eventHandlerImpl = (XFormsEventHandler) j.next();
if (eventHandlerImpl.isPhase() && eventHandlerImpl.getEventName().equals(event.getEventName())) {
// Bubbling phase match
startHandleEvent(event);
try {
eventHandlerImpl.handleEvent(pipelineContext, event);
} finally {
endHandleEvent();
}
propagate &= eventHandlerImpl.isPropagate();
performDefaultAction &= eventHandlerImpl.isDefaultAction();
}
}
// Cancel propagation if requested and if authorized by event
if (!propagate)
break;
}
}
}
// Perform default action is allowed to
if (performDefaultAction || !event.isCancelable()) {
startHandleEvent(event);
try {
targetObject.performDefaultAction(pipelineContext, event);
} finally {
endHandleEvent();
}
}
} catch (Exception e) {
// Add location information if possible
final LocationData locationData = (targetObject != null)
? ((targetObject.getLocationData() != null)
? targetObject.getLocationData()
: getLocationData())
: null;
throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "dispatching XForms event",
new String[] { "event", event.getEventName(), "target id", targetObject.getEffectiveId() }));
}
}
private Stack eventStack = new Stack();
private void startHandleEvent(XFormsEvent event) {
eventStack.push(event);
}
private void endHandleEvent() {
eventStack.pop();
}
private String getEventLogSpaces() {
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < eventStack.size(); i++)
sb.append(" ");
return sb.toString();
}
/**
* Return the event being processed by the current event handler, null if no event is being processed.
*/
public XFormsEvent getCurrentEvent() {
return (eventStack.size() == 0) ? null : (XFormsEvent) eventStack.peek();
}
/**
* Execute an XForms action.
*
* @param pipelineContext current PipelineContext
* @param targetId id of the target control
* @param eventHandlerContainer event handler containe this action is running in
* @param actionElement Element specifying the action to execute
*/
public void runAction(final PipelineContext pipelineContext, String targetId, XFormsEventHandlerContainer eventHandlerContainer, Element actionElement) {
if (actionInterpreter == null)
actionInterpreter = new XFormsActionInterpreter(this);
actionInterpreter.runAction(pipelineContext, targetId, eventHandlerContainer, actionElement);
}
/**
* Create an encoded dynamic state that represents the dynamic state of this XFormsContainingDocument.
*
* @param pipelineContext current PipelineContext
* @return encoded dynamic state
*/
public String createEncodedDynamicState(PipelineContext pipelineContext) {
return XFormsUtils.encodeXML(pipelineContext, createDynamicStateDocument(),
XFormsProperties.isClientStateHandling(this) ? XFormsProperties.getXFormsPassword() : null, false);
}
private Document createDynamicStateDocument() {
final XFormsControls.ControlsState currentControlsState = getXFormsControls().getCurrentControlsState();
final Document dynamicStateDocument = Dom4jUtils.createDocument();
final Element dynamicStateElement = dynamicStateDocument.addElement("dynamic-state");
// Output instances
{
final Element instancesElement = dynamicStateElement.addElement("instances");
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
if (currentModel.getInstances() != null) {
for (Iterator j = currentModel.getInstances().iterator(); j.hasNext();) {
final XFormsInstance currentInstance = (XFormsInstance) j.next();
// TODO: can we avoid storing the instance in the dynamic state if it has not changed from static state?
if (currentInstance.isReplaced() || !(currentInstance instanceof SharedXFormsInstance)) {
// Instance has been replaced, or it is not shared, so it has to go in the dynamic state
instancesElement.add(currentInstance.createContainerElement(!currentInstance.isApplicationShared()));
// Log instance if needed
currentInstance.logIfNeeded("storing instance to dynamic state");
}
}
}
}
}
// Output divs information
{
final Element divsElement = Dom4jUtils.createElement("divs");
outputSwitchesDialogs(divsElement, getXFormsControls());
if (divsElement.hasContent())
dynamicStateElement.add(divsElement);
}
// Output repeat index information
{
final Map repeatIdToIndex = currentControlsState.getRepeatIdToIndex();
if (repeatIdToIndex.size() != 0) {
final Element repeatIndexesElement = dynamicStateElement.addElement("repeat-indexes");
for (Iterator i = repeatIdToIndex.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String repeatId = (String) currentEntry.getKey();
final Integer index = (Integer) currentEntry.getValue();
final Element newElement = repeatIndexesElement.addElement("repeat-index");
newElement.addAttribute("id", repeatId);
newElement.addAttribute("index", index.toString());
}
}
}
return dynamicStateDocument;
}
public static void outputSwitchesDialogs(Element divsElement, XFormsControls xformsControls) {
{
final Map switchIdToSelectedCaseIdMap = xformsControls.getCurrentSwitchState().getSwitchIdToSelectedCaseIdMap();
if (switchIdToSelectedCaseIdMap != null) {
// There are some xforms:switch/xforms:case controls
for (Iterator i = switchIdToSelectedCaseIdMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String switchId = (String) currentEntry.getKey();
final String selectedCaseId = (String) currentEntry.getValue();
// Output selected ids
{
final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI);
divElement.addAttribute("switch-id", switchId);
divElement.addAttribute("case-id", selectedCaseId);
divElement.addAttribute("visibility", "visible");
}
// Output deselected ids
final XFormsControl switchXFormsControl = (XFormsControl) xformsControls.getObjectById(switchId);
final List children = switchXFormsControl.getChildren();
if (children != null && children.size() > 0) {
for (Iterator j = children.iterator(); j.hasNext();) {
final XFormsControl caseXFormsControl = (XFormsControl) j.next();
if (!caseXFormsControl.getEffectiveId().equals(selectedCaseId)) {
final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI);
divElement.addAttribute("switch-id", switchId);
divElement.addAttribute("case-id", caseXFormsControl.getEffectiveId());
divElement.addAttribute("visibility", "hidden");
}
}
}
}
}
}
{
final Map dialogIdToVisibleMap = xformsControls.getCurrentDialogState().getDialogIdToVisibleMap();
if (dialogIdToVisibleMap != null) {
// There are some xxforms:dialog controls
for (Iterator i = dialogIdToVisibleMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String dialogId = (String) currentEntry.getKey();
final XFormsControls.DialogState.DialogInfo dialogInfo
= (XFormsControls.DialogState.DialogInfo) currentEntry.getValue();
// Output element and attributes
{
final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI);
divElement.addAttribute("dialog-id", dialogId);
divElement.addAttribute("visibility", dialogInfo.isShow() ? "visible" : "hidden");
if (dialogInfo.isShow()) {
if (dialogInfo.getNeighbor() != null)
divElement.addAttribute("neighbor", dialogInfo.getNeighbor());
if (dialogInfo.isConstrainToViewport())
divElement.addAttribute("constrain", Boolean.toString(dialogInfo.isConstrainToViewport()));
}
}
}
}
}
}
private void restoreDynamicState(PipelineContext pipelineContext, String encodedDynamicState) {
// Get dynamic state document
final Document dynamicStateDocument = XFormsUtils.decodeXML(pipelineContext, encodedDynamicState);
// Get repeat indexes from dynamic state
final Element repeatIndexesElement = dynamicStateDocument.getRootElement().element("repeat-indexes");
// Create XForms controls and models
createControlAndModel(repeatIndexesElement);
// Extract and restore instances
{
// Get instances from dynamic state first
final Element instancesElement = dynamicStateDocument.getRootElement().element("instances");
if (instancesElement != null) {
for (Iterator i = instancesElement.elements().iterator(); i.hasNext();) {
final Element instanceElement = (Element) i.next();
// Create and set instance document on current model
final XFormsInstance newInstance = new XFormsInstance(instanceElement);
if (newInstance.getDocumentInfo() == null) {
// Instance is not initialized yet
// This means that the instance was application shared
if (!newInstance.isApplicationShared())
throw new ValidationException("Non-initialized instance has to be application shared for id: " + newInstance.getEffectiveId(), getLocationData());
final SharedXFormsInstance sharedInstance
= XFormsServerSharedInstancesCache.instance().find(pipelineContext, newInstance.getEffectiveId(), newInstance.getModelId(), newInstance.getSourceURI(), newInstance.getTimeToLive(), newInstance.getValidation());
getModel(sharedInstance.getModelId()).setInstance(sharedInstance, false);
} else {
// Instance is initialized, just use it
getModel(newInstance.getModelId()).setInstance(newInstance, newInstance.isReplaced());
}
// Log instance if needed
newInstance.logIfNeeded("restoring instance from dynamic state");
}
}
// Then get instances from static state if necessary
final Map staticInstancesMap = xformsStaticState.getInstancesMap();
if (staticInstancesMap != null && staticInstancesMap.size() > 0) {
for (Iterator instancesIterator = staticInstancesMap.values().iterator(); instancesIterator.hasNext();) {
final XFormsInstance currentInstance = (XFormsInstance) instancesIterator.next();
if (findInstance(currentInstance.getEffectiveId()) == null) {
// Instance was not set from dynamic state
if (currentInstance.getDocumentInfo() == null) {
// Instance is not initialized yet
// This means that the instance was application shared
if (!currentInstance.isApplicationShared())
throw new ValidationException("Non-initialized instance has to be application shared for id: " + currentInstance.getEffectiveId(), getLocationData());
final SharedXFormsInstance sharedInstance
= XFormsServerSharedInstancesCache.instance().find(pipelineContext, currentInstance.getEffectiveId(), currentInstance.getModelId(), currentInstance.getSourceURI(), currentInstance.getTimeToLive(), currentInstance.getValidation());
getModel(sharedInstance.getModelId()).setInstance(sharedInstance, false);
} else {
// Instance is initialized, just use it
getModel(currentInstance.getModelId()).setInstance(currentInstance, false);
}
}
}
}
}
// Restore models state
for (Iterator j = getModels().iterator(); j.hasNext();) {
final XFormsModel currentModel = (XFormsModel) j.next();
currentModel.initializeState(pipelineContext);
}
// Restore controls
final Element divsElement = dynamicStateDocument.getRootElement().element("divs");
xformsControls.initializeState(pipelineContext, divsElement, repeatIndexesElement, true);
xformsControls.evaluateAllControlsIfNeeded(pipelineContext);
}
/**
* Whether, during initialization, this is the first refresh. The flag is automatically cleared during this call so
* that only the first call returns true.
*
* @return true if this is the first refresh, false otherwise
*/
public boolean isInitializationFirstRefreshClear() {
boolean result = mustPerformInitializationFirstRefresh;
mustPerformInitializationFirstRefresh = false;
return result;
}
private void initialize(PipelineContext pipelineContext) {
// This is called upon the first creation of the XForms engine only
// Create XForms controls and models
createControlAndModel(null);
// 4.2 Initialization Events
// 1. Dispatch xforms-model-construct to all models
// 2. Dispatch xforms-model-construct-done to all models
// 3. Dispatch xforms-ready to all models
// Before dispaching initialization events, remember that first refresh must be performed
this.mustPerformInitializationFirstRefresh = true;
final String[] eventsToDispatch = { XFormsEvents.XFORMS_MODEL_CONSTRUCT, XFormsEvents.XFORMS_MODEL_CONSTRUCT_DONE, XFormsEvents.XFORMS_READY, XFormsEvents.XXFORMS_READY };
for (int i = 0; i < eventsToDispatch.length; i++) {
// Initialize controls right at the beginning
final boolean isXFormsModelConstructDone = i == 1;
if (isXFormsModelConstructDone) {
// Initialize controls after all the xforms-model-construct events have been sent
xformsControls.initialize(pipelineContext);
}
// Group all xforms-ready events within a single outermost action handler in order to optimize events
final boolean isXFormsReady = i == 2;
if (isXFormsReady) {
// Performed deferred updates only for xforms-ready
startOutermostActionHandler();
}
// Iterate over all the models
for (Iterator j = getModels().iterator(); j.hasNext();) {
final XFormsModel currentModel = (XFormsModel) j.next();
// Make sure there is at least one refresh
final XFormsModel.DeferredActionContext deferredActionContext = currentModel.getDeferredActionContext();
if (deferredActionContext != null) {
deferredActionContext.refresh = true;
}
dispatchEvent(pipelineContext, XFormsEventFactory.createEvent(eventsToDispatch[i], currentModel));
}
if (isXFormsReady) {
// Performed deferred updates only for xforms-ready
endOutermostActionHandler(pipelineContext);
}
}
// In case there is no model or no controls, make sure the flag is cleared as it is only relevant during
// initialization
this.mustPerformInitializationFirstRefresh = false;
}
private void createControlAndModel(Element repeatIndexesElement) {
if (xformsStaticState != null) {
// Create XForms controls
xformsControls = new XFormsControls(this, xformsStaticState.getControlsDocument(), repeatIndexesElement);
// Create and index models
for (Iterator i = xformsStaticState.getModelDocuments().iterator(); i.hasNext();) {
final Document modelDocument = (Document) i.next();
final XFormsModel model = new XFormsModel(modelDocument);
model.setContainingDocument(this); // NOTE: This requires the XFormsControls to be set on XFormsContainingDocument
this.models.add(model);
if (model.getEffectiveId() != null)
this.modelsMap.put(model.getEffectiveId(), model);
}
}
}
} |
package org.orbeon.oxf.xforms;
import org.apache.commons.pool.ObjectPool;
import org.apache.log4j.Level;
import org.dom4j.Document;
import org.dom4j.Element;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.util.NetUtils;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsValueControl;
import org.orbeon.oxf.xforms.control.XFormsSingleNodeControl;
import org.orbeon.oxf.xforms.control.controls.XFormsOutputControl;
import org.orbeon.oxf.xforms.control.controls.XFormsUploadControl;
import org.orbeon.oxf.xforms.control.controls.XXFormsDialogControl;
import org.orbeon.oxf.xforms.event.*;
import org.orbeon.oxf.xforms.event.events.*;
import org.orbeon.oxf.xforms.processor.XFormsServer;
import org.orbeon.oxf.xforms.state.XFormsState;
import org.orbeon.oxf.xforms.processor.XFormsURIResolver;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.saxon.om.NodeInfo;
import org.orbeon.saxon.om.FastStringBuffer;
import java.io.IOException;
import java.util.*;
/**
* Represents an XForms containing document.
*
* The containing document includes:
*
* o XForms models (including multiple instances)
* o XForms controls
* o Event handlers hierarchy
*/
public class XFormsContainingDocument implements XFormsEventTarget, XFormsEventHandlerContainer {
public static final String CONTAINING_DOCUMENT_PSEUDO_ID = "$containing-document$";
// Global XForms function library
private static XFormsFunctionLibrary functionLibrary = new XFormsFunctionLibrary();
// Object pool this object must be returned to, if any
private ObjectPool sourceObjectPool;
// URI resolver
private XFormsURIResolver uriResolver;
// Whether this document is currently being initialized
private boolean isInitializing;
// A document contains models and controls
private XFormsStaticState xformsStaticState;
private List models = new ArrayList();
private Map modelsMap = new HashMap();
private XFormsControls xformsControls;
// Client state
private boolean dirtySinceLastRequest;
private XFormsModelSubmission activeSubmission;
private boolean gotSubmission;
private boolean gotSubmissionSecondPass;
private List messagesToRun;
private List loadsToRun;
private List scriptsToRun;
private String focusEffectiveControlId;
private String helpEffectiveControlId;
private boolean goingOffline;
// Global flag used during initialization only
private boolean mustPerformInitializationFirstRefresh;
// Legacy information
private String legacyContainerType;
private String legacyContainerNamespace;
// Event information
private static final Map ignoredXFormsOutputExternalEvents = new HashMap();
private static final Map allowedXFormsOutputExternalEvents = new HashMap();
private static final Map allowedXFormsUploadExternalEvents = new HashMap();
private static final Map allowedExternalEvents = new HashMap();
private static final Map allowedXFormsSubmissionExternalEvents = new HashMap();
private static final Map allowedXFormsContainingDocumentExternalEvents = new HashMap();
private static final Map allowedXXFormsDialogExternalEvents = new HashMap();
static {
// External events ignored on xforms:output
ignoredXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_DOM_FOCUS_IN, "");
ignoredXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_DOM_FOCUS_OUT, "");
// External events allowed on xforms:output
allowedXFormsOutputExternalEvents.putAll(ignoredXFormsOutputExternalEvents);
allowedXFormsOutputExternalEvents.put(XFormsEvents.XFORMS_HELP, "");
// External events allowed on xforms:upload
allowedXFormsUploadExternalEvents.putAll(allowedXFormsOutputExternalEvents);
allowedXFormsUploadExternalEvents.put(XFormsEvents.XFORMS_SELECT, "");
allowedXFormsUploadExternalEvents.put(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE, "");
// External events allowed on other controls
allowedExternalEvents.putAll(allowedXFormsOutputExternalEvents);
allowedExternalEvents.put(XFormsEvents.XFORMS_DOM_ACTIVATE, "");
allowedExternalEvents.put(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE, "");
// External events allowed on xforms:submission
allowedXFormsSubmissionExternalEvents.put(XFormsEvents.XXFORMS_SUBMIT, "");
// External events allowed on containing document
allowedXFormsContainingDocumentExternalEvents.put(XFormsEvents.XXFORMS_LOAD, "");
allowedXFormsContainingDocumentExternalEvents.put(XFormsEvents.XXFORMS_OFFLINE, "");
// External events allowed on xxforms:dialog
allowedXXFormsDialogExternalEvents.put(XFormsEvents.XXFORMS_DIALOG_CLOSE, "");
}
// For testing only
private static int testAjaxToggleValue = 0;
/**
* Return the global function library.
*/
public static XFormsFunctionLibrary getFunctionLibrary() {
return functionLibrary;
}
/**
* Create an XFormsContainingDocument from an XFormsEngineStaticState object.
*
* @param pipelineContext current pipeline context
* @param xformsStaticState XFormsEngineStaticState
* @param uriResolver optional URIResolver for loading instances during initialization (and possibly more, such as schemas and "GET" submissions upon initialization)
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsStaticState xformsStaticState,
XFormsURIResolver uriResolver) {
logDebug("containing document", "creating new ContainingDocument (static state object provided).");
// Remember static state
this.xformsStaticState = xformsStaticState;
// Remember URI resolver for initialization
this.uriResolver = uriResolver;
this.isInitializing = true;
// Initialize the containing document
try {
initialize(pipelineContext);
} catch (Exception e) {
throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "initializing XForms containing document"));
}
// Clear URI resolver, since it is of no use after initialization, and it may keep dangerous references (PipelineContext)
this.uriResolver = null;
// NOTE: we clear isInitializing when Ajax requests come in
}
/**
* Create an XFormsContainingDocument from an XFormsState object.
*
* @param pipelineContext current pipeline context
* @param xformsState XFormsState containing static and dynamic state
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsState xformsState) {
logDebug("containing document", "creating new ContainingDocument (static state object not provided).");
// Create static state object
// TODO: Handle caching of XFormsStaticState object
xformsStaticState = new XFormsStaticState(pipelineContext, xformsState.getStaticState());
// Restore the containing document's dynamic state
final String encodedDynamicState = xformsState.getDynamicState();
try {
if (encodedDynamicState == null || encodedDynamicState.equals("")) {
// Just for tests, we allow the dynamic state to be empty
initialize(pipelineContext);
xformsControls.evaluateAllControlsIfNeeded(pipelineContext);
} else {
// Regular case
restoreDynamicState(pipelineContext, encodedDynamicState);
}
} catch (Exception e) {
throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "re-initializing XForms containing document"));
}
}
/**
* Legacy constructor for XForms Classic.
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsModel xformsModel) {
this.models = Collections.singletonList(xformsModel);
this.xformsControls = new XFormsControls(this, null, null);
if (xformsModel.getEffectiveId() != null)
modelsMap.put(xformsModel.getEffectiveId(), xformsModel);
xformsModel.setContainingDocument(this);
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
this.legacyContainerType = externalContext.getRequest().getContainerType();
this.legacyContainerNamespace = externalContext.getRequest().getContainerNamespace();
initialize(pipelineContext);
}
public void setSourceObjectPool(ObjectPool sourceObjectPool) {
this.sourceObjectPool = sourceObjectPool;
}
public ObjectPool getSourceObjectPool() {
return sourceObjectPool;
}
public XFormsURIResolver getURIResolver() {
return uriResolver;
}
public boolean isInitializing() {
return isInitializing;
}
/**
* Return model with the specified id, null if not found. If the id is the empty string, return
* the default model, i.e. the first model.
*/
public XFormsModel getModel(String modelId) {
return (XFormsModel) ("".equals(modelId) ? getDefaultModel() : modelsMap.get(modelId));
}
public XFormsModel getDefaultModel() {
if (models != null && models.size() > 0)
return (XFormsModel) models.get(0);
else
return null;
}
/**
* Get a list of all the models in this document.
*/
public List getModels() {
return models;
}
/**
* Return the XForms controls.
*/
public XFormsControls getXFormsControls() {
return xformsControls;
}
/**
* Whether the document is dirty since the last request.
*
* @return whether the document is dirty since the last request
*/
public boolean isDirtySinceLastRequest() {
return dirtySinceLastRequest || xformsControls == null || xformsControls.isDirtySinceLastRequest();
}
public void markCleanSinceLastRequest() {
this.dirtySinceLastRequest = false;
}
public void markDirtySinceLastRequest() {
this.dirtySinceLastRequest = true;
}
/**
* Return the XFormsEngineStaticState.
*/
public XFormsStaticState getStaticState() {
return xformsStaticState;
}
/**
* Return a map of script id -> script text.
*/
public Map getScripts() {
return (xformsStaticState == null) ? null : xformsStaticState.getScripts();
}
/**
* Return the document base URI.
*/
public String getBaseURI() {
return (xformsStaticState == null) ? null : xformsStaticState.getBaseURI();
}
/**
* Return the container type that generate the XForms page, either "servlet" or "portlet".
*/
public String getContainerType() {
return (xformsStaticState == null) ? legacyContainerType : xformsStaticState.getContainerType();
}
/**
* Return the container namespace that generate the XForms page. Always "" for servlets.
*/
public String getContainerNamespace() {
return (xformsStaticState == null) ? legacyContainerNamespace : xformsStaticState.getContainerNamespace();
}
public Map getNamespaceMappings(Element element) {
if (xformsStaticState != null)
return xformsStaticState.getNamespaceMappings(element);
else // should happen only with the legacy XForms engine
return Dom4jUtils.getNamespaceContextNoDefault(element);
}
/**
* Return external-events configuration attribute.
*/
private Map getExternalEventsMap() {
return (xformsStaticState == null) ? null : xformsStaticState.getExternalEventsMap();
}
/**
* Return whether an external event name is explicitly allowed by the configuration.
*
* @param eventName event name to check
* @return true if allowed, false otherwise
*/
private boolean isExplicitlyAllowedExternalEvent(String eventName) {
return !XFormsEventFactory.isBuiltInEvent(eventName) && getExternalEventsMap() != null && getExternalEventsMap().get(eventName) != null;
}
/**
* Get object with the id specified.
*/
public Object getObjectById(String id) {
// Search in models
for (Iterator i = models.iterator(); i.hasNext();) {
XFormsModel model = (XFormsModel) i.next();
final Object resultObject = model.getObjectByid(id);
if (resultObject != null)
return resultObject;
}
// Search in controls
{
final Object resultObject = xformsControls.getObjectById(id);
if (resultObject != null)
return resultObject;
}
// Check containing document
if (id.equals(getEffectiveId()))
return this;
return null;
}
/**
* Find the instance containing the specified node, in any model.
*
* @param nodeInfo node contained in an instance
* @return instance containing the node
*/
public XFormsInstance getInstanceForNode(NodeInfo nodeInfo) {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
final XFormsInstance currentInstance = currentModel.getInstanceForNode(nodeInfo);
if (currentInstance != null)
return currentInstance;
}
// This should not happen if the node is currently in an instance!
return null;
}
/**
* Find the instance with the specified id, searching in any model.
*
* @param instanceId id of the instance to find
* @return instance containing the node
*/
public XFormsInstance findInstance(String instanceId) {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
final XFormsInstance currentInstance = currentModel.getInstance(instanceId);
if (currentInstance != null)
return currentInstance;
}
return null;
}
/**
* Return the active submission if any or null.
*/
public XFormsModelSubmission getClientActiveSubmission() {
return activeSubmission;
}
/**
* Clear current client state.
*/
private void clearClientState() {
this.isInitializing = false;
this.activeSubmission = null;
this.gotSubmission = false;
this.gotSubmissionSecondPass = false;
this.messagesToRun = null;
this.loadsToRun = null;
this.scriptsToRun = null;
this.focusEffectiveControlId = null;
this.helpEffectiveControlId = null;
this.goingOffline = false;
}
/**
* Set the active submission.
*
* This can be called with a non-null value at most once.
*/
public void setClientActiveSubmission(XFormsModelSubmission activeSubmission) {
if (this.activeSubmission != null)
throw new ValidationException("There is already an active submission.", activeSubmission.getLocationData());
if (loadsToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData());
if (messagesToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData());
if (scriptsToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData());
if (focusEffectiveControlId != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData());
if (helpEffectiveControlId != null)
throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData());
this.activeSubmission = activeSubmission;
}
public boolean isGotSubmission() {
return gotSubmission;
}
public void setGotSubmission() {
this.gotSubmission = true;
}
public boolean isGotSubmissionSecondPass() {
return gotSubmissionSecondPass;
}
public void setGotSubmissionSecondPass() {
this.gotSubmissionSecondPass = true;
}
/**
* Add an XForms message to send to the client.
*/
public void addMessageToRun(String message, String level) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData());
if (messagesToRun == null)
messagesToRun = new ArrayList();
messagesToRun.add(new Message(message, level));
}
/**
* Return the list of messages to send to the client, null if none.
*/
public List getMessagesToRun() {
return messagesToRun;
}
public static class Message {
private String message;
private String level;
public Message(String message, String level) {
this.message = message;
this.level = level;
}
public String getMessage() {
return message;
}
public String getLevel() {
return level;
}
}
public void addScriptToRun(String scriptId, String eventTargetId, String eventHandlerContainerId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData());
if (scriptsToRun == null)
scriptsToRun = new ArrayList();
scriptsToRun.add(new Script(XFormsUtils.scriptIdToScriptName(scriptId), eventTargetId, eventHandlerContainerId));
}
public static class Script {
private String functionName;
private String eventTargetId;
private String eventHandlerContainerId;
public Script(String functionName, String eventTargetId, String eventHandlerContainerId) {
this.functionName = functionName;
this.eventTargetId = eventTargetId;
this.eventHandlerContainerId = eventHandlerContainerId;
}
public String getFunctionName() {
return functionName;
}
public String getEventTargetId() {
return eventTargetId;
}
public String getEventHandlerContainerId() {
return eventHandlerContainerId;
}
}
public List getScriptsToRun() {
return scriptsToRun;
}
/**
* Add an XForms load to send to the client.
*/
public void addLoadToRun(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData());
if (loadsToRun == null)
loadsToRun = new ArrayList();
loadsToRun.add(new Load(resource, target, urlType, isReplace, isPortletLoad, isShowProgress));
}
/**
* Return the list of messages to send to the client, null if none.
*/
public List getLoadsToRun() {
return loadsToRun;
}
public static class Load {
private String resource;
private String target;
private String urlType;
private boolean isReplace;
private boolean isPortletLoad;
private boolean isShowProgress;
public Load(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) {
this.resource = resource;
this.target = target;
this.urlType = urlType;
this.isReplace = isReplace;
this.isPortletLoad = isPortletLoad;
this.isShowProgress = isShowProgress;
}
public String getResource() {
return resource;
}
public String getTarget() {
return target;
}
public String getUrlType() {
return urlType;
}
public boolean isReplace() {
return isReplace;
}
public boolean isPortletLoad() {
return isPortletLoad;
}
public boolean isShowProgress() {
return isShowProgress;
}
}
/**
* Tell the client that focus must be changed to the given effective control id.
*
* This can be called several times, but only the last controld id is remembered.
*
* @param effectiveControlId
*/
public void setClientFocusEffectiveControlId(String effectiveControlId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData());
this.focusEffectiveControlId = effectiveControlId;
}
/**
* Return the effective control id of the control to set the focus to, or null.
*/
public String getClientFocusEffectiveControlId() {
if (focusEffectiveControlId == null)
return null;
final XFormsControl xformsControl = (XFormsControl) getObjectById(focusEffectiveControlId);
// It doesn't make sense to tell the client to set the focus to an element that is non-relevant or readonly
if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) {
final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl;
if (xformsSingleNodeControl.isRelevant() && !xformsSingleNodeControl.isReadonly())
return focusEffectiveControlId;
else
return null;
} else {
return null;
}
}
/**
* Tell the client that help must be shown for the given effective control id.
*
* This can be called several times, but only the last controld id is remembered.
*
* @param effectiveControlId
*/
public void setClientHelpEffectiveControlId(String effectiveControlId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData());
this.helpEffectiveControlId = effectiveControlId;
}
/**
* Return the effective control id of the control to help for, or null.
*/
public String getClientHelpEffectiveControlId() {
if (helpEffectiveControlId == null)
return null;
final XFormsControl xformsControl = (XFormsControl) getObjectById(helpEffectiveControlId);
// It doesn't make sense to tell the client to show help for an element that is non-relevant, but we allow readonly
if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) {
final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl;
if (xformsSingleNodeControl.isRelevant())
return helpEffectiveControlId;
else
return null;
} else {
return null;
}
}
/**
* Execute an external event on element with id targetElementId and event eventName.
*/
public void executeExternalEvent(PipelineContext pipelineContext, String eventName, String controlId, String otherControlId, String contextString, Element filesElement) {
// Get event target object
final XFormsEventTarget eventTarget;
{
final Object eventTargetObject = getObjectById(controlId);
if (!(eventTargetObject instanceof XFormsEventTarget)) {
if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) {
throw new ValidationException("Event target id '" + controlId + "' is not an XFormsEventTarget.", getLocationData());
} else {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring client event with invalid control id", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
}
eventTarget = (XFormsEventTarget) eventTargetObject;
}
// Don't allow for events on non-relevant, readonly or xforms:output controls (we accept focus events on
// xforms:output though).
// This is also a security measures that also ensures that somebody is not able to change values in an instance
// by hacking external events.
if (eventTarget instanceof XFormsControl) {
// Target is a control
if (eventTarget instanceof XXFormsDialogControl) {
// Target is a dialog
// Check for implicitly allowed events
if (allowedXXFormsDialogExternalEvents.get(eventName) == null) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on xxforms:dialog", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
} else {
// Target is a regular control
// Only single-node controls accept events from the client
if (!(eventTarget instanceof XFormsSingleNodeControl)) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on non-single-node control", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
final XFormsSingleNodeControl xformsControl = (XFormsSingleNodeControl) eventTarget;
if (!xformsControl.isRelevant() || (xformsControl.isReadonly() && !(xformsControl instanceof XFormsOutputControl))) {
// Controls accept event only if they are relevant and not readonly, except for xforms:output which may be readonly
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on non-relevant or read-only control", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed: check for implicitly allowed events
if (xformsControl instanceof XFormsOutputControl) {
if (allowedXFormsOutputExternalEvents.get(eventName) == null) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on xforms:output", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
} else if (xformsControl instanceof XFormsUploadControl) {
if (allowedXFormsUploadExternalEvents.get(eventName) == null) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on xforms:upload", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
} else {
if (allowedExternalEvents.get(eventName) == null) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
}
}
}
} else if (eventTarget instanceof XFormsModelSubmission) {
// Target is a submission
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed: check for implicitly allowed events
if (allowedXFormsSubmissionExternalEvents.get(eventName) == null) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on xforms:submission", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
}
} else if (eventTarget instanceof XFormsContainingDocument) {
// Target is the containing document
// Check for implicitly allowed events
if (allowedXFormsContainingDocumentExternalEvents.get(eventName) == null) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event on containing document", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
} else {
// Target is not a control
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event", new String[] { "control id", controlId, "event name", eventName });
}
return;
}
}
// Get other event target
final XFormsEventTarget otherEventTarget;
{
final Object otherEventTargetObject = (otherControlId == null) ? null : getObjectById(otherControlId);
if (otherEventTargetObject == null) {
otherEventTarget = null;
} else if (!(otherEventTargetObject instanceof XFormsEventTarget)) {
if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) {
throw new ValidationException("Other event target id '" + otherControlId + "' is not an XFormsEventTarget.", getLocationData());
} else {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("containing document", "ignoring invalid client event with invalid second control id", new String[] { "control id", controlId, "event name", eventName, "second control id", otherControlId });
}
return;
}
} else {
otherEventTarget = (XFormsEventTarget) otherEventTargetObject;
}
}
// Handle repeat focus. Don't dispatch event on DOMFocusOut however.
if (controlId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1 && !XFormsEvents.XFORMS_DOM_FOCUS_OUT.equals(eventName)) {
// The event target is in a repeated structure, so make sure it gets repeat focus
dispatchEvent(pipelineContext, new XXFormsRepeatFocusEvent(eventTarget));
}
// Handle xforms:output
if (eventTarget instanceof XFormsOutputControl) {
// Note that repeat focus may have been dispatched already
if (XFormsEvents.XFORMS_DOM_FOCUS_IN.equals(eventName)) {
// We convert the focus event into a DOMActivate unless the control is read-only
final XFormsOutputControl xformsOutputControl = (XFormsOutputControl) eventTarget;
if (xformsOutputControl.isReadonly()) {
return;
} else {
eventName = XFormsEvents.XFORMS_DOM_ACTIVATE;
}
} else if (ignoredXFormsOutputExternalEvents.equals(eventName)) {
return;
}
}
// Create event
if (XFormsProperties.isAjaxTest()) {
if (eventName.equals(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE)) {
if ("category-select1".equals(controlId)) {
if (testAjaxToggleValue == 0) {
testAjaxToggleValue = 1;
contextString = "supplier";
} else {
testAjaxToggleValue = 0;
contextString = "customer";
}
} else if (("xforms-element-287" + XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1 + "1").equals(controlId)) {
contextString = "value" + System.currentTimeMillis();
}
}
}
final XFormsEvent xformsEvent = XFormsEventFactory.createEvent(eventName, eventTarget, otherEventTarget, true, true, true, contextString, null, null, filesElement);
// Interpret event
if (xformsEvent instanceof XXFormsValueChangeWithFocusChangeEvent) {
// 4.6.7 Sequence: Value Change
// What we want to do here is set the value on the initial controls state, as the value
// has already been changed on the client. This means that this event(s) must be the
// first to come!
final XXFormsValueChangeWithFocusChangeEvent concreteEvent = (XXFormsValueChangeWithFocusChangeEvent) xformsEvent;
// 1. xforms-recalculate
// 2. xforms-revalidate
// 3. xforms-refresh performs reevaluation of UI binding expressions then dispatches
// these events according to value changes, model item property changes and validity
// changes
// [n] xforms-value-changed, [n] xforms-valid or xforms-invalid, [n] xforms-enabled or
// xforms-disabled, [n] xforms-optional or xforms-required, [n] xforms-readonly or
// xforms-readwrite, [n] xforms-out-of-range or xforms-in-range
final String targetControlEffectiveId;
{
final XFormsValueControl valueXFormsControl = (XFormsValueControl) concreteEvent.getTargetObject();
targetControlEffectiveId = valueXFormsControl.getEffectiveId();
// Notify the control of the value change
final String eventValue = concreteEvent.getNewValue();
valueXFormsControl.storeExternalValue(pipelineContext, eventValue, null);
}
{
// NOTE: Recalculate and revalidate are done with the automatic deferred updates
// Handle focus change DOMFocusOut / DOMFocusIn
if (concreteEvent.getOtherTargetObject() != null) {
// NOTE: setExternalValue() above may cause e.g. xforms-select / xforms-deselect events to be
// dispatched, so we get the control again to have a fresh reference
final XFormsControl sourceXFormsControl = (XFormsControl) getObjectById(targetControlEffectiveId);
final XFormsControl otherTargetXFormsControl
= (XFormsControl) getObjectById(((XFormsControl) concreteEvent.getOtherTargetObject()).getEffectiveId());
// We have a focus change (otherwise, the focus is assumed to remain the same)
if (sourceXFormsControl != null)
dispatchEvent(pipelineContext, new XFormsDOMFocusOutEvent(sourceXFormsControl));
if (otherTargetXFormsControl != null)
dispatchEvent(pipelineContext, new XFormsDOMFocusInEvent(otherTargetXFormsControl));
}
// NOTE: Refresh is done with the automatic deferred updates
}
} else {
// Dispatch any other allowed event
dispatchEvent(pipelineContext, xformsEvent);
}
}
/**
* Prepare the ContainingDocumentg for a sequence of external events.
*/
public void prepareForExternalEventsSequence(PipelineContext pipelineContext) {
// Clear containing document state
clearClientState();
// Initialize controls
xformsControls.initialize(pipelineContext);
}
public void startOutermostActionHandler() {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
currentModel.startOutermostActionHandler();
}
}
public void endOutermostActionHandler(PipelineContext pipelineContext) {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
currentModel.endOutermostActionHandler(pipelineContext);
}
}
public void synchronizeInstanceDataEventState() {
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
currentModel.synchronizeInstanceDataEventState();
}
}
public XFormsEventHandlerContainer getParentContainer(XFormsContainingDocument containingDocument) {
return null;
}
public List getEventHandlers(XFormsContainingDocument containingDocument) {
return null;
}
public String getId() {
return CONTAINING_DOCUMENT_PSEUDO_ID;
}
public String getEffectiveId() {
return getId();
}
public LocationData getLocationData() {
return (xformsStaticState != null) ? xformsStaticState.getLocationData() : null;
}
public void performDefaultAction(PipelineContext pipelineContext, XFormsEvent event) {
final String eventName = event.getEventName();
if (XFormsEvents.XXFORMS_LOAD.equals(eventName)) {
// Internal load event
final XXFormsLoadEvent xxformsLoadEvent = (XXFormsLoadEvent) event;
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
try {
final String resource = xxformsLoadEvent.getResource();
final String pathInfo;
final Map parameters;
final int qmIndex = resource.indexOf('?');
if (qmIndex != -1) {
pathInfo = resource.substring(0, qmIndex);
parameters = NetUtils.decodeQueryString(resource.substring(qmIndex + 1), false);
} else {
pathInfo = resource;
parameters = null;
}
externalContext.getResponse().sendRedirect(pathInfo, parameters, false, false);
} catch (IOException e) {
throw new ValidationException(e, getLocationData());
}
} else if (XFormsEvents.XXFORMS_ONLINE.equals(eventName)) {
// Internal event for going online
goOnline(pipelineContext);
} else if (XFormsEvents.XXFORMS_OFFLINE.equals(eventName)) {
// Internal event for going offline
goOffline(pipelineContext);
}
}
public void goOnline(PipelineContext pipelineContext) {
// Dispatch to all models
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
dispatchEvent(pipelineContext, new XXFormsOnlineEvent(currentModel));
}
this.goingOffline = false;
}
public void goOffline(PipelineContext pipelineContext) {
// Dispatch to all models
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
dispatchEvent(pipelineContext, new XXFormsOfflineEvent(currentModel));
}
this.goingOffline = true;
}
public boolean goingOffline() {
return goingOffline;
}
/**
* Main event dispatching entry.
*/
public void dispatchEvent(PipelineContext pipelineContext, XFormsEvent event) {
if (XFormsServer.logger.isDebugEnabled()) {
logDebug("event", "dispatching", new String[] { "name", event.getEventName(), "id", event.getTargetObject().getEffectiveId(), "location", event.getLocationData().toString() });
}
final XFormsEventTarget targetObject = event.getTargetObject();
try {
if (targetObject == null)
throw new ValidationException("Target object null for event: " + event.getEventName(), getLocationData());
// Find all event handler containers
final List containers = new ArrayList();
{
XFormsEventHandlerContainer container
= (targetObject instanceof XFormsEventHandlerContainer) ? (XFormsEventHandlerContainer) targetObject : targetObject.getParentContainer(this);
while (container != null) {
containers.add(container);
container = container.getParentContainer(this);
}
}
boolean propagate = true;
boolean performDefaultAction = true;
// Go from root to leaf
Collections.reverse(containers);
// Capture phase
for (Iterator i = containers.iterator(); i.hasNext();) {
final XFormsEventHandlerContainer container = (XFormsEventHandlerContainer) i.next();
final List eventHandlers = container.getEventHandlers(this);
if (eventHandlers != null) {
if (container != targetObject) {
// Event listeners on the target which are in capture mode are not called
for (Iterator j = eventHandlers.iterator(); j.hasNext();) {
final XFormsEventHandler eventHandler = (XFormsEventHandler) j.next();
if (!eventHandler.isBubblingPhase()
&& eventHandler.isMatchEventName(event.getEventName())
&& eventHandler.isMatchTarget(event.getTargetObject().getId())) {
// Capture phase match on event name and target is specified
startHandleEvent(event);
try {
eventHandler.handleEvent(pipelineContext, XFormsContainingDocument.this, container, event);
} finally {
endHandleEvent();
}
propagate &= eventHandler.isPropagate();
performDefaultAction &= eventHandler.isPerformDefaultAction();
}
}
// Cancel propagation if requested and if authorized by event
if (!propagate && event.isCancelable())
break;
}
}
}
// Go from leaf to root
Collections.reverse(containers);
// Bubbling phase
if (propagate && event.isBubbles()) {
for (Iterator i = containers.iterator(); i.hasNext();) {
final XFormsEventHandlerContainer container = (XFormsEventHandlerContainer) i.next();
final List eventHandlers = container.getEventHandlers(this);
if (eventHandlers != null) {
for (Iterator j = eventHandlers.iterator(); j.hasNext();) {
final XFormsEventHandler eventHandler = (XFormsEventHandler) j.next();
if (eventHandler.isBubblingPhase()
&& eventHandler.isMatchEventName(event.getEventName())
&& eventHandler.isMatchTarget(event.getTargetObject().getId())) {
// Bubbling phase match on event name and target is specified
startHandleEvent(event);
try {
eventHandler.handleEvent(pipelineContext, XFormsContainingDocument.this, container, event);
} finally {
endHandleEvent();
}
propagate &= eventHandler.isPropagate();
performDefaultAction &= eventHandler.isPerformDefaultAction();
}
}
// Cancel propagation if requested and if authorized by event
if (!propagate)
break;
}
}
}
// Perform default action is allowed to
if (performDefaultAction || !event.isCancelable()) {
startHandleEvent(event);
try {
targetObject.performDefaultAction(pipelineContext, event);
} finally {
endHandleEvent();
}
}
} catch (Exception e) {
// Add location information if possible
final LocationData locationData = (targetObject != null)
? ((targetObject.getLocationData() != null)
? targetObject.getLocationData()
: getLocationData())
: null;
throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "dispatching XForms event",
new String[] { "event", event.getEventName(), "target id", targetObject.getEffectiveId() }));
}
}
private int logIndentLevel = 0;
private Stack eventStack = new Stack();
private void startHandleEvent(XFormsEvent event) {
eventStack.push(event);
logIndentLevel++;
}
private void endHandleEvent() {
eventStack.pop();
logIndentLevel
}
public void startHandleOperation() {
logIndentLevel++;
}
public void endHandleOperation() {
logIndentLevel
}
private static String getLogIndentSpaces(int level) {
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < level; i++)
sb.append(" ");
return sb.toString();
}
public void logDebug(String type, String message) {
log(Level.DEBUG, logIndentLevel, type, message, null);
}
public void logDebug(String type, String message, String[] parameters) {
log(Level.DEBUG, logIndentLevel, type, message, parameters);
}
public static void logDebugStatic(String type, String message) {
logDebugStatic(null, type, message);
}
public static void logDebugStatic(String type, String message, String[] parameters) {
logDebugStatic(null, type, message, parameters);
}
public static void logDebugStatic(XFormsContainingDocument containingDocument, String type, String message) {
log(Level.DEBUG, (containingDocument != null) ? containingDocument.logIndentLevel : 0, type, message, null);
}
public static void logDebugStatic(XFormsContainingDocument containingDocument, String type, String message, String[] parameters) {
log(Level.DEBUG, (containingDocument != null) ? containingDocument.logIndentLevel : 0, type, message, parameters);
}
public void logWarning(String type, String message, String[] parameters) {
log(Level.WARN, logIndentLevel, type, message, parameters);
}
private static void log(Level level, int indentLevel, String type, String message, String[] parameters) {
final String parametersString;
if (parameters != null) {
final FastStringBuffer sb = new FastStringBuffer(" {");
if (parameters != null) {
boolean first = true;
for (int i = 0; i < parameters.length; i += 2) {
final String paramName = parameters[i];
final String paramValue = parameters[i + 1];
if (paramValue != null) {
if (!first)
sb.append(", ");
sb.append(paramName);
sb.append(": \"");
sb.append(paramValue);
sb.append('\"');
first = false;
}
}
}
sb.append('}');
parametersString = sb.toString();
} else {
parametersString = "";
}
XFormsServer.logger.log(level, "XForms - " + getLogIndentSpaces(indentLevel) + type + " - " + message + parametersString);
}
/**
* Return the event being processed by the current event handler, null if no event is being processed.
*/
public XFormsEvent getCurrentEvent() {
return (eventStack.size() == 0) ? null : (XFormsEvent) eventStack.peek();
}
/**
* Create an encoded dynamic state that represents the dynamic state of this XFormsContainingDocument.
*
* @param pipelineContext current PipelineContext
* @return encoded dynamic state
*/
public String createEncodedDynamicState(PipelineContext pipelineContext) {
return XFormsUtils.encodeXML(pipelineContext, createDynamicStateDocument(),
XFormsProperties.isClientStateHandling(this) ? XFormsProperties.getXFormsPassword() : null, false);
}
private Document createDynamicStateDocument() {
final XFormsControls.ControlsState currentControlsState = getXFormsControls().getCurrentControlsState();
final Document dynamicStateDocument = Dom4jUtils.createDocument();
final Element dynamicStateElement = dynamicStateDocument.addElement("dynamic-state");
// Output instances
{
final Element instancesElement = dynamicStateElement.addElement("instances");
for (Iterator i = getModels().iterator(); i.hasNext();) {
final XFormsModel currentModel = (XFormsModel) i.next();
if (currentModel.getInstances() != null) {
for (Iterator j = currentModel.getInstances().iterator(); j.hasNext();) {
final XFormsInstance currentInstance = (XFormsInstance) j.next();
// TODO: can we avoid storing the instance in the dynamic state if it has not changed from static state?
if (currentInstance.isReplaced() || !(currentInstance instanceof SharedXFormsInstance)) {
// Instance has been replaced, or it is not shared, so it has to go in the dynamic state
instancesElement.add(currentInstance.createContainerElement(!currentInstance.isApplicationShared()));
// Log instance if needed
currentInstance.logIfNeeded(this, "storing instance to dynamic state");
}
}
}
}
}
// Output divs information
{
final Element divsElement = Dom4jUtils.createElement("divs");
outputSwitchesDialogs(divsElement, getXFormsControls());
if (divsElement.hasContent())
dynamicStateElement.add(divsElement);
}
// Output repeat index information
{
final Map repeatIdToIndex = currentControlsState.getRepeatIdToIndex();
if (repeatIdToIndex.size() != 0) {
final Element repeatIndexesElement = dynamicStateElement.addElement("repeat-indexes");
for (Iterator i = repeatIdToIndex.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String repeatId = (String) currentEntry.getKey();
final Integer index = (Integer) currentEntry.getValue();
final Element newElement = repeatIndexesElement.addElement("repeat-index");
newElement.addAttribute("id", repeatId);
newElement.addAttribute("index", index.toString());
}
}
}
return dynamicStateDocument;
}
public static void outputSwitchesDialogs(Element divsElement, XFormsControls xformsControls) {
{
final Map switchIdToSelectedCaseIdMap = xformsControls.getCurrentSwitchState().getSwitchIdToSelectedCaseIdMap();
if (switchIdToSelectedCaseIdMap != null) {
// There are some xforms:switch/xforms:case controls
for (Iterator i = switchIdToSelectedCaseIdMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String switchId = (String) currentEntry.getKey();
final String selectedCaseId = (String) currentEntry.getValue();
// Output selected ids
{
final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI);
divElement.addAttribute("switch-id", switchId);
divElement.addAttribute("case-id", selectedCaseId);
divElement.addAttribute("visibility", "visible");
}
// Output deselected ids
final XFormsControl switchXFormsControl = (XFormsControl) xformsControls.getObjectById(switchId);
final List children = switchXFormsControl.getChildren();
if (children != null && children.size() > 0) {
for (Iterator j = children.iterator(); j.hasNext();) {
final XFormsControl caseXFormsControl = (XFormsControl) j.next();
if (!caseXFormsControl.getEffectiveId().equals(selectedCaseId)) {
final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI);
divElement.addAttribute("switch-id", switchId);
divElement.addAttribute("case-id", caseXFormsControl.getEffectiveId());
divElement.addAttribute("visibility", "hidden");
}
}
}
}
}
}
{
final Map dialogIdToVisibleMap = xformsControls.getCurrentDialogState().getDialogIdToVisibleMap();
if (dialogIdToVisibleMap != null) {
// There are some xxforms:dialog controls
for (Iterator i = dialogIdToVisibleMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final String dialogId = (String) currentEntry.getKey();
final XFormsControls.DialogState.DialogInfo dialogInfo
= (XFormsControls.DialogState.DialogInfo) currentEntry.getValue();
// Output element and attributes
{
final Element divElement = divsElement.addElement("xxf:div", XFormsConstants.XXFORMS_NAMESPACE_URI);
divElement.addAttribute("dialog-id", dialogId);
divElement.addAttribute("visibility", dialogInfo.isShow() ? "visible" : "hidden");
if (dialogInfo.isShow()) {
if (dialogInfo.getNeighbor() != null)
divElement.addAttribute("neighbor", dialogInfo.getNeighbor());
if (dialogInfo.isConstrainToViewport())
divElement.addAttribute("constrain", Boolean.toString(dialogInfo.isConstrainToViewport()));
}
}
}
}
}
}
private void restoreDynamicState(PipelineContext pipelineContext, String encodedDynamicState) {
// Get dynamic state document
final Document dynamicStateDocument = XFormsUtils.decodeXML(pipelineContext, encodedDynamicState);
// Get repeat indexes from dynamic state
final Element repeatIndexesElement = dynamicStateDocument.getRootElement().element("repeat-indexes");
// Create XForms controls and models
createControlAndModel(pipelineContext, repeatIndexesElement);
// Extract and restore instances
{
// Get instances from dynamic state first
final Element instancesElement = dynamicStateDocument.getRootElement().element("instances");
if (instancesElement != null) {
for (Iterator i = instancesElement.elements().iterator(); i.hasNext();) {
final Element instanceElement = (Element) i.next();
// Create and set instance document on current model
final XFormsInstance newInstance = new XFormsInstance(instanceElement);
if (newInstance.getDocumentInfo() == null) {
// Instance is not initialized yet
// This means that the instance was application shared
if (!newInstance.isApplicationShared())
throw new ValidationException("Non-initialized instance has to be application shared for id: " + newInstance.getEffectiveId(), getLocationData());
final SharedXFormsInstance sharedInstance
= XFormsServerSharedInstancesCache.instance().find(pipelineContext, this, newInstance.getEffectiveId(), newInstance.getModelId(), newInstance.getSourceURI(), newInstance.getTimeToLive(), newInstance.getValidation());
getModel(sharedInstance.getModelId()).setInstance(sharedInstance, false);
} else {
// Instance is initialized, just use it
getModel(newInstance.getModelId()).setInstance(newInstance, newInstance.isReplaced());
}
// Log instance if needed
newInstance.logIfNeeded(this, "restoring instance from dynamic state");
}
}
// Then get instances from static state if necessary
final Map staticInstancesMap = xformsStaticState.getInstancesMap();
if (staticInstancesMap != null && staticInstancesMap.size() > 0) {
for (Iterator instancesIterator = staticInstancesMap.values().iterator(); instancesIterator.hasNext();) {
final XFormsInstance currentInstance = (XFormsInstance) instancesIterator.next();
if (findInstance(currentInstance.getEffectiveId()) == null) {
// Instance was not set from dynamic state
if (currentInstance.getDocumentInfo() == null) {
// Instance is not initialized yet
// This means that the instance was application shared
if (!currentInstance.isApplicationShared())
throw new ValidationException("Non-initialized instance has to be application shared for id: " + currentInstance.getEffectiveId(), getLocationData());
final SharedXFormsInstance sharedInstance
= XFormsServerSharedInstancesCache.instance().find(pipelineContext, this, currentInstance.getEffectiveId(), currentInstance.getModelId(), currentInstance.getSourceURI(), currentInstance.getTimeToLive(), currentInstance.getValidation());
getModel(sharedInstance.getModelId()).setInstance(sharedInstance, false);
} else {
// Instance is initialized, just use it
getModel(currentInstance.getModelId()).setInstance(currentInstance, false);
}
}
}
}
}
// Restore models state
for (Iterator j = getModels().iterator(); j.hasNext();) {
final XFormsModel currentModel = (XFormsModel) j.next();
currentModel.initializeState(pipelineContext);
}
// Restore controls
final Element divsElement = dynamicStateDocument.getRootElement().element("divs");
xformsControls.initializeState(pipelineContext, divsElement, repeatIndexesElement, true);
xformsControls.evaluateAllControlsIfNeeded(pipelineContext);
}
/**
* Whether, during initialization, this is the first refresh. The flag is automatically cleared during this call so
* that only the first call returns true.
*
* @return true if this is the first refresh, false otherwise
*/
public boolean isInitializationFirstRefreshClear() {
boolean result = mustPerformInitializationFirstRefresh;
mustPerformInitializationFirstRefresh = false;
return result;
}
private void initialize(PipelineContext pipelineContext) {
// This is called upon the first creation of the XForms engine only
// Create XForms controls and models
createControlAndModel(pipelineContext, null);
// 4.2 Initialization Events
// 1. Dispatch xforms-model-construct to all models
// 2. Dispatch xforms-model-construct-done to all models
// 3. Dispatch xforms-ready to all models
// Before dispaching initialization events, remember that first refresh must be performed
this.mustPerformInitializationFirstRefresh = true;
final String[] eventsToDispatch = { XFormsEvents.XFORMS_MODEL_CONSTRUCT, XFormsEvents.XFORMS_MODEL_CONSTRUCT_DONE, XFormsEvents.XFORMS_READY, XFormsEvents.XXFORMS_READY };
for (int i = 0; i < eventsToDispatch.length; i++) {
if (i == 2) {
// Initialize controls after all the xforms-model-construct-done events have been sent
xformsControls.initialize(pipelineContext);
}
// Group all xforms-model-construct-done and xforms-ready events within a single outermost action handler in
// order to optimize events
if (i == 1) {
// Performed deferred updates only for xforms-ready
startOutermostActionHandler();
}
// Iterate over all the models
for (Iterator j = getModels().iterator(); j.hasNext();) {
final XFormsModel currentModel = (XFormsModel) j.next();
// Make sure there is at least one refresh
final XFormsModel.DeferredActionContext deferredActionContext = currentModel.getDeferredActionContext();
if (deferredActionContext != null) {
deferredActionContext.refresh = true;
}
dispatchEvent(pipelineContext, XFormsEventFactory.createEvent(eventsToDispatch[i], currentModel));
}
if (i == 2) {
// Performed deferred updates only for xforms-ready
endOutermostActionHandler(pipelineContext);
}
}
// In case there is no model or no controls, make sure the flag is cleared as it is only relevant during
// initialization
this.mustPerformInitializationFirstRefresh = false;
}
private void createControlAndModel(PipelineContext pipelineContext, Element repeatIndexesElement) {
if (xformsStaticState != null) {
// Gather static analysis information
final long startTime = XFormsServer.logger.isDebugEnabled() ? System.currentTimeMillis() : 0;
final boolean analyzed = xformsStaticState.analyzeIfNecessary(pipelineContext);
if (XFormsServer.logger.isDebugEnabled()) {
if (analyzed)
logDebug("containing document", "performed static analysis", new String[] { "time", Long.toString(System.currentTimeMillis() - startTime) });
else
logDebug("containing document", "static analysis already available");
}
// Create XForms controls
xformsControls = new XFormsControls(this, xformsStaticState, repeatIndexesElement);
// Create and index models
for (Iterator i = xformsStaticState.getModelDocuments().iterator(); i.hasNext();) {
final Document modelDocument = (Document) i.next();
final XFormsModel model = new XFormsModel(modelDocument);
model.setContainingDocument(this); // NOTE: This requires the XFormsControls to be set on XFormsContainingDocument
this.models.add(model);
if (model.getEffectiveId() != null)
this.modelsMap.put(model.getEffectiveId(), model);
}
}
}
} |
package org.orbeon.oxf.xforms.state;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.util.UUIDUtils;
import org.orbeon.oxf.xforms.XFormsContainingDocument;
import org.orbeon.oxf.xforms.XFormsProperties;
/**
* Centralize XForms state management.
*
* TODO: Get rid of the old "session" store code as it is replaced by the new persistent store.
*/
public class XFormsStateManager {
// All these must have the same length
public static final String SESSION_STATE_PREFIX = "sess:";
public static final String APPLICATION_STATE_PREFIX = "appl:";
public static final String PERSISTENT_STATE_PREFIX = "pers:";
private static final int PREFIX_COLON_POSITION = SESSION_STATE_PREFIX.length() - 1;
// Ideally we wouldn't want to force session creation, but it's hard to implement the more elaborate expiration
public static final boolean FORCE_SESSION_CREATION = true;
/**
* Get the initial encoded XForms state as it must be sent to the client within the (X)HTML.
*
* @param containingDocument containing document
* @param externalContext external context (for access to session and application scopes)
* @param xformsState post-initialization XFormsState
* @param staticStateUUID static state UUID (if static state was cached against input document)
* @param dynamicStateUUID dynamic state UUID (if dynamic state was cached against output document)
* @return XFormsState containing the encoded static and dynamic states
*/
public static XFormsState getInitialEncodedClientState(XFormsContainingDocument containingDocument, ExternalContext externalContext, XFormsState xformsState, String staticStateUUID, String dynamicStateUUID) {
final String currentPageGenerationId;
final String staticStateString;
{
if (containingDocument.isServerStateHandling()) {
if (containingDocument.isLegacyServerStateHandling()) {
// Legacy session server handling
// Produce UUID
if (staticStateUUID == null) {
currentPageGenerationId = UUIDUtils.createPseudoUUID();
staticStateString = SESSION_STATE_PREFIX + currentPageGenerationId;
} else {
// In this case, we first store in the application scope, so that multiple requests can use the
// same cached state.
currentPageGenerationId = staticStateUUID;
staticStateString = APPLICATION_STATE_PREFIX + currentPageGenerationId;
}
} else {
// New server state handling with persistent store
if (staticStateUUID == null) {
currentPageGenerationId = UUIDUtils.createPseudoUUID();
} else {
currentPageGenerationId = staticStateUUID;
}
staticStateString = PERSISTENT_STATE_PREFIX + currentPageGenerationId;
}
} else {
// Produce encoded static state
staticStateString = xformsState.getStaticState();
currentPageGenerationId = null;
}
}
final String dynamicStateString;
{
if (containingDocument.isServerStateHandling()) {
if (containingDocument.isLegacyServerStateHandling()) {
// Legacy session server handling
if (dynamicStateUUID == null) {
// In this case, we use session scope since not much sharing will occur, if at all.
// Produce dynamic state key
final String newRequestId = UUIDUtils.createPseudoUUID();
final XFormsStateStore stateStore = XFormsSessionStateStore.instance(externalContext, true);
stateStore.add(currentPageGenerationId, null, newRequestId, xformsState, null);
dynamicStateString = SESSION_STATE_PREFIX + newRequestId;
} else {
// In this case, we first store in the application scope, so that multiple requests can use the
// same cached state.
dynamicStateString = APPLICATION_STATE_PREFIX + dynamicStateUUID;
final XFormsStateStore applicationStateStore = XFormsApplicationStateStore.instance(externalContext);
applicationStateStore.add(currentPageGenerationId, null, dynamicStateUUID, xformsState, null);
}
} else {
// New server state handling with persistent store
// Get session id if needed
final ExternalContext.Session session = externalContext.getSession(FORCE_SESSION_CREATION);
final String sessionId = (session != null) ? session.getId() : null;
final XFormsStateStore stateStore = XFormsPersistentApplicationStateStore.instance(externalContext);
if (dynamicStateUUID == null) {
// In this case, we use session scope since not much sharing will occur, if at all.
// Produce dynamic state key
final String newRequestId = UUIDUtils.createPseudoUUID();
stateStore.add(currentPageGenerationId, null, newRequestId, xformsState, sessionId);
dynamicStateString = PERSISTENT_STATE_PREFIX + newRequestId;
} else {
// In this case, we first store in the application scope, so that multiple requests can use the
// same cached state.
dynamicStateString = PERSISTENT_STATE_PREFIX + dynamicStateUUID;
stateStore.add(currentPageGenerationId, null, dynamicStateUUID, xformsState, sessionId);
}
}
} else {
// Send state to the client
dynamicStateString = xformsState.getDynamicState();
}
}
return new XFormsState(staticStateString, dynamicStateString);
}
/**
* Decode static and dynamic state strings coming from the client.
*
* @param pipelineContext pipeline context
* @param staticStateString static state string as sent by client
* @param dynamicStateString dynamic state string as sent by client
* @return decoded state
*/
public static XFormsDecodedClientState decodeClientState(PipelineContext pipelineContext, String staticStateString, String dynamicStateString) {
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
final XFormsDecodedClientState xformsDecodedClientState;
if (staticStateString.length() > PREFIX_COLON_POSITION && staticStateString.charAt(PREFIX_COLON_POSITION) == ':') {
// State doesn't come directly with request
// Separate prefixes from UUIDs
final String staticStatePrefix = staticStateString.substring(0, PREFIX_COLON_POSITION + 1);
final String staticStateUUID = staticStateString.substring(PREFIX_COLON_POSITION + 1);
final String dynamicStatePrefix = dynamicStateString.substring(0, PREFIX_COLON_POSITION + 1);
final String dynamicStateUUID = dynamicStateString.substring(PREFIX_COLON_POSITION + 1);
// Both prefixes must be the same
if (!staticStatePrefix.equals(dynamicStatePrefix)) {
throw new OXFException("Inconsistent XForms state prefixes: " + staticStatePrefix + ", " + dynamicStatePrefix);
}
// Get relevant store
final XFormsStateStore stateStore;
if (staticStatePrefix.equals(PERSISTENT_STATE_PREFIX)) {
stateStore = XFormsPersistentApplicationStateStore.instance(externalContext);
} else if (staticStatePrefix.equals(SESSION_STATE_PREFIX)) {
// NOTE: Don't create session at this time if it is not found
stateStore = XFormsSessionStateStore.instance(externalContext, false);
} else if (staticStatePrefix.equals(APPLICATION_STATE_PREFIX)) {
stateStore = XFormsApplicationStateStore.instance(externalContext);
} else {
// Invalid prefix
throw new OXFException("Invalid state prefix: " + staticStatePrefix);
}
// Get state from store
final XFormsState xformsState = (stateStore == null) ? null : stateStore.find(staticStateUUID, dynamicStateUUID);
if (xformsState == null) {
// Oops, we couldn't find the state in the store
final String UNABLE_TO_RETRIEVE_XFORMS_STATE_MESSAGE = "Unable to retrieve XForms engine state.";
final String PLEASE_RELOAD_PAGE_MESSAGE = "Please reload the current page. Note that you will lose any unsaved changes.";
if (staticStatePrefix.equals(PERSISTENT_STATE_PREFIX)) {
final ExternalContext.Session currentSession = externalContext.getSession(false);
if (currentSession == null || currentSession.isNew()) {
// This means that no session is currently existing, or a session exists but it is newly created
throw new OXFException("Your session has expired. " + PLEASE_RELOAD_PAGE_MESSAGE);
} else {
// There is a session and it is still known by the client
throw new OXFException(UNABLE_TO_RETRIEVE_XFORMS_STATE_MESSAGE + " " + PLEASE_RELOAD_PAGE_MESSAGE);
}
} else {
throw new OXFException(UNABLE_TO_RETRIEVE_XFORMS_STATE_MESSAGE + " " + PLEASE_RELOAD_PAGE_MESSAGE);
}
}
xformsDecodedClientState = new XFormsDecodedClientState(xformsState, staticStateUUID, dynamicStateUUID);
} else {
// State comes directly with request
xformsDecodedClientState = new XFormsDecodedClientState(new XFormsState(staticStateString, dynamicStateString), null, null);
}
return xformsDecodedClientState;
}
/**
* Get the encoded XForms state as it must be sent to the client within an Ajax response.
*
* @param containingDocument containing document
* @param pipelineContext pipeline context
* @param xformsDecodedClientState decoded state as received in Ajax request
* @param isAllEvents whether this is a special "all events" request
* @return XFormsState containing the encoded static and dynamic states
*/
public static XFormsState getEncodedClientStateDoCache(XFormsContainingDocument containingDocument, PipelineContext pipelineContext,
XFormsDecodedClientState xformsDecodedClientState, boolean isAllEvents) {
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
// Output static state (FOR TESTING ONLY)
final String staticStateString = xformsDecodedClientState.getXFormsState().getStaticState();
// Output dynamic state
final String dynamicStateString;
{
// Produce page generation id if needed
final String currentPageGenerationId = (xformsDecodedClientState.getStaticStateUUID() != null) ? xformsDecodedClientState.getStaticStateUUID() : UUIDUtils.createPseudoUUID();
// Create and encode dynamic state
final String newEncodedDynamicState = containingDocument.createEncodedDynamicState(pipelineContext);
final XFormsState newXFormsState = new XFormsState(staticStateString, newEncodedDynamicState);
if (containingDocument.isServerStateHandling()) {
final String requestId = xformsDecodedClientState.getDynamicStateUUID();
// Get session id if needed
final ExternalContext.Session session = externalContext.getSession(FORCE_SESSION_CREATION);
final String sessionId = (session != null) ? session.getId() : null;
// Produce dynamic state key (keep the same when allEvents!)
final String newRequestId = isAllEvents ? requestId : UUIDUtils.createPseudoUUID();
if (containingDocument.isLegacyServerStateHandling()) {
// Legacy session server handling
final XFormsStateStore stateStore = XFormsSessionStateStore.instance(externalContext, true);
stateStore.add(currentPageGenerationId, requestId, newRequestId, newXFormsState, sessionId);
dynamicStateString = SESSION_STATE_PREFIX + newRequestId;
} else {
// New server state handling with persistent store
final XFormsStateStore stateStore = XFormsPersistentApplicationStateStore.instance(externalContext);
stateStore.add(currentPageGenerationId, requestId, newRequestId, newXFormsState, sessionId);
dynamicStateString = PERSISTENT_STATE_PREFIX + newRequestId;
}
} else {
// Send state directly to the client
dynamicStateString = newEncodedDynamicState;
}
// Cache document if requested and possible
if (XFormsProperties.isCacheDocument()) {
XFormsDocumentCache.instance().add(pipelineContext, newXFormsState, containingDocument);
}
}
return new XFormsState(staticStateString, dynamicStateString);
}
/**
* Represent a decoded client state, i.e. a decoded XFormsState with some information extracted from the Ajax
* request.
*/
public static class XFormsDecodedClientState {
private XFormsState xformsState;
private String staticStateUUID;
private String dynamicStateUUID;
public XFormsDecodedClientState(XFormsState xformsState, String staticStateUUID, String dynamicStateUUID) {
this.xformsState = xformsState;
this.staticStateUUID = staticStateUUID;
this.dynamicStateUUID = dynamicStateUUID;
}
public XFormsState getXFormsState() {
return xformsState;
}
public String getStaticStateUUID() {
return staticStateUUID;
}
public String getDynamicStateUUID() {
return dynamicStateUUID;
}
}
} |
package com.exphc.FreeTrade;
import java.util.logging.Logger;
import java.util.regex.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.command.*;
import org.bukkit.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.enchantments.*;
import org.bukkit.*;
import info.somethingodd.bukkit.OddItem.OddItem;
class ItemQuery
{
ItemStack itemStack;
static Logger log = Logger.getLogger("Minecraft");
public ItemQuery(String s) {
Pattern p = Pattern.compile("^(\\d*)([
Matcher m = p.matcher(s);
int quantity;
while(m.find()) {
String quantityString = m.group(1);
String isStackString = m.group(2);
String nameString = m.group(3);
String usesString = m.group(4);
String enchString = m.group(5);
//log.info("uses=" + usesString + ", ench="+enchString);
if (quantityString.equals("")) {
quantity = 1;
} else {
quantity = Integer.parseInt(quantityString);
if (quantity < 0) {
throw new UsageException("Invalid quantity: " + quantity);
}
}
// Lookup item name
if (Bukkit.getServer().getPluginManager().getPlugin("OddItem") != null) {
try {
itemStack = OddItem.getItemStack(nameString).clone();
} catch (IllegalArgumentException suggestion) {
throw new UsageException("No such item '" + nameString + "', did you mean '" + suggestion.getMessage() + "'?");
}
} else {
// OddItem isn't installed so use Bukkit's long names (diamond_pickaxe, cumbersome)
// Note this also means you need to manually specify damage values (wool/1, not orangewool!)
// Therefore installing OddItem is highly recommended
Material material = Material.matchMaterial(nameString);
if (material == null) {
throw new UsageException("Unrecognized item name: " + nameString + " (please install OddItem)");
}
itemStack = new ItemStack(material);
}
if (itemStack == null) {
throw new UsageException("Unrecognized item name: " + nameString);
}
// Quantity, shorthand 10# = 10 stacks
if (isStackString.equals("
quantity *= Math.abs(itemStack.getType().getMaxStackSize());
}
itemStack.setAmount(quantity);
// Damage value aka durability
// User specifies how much they want left, 100% = unused tool
short maxDamage = itemStack.getType().getMaxDurability();
if (usesString != null && !usesString.equals("")) {
short damage;
if (usesString.endsWith("%")) {
String percentageString = usesString.substring(0, usesString.length() - 1);
double percentage = Double.parseDouble(percentageString);
damage = (short)(maxDamage - (short)(percentage / 100.0 * maxDamage));
} else {
damage = (short)(maxDamage - Short.parseShort(usesString));
}
if (damage > maxDamage) {
damage = maxDamage; // Breaks right after one use
}
if (damage < 0) {
damage = 0; // Completely unused
}
itemStack.setDurability(damage);
} else {
// If they didn't specify a durability, but they want a durable item, assume no damage (0)
// TODO: only assume 0 for wants. For gives, need to use value from inventory! Underspecified
}
// TODO: enchantments
return;
}
throw new UsageException("Unrecognized item specification: " + s);
}
// Return whether an item degrades when used
public static boolean isDurable(Material m) {
return isTool(m) || isWeapon(m) || isArmor(m);
}
// Return whether the "damage"(durability) value is overloaded to mean
// a different kind of material, instead of actual damage on a tool
public static boolean dmgMeansSubtype(Material m) {
// TODO: should this check be inverted, just checking for tools/weapons/armor (isDurable??) and returning true instead?
switch (m) {
// Blocks
case SAPLING:
case LEAVES:
case LOG:
case WOOL:
case DOUBLE_STEP:
case STEP:
case SMOOTH_BRICK:
// Items
case COAL:
case INK_SACK:
case POTION:
case MAP:
case MONSTER_EGGS:
// Materials not legitimately acquirable in inventory, but here for completeness
// (refer to Material enum, entries with MaterialData classes)
// See http://www.minecraftwiki.net/wiki/Data_values#Data for their data value usage
// Note that environmental data (age,orientation,etc.) on IDs used as both blocks
// but not required for items does NOT cause true to be returned here.
case WATER: // item: WATER_BUCKET
case STATIONARY_WATER:
case LAVA: // item: LAVA_BUCKET
case STATIONARY_LAVA:
//case DISPENSER: // orientation, but not relevant to item
case BED_BLOCK: // item: BED
//case POWERED_RAIL: // whether powered, but not relevant to item
//case DETECTOR_RAIL: // whether detecting, but not relevant to item
case PISTON_STICKY_BASE:
case LONG_GRASS: // TODO: http://www.minecraftwiki.net/wiki/Data_values#Tall_Grass, can enchanted tool acquire?
case PISTON_BASE:
case PISTON_EXTENSION:
//case TORCH: // orientation, but not relevant to item
//case WOOD_STAIRS: // orientation, but not relevant to item
case REDSTONE_WIRE: // item: REDSTONE
case CROPS: // item: SEEDS
case SOIL: // TODO: can silk touch acquire farmland?
//case FURNANCE: // orientation, but not relevant to item
//case BURNING_FURNANCE: // TODO: supposedly silk touch can acquire?
case SIGN_POST: // item: SIGN
case WOODEN_DOOR: // item: WOOD_DOOR (confusing!)
//case LADDER: // orientation, but not relevant to item
//case RAILS: // orientation, but not relevant to item
//case COBBLESTONE_STAIRS: // orientation, but not relevant to item
case WALL_SIGN: // item: SIGN
//case LEVER: // orientation & state, but not relevant to item
//case STONE_PLATE: // state, but not relevant to item
case IRON_DOOR_BLOCK: // item: IRON_DOOR
//case WOOD_PLATE: // state, but not relevant to item
case REDSTONE_TORCH_OFF:
//case REDSTONE_TORCH_ON: // orientation, but not relevant to item
//case STONE_BUTTON: // state, but not relevant to item
//case CACTUS: // age, but not relevant to item
case SUGAR_CANE_BLOCK: // item: 338
//case PUMPKIN: // orientation, but not relevant to item
//case JACK_O_LATERN: // orientation, but not relevant to item
case CAKE_BLOCK: // item: CAKE
case DIODE_BLOCK_OFF: // item: DIODE
case DIODE_BLOCK_ON: // item: DIODE
//case TRAP_DOOR: // orientation, but not relevant to type
//case ENDER_PORTAL_FRAME: // TODO: has data, but no class in Bukkit? there are others
return true;
default:
return false;
}
}
public static boolean isTool(Material m) {
switch (m) {
case WOOD_PICKAXE: case STONE_PICKAXE: case IRON_PICKAXE: case GOLD_PICKAXE: case DIAMOND_PICKAXE:
case WOOD_AXE: case STONE_AXE: case IRON_AXE: case GOLD_AXE: case DIAMOND_AXE:
case WOOD_SPADE: case STONE_SPADE: case IRON_SPADE: case GOLD_SPADE: case DIAMOND_SPADE:
case FISHING_ROD:
return true;
default:
return false;
}
}
public static boolean isWeapon(Material m) {
switch (m) {
case WOOD_SWORD: case STONE_SWORD: case IRON_SWORD: case GOLD_SWORD: case DIAMOND_SWORD:
case BOW:
return true;
default:
return false;
}
}
public static boolean isArmor(Material m) {
switch (m) {
case LEATHER_BOOTS: case IRON_BOOTS: case GOLD_BOOTS: case DIAMOND_BOOTS:
case LEATHER_LEGGINGS: case IRON_LEGGINGS: case GOLD_LEGGINGS: case DIAMOND_LEGGINGS:
case LEATHER_CHESTPLATE:case IRON_CHESTPLATE: case GOLD_CHESTPLATE: case DIAMOND_CHESTPLATE:
case LEATHER_HELMET: case IRON_HELMET: case GOLD_HELMET: case DIAMOND_HELMET:
// PUMPKIN is wearable on head, but isn't really armor, it doesn't take any damage
return true;
default:
return false;
}
}
public static String nameStack(ItemStack itemStack) {
String name, extra;
Material m = itemStack.getType();
// If all else fails, use generic name from Bukkit
name = itemStack.getType().toString();
if (isDurable(m)) {
// Percentage remaining
// Round down so '100%' always means completely unused? (1 dmg = 99%)
//int percentage = Math.round(Math.floor((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability()))
// but then lower percentages are always one lower..
// So just special-case 100% to avoid misleading
int percentage;
if (itemStack.getDurability() == 0) {
percentage = 100;
} else {
percentage = (int)((m.getMaxDurability() - itemStack.getDurability()) * 100.0 / m.getMaxDurability());
if (percentage == 100) {
percentage = 99;
}
}
extra = "/" + percentage + "%";
} else {
extra = "";
}
// Find canonical name of item
// TODO: better way? OddItem can have uncommon aliases we might pick..
if (Bukkit.getServer().getPluginManager().getPlugin("OddItem") != null) {
List<String> names;
// Compatibility note:
// OddItem 0.8.1 only has String method:
// getAliases(java.lang.String) in info.somethingodd.bukkit.OddItem.OddItem cannot be applied to (org.bukkit.inventory.ItemStack)
//names = OddItem.getAliases(itemStack);
String codeName;
if (isDurable(m)) {
// durable items don't have unique names for each durability
codeName = itemStack.getTypeId() + ";0";
} else {
// durability here actually is overloaded to mean a different item
codeName = itemStack.getTypeId() + ";" + itemStack.getDurability();
}
try {
names = OddItem.getAliases(codeName);
name = names.get(names.size() - 1);
} catch (Exception e) {
log.info("OddItem doesn't know about " + codeName + ", using " + name);
}
} else {
log.info("OddItem not found, no more specific name available for " + name + ";" + itemStack.getDurability());
}
// TODO: enchantments
return itemStack.getAmount() + "-" + name + extra;
}
// Return whether two item stacks have the same item, taking into account 'subtypes'
// stored in the damage value (ex: blue wool, only same as blue wool) - but will
// ignore damage for durable items (ex: diamond sword, 50% = diamond sword, 100%)
public static boolean isSameType(ItemStack a, ItemStack b) {
if (a.getType() != b.getType()) {
return false;
}
Material m = a.getType();
if (isDurable(m)) {
return true;
}
return a.getDurability() == b.getDurability();
}
}
class EnchantQuery
{
static Logger log = Logger.getLogger("Minecraft");
Map<Enchantment,Integer> all;
public EnchantQuery(String allString) {
all = new HashMap<Enchantment,Integer>();
String[] enchStrings = allString.split("[, /-]+");
for (String enchString: enchStrings) {
Pattern p = Pattern.compile("^([a-z-]+)([IV0-9]*)$");
Matcher m = p.matcher(enchString);
if (!m.find()) {
throw new UsageException("Unrecognizable enchantment: '" + enchString + "'");
}
String baseName = m.group(1);
String levelString = m.group(2);
Enchantment ench = enchFromBaseName(baseName);
int level = levelFromString(levelString);
// Odd, what's the point of having a separate 'wrapper' class?
// Either way, it has useful methods for us
EnchantmentWrapper enchWrapper = new EnchantmentWrapper(ench.getId());
if (level > enchWrapper.getMaxLevel()) {
level = ench.getMaxLevel();
}
log.info("Enchantment: " + ench + ", level="+level);
all.put(enchWrapper, new Integer(level));
}
}
// Return whether all the enchantments can apply to an item
public boolean canEnchantItem(ItemStack item) {
Iterator it = all.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
EnchantmentWrapper ench = (EnchantmentWrapper)pair.getKey();
Integer level = (Integer)pair.getValue();
if (!ench.canEnchantItem(item)) {
log.info("Cannot apply enchantment " + ench + " to " + item);
return false;
}
}
return true;
}
public String toString() {
StringBuffer names = new StringBuffer();
Iterator it = all.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
EnchantmentWrapper ench = (EnchantmentWrapper)pair.getKey();
Integer level = (Integer)pair.getValue();
names.append(enchName(ench));
names.append(levelToString(level));
names.append(",");
}
// Remove the trailing comma
// Would have liked to just build an array then join it, but not easier in Java either
names.deleteCharAt(names.length() - 1);
return names.toString();
}
static Enchantment enchFromBaseName(String n) {
// TODO: something like OddItem for enchantment names! hideous, this
n = n.toLowerCase();
Enchantment ench = Enchantment.getByName(n);
if (ench != null) {
return ench;
}
// Armor
if (n.equals("protection")) {
return Enchantment.PROTECTION_ENVIRONMENTAL;
} else if (n.equals("fire-protection") || n.equals("fireprotection") || n.equals("fire")) {
return Enchantment.PROTECTION_FIRE;
} else if (n.equals("feather-falling") || n.equals("featherfalling") || n.equals("feather") || n.equals("falling") || n.equals("fall")) {
return Enchantment.PROTECTION_FALL;
} else if (n.equals("blast-protection") || n.equals("blastprotection") || n.equals("blast") || n.equals("explosion-protection")) {
return Enchantment.PROTECTION_EXPLOSIONS;
} else if (n.equals("projectile-protection") || n.equals("projectileprotection") || n.equals("projectile")) {
return Enchantment.PROTECTION_PROJECTILE;
} else if (n.equals("respiration") || n.equals("oxygen")) {
return Enchantment.OXYGEN;
} else if (n.equals("aqua-affinity") || n.equals("aquaaffinity") || n.equals("aqua") || n.equals("waterworker")) {
return Enchantment.WATER_WORKER;
// Weapons
} else if (n.equals("sharpness") || n.equals("damage-all")) {
return Enchantment.DAMAGE_ALL;
} else if (n.equals("smite") || n.equals("damage-undead")) {
return Enchantment.DAMAGE_UNDEAD;
} else if (n.equals("bane-of-arthropods") || n.equals("bane") || n.equals("arthropods")) {
return Enchantment.DAMAGE_ARTHROPODS;
} else if (n.equals("knockback")) {
return Enchantment.KNOCKBACK;
} else if (n.equals("fire-aspect") || n.equals("fireaspect") || n.equals("fire")) {
return Enchantment.FIRE_ASPECT;
} else if (n.equals("looting") || n.equals("loot") || n.equals("loot-bonus-mobs")) {
return Enchantment.LOOT_BONUS_MOBS;
// Tools
} else if (n.equals("efficiency") || n.equals("dig-speed")) {
return Enchantment.DIG_SPEED;
} else if (n.equals("silk-touch") || n.equals("silktouch") || n.equals("silk")) {
return Enchantment.SILK_TOUCH;
} else if (n.equals("unbreaking") || n.equals("durability")) {
return Enchantment.DURABILITY;
} else if (n.equals("fortune") || n.equals("loot-bonus-blocks")) {
return Enchantment.LOOT_BONUS_BLOCKS;
} else {
throw new UsageException("Unrecognized enchantment name: " + n);
}
}
static String enchName(EnchantmentWrapper ench) {
switch (ench.getId()) {
case 0: return "Protection";
case 1: return "FireProtection";
case 2: return "FeatherFalling";
case 3: return "BlastProtection";
case 4: return "ProjectileProtection";
case 5: return "Respiration";
case 6: return "AquaAffinity";
case 16: return "Sharpness";
case 17: return "Smite";
case 18: return "BaneOfArthropods";
case 19: return "Knockback";
case 20: return "FireAspect";
case 21: return "Looting";
case 32: return "Efficiency";
case 33: return "SilkTouch";
case 34: return "Unbreaking";
case 35: return "Fortune";
default: return "Unknown(" + ench.getId() + ")";
}
// There is ench.getName(), but the names don't match in-game
}
static int levelFromString(String s) {
if (s.equals("") || s.equals("I")) {
return 1;
} else if (s.equals("II")) {
return 2;
} else if (s.equals("III")) {
return 3;
} else if (s.equals("IV")) {
return 4;
} else if (s.equals("V")) {
return 5;
} else {
return Integer.parseInt(s);
}
}
static String levelToString(int n) {
switch (n) {
case 1: return "I";
case 2: return "II";
case 3: return "III";
case 4: return "IV";
case 5: return "V";
default: return Integer.toString(n);
}
}
}
class Order
{
Player player;
ItemStack want, give;
boolean exact;
public Order(Player p, String wantString, String giveString) {
player = p;
if (wantString.contains("!")) {
exact = true;
wantString = wantString.replace("!", "");
}
if (giveString.contains("!")) {
exact = true;
giveString = giveString.replace("!", "");
}
want = (new ItemQuery(wantString)).itemStack;
give = (new ItemQuery(giveString)).itemStack;
}
public Order(Player p, ItemStack w, ItemStack g, boolean e) {
player = p;
want = w;
give = g;
exact = e;
}
public String toString() {
return player.getDisplayName() + " wants " + ItemQuery.nameStack(want) + " for " + ItemQuery.nameStack(give) + (exact ? " (exact)" : "");
}
}
class UsageException extends RuntimeException
{
public String message;
public UsageException(String msg) {
message = msg;
}
public String toString() {
return "UsageException: " + message;
}
}
class Market
{
ArrayList<Order> orders;
Logger log = Logger.getLogger("Minecraft");
public Market() {
// TODO: load from file, save to file
orders = new ArrayList<Order>();
}
public boolean showOutstanding(CommandSender sender) {
sender.sendMessage("Open orders:");
for (int i = 0; i < orders.size(); i++) {
sender.sendMessage(i + ". " + orders.get(i));
}
sender.sendMessage("To add or fulfill an order:");
return false;
}
public void placeOrder(Order order) {
if (matchOrder(order)) {
// Executed
return;
}
// Not fulfilled; add to outstanding to match with future order
// Broadcast to all players so they know someone wants something, then add
Bukkit.getServer().broadcastMessage("Wanted: " + order);
orders.add(order);
}
public boolean matchOrder(Order newOrder) {
for (int i = 0; i < orders.size(); i++) {
Order oldOrder = orders.get(i);
//log.info("oldOrder: " + oldOrder);
//log.info("newOrder: " + newOrder);
// Are they giving what anyone else wants?
if (!ItemQuery.isSameType(newOrder.give, oldOrder.want) ||
!ItemQuery.isSameType(newOrder.want, oldOrder.give)) {
log.info("Not matched, different types");
continue;
}
double newRatio = (double)newOrder.give.getAmount() / newOrder.want.getAmount();
double oldRatio = (double)oldOrder.want.getAmount() / oldOrder.give.getAmount();
// Offering a better or equal deal? (Quantity = relative value)
log.info("ratio " + newRatio + " >= " + oldRatio);
if (!(newRatio >= oldRatio)) {
log.info("Not matched, worse relative value");
continue;
}
// Is item less damaged or equally damaged than wanted? (Durability)
if (ItemQuery.isDurable(newOrder.give.getType())) {
if (newOrder.give.getDurability() > oldOrder.want.getDurability()) {
log.info("Not matched, worse damage new, " + newOrder.give.getDurability() + " < " + oldOrder.want.getDurability());
continue;
}
}
if (ItemQuery.isDurable(oldOrder.give.getType())) {
if (oldOrder.give.getDurability() > newOrder.want.getDurability()) {
log.info("Not matched, worse damage old, " + oldOrder.give.getDurability() + " < " + newOrder.want.getDurability());
continue;
}
}
// TODO: enchantment checks
// Generalize to "betterness"
// Determine how much of the order can be fulfilled
int remainingWant = oldOrder.want.getAmount() - newOrder.give.getAmount();
int remainingGive = oldOrder.give.getAmount() - newOrder.want.getAmount();
log.info("remaining want="+remainingWant+", give="+remainingGive);
// They get what they want!
// TODO: ensure contains() before removing
// Calculate amount exchanged
ItemStack exchWant = new ItemStack(oldOrder.want.getType(), Math.min(oldOrder.want.getAmount(), newOrder.give.getAmount()), newOrder.give.getDurability());
ItemStack exchGive = new ItemStack(oldOrder.give.getType(), Math.min(oldOrder.give.getAmount(), newOrder.want.getAmount()), oldOrder.give.getDurability());
log.info("exchWant="+ItemQuery.nameStack(exchWant));
log.info("exchGive="+ItemQuery.nameStack(exchGive));
oldOrder.player.getInventory().addItem(exchWant);
newOrder.player.getInventory().remove(exchWant);
Bukkit.getServer().broadcastMessage(oldOrder.player.getDisplayName() + " received " +
ItemQuery.nameStack(exchWant) + " from " + newOrder.player.getDisplayName());
newOrder.player.getInventory().addItem(exchGive);
oldOrder.player.getInventory().remove(exchGive);
Bukkit.getServer().broadcastMessage(newOrder.player.getDisplayName() + " received " +
ItemQuery.nameStack(exchGive) + " from " + oldOrder.player.getDisplayName());
// Remove oldOrder from orders, if complete, or add partial if incomplete
if (remainingWant == 0) {
// This order is finished, old player got everything they wanted
// Note: remainingWant can be negative if they got more than they bargained for
// (other player offered a better deal than expected). Either way, done deal.
orders.remove(oldOrder);
log.info("Closed order " + oldOrder);
return true;
} else if (remainingWant > 0) {
oldOrder.want.setAmount(remainingWant);
oldOrder.give.setAmount(remainingGive);
Bukkit.getServer().broadcastMessage("Updated order: " + oldOrder);
return true;
} else if (remainingWant < 0) {
orders.remove(oldOrder);
orders.remove("Closed order " + oldOrder);
newOrder.want.setAmount(-remainingGive);
newOrder.give.setAmount(-remainingWant);
log.info("Adding new partial order");
return false;
}
}
return false;
}
}
public class FreeTrade extends JavaPlugin {
Logger log = Logger.getLogger("Minecraft");
Market market = new Market();
public void onEnable() {
log.info(getDescription().getName() + " enabled");
log.info("e=" + new EnchantQuery("smiteV,lootingII,knockbackII"));
}
public void onDisable() {
log.info(getDescription().getName() + " disabled");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player;
int n = 0;
if (!cmd.getName().equalsIgnoreCase("want")) {
return false;
}
// /want
if (args.length == 0) {
return market.showOutstanding(sender);
}
if (sender instanceof Player) {
player = (Player)sender;
} else {
// Get player name from first argument
player = Bukkit.getServer().getPlayer(args[0]);
if (player == null) {
sender.sendMessage("no such player");
return false;
}
n++;
}
if (args.length < 2+n) {
return false;
}
String wantString, giveString;
wantString = args[n];
if (args[n+1].equalsIgnoreCase("for")) {
giveString = args[n+2];
} else {
giveString = args[n+1];
}
Order order = new Order(player, wantString, giveString);
sender.sendMessage(order.toString());
market.placeOrder(order);
return true;
}
} |
package org.apache.poi.benchmark.email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.ImageHtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.resolver.DataSourceUrlResolver;
import org.dstadler.commons.email.EmailConfig;
import org.dstadler.commons.email.MailserverConfig;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
*
* @author dominik.stadler
*/
public class EmailSender {
//private static final Log logger = LogFactory.getLog(EmailSender.class);
// error messages
//private static final String CANNOT_SEND_EMAIL_WITHOUT_SMTP_SERVER = "Cannot send email without SMTP server set in the configuration.";
private static final String CANNOT_SEND_EMAIL_NO_EMAIL_DATA = "Cannot send email, no email data provided.";
private static final String CANNOT_SEND_EMAIL_NO_MAIL_SERVER_CONFIGURATION = "Cannot send email, no mail server configuration available";
//private static final String CANNOT_SEND_EMAIL_NO_USER_DATA = "Cannot send email, no user data provided.";
private static final char SCOLON = ';';
private static final char COMMA = ':';
/**
* Send an email with the specified files as attachments.
*
* Note: This method does not resolve the email addresses in EmailConfig from users/groups, use the
* other provided methods in this class to do this.
*
* Note: This does not perform HTML image replacement!
*
* @throws IOException If sending the email fails.
*/
public void sendAttachmentEmail(List<File> attachments, MailserverConfig mailserverConfig,
EmailConfig emailConfig, String html) throws IOException {
if(mailserverConfig == null) {
throw new IOException(CANNOT_SEND_EMAIL_NO_MAIL_SERVER_CONFIGURATION);
}
if(emailConfig == null) {
throw new IOException(CANNOT_SEND_EMAIL_NO_EMAIL_DATA);
}
try {
final ImageHtmlEmail email = new ImageHtmlEmail();
email.setDataSourceResolver(new DataSourceUrlResolver(new File(".").toURI().toURL(), true));
if(attachments != null) {
for (File report : attachments) {
// Create the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(report.getAbsolutePath());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("The generated report");
attachment.setName(report.getName());
// add the attachment
email.attach(attachment);
}
}
setSMTPConfig(email, mailserverConfig);
try {
setEmailConfig(email, emailConfig, mailserverConfig.getSubjectPrefix());
} catch (AddressException e) {
throw new IOException("AddressException", e);
}
email.setMsg("Your email client does not support HTML messages");
if(html != null && html.length() > 0) {
email.setHtmlMsg(html);
}
email.send();
} catch (EmailException e) {
throw new IOException("Sending the email caused an exception", e);
}
}
/**
* Helper method to populate the javax-email components with the Mailserver configuration
*/
private void setSMTPConfig(MultiPartEmail email, MailserverConfig config) {
// set properties on the Email object
int port = config.getServerPort();
email.setHostName(config.getServerAddress());
if (port != -1) {
email.setSmtpPort(port);
}
// set optional SMTP username and password
String smtpUser = config.getUserId();
String smtpPassword = config.getPassword();
if (smtpUser != null && !smtpUser.isEmpty() && smtpPassword != null && !smtpPassword.isEmpty()) {
email.setAuthentication(smtpUser, smtpPassword);
}
// set optional bounce address
String emailBounce = config.getBounce();
if (emailBounce != null && !emailBounce.isEmpty()) {
email.setBounceAddress(emailBounce);
}
// set debug if specified to get more output in case it does not work
// for some technical reason
email.setDebug(config.isDebug());
// some SMTP hosts require SSL, e.g. Google Mail seems to in some cases...
email.setSSLOnConnect(config.isSSLEnabled());
}
/**
* Helper method to populate the javax-email components with the Email configuration
* @throws AddressException If any of the recipient-addresses can not be parsed
* @throws EmailException If sending the email causes an error
*/
private void setEmailConfig(MultiPartEmail email, EmailConfig emailConfig, String subjectPrefix)
throws AddressException, EmailException, IOException {
boolean hadAddress = false;
// JLT-17850: semicolons are replaced with commas to preempt parsing
// errors.
// note that a semicolon is not a RFC822 compatible recipient separator
// but it seems users are very used to use it as such.
if (emailConfig.getTo() != null && !emailConfig.getTo().isEmpty()) {
String toWithoutScolons = emailConfig.getToAsEmail().replace(SCOLON, COMMA);
// something might go wrong in conversion from Resolved Email Address to string
if(toWithoutScolons.length() > 0) {
email.setTo(Arrays.asList(InternetAddress.parse(toWithoutScolons)));
hadAddress = true;
}
}
//email.setTo(Arrays.asList(new String[] { emailAddress }));
// set optional "cc" addresses
if (emailConfig.getCc() != null && !emailConfig.getCc().isEmpty()) {
String ccWithoutScolons = emailConfig.getCcAsEmail().replace(SCOLON, COMMA);
// something might go wrong in conversion from Resolved Email Address to string
if(ccWithoutScolons.length() > 0) {
email.setCc(Arrays.asList(InternetAddress.parse(ccWithoutScolons)));
hadAddress = true;
}
}
// set optional "bcc" addresses
if (emailConfig.getBcc() != null && !emailConfig.getBcc().isEmpty()) {
String bccWithoutScolons = emailConfig.getBccAsEmail().replace(SCOLON, COMMA);
// something might go wrong in conversion from Resolved Email Address to string
if(bccWithoutScolons.length() > 0) {
email.setBcc(Arrays.asList(InternetAddress.parse(bccWithoutScolons)));
hadAddress = true;
}
}
// throw an error without recipient
if(!hadAddress) {
throw new IOException("At least one receiver address required, could not send email: '" + emailConfig.getSubject() + "' from '" + emailConfig.getFrom() + "'");
}
if(emailConfig.getFrom() != null) {
email.setFrom(emailConfig.getFrom());
}
email.setSubject((subjectPrefix != null ? subjectPrefix : "" ) + emailConfig.getSubject());
}
} |
package jp.gr.java_conf.neko_daisuki.photonote;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.JsonWriter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import jp.gr.java_conf.neko_daisuki.photonote.widget.PaintView;
import jp.gr.java_conf.neko_daisuki.photonote.widget.PaletteView;
public class EditActivity extends Activity {
public enum Extra {
ORIGINAL_PATH,
ADDITIONAL_PATH
}
private class OkeyButtonOnClickListener implements View.OnClickListener {
public void onClick(View view) {
writeLines();
setResult(RESULT_OK, getIntent());
finish();
}
}
private class PaletteChangeListener implements PaletteView.OnChangeListener {
public void onChange(PaletteView view) {
mPaintView.setColor(view.getSelectedColor());
}
}
private static class Line {
private List<PointF> mPoints;
private int mColor;
private float mStrokeWidth;
public Line(int color, float strokeWidth) {
mPoints = new LinkedList<PointF>();
mColor = color;
mStrokeWidth = strokeWidth;
}
public int getColor() {
return mColor;
}
public float getStrokeWidth() {
return mStrokeWidth;
}
public List<PointF> getPoints() {
return mPoints;
}
}
private class Adapter implements PaintView.Adapter {
private List<Line> mLines;
public Adapter() {
mLines = new LinkedList<Line>();
}
public int getLineCount() {
return mLines.size();
}
public int getPointCount(int line) {
return mLines.get(line).getPoints().size();
}
public PointF getPoint(int line, int n) {
return mLines.get(line).getPoints().get(n);
}
public void startLine(int color, float strokeWidth, PointF point) {
Line line = new Line(color, strokeWidth);
line.getPoints().add(point);
mLines.add(line);
}
public void addPoint(PointF point) {
mLines.get(mLines.size() - 1).getPoints().add(point);
}
public float getStrokeWidth(int line) {
return mLines.get(line).getStrokeWidth();
}
public int getLineColor(int line) {
return mLines.get(line).getColor();
}
public float getLineWidth(int line) {
return mLines.get(line).getStrokeWidth();
}
}
private static final String LOG_TAG = "photonote";
private PaintView mPaintView;
private Adapter mAdapter;
private String mAdditionalPath;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit, menu);
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_edit);
Intent i = getIntent();
setImage(R.id.original, i, Extra.ORIGINAL_PATH);
mAdapter = new Adapter();
mPaintView = (PaintView)findViewById(R.id.additional);
mPaintView.setAdapter(mAdapter);
PaletteView paletteView = (PaletteView)findViewById(R.id.palette);
paletteView.setOnChangeListener(new PaletteChangeListener());
Button okeyButton = (Button)findViewById(R.id.okey_button);
okeyButton.setOnClickListener(new OkeyButtonOnClickListener());
mAdditionalPath = i.getStringExtra(Extra.ADDITIONAL_PATH.name());
/*
* TODO: Move calling of readLines() to onResume().
* Moreover, data must be stored in a temporary file. onResume() must
* read it. Or unsaved data shall be lost. EditActivity can have one
* more extra string such as Extra.TEMPORARY_PATH, which is given by
* MainActivity.
*/
readLines(mAdditionalPath);
}
private void setImage(int view, Intent i, Extra key) {
ImageView v = (ImageView)findViewById(view);
v.setImageURI(Uri.fromFile(new File(i.getStringExtra(key.name()))));
}
private void writeLinesToJson(JsonWriter writer) throws IOException {
writer.setIndent(" ");
writer.beginArray();
int nLines = mAdapter.getLineCount();
for (int i = 0; i < nLines; i++) {
writer.beginObject();
writer.name("color").value(mAdapter.getLineColor(i));
writer.name("width").value(mAdapter.getLineWidth(i));
writer.name("points");
writer.beginArray();
int nPoints = mAdapter.getPointCount(i);
for (int j = 0; j < nPoints; j++) {
PointF point = mAdapter.getPoint(i, j);
writer.beginObject();
writer.name("x").value(point.x);
writer.name("y").value(point.y);
writer.endObject();
}
writer.endArray();
writer.endObject();
}
writer.endArray();
}
private void writeLines() {
OutputStream out;
try {
out = new FileOutputStream(mAdditionalPath);
}
catch (IOException e) {
String fmt = "failed to open %s: %s";
Log.e(LOG_TAG, String.format(fmt, mAdditionalPath, e.getMessage()));
return;
}
String encoding = "UTF-8";
Writer writer;
try {
writer = new OutputStreamWriter(out, encoding);
}
catch (UnsupportedEncodingException e) {
String fmt = "failed to write %s with encoding %s: %s";
String message = e.getMessage();
Log.e(LOG_TAG,
String.format(fmt, mAdditionalPath, encoding, message));
return;
}
JsonWriter jsonWriter = new JsonWriter(writer);
try {
try {
writeLinesToJson(jsonWriter);
}
finally {
jsonWriter.close();
}
}
catch (IOException e) {
String fmt = "failed to write %s: %s";
Log.e(LOG_TAG, String.format(fmt, mAdditionalPath, e.getMessage()));
}
}
private void readLinesFromJson(JsonReader reader) throws IOException {
reader.beginArray();
while (reader.hasNext()) {
int color = Color.BLACK;
float width = 16.0f;
List<PointF> points = new LinkedList<PointF>();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("color")) {
color = reader.nextInt();
}
else if (name.equals("width")) {
width = (float)reader.nextDouble();
}
else if (name.equals("points")) {
reader.beginArray();
while (reader.hasNext()) {
float x = 0.0f;
float y = 0.0f;
reader.beginObject();
while (reader.hasNext()) {
String name2 = reader.nextName();
if (name2.equals("x")) {
x = (float)reader.nextDouble();
}
else if (name2.equals("y")) {
y = (float)reader.nextDouble();
}
else {
String fmt = "unexpected json attribute: %s";
Log.e(LOG_TAG, String.format(fmt, name2));
}
}
reader.endObject();
points.add(new PointF(x, y));
}
reader.endArray();
}
else {
String fmt = "unexpected json attribute: %s";
Log.e(LOG_TAG, String.format(fmt, name));
}
}
reader.endObject();
int size = points.size();
if (size == 0) {
continue;
}
mAdapter.startLine(color, width, points.get(0));
for (int i = 1; i < size; i++) {
mAdapter.addPoint(points.get(i));
}
}
reader.endArray();
}
private void readLines(String path) {
Reader reader;
try {
reader = new FileReader(path);
}
catch (FileNotFoundException e) {
String fmt = "failed to read %s: %s";
Log.e(LOG_TAG, String.format(fmt, path, e.getMessage()));
return;
}
JsonReader jsonReader = new JsonReader(reader);
try {
try {
readLinesFromJson(jsonReader);
}
finally {
jsonReader.close();
}
}
catch (IOException e) {
String fmt = "failed to read json %s: %s";
Log.e(LOG_TAG, String.format(fmt, mAdditionalPath, e.getMessage()));
}
}
}
/**
* vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
*/ |
package jp.gr.java_conf.neko_daisuki.photonote;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static class DialogCancelListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
}
}
private class DialogDeleteGroupListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
deleteGroup(mDeletingGroup);
updateData();
updateList();
}
}
private class DialogAddGroupListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
EditText text = (EditText)mGroupNameView.findViewById(R.id.name);
CharSequence name = text.getText();
if (name.length() == 0) {
showInformation(
"You gave empty group name. No groups are added.");
return;
}
makeGroup(name);
updateData();
updateList();
}
}
private abstract class DialogCreatingProc {
public abstract Dialog create();
}
private class DeleteGroupDialogCreatingProc extends DialogCreatingProc {
public Dialog create() {
return createDeleteGroupDialog();
}
}
private class GroupNameDialogCreatingProc extends DialogCreatingProc {
public Dialog create() {
return createGroupNameDialog();
}
}
private class AddGroupListener implements OnClickListener {
public void onClick(View view) {
showDialog(DIALOG_GROUP_NAME);
}
}
private class ListAdapter extends BaseExpandableListAdapter {
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
return isLastChild ? getGroupControlView(groupPosition, childPosition, parent) : getEntryView(groupPosition, childPosition, parent);
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = mInflater.inflate(R.layout.group_row, parent, false);
TextView text = (TextView)view.findViewById(R.id.name);
Group group = (Group)getGroup(groupPosition);
text.setText(group.getName());
return view;
}
public boolean hasStableIds() {
return true;
}
public long getGroupId(int groupPosition) {
return mGroups.get(groupPosition).getName().hashCode();
}
public long getChildId(int groupPosition, int childPosition) {
Group group = mGroups.get(groupPosition);
Entry entry = group.getEntries().get(childPosition);
return entry.getName().hashCode();
}
public Object getChild(int groupPosition, int childPosition) {
return mGroups.get(groupPosition).getEntries().get(childPosition);
}
public Object getGroup(int groupPosition) {
return mGroups.get(groupPosition);
}
public int getChildrenCount(int groupPosition) {
return mGroups.get(groupPosition).getEntries().size() + 1;
}
public int getGroupCount() {
return mGroups.size();
}
private View getEntryView(int groupPosition, int childPosition, ViewGroup parent) {
View view = mInflater.inflate(R.layout.child_row, parent, false);
TextView text = (TextView)view.findViewById(R.id.name);
Entry entry = (Entry)getChild(groupPosition, childPosition);
text.setText(entry.getName());
return view;
}
private View getGroupControlView(int groupPosition, int childPosition, ViewGroup parent) {
View view = mInflater.inflate(R.layout.child_last_row, parent, false);
Group group = (Group)getGroup(groupPosition);
View shotButton = view.findViewById(R.id.shot_button);
shotButton.setOnClickListener(new ShotButtonOnClickListener(group));
View deleteButton = view.findViewById(R.id.delete_button);
deleteButton.setOnClickListener(new DeleteButtonOnClickListener(group));
return view;
}
}
private abstract class GroupButtonOnClickListener implements OnClickListener {
private Group mGroup;
public GroupButtonOnClickListener(Group group) {
mGroup = group;
}
public abstract void onClick(View view);
protected Group getGroup() {
return mGroup;
}
}
private class DeleteButtonOnClickListener extends GroupButtonOnClickListener {
public DeleteButtonOnClickListener(Group group) {
super(group);
}
public void onClick(View view) {
mDeletingGroup = getGroup();
showDialog(DIALOG_DELETE_GROUP);
}
}
private class ShotButtonOnClickListener extends GroupButtonOnClickListener {
public ShotButtonOnClickListener(Group group) {
super(group);
}
public void onClick(View view) {
shot(getGroup());
}
}
private class Entry {
private String mName;
public Entry(String name) {
mName = name;
}
public String getName() {
return mName;
}
public String getDirectory() {
return String.format("%s/%s", getEntriesDirectory(), mName);
}
public String getOriginalPath() {
return String.format("%s/original.png", getDirectory());
}
}
private class Group {
private String mName;
private List<Entry> mEntries;
public Group(String name) {
mName = name;
mEntries = new ArrayList<Entry>();
}
public List<Entry> getEntries() {
return mEntries;
}
public String getName() {
return mName;
}
public String getPath() {
return String.format("%s/%s", getGroupsDirectory(), getName());
}
}
private enum Key {
SHOTTING_GROUP_NAME
}
private static final String LOG_TAG = "photonote";
private static final int REQUEST_CAPTURE = 42;
private static final int DIALOG_GROUP_NAME = 42;
private static final int DIALOG_DELETE_GROUP = 43;
// document
private List<Group> mGroups;
// view
private ListAdapter mAdapter;
// stateful helpers
private String mShottingGroupName;
private Entry mResultEntry;
private Group mDeletingGroup;
// stateless helpers
private SimpleDateFormat mDateFormat;
private LayoutInflater mInflater;
private Map<Integer, DialogCreatingProc> mDialogCreatingProcs;
private View mGroupNameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGroups = new ArrayList<Group>();
ExpandableListView list = (ExpandableListView)findViewById(R.id.list);
mAdapter = new ListAdapter();
list.setAdapter(mAdapter);
Button addGroupButton = (Button)findViewById(R.id.add_a_new_group_button);
addGroupButton.setOnClickListener(new AddGroupListener());
setupFileTree();
mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String service = Context.LAYOUT_INFLATER_SERVICE;
mInflater = (LayoutInflater)getSystemService(service);
mDialogCreatingProcs = new HashMap<Integer, DialogCreatingProc>();
mDialogCreatingProcs.put(
new Integer(DIALOG_GROUP_NAME),
new GroupNameDialogCreatingProc());
mDialogCreatingProcs.put(
new Integer(DIALOG_DELETE_GROUP),
new DeleteGroupDialogCreatingProc());
mGroupNameView = mInflater.inflate(R.layout.dialog_group_name, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setupFileTree() {
makeDirectories();
makeDefaultGroup();
}
private void makeGroup(CharSequence name) {
boolean done;
String path = String.format("%s/%s", getGroupsDirectory(), name);
try {
done = new File(path).createNewFile();
}
catch (IOException e) {
String fmt = "failed to open %s: %s";
logError(String.format(fmt, path, e.getMessage()));
return;
}
if (done) {
Log.i(LOG_TAG, String.format("created a new group: %s", path));
}
}
private void makeDefaultGroup() {
makeGroup("default");
}
private void makeDirectories() {
String[] directories = new String[] {
getDataDirectory(),
getEntriesDirectory(),
getGroupsDirectory(),
getTemporaryDirectory() };
for (String directory: directories) {
File file = new File(directory);
if (file.exists()) {
continue;
}
if (file.mkdir()) {
Log.i(LOG_TAG, String.format("make directory: %s", directory));
continue;
}
logError(String.format("failed to mkdir: %s", directory));
}
}
protected Dialog onCreateDialog(int id) {
return mDialogCreatingProcs.get(new Integer(id)).create();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(Key.SHOTTING_GROUP_NAME.name(), mShottingGroupName);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mShottingGroupName = savedInstanceState.getString(Key.SHOTTING_GROUP_NAME.name());
}
protected void onResume() {
super.onResume();
updateData();
if (mResultEntry != null) {
findGroupOfName(mShottingGroupName).getEntries().add(mResultEntry);
updateList();
mResultEntry = null;
}
}
protected void onPause() {
super.onPause();
saveGroups();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode != REQUEST_CAPTURE) || (resultCode != RESULT_OK)) {
return;
}
Entry entry = new Entry(makeNewEntryName());
new File(entry.getDirectory()).mkdir();
String src = getTemporaryPath();
String dest = entry.getOriginalPath();
if (!new File(src).renameTo(new File(dest))) {
logError(String.format("failed to move %s into %s.", src, dest));
return;
}
mResultEntry = entry;
Log.i(LOG_TAG, String.format("added %s.", dest));
}
private String getDataDirectory() {
return "/mnt/sdcard/.photonote";
}
private String getTemporaryDirectory() {
return String.format("%s/tmp", getDataDirectory());
}
private String getEntriesDirectory() {
return String.format("%s/entries", getDataDirectory());
}
private String getGroupsDirectory() {
return String.format("%s/groups", getDataDirectory());
}
private Map<String, Entry> readEntries() {
Map<String, Entry> entries = new HashMap<String, Entry>();
for (String name: new File(getEntriesDirectory()).list()) {
entries.put(name, new Entry(name));
}
return entries;
}
private List<Group> readGroups(Map<String, Entry> entries) {
List<Group> groups = new ArrayList<Group>();
for (File file: new File(getGroupsDirectory()).listFiles()) {
String name = file.getName();
try {
groups.add(readGroup(name, entries));
}
catch (IOException e) {
logError(String.format("failed to read a group of %s.", name));
}
}
return groups;
}
private Group readGroup(String name, Map<String, Entry> entries) throws IOException {
Group group = new Group(name);
String path = String.format("%s/%s", getGroupsDirectory(), name);
BufferedReader in = new BufferedReader(new FileReader(path));
String entryName;
while ((entryName = in.readLine()) != null) {
group.getEntries().add(entries.get(entryName));
}
return group;
}
private void shot(Group group) {
mShottingGroupName = group.getName();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.fromFile(new File(getTemporaryPath()));
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(i, REQUEST_CAPTURE);
}
private String makeNewEntryName() {
return mDateFormat.format(new Date());
}
private Group findGroupOfName(String name) {
for (Group group: mGroups) {
if (group.getName().equals(name)) {
return group;
}
}
return null;
}
private void saveGroups() {
for (Group group: mGroups) {
String path = group.getPath();
OutputStream out;
try {
out = new FileOutputStream(path);
}
catch (FileNotFoundException e) {
String fmt = "failed to write %s: %s";
logError(String.format(fmt, path, e.getMessage()));
continue;
}
PrintWriter writer = new PrintWriter(out);
try {
for (Entry entry: group.getEntries()) {
writer.println(entry.getName());
}
}
finally {
writer.close();
}
}
}
private Dialog createDeleteGroupDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Resources res = getResources();
String fmt = res.getString(R.string.delete_dialog_message);
String name = mDeletingGroup.getName();
String positive = res.getString(R.string.positive);
String negative = res.getString(R.string.negative);
builder.setMessage(String.format(fmt, name, positive, negative));
builder.setPositiveButton(positive, new DialogDeleteGroupListener());
builder.setNegativeButton(negative, new DialogCancelListener());
return builder.create();
}
private Dialog createGroupNameDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(mGroupNameView);
builder.setPositiveButton("Okey", new DialogAddGroupListener());
builder.setNegativeButton("Cancel", new DialogCancelListener());
return builder.create();
}
private void updateData() {
mGroups = readGroups(readEntries());
}
private void updateList() {
mAdapter.notifyDataSetChanged();
}
private void deleteFile(File file) {
file.delete();
Log.i(LOG_TAG, String.format("deleted: %s", file.getAbsolutePath()));
}
private void deleteDirectory(File directory) {
for (File file: directory.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
deleteFile(file);
}
deleteFile(directory);
}
private void deleteGroup(Group group) {
for (Entry entry: group.getEntries()) {
deleteDirectory(new File(entry.getDirectory()));
}
deleteFile(new File(group.getPath()));
}
private void showInformation(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void logError(String message) {
Log.e(LOG_TAG, message);
showInformation(message);
}
private String getTemporaryPath() {
return String.format("%s/original.png", getTemporaryDirectory());
}
}
/**
* vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
*/ |
package agaricus.mods.highlighttips;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.FMLRelauncher;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.ITankContainer;
import net.minecraftforge.liquids.LiquidStack;
import java.util.EnumSet;
import java.util.logging.Level;
@Mod(modid = "HighlightTips", name = "HighlightTips", version = "1.0-SNAPSHOT") // TODO: version from resource
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class HighlightTips implements ITickHandler {
private static final int DEFAULT_KEY_TOGGLE = 62;
private static final double DEFAULT_RANGE = 300;
private static final int DEFAULT_X = 0;
private static final int DEFAULT_Y = 0;
private static final int DEFAULT_COLOR = 0xffffff;
private boolean enable = true;
private int keyToggle = DEFAULT_KEY_TOGGLE;
private double range = DEFAULT_RANGE;
private int x = DEFAULT_X;
private int y = DEFAULT_Y;
private int color = DEFAULT_COLOR;
private ToggleKeyHandler toggleKeyHandler;
@Mod.PreInit
public void preInit(FMLPreInitializationEvent event) {
Configuration cfg = new Configuration(event.getSuggestedConfigurationFile());
try {
cfg.load();
enable = cfg.get(Configuration.CATEGORY_GENERAL, "enable", true).getBoolean(true);
keyToggle = cfg.get(Configuration.CATEGORY_GENERAL, "key.toggle", DEFAULT_KEY_TOGGLE).getInt(DEFAULT_KEY_TOGGLE);
range = cfg.get(Configuration.CATEGORY_GENERAL, "range", DEFAULT_RANGE).getDouble(DEFAULT_RANGE);
x = cfg.get(Configuration.CATEGORY_GENERAL, "x", DEFAULT_X).getInt(DEFAULT_X);
y = cfg.get(Configuration.CATEGORY_GENERAL, "y", DEFAULT_Y).getInt(DEFAULT_Y);
color = cfg.get(Configuration.CATEGORY_GENERAL, "color", DEFAULT_COLOR).getInt(DEFAULT_COLOR);
} catch (Exception e) {
FMLLog.log(Level.SEVERE, e, "HighlightTips had a problem loading it's configuration");
} finally {
cfg.save();
}
if (!FMLRelauncher.side().equals("CLIENT")) {
// gracefully disable on non-client (= server) instead of crashing
enable = false;
}
if (!enable) {
FMLLog.log(Level.INFO, "HighlightTips disabled");
return;
}
TickRegistry.registerTickHandler(this, Side.CLIENT);
KeyBindingRegistry.registerKeyBinding(toggleKeyHandler = new ToggleKeyHandler(keyToggle));
}
private String describeBlock(int id, int meta, TileEntity tileEntity) {
StringBuilder sb = new StringBuilder();
describeBlockID(sb, id, meta);
describeTileEntity(sb, tileEntity);
return sb.toString();
}
private void describeTileEntity(StringBuilder sb, TileEntity te) {
if (te == null) return;
if (te instanceof ITankContainer) {
sb.append(" ITankContainer: ");
ITankContainer tankContainer = (ITankContainer) te;
ILiquidTank[] tanks = ((ITankContainer) te).getTanks(ForgeDirection.UP);
for (ILiquidTank tank : tanks) {
sb.append("capacity=" + tank.getCapacity());
sb.append(" pressure=" + tank.getTankPressure());
sb.append(" liquid=" + describeLiquidStack(tank.getLiquid()));
sb.append(" ");
}
}
}
private String describeLiquidStack(LiquidStack liquidStack) {
if (liquidStack == null) return "null";
ItemStack itemStack = liquidStack.canonical().asItemStack();
if (itemStack == null) return "null";
return itemStack.getDisplayName();
}
private void describeBlockID(StringBuilder sb, int id, int meta) {
Block block = Block.blocksList[id];
if (block == null) {
sb.append("block
return;
}
// block info
sb.append(id);
sb.append(':');
sb.append(meta);
sb.append(' ');
String blockName = block.getLocalizedName();
sb.append(blockName);
// item info, if it was mined (this often has more user-friendly information, but sometimes is identical)
sb.append(" ");
int itemDropDamage = block.damageDropped(meta);
if (Item.itemsList[id + 256] != null) {
ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage);
String itemDropName = itemDropStack.getDisplayName();
if (!blockName.equals(itemDropName)) {
sb.append(itemDropName);
}
// item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative
try {
ItemStack itemMetaStack = new ItemStack(id, 1, meta);
String itemMetaName = itemMetaStack.getDisplayName();
if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) {
sb.append(' ');
sb.append(itemMetaName);
}
} catch (Throwable t) {
}
}
if (itemDropDamage != meta) {
sb.append(' ');
sb.append(itemDropDamage);
}
}
// copied from net/minecraft/item/Item since it is needlessly protected
protected MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer, boolean isBucketEmpty)
{
float f = 1.0F;
float f1 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * f;
float f2 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * f;
double d0 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * (double)f;
double d1 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par2EntityPlayer.yOffset;
double d2 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * (double)f;
Vec3 vec3 = par1World.getWorldVec3Pool().getVecFromPool(d0, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI);
float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI);
float f5 = -MathHelper.cos(-f1 * 0.017453292F);
float f6 = MathHelper.sin(-f1 * 0.017453292F);
float f7 = f4 * f5;
float f8 = f3 * f5;
double d3 = 5.0D;
if (par2EntityPlayer instanceof EntityPlayerMP)
{
d3 = ((EntityPlayerMP)par2EntityPlayer).theItemInWorldManager.getBlockReachDistance();
}
Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3);
return par1World.rayTraceBlocks_do_do(vec3, vec31, isBucketEmpty, !isBucketEmpty);
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if (!toggleKeyHandler.showInfo) return;
Minecraft mc = Minecraft.getMinecraft();
GuiScreen screen = mc.currentScreen;
if (screen != null) return;
float partialTickTime = 1;
MovingObjectPosition mop = getMovingObjectPositionFromPlayer(mc.theWorld, mc.thePlayer, true);
String s;
if (mop == null) {
return;
} else if (mop.typeOfHit == EnumMovingObjectType.ENTITY) {
// TODO: find out why this apparently never triggers
s = "entity " + mop.entityHit.getClass().getName();
} else if (mop.typeOfHit == EnumMovingObjectType.TILE) {
int id = mc.thePlayer.worldObj.getBlockId(mop.blockX, mop.blockY, mop.blockZ);
int meta = mc.thePlayer.worldObj.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ);
TileEntity tileEntity = mc.thePlayer.worldObj.blockHasTileEntity(mop.blockX, mop.blockY, mop.blockZ) ? mc.thePlayer.worldObj.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ) : null;
try {
s = describeBlock(id, meta, tileEntity);
} catch (Throwable t) {
s = id + ":" + meta + " - " + t;
t.printStackTrace();
}
} else {
s = "unknown";
}
mc.fontRenderer.drawStringWithShadow(s, x, y, color);
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.RENDER);
}
@Override
public String getLabel() {
return "HighlightTips";
}
} |
package ameba.websocket.internal;
import ameba.util.ClassUtils;
import ameba.websocket.WebSocketException;
import com.google.common.collect.Lists;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.jersey.internal.util.collection.Ref;
import org.glassfish.jersey.process.internal.RequestScope;
import org.glassfish.jersey.server.model.Invocable;
import org.glassfish.jersey.server.model.MethodHandler;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ParameterValueHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.websocket.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.security.PrivilegedAction;
import java.util.List;
/**
* @author icode
*/
public abstract class EndpointDelegate extends Endpoint {
public static final String MESSAGE_HANDLER_WHOLE_OR_PARTIAL = "MessageHandler must implement MessageHandler.Whole or MessageHandler.Partial.";
protected static final InvocationHandler DEFAULT_HANDLER = new InvocationHandler() {
@Override
public Object invoke(Object target, Method method, Object[] args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
boolean isPrivate = Modifier.isPrivate(method.getModifiers());
try {
if (isPrivate)
method.setAccessible(true);
return method.invoke(target, args);
} finally {
if (isPrivate)
method.setAccessible(false);
}
}
};
static final Type MESSAGE_STATE_TYPE = (new TypeLiteral<Ref<MessageState>>() {
}).getType();
private static final Logger logger = LoggerFactory.getLogger(EndpointDelegate.class);
protected List<EventInvocation> onErrorList;
protected List<EventInvocation> onCloseList;
protected List<EventInvocation> onOpenList;
protected Session session;
protected EndpointConfig endpointConfig;
@Inject
private ServiceLocator serviceLocator;
@Inject
private MessageScope messageScope;
@Inject
private RequestScope requestScope;
private RequestScope.Instance reqInstance;
public RequestScope getRequestScope() {
return requestScope;
}
public ServiceLocator getServiceLocator() {
return serviceLocator;
}
public MessageScope getMessageScope() {
return messageScope;
}
protected Ref<MessageState> getMessageStateRef() {
return serviceLocator.<Ref<MessageState>>getService(MESSAGE_STATE_TYPE);
}
private void initMessageScope(MessageState messageState) {
getMessageStateRef().set(messageState);
}
@Override
public final void onOpen(final Session session, final EndpointConfig config) {
this.session = session;
this.endpointConfig = config;
reqInstance = getRequestScope().createInstance();
runInScope(new Runnable() {
@Override
public void run() {
onOpen();
}
});
}
protected void runInScope(final Runnable task) {
requestScope.runInScope(reqInstance, new Runnable() {
@Override
public void run() {
MessageScope.Instance instance = getMessageScope().suspendCurrent();
if (instance == null) {
instance = getMessageScope().createInstance();
} else {
instance.release();
}
getMessageScope().runInScope(instance, task);
}
});
}
protected abstract void onOpen();
protected MessageState getMessageState() {
return getMessageStateRef().get();
}
private List<EventInvocation> findEventInvocation(Class<? extends Annotation> ann, Object... instance) {
List<EventInvocation> invocations = Lists.newArrayList();
if (instance != null) {
for (Object obj : instance) {
Class clazz = obj.getClass();
for (Method m : clazz.getDeclaredMethods()) {
if (m.isAnnotationPresent(ann)) {
invocations.add(EventInvocation.create(m, obj, serviceLocator));
}
}
}
}
return invocations;
}
protected void addMessageHandler(MessageHandler handler) {
final Class<?> handlerClass = ClassUtils.getGenericClass(handler.getClass());
addMessageHandler(handlerClass, handler);
}
@SuppressWarnings("unchecked")
protected <T> void addMessageHandler(Class<T> messageClass, final MessageHandler handler) {
if (handler instanceof MessageHandler.Whole) { //WHOLE MESSAGE HANDLER
serviceLocator.inject(handler);
serviceLocator.postConstruct(handler);
getMessageState().getSession().addMessageHandler(messageClass,
new BasicMessageHandler<T>((MessageHandler.Whole<T>) handler));
} else if (handler instanceof MessageHandler.Partial) { // PARTIAL MESSAGE HANDLER
serviceLocator.inject(handler);
serviceLocator.postConstruct(handler);
getMessageState().getSession().addMessageHandler(messageClass,
new AsyncMessageHandler<T>((MessageHandler.Partial<T>) handler));
} else {
throw new WebSocketException(MESSAGE_HANDLER_WHOLE_OR_PARTIAL);
}
}
protected void initEventList(Object... instance) {
onOpenList = findEventInvocation(OnOpen.class, instance);
onErrorList = findEventInvocation(OnError.class, instance);
onCloseList = findEventInvocation(OnClose.class, instance);
}
protected void emmit(List<EventInvocation> eventInvocations, boolean isException) {
try {
if (eventInvocations != null)
for (EventInvocation invocation : eventInvocations) {
if (isException) {
if (getMessageState().getThrowable() == null)
break;
boolean find = false;
for (Parameter parameter : invocation.getInvocable().getParameters()) {
if (parameter.getRawType().isAssignableFrom(getMessageState().getThrowable().getClass())) {
find = true;
break;
}
}
if (!find)
continue;
}
invocation.invoke();
}
} catch (Throwable t) {
if (!isException)
onError(getMessageState().getSession(), t);
else
logger.error("web socket onError has a error", t);
}
}
@Override
public final void onClose(Session session, final CloseReason closeReason) {
runInScope(new Runnable() {
@Override
public void run() {
getMessageState().change().closeReason(closeReason);
try {
onClose();
} finally {
emmit(onCloseList, false);
}
}
});
reqInstance = null;
}
protected void onClose() {
}
@Override
public final void onError(Session session, Throwable thr) {
if (thr instanceof InvocationTargetException) {
thr = thr.getCause();
}
final Throwable finalThr = thr;
runInScope(new Runnable() {
@Override
public void run() {
getMessageState().change().throwable(finalThr);
try {
onError();
} finally {
emmit(onErrorList, true);
logger.error("web socket has a err", finalThr);
}
}
});
}
protected void onError() {
}
private MessageState.Builder createMessageStateBuilder() {
return MessageState.builder(session, endpointConfig);
}
private static class EventInvocation {
private Invocable invocable;
private List<Factory<?>> argsProviders;
private ServiceLocator serviceLocator;
private Object instance;
private EventInvocation(Invocable invocable, ServiceLocator serviceLocator) {
this.invocable = invocable;
this.serviceLocator = serviceLocator;
}
private static EventInvocation create(Method method, Object parentInstance, ServiceLocator serviceLocator) {
Invocable invo = Invocable.create(MethodHandler.create(parentInstance), method);
return new EventInvocation(invo, serviceLocator);
}
public Invocable getInvocable() {
return invocable;
}
public ServiceLocator getServiceLocator() {
return serviceLocator;
}
public Object getInstance() {
if (instance == null) {
instance = invocable.getHandler().getInstance(serviceLocator);
}
return instance;
}
public List<Factory<?>> getArgsProviders() {
if (argsProviders == null) {
argsProviders = invocable.getValueProviders(serviceLocator);
}
return argsProviders;
}
public void invoke() throws InvocationTargetException, IllegalAccessException {
final Object[] args = ParameterValueHelper.getParameterValues(getArgsProviders());
final Method m = invocable.getHandlingMethod();
new PrivilegedAction() {
@Override
public Object run() {
try {
return DEFAULT_HANDLER.invoke(getInstance(), m, args);
} catch (Throwable t) {
if (t instanceof InvocationTargetException) {
t = t.getCause();
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
throw new WebSocketException(t.getMessage(), t);
}
}
}.run();
}
}
protected class AsyncMessageHandler<M> implements MessageHandler.Partial<M> {
private Partial<M> handler;
public AsyncMessageHandler(Partial<M> handler) {
this.handler = handler;
}
@Override
public void onMessage(final M partialMessage, final boolean last) {
messageScope.runInScope(new Runnable() {
@Override
public void run() {
MessageState state = createMessageStateBuilder()
.message(partialMessage)
.last(last).build();
initMessageScope(state);
handler.onMessage(partialMessage, last);
}
});
}
}
protected class BasicMessageHandler<M> implements MessageHandler.Whole<M> {
private Whole<M> handler;
public BasicMessageHandler(Whole<M> handler) {
this.handler = handler;
}
@Override
public void onMessage(final M partialMessage) {
messageScope.runInScope(new Runnable() {
@Override
public void run() {
MessageState state = createMessageStateBuilder()
.message(partialMessage).build();
initMessageScope(state);
handler.onMessage(partialMessage);
}
});
}
}
} |
package betterwithaddons.block;
import betterwithaddons.BetterWithAddons;
import betterwithaddons.interaction.InteractionBWA;
import betterwithaddons.lib.Reference;
import betterwithaddons.tileentity.TileEntityAqueductWater;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityFallingBlock;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.common.IPlantable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.EnumSet;
import java.util.Random;
import java.util.Set;
public class BlockAqueductWater extends BlockLiquid {
protected BlockAqueductWater() {
super(Material.WATER);
String name = "aqueduct_water";
this.setUnlocalizedName(name);
this.setRegistryName(new ResourceLocation(Reference.MOD_ID, name));
this.setCreativeTab(BetterWithAddons.instance.creativeTab);
this.setTickRandomly(true);
this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, 0));
}
@Override
public boolean hasTileEntity(IBlockState state)
{
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state)
{
return new TileEntityAqueductWater();
}
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos) {
world.scheduleUpdate(pos, this, this.tickRate(world));
}
/*@Nullable
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos)
{
return FULL_BLOCK_AABB;
}*/
/*public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
{
return false;
}*/
public boolean checkAndDry(World world, BlockPos pos, IBlockState state) {
IBlockState bottomstate = world.getBlockState(pos.down());
if(world.isAirBlock(pos.down()) || !(bottomstate.getBlock() instanceof BlockAqueduct))
{
dry(world,pos);
return false;
}
else
{
TileEntity te = world.getTileEntity(pos);
if(te instanceof TileEntityAqueductWater)
{
int currdist = ((TileEntityAqueductWater) te).getDistanceFromSource();
int dist = TileEntityAqueductWater.getMinDistance(world,pos)+1;
if(dist > currdist || dist > InteractionBWA.AQUEDUCT_MAX_LENGTH)
{
dry(world,pos);
return false;
}
((TileEntityAqueductWater) te).setDistanceFromSource(dist);
}
else
{
dry(world,pos);
return false;
}
}
return true;
}
public void dry(World world, BlockPos pos)
{
world.setBlockState(pos, Blocks.FLOWING_WATER.getDefaultState().withProperty(LEVEL, 8));
}
/*public EnumFacing getAdjacentWaterSource(World world, BlockPos pos)
{
for (EnumFacing facing : EnumFacing.HORIZONTALS) {
if(hasWaterSource(world,pos.offset(facing),facing))
return facing;
}
return EnumFacing.NORTH;
}*/
/*public boolean hasWaterSource(World world, BlockPos pos, EnumFacing flowdir)
{
IBlockState state = world.getBlockState(pos);
if(state.getBlock() == this && state.getValue(FLOWFROM) == flowdir.getOpposite())
return false;
return state.getMaterial() == Material.WATER && state.getValue(LEVEL) == 0;
}*/
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) {
int level = state.getValue(LEVEL);
boolean keep = checkAndDry(worldIn, pos, state);
if(!keep)
return;
IBlockState stateBelow = worldIn.getBlockState(pos.down());
if (this.canFlowInto(worldIn, pos.down(), stateBelow)) {
if (level >= 8) {
this.tryFlowInto(worldIn, pos.down(), stateBelow, level);
} else {
this.tryFlowInto(worldIn, pos.down(), stateBelow, level + 8);
}
} else if (level >= 0 && (level == 0 || this.isBlocked(worldIn, pos.down(), stateBelow))) {
Set<EnumFacing> set = this.getPossibleFlowDirections(worldIn, pos);
int nextLevel = level + 1;
if (level >= 8) {
nextLevel = 1;
}
if (nextLevel >= 8) {
return;
}
for (EnumFacing facing : set) {
this.tryFlowInto(worldIn, pos.offset(facing), worldIn.getBlockState(pos.offset(facing)), nextLevel);
}
}
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn));
}
private boolean canFlowInto(World worldIn, BlockPos pos, IBlockState state) {
Material material = state.getMaterial();
return material != this.blockMaterial && material != Material.LAVA && !this.isBlocked(worldIn, pos, state);
}
private void tryFlowInto(World worldIn, BlockPos pos, IBlockState state, int level) {
if (this.canFlowInto(worldIn, pos, state)) {
if (state.getMaterial() != Material.AIR) {
state.getBlock().dropBlockAsItem(worldIn, pos, state, 0);
}
worldIn.setBlockState(pos,
Blocks.FLOWING_WATER.getDefaultState().withProperty(LEVEL, level), 3);
}
}
private boolean isBlocked(World worldIn, BlockPos pos, IBlockState state) {
Block block = worldIn.getBlockState(pos).getBlock();
return !(!(block instanceof BlockDoor) && block != Blocks.STANDING_SIGN && block != Blocks.LADDER
&& block != Blocks.REEDS) || (!(state.getMaterial() != Material.PORTAL
&& state.getMaterial() != Material.STRUCTURE_VOID) || state.getMaterial().blocksMovement());
}
private Set<EnumFacing> getPossibleFlowDirections(World worldIn, BlockPos pos) {
int i = 1000;
Set<EnumFacing> set = EnumSet.noneOf(EnumFacing.class);
for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL) {
BlockPos blockpos = pos.offset(enumfacing);
IBlockState iblockstate = worldIn.getBlockState(blockpos);
if (!this.isBlocked(worldIn, blockpos, iblockstate) && (iblockstate.getMaterial() != this.blockMaterial
|| iblockstate.getValue(LEVEL) > 0)) {
int j;
if (this.isBlocked(worldIn, blockpos.down(), worldIn.getBlockState(blockpos.down()))) {
j = this.getSlopeDistance(worldIn, blockpos, 1, enumfacing.getOpposite());
} else {
j = 0;
}
if (j < i) {
set.clear();
}
if (j <= i) {
set.add(enumfacing);
i = j;
}
}
}
return set;
}
private int getSlopeDistance(World worldIn, BlockPos pos, int distance, EnumFacing calculateFlowCost) {
int i = 1000;
for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL) {
if (enumfacing != calculateFlowCost) {
BlockPos blockpos = pos.offset(enumfacing);
IBlockState iblockstate = worldIn.getBlockState(blockpos);
if (!this.isBlocked(worldIn, blockpos, iblockstate) && (iblockstate.getMaterial() != this.blockMaterial
|| iblockstate.getValue(LEVEL) > 0)) {
if (!this.isBlocked(worldIn, blockpos.down(), iblockstate)) {
return distance;
}
if (distance < 4) {
int j = this.getSlopeDistance(worldIn, blockpos, distance + 1, enumfacing.getOpposite());
if (j < i) {
i = j;
}
}
}
}
}
return i;
}
@Override
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) {
if (!this.checkForMixing(worldIn, pos, state)) {
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn));
}
}
//@Override
//protected Vec3d getFlow(IBlockAccess world, BlockPos pos, IBlockState state) {
//EnumFacing flowfrom = state.getValue(FLOWFROM);
// return new Vec3d(flowfrom.getFrontOffsetX(),flowfrom.getFrontOffsetY(),flowfrom.getFrontOffsetZ());
@Override
public boolean canSustainPlant(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing direction, IPlantable plantable) {
return direction == EnumFacing.UP && plantable.getPlantType(world,pos.up()) == EnumPlantType.Water;
}
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(LEVEL,8);
}
@Override
public int getMetaFromState(IBlockState state)
{
return 0;
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] { LEVEL });
}
} |
package com.JasonILTG.ScienceMod.gui;
import com.JasonILTG.ScienceMod.reference.Textures;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.IInventory;
public class InventoryGUI extends GuiContainer
{
public InventoryGUIContainer container;
public IInventory playerInv;
public InventoryGUI(InventoryGUIContainer container, IInventory playerInv)
{
super(container);
this.playerInv = playerInv;
this.container = container;
this.xSize = Textures.GUI.DEFUALT_GUI_X_SIZE;
this.ySize = Textures.GUI.DEFUALT_GUI_Y_SIZE;
}
public InventoryGUI(InventoryGUIContainer container, IInventory playerInv, int xSize, int ySize)
{
super(container);
this.playerInv = playerInv;
this.xSize = xSize;
this.ySize = ySize;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
{
this.mc.getTextureManager().bindTexture(Textures.GUI.PLAYER_INV);
this.drawTexturedModalRect(this.guiLeft, this.guiTop + this.container.playerInvY - 18, 0, 0, Textures.GUI.PLAYER_INV_WIDTH, Textures.GUI.PLAYER_INV_HEIGHT);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
this.fontRendererObj.drawString(this.playerInv.getDisplayName().getUnformattedText(), 8, this.container.playerInvY - 12, 4210752);
}
} |
package com.akiban.server.encoding;
import java.math.BigDecimal;
import com.akiban.ais.model.Column;
import com.akiban.ais.model.Type;
import com.akiban.server.AkServerUtil;
import com.akiban.server.FieldDef;
import com.akiban.server.Quote;
import com.akiban.server.RowData;
import com.akiban.util.AkibanAppender;
import com.persistit.Key;
public final class DecimalEncoder extends EncodingBase<BigDecimal> {
DecimalEncoder() {
}
@Override
protected Class<BigDecimal> getToObjectClass() {
return BigDecimal.class;
}
// DECIMAL related defines as specified at:
// In short, up to 9 digits get packed into a 4 bytes.
private static final int DECIMAL_TYPE_SIZE = 4;
private static final int DECIMAL_DIGIT_PER = 9;
private static final int DECIMAL_BYTE_DIGITS[] = { 0, 1, 1, 2, 2, 3, 3, 4,
4, 4 };
/**
* Unpack an int from a byte buffer when stored high bytes first.
* Corresponds to the defines in found in MySQL's myisampack.h
*
* @param len
* length to pull out of buffer
* @param buf
* source array to get bytes from
* @param off
* offset to start at in buf
*/
private static int miUnpack(int len, byte[] buf, int off) {
int val = 0;
if (len == 1) {
val = buf[off];
} else if (len == 2) {
val = (buf[off + 0] << 8) | (buf[off + 1] & 0xFF);
} else if (len == 3) {
val = (buf[off + 0] << 16) | ((buf[off + 1] & 0xFF) << 8)
| (buf[off + 2] & 0xFF);
if ((buf[off] & 128) != 0)
val |= (255 << 24);
} else if (len == 4) {
val = (buf[off + 0] << 24) | ((buf[off + 1] & 0xFF) << 16)
| ((buf[off + 2] & 0xFF) << 8) | (buf[off + 3] & 0xFF);
}
return val;
}
/**
* Pack an int into a byte buffer stored with high bytes first.
* Corresponds to the defines in found in MySQL's myisampack.h
*
* @param len
* length to put into buffer
* @param val
* value to store in the buffer
* @param buf
* destination array to put bytes in
* @param offset
* offset to start at in buf
*/
private void miPack(int len, int val, byte[] buf, int offset) {
if (len == 1) {
buf[offset] = (byte) (val);
} else if (len == 2) {
buf[offset + 1] = (byte) (val);
buf[offset + 0] = (byte) (val >> 8);
} else if (len == 3) {
buf[offset + 2] = (byte) (val);
buf[offset + 1] = (byte) (val >> 8);
buf[offset + 0] = (byte) (val >> 16);
} else if (len == 4) {
buf[offset + 3] = (byte) (val);
buf[offset + 2] = (byte) (val >> 8);
buf[offset + 1] = (byte) (val >> 16);
buf[offset + 0] = (byte) (val >> 24);
}
}
private int calcBinSize(int digits) {
int full = digits / DECIMAL_DIGIT_PER;
int partial = digits % DECIMAL_DIGIT_PER;
return (full * DECIMAL_TYPE_SIZE) + DECIMAL_BYTE_DIGITS[partial];
}
private static BigDecimal fromObject(Object obj) {
final BigDecimal value;
if(obj == null) {
value = new BigDecimal(0);
}
else if(obj instanceof BigDecimal) {
value = (BigDecimal)obj;
}
else if(obj instanceof Number || obj instanceof String) {
value = new BigDecimal(obj.toString());
}
else {
throw new IllegalArgumentException("Must be a Number or String: " + obj);
}
return value;
}
@Override
public void toKey(FieldDef fieldDef, RowData rowData, Key key) {
final long location = fieldDef.getRowDef().fieldLocation(rowData,
fieldDef.getFieldIndex());
if (location == 0) {
key.append(null);
} else {
AkibanAppender sb = AkibanAppender.of(new StringBuilder());
toString(fieldDef, rowData, sb, Quote.NONE);
BigDecimal decimal = new BigDecimal(sb.toString());
key.append(decimal);
}
}
@Override
public void toKey(FieldDef fieldDef, Object value, Key key) {
if(value == null) {
key.append(null);
}
else {
BigDecimal dec = fromObject(value);
key.append(dec);
}
}
/**
* Note: Only a "good guess". No way to determine how much room
* key.append(BigDecimal) will take currently.
*/
@Override
public long getMaxKeyStorageSize(final Column column) {
return column.getMaxStorageSize();
}
@Override
public int fromObject(FieldDef fieldDef, Object value, byte[] dest, int offset) {
final String from = fromObject(value).toPlainString();
final int mask = (from.charAt(0) == '-') ? -1 : 0;
int fromOff = 0;
if (mask != 0)
++fromOff;
int signSize = mask == 0 ? 0 : 1;
int periodIndex = from.indexOf('.');
final int intCnt;
final int fracCnt;
if (periodIndex == -1) {
intCnt = from.length() - signSize;
fracCnt = 0;
}
else {
intCnt = periodIndex - signSize;
fracCnt = from.length() - intCnt - 1 - signSize;
}
final int intFull = intCnt / DECIMAL_DIGIT_PER;
final int intPart = intCnt % DECIMAL_DIGIT_PER;
final int fracFull = fracCnt / DECIMAL_DIGIT_PER;
final int fracPart = fracCnt % DECIMAL_DIGIT_PER;
final int intSize = calcBinSize(intCnt);
final int declPrec = fieldDef.getTypeParameter1().intValue();
final int declScale = fieldDef.getTypeParameter2().intValue();
final int declIntSize = calcBinSize(declPrec - declScale);
final int declFracSize = calcBinSize(declScale);
int toItOff = offset;
int toEndOff = offset + declIntSize + declFracSize;
for (int i = 0; (intSize + i) < declIntSize; ++i)
dest[toItOff++] = (byte) mask;
int sum = 0;
// Partial integer
if (intPart != 0) {
for (int i = 0; i < intPart; ++i) {
sum *= 10;
sum += (from.charAt(fromOff + i) - '0');
}
int count = DECIMAL_BYTE_DIGITS[intPart];
miPack(count, sum ^ mask, dest, toItOff);
toItOff += count;
fromOff += intPart;
}
// Full integers
for (int i = 0; i < intFull; ++i) {
sum = 0;
for (int j = 0; j < DECIMAL_DIGIT_PER; ++j) {
sum *= 10;
sum += (from.charAt(fromOff + j) - '0');
}
int count = DECIMAL_TYPE_SIZE;
miPack(count, sum ^ mask, dest, toItOff);
toItOff += count;
fromOff += DECIMAL_DIGIT_PER;
}
// Move past decimal point (or to end)
++fromOff;
// Full fractions
for (int i = 0; i < fracFull; ++i) {
sum = 0;
for (int j = 0; j < DECIMAL_DIGIT_PER; ++j) {
sum *= 10;
sum += (from.charAt(fromOff + j) - '0');
}
int count = DECIMAL_TYPE_SIZE;
miPack(count, sum ^ mask, dest, toItOff);
toItOff += count;
fromOff += DECIMAL_DIGIT_PER;
}
// Fraction left over
if (fracPart != 0) {
sum = 0;
for (int i = 0; i < fracPart; ++i) {
sum *= 10;
sum += (from.charAt(fromOff + i) - '0');
}
int count = DECIMAL_BYTE_DIGITS[fracPart];
miPack(count, sum ^ mask, dest, toItOff);
toItOff += count;
}
while (toItOff < toEndOff)
dest[toItOff++] = (byte) mask;
dest[offset] ^= 0x80;
return declIntSize + declFracSize;
}
@Override
public void toString(FieldDef fieldDef, RowData rowData,
AkibanAppender sb, final Quote quote) {
decodeAndParse(fieldDef, rowData, sb);
}
/**
* Decodes the field into the given StringBuilder and then returns the parsed BigDecimal.
* (Always parsing the BigDecimal lets us fail fast if there was a decoding error.)
* @param fieldDef the field to decode
* @param rowData the rowdata taht contains the field
* @param sb the stringbuilder to use
* @return the parsed BigDecimal
* @throws NullPointerException if any arguments are null
* @throws EncodingException if the string can't be parsed to a BigDecimal; the exception's cause will be a
* NumberFormatException
*/
private static void decodeAndParse(FieldDef fieldDef, RowData rowData, AkibanAppender sb) {
final int precision = fieldDef.getTypeParameter1().intValue();
final int scale = fieldDef.getTypeParameter2().intValue();
final long locationAndOffset = fieldDef.getRowDef().fieldLocation(rowData, fieldDef.getFieldIndex());
final int location = (int) locationAndOffset;
final byte[] from = rowData.getBytes();
try {
decodeAndParse(from, location, precision, scale, sb);
} catch (NumberFormatException e) {
StringBuilder errSb = new StringBuilder();
errSb.append("in field[");
errSb.append(fieldDef.getRowDef().getRowDefId()).append('.').append(fieldDef.getFieldIndex());
errSb.append(" decimal(");
errSb.append(fieldDef.getTypeParameter1()).append(',').append(fieldDef.getTypeParameter2());
errSb.append(")] 0x");
final int bytesLen = (int) (locationAndOffset >>> 32);
AkServerUtil.hex(AkibanAppender.of(errSb), rowData.getBytes(), location, bytesLen);
errSb.append(": ").append( e.getMessage() );
throw new EncodingException(errSb.toString(), e);
}
}
/**
* Decodes bytes into the given StringBuilder and returns the parsed BigDecimal.
* @param from the bytes to parse
* @param location the starting offset within the "from" array
* @param precision the decimal's precision
* @param scale the decimal's scale
* @param sb the StringBuilder to write to
* @return the parsed BigDecimal
* @throws NullPointerException if from or sb are null
* @throws NumberFormatException if the parse failed; the exception's message will be the String that we
* tried to parse
*/
static void decodeAndParse(byte[] from, int location, int precision, int scale, AkibanAppender sb) {
final int intCount = precision - scale;
final int intFull = intCount / DECIMAL_DIGIT_PER;
final int intPartial = intCount % DECIMAL_DIGIT_PER;
final int fracFull = scale / DECIMAL_DIGIT_PER;
final int fracPartial = scale % DECIMAL_DIGIT_PER;
int curOff = location;
final int mask = (from[curOff] & 0x80) != 0 ? 0 : -1;
// Flip high bit during processing
from[curOff] ^= 0x80;
if (mask != 0)
sb.append('-');
boolean hadOutput = false;
if (intPartial != 0) {
int count = DECIMAL_BYTE_DIGITS[intPartial];
int x = miUnpack(count, from, curOff) ^ mask;
curOff += count;
if (x != 0) {
hadOutput = true;
sb.append(x);
}
}
for (int i = 0; i < intFull; ++i) {
int x = miUnpack(DECIMAL_TYPE_SIZE, from, curOff) ^ mask;
curOff += DECIMAL_TYPE_SIZE;
if (hadOutput) {
sb.append(String.format("%09d", x));
} else if (x != 0) {
hadOutput = true;
sb.append(x);
}
}
if (fracFull + fracPartial > 0) {
if (hadOutput) {
sb.append('.');
}
else {
sb.append("0.");
}
}
else if(hadOutput == false)
sb.append('0');
for (int i = 0; i < fracFull; ++i) {
int x = miUnpack(DECIMAL_TYPE_SIZE, from, curOff) ^ mask;
curOff += DECIMAL_TYPE_SIZE;
sb.append(String.format("%09d", x));
}
if (fracPartial != 0) {
int count = DECIMAL_BYTE_DIGITS[fracPartial];
int x = miUnpack(count, from, curOff) ^ mask;
int width = scale - (fracFull * DECIMAL_DIGIT_PER);
sb.append(String.format("%0" + width + "d", x));
}
// Restore high bit
from[location] ^= 0x80;
}
@Override
public BigDecimal toObject(FieldDef fieldDef, RowData rowData) throws EncodingException {
StringBuilder sb = new StringBuilder(fieldDef.getMaxStorageSize());
decodeAndParse(fieldDef, rowData, AkibanAppender.of(sb));
final String createdStr = sb.toString();
try {
assert createdStr.isEmpty() == false;
return new BigDecimal(createdStr);
} catch (NumberFormatException e) {
throw new NumberFormatException(createdStr);
}
}
@Override
public int widthFromObject(final FieldDef fieldDef, final Object value) {
return fieldDef.getMaxStorageSize();
}
@Override
public boolean validate(Type type) {
return type.fixedSize() && type.nTypeParameters() == 2;
}
} |
package com.blamejared.mcbot.commands;
import com.blamejared.mcbot.commands.api.*;
import com.google.common.collect.Lists;
import sx.blah.discord.handle.obj.IMessage;
import java.util.*;
@Command
public class CommandSlap extends CommandBase {
private List<String> options = Lists.newArrayList();
private Random rand = new Random();
public CommandSlap() {
super("slap", false);
options.add(" with a large trout!");
options.add(" with a big bat!");
options.add(" with a frying pan!");
options.add(" like a little bitch!");
}
@Override
public void process(IMessage message, List<String> flags, List<String> args) throws CommandException {
if(args.size() < 1) {
throw new CommandException("Not enough arguments.");
}
StringBuilder builder = new StringBuilder(message.getAuthor().getName());
builder.append(" slapped ").append(args.get(0)).append(options.get(rand.nextInt(options.size())));
if(!validateMessage(builder.toString())){
message.getChannel().sendMessage("Unable to send a message mentioning a user!");
return;
}
message.getChannel().sendMessage(builder.toString());
}
public String getUsage() {
return "!slap <user>";
}
} |
package com.boundary.sdk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import java.net.ConnectException;
//import java.nio.channels.ClosedChannelException;
/**
* Creates a route that checks periodically checks a port on a host
* to see if it available.
*
* @author davidg
*
*/
public class SocketPollerRouteBuilder extends UDPRouteBuilder {
@SuppressWarnings("unused")
private static Logger LOG = LoggerFactory.getLogger(SocketPollerRouteBuilder.class);
private String cron;
public SocketPollerRouteBuilder() {
// Default to poll every minute
this.cron = "0/60+*+*+*+*+?";
}
/**
*
* @param cron
*/
public void setCron(String cron) {
}
@SuppressWarnings("unchecked")
@Override
public void configure() throws Exception {
String socketUri = String.format("netty:tcp://" + this.host + ":" + this.port + "?sync=false");
String timerUri = String.format("quartz://" + this.routeId + "?cron=" + this.cron);
LOG.info("Polling host: " + this.host + " on port: " + this.port + " with this schedule: " + this.cron);
from(timerUri)
.routeId(this.routeId)
// These are the exception classes that indicate the connection failed.
.onException(java.net.ConnectException.class,java.nio.channels.ClosedChannelException.class)
.handled(true) // Mark these exceptions as handled
.bean(HostConnectionFailure.class)
.to("log:com.boundary.sdk.SocketPollerRouteBuilder?level=INFO&showHeaders=true&showBody=true&multiline=true")
.marshal().serialization() // Marshal the RawEvent before sending
.to(this.toUri)
.end()
.transform(constant("")) // Netty requires a body to initiate the connection. Set body to an empty string.
.to(socketUri)
.to("log:com.boundary.sdk.SocketPollerRouteBuilder?level=INFO&showHeaders=true&showBody=true&multiline=true")
// Connection succeeds
;
}
} |
package com.bupt.poirot.z3.parseAndDeduceOWL;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.BoolSort;
import com.microsoft.z3.Context;
import com.microsoft.z3.Expr;
import com.microsoft.z3.FuncDecl;
import com.microsoft.z3.Quantifier;
import com.microsoft.z3.Solver;
import com.microsoft.z3.Sort;
import com.microsoft.z3.Status;
import org.semanticweb.HermiT.model.DLClause;
public class Main {
public static Map<String, FuncDecl> stringToFuncMap = new HashMap<>();
public static Pattern pattern = Pattern.compile("(.+)\\((.+?)\\)");
public static int begin = 0;
public static BoolExpr mkQuantifier(Context ctx, String string1, String string2, Set<String> sortSet, Set<String> quantifierSet) {
Map<String, String> varaibleNameToExprName = new HashMap<>();
String domain, formua;
if (string1.contains("atLeast") || string1.contains("atMost") || string1.contains(" v ")) {
domain = string2;
formua = string1;
} else if (string2.contains("atLeast") || string2.contains("atMost") || string2.contains(" v ")) {
domain = string1;
formua = string2;
} else {
if (string1.contains(",")) {
domain = string2;
formua = string1;
} else {
domain = string1;
formua = string2;
}
}
BoolExpr expression = null;
String[] strings = domain.split(", ");
for (String str : strings) {
if (str.equals("<http://www.semanticweb.org/traffic-ontology#hasLatitude>(X,Y")) {
System.out.println("mark : " + expression);
}
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String funcString = matcher.group(1);
FuncDecl funcDecl = null;
if (stringToFuncMap.containsKey(funcString)) {
funcDecl = stringToFuncMap.get(funcString);
}
String string = matcher.group(2);
String[] variables = string.split(",");
Sort[] domains = new Sort[variables.length];
if (funcDecl != null) {
domains = funcDecl.getDomain();
} else {
// need to mk FuncDecl
for (int i = 0; i < domains.length; i++) {
domains[i] = ctx.mkUninterpretedSort(variables[i]);
}
funcDecl = ctx.mkFuncDecl(funcString, domains, ctx.getBoolSort());
stringToFuncMap.put(funcString, funcDecl);
}
Expr[] exprs = new Expr[variables.length];
for (int i = 0; i < exprs.length; i++) {
String variableName = varaibleNameToExprName.containsKey(variables[i]) ? varaibleNameToExprName.get(variables[i]) :variables[i] + (begin++);
varaibleNameToExprName.put(variables[i], variableName);
exprs[i] = ctx.mkConst(variables[i], domains[i]);
}
if (expression == null) {
expression = (BoolExpr)ctx.mkApp(funcDecl, exprs);
} else {
expression = ctx.mkAnd(expression, (BoolExpr)ctx.mkApp(funcDecl, exprs));
}
}
}
BoolExpr formuaExpr = null;
for (String s : formua.split(" v ")) {
BoolExpr expression2 = null;
strings = s.split(", ");
for (String str : strings) {
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String funcString = matcher.group(1);
FuncDecl funcDecl = null;
if (stringToFuncMap.containsKey(funcString)) {
funcDecl = stringToFuncMap.get(funcString);
}
String string = matcher.group(2);
String[] variables = string.split(",");
Sort[] domains = new Sort[variables.length];
if (funcDecl != null) {
domains = funcDecl.getDomain();
} else {
// need to mk FuncDecl
for (int i = 0; i < domains.length; i++) {
domains[i] = ctx.mkUninterpretedSort(variables[i]);
}
funcDecl = ctx.mkFuncDecl(funcString, domains, ctx.getBoolSort());
stringToFuncMap.put(funcString, funcDecl);
}
Expr[] exprs = new Expr[variables.length];
for (int i = 0; i < exprs.length; i++) {
String variableName = varaibleNameToExprName.containsKey(variables[i]) ? varaibleNameToExprName.get(variables[i]) : variables[i] + (begin++);
varaibleNameToExprName.put(variables[i], variableName);
System.out.println(variableName);
exprs[i] = ctx.mkConst(variables[i], domains[i]);
}
if (expression2 == null) {
expression2 = (BoolExpr)ctx.mkApp(funcDecl, exprs);
} else {
expression2 = ctx.mkAnd(expression2, (BoolExpr)ctx.mkApp(funcDecl, exprs));
}
}
}
if (expression2 == null) {
continue;
}
if (formuaExpr == null) {
formuaExpr = expression2;
} else {
formuaExpr = ctx.mkOr(formuaExpr, expression2);
}
}
System.out.println("expression : " + expression);
System.out.println("expression2 : " + formuaExpr);
if (expression == null || formuaExpr == null) {
return null;
}
BoolExpr finalExpr = ctx.mkImplies(expression, formuaExpr);
System.out.println(finalExpr);
System.out.println();
// Quantifier quantifier = null;
// return quantifier;
return finalExpr;
}
public static void main(String[] args) {
System.out.println("begin");
// File file = new File("data/ontologies/warnSchemaTest0.xml");
File file = new File("data/schema.owl");
Set<DLClause> set = ParseOWL.parseOwl(file);
System.out.println(set.size());
Set<String> quantifiersSet = new HashSet<>();
Set<String> sortSet = new HashSet<>();
Context context = new Context();
Solver solver = context.mkSolver();
for (DLClause dlClause: set) {
String dlClauseString = dlClause.toString();
String[] strings = dlClauseString.split(":-");
System.out.println(dlClauseString);
BoolExpr boolExpr = mkQuantifier(context, strings[0], strings[1], sortSet, quantifiersSet);
if (boolExpr != null) {
solver.add(boolExpr);
}
}
if (solver.check() == Status.SATISFIABLE) {
System.out.println(Status.SATISFIABLE);
// System.out.println(solver.getModel());
} else {
System.out.println(Status.UNSATISFIABLE);
}
}
} |
package com.buuz135.industrial.item;
import com.buuz135.industrial.proxy.ItemRegistry;
import com.buuz135.industrial.utils.RecipeUtils;
import lombok.Getter;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.registries.IForgeRegistry;
public class LaserLensItem extends IFCustomItem {
@Getter
private boolean inverted;
public LaserLensItem(boolean inverted) {
super("laser_lens" + (inverted ? "_inverted" : ""));
setMaxStackSize(1);
setHasSubtypes(true);
this.inverted = inverted;
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
if (isInCreativeTab(tab))
for (int i = 0; i < 16; ++i) subItems.add(new ItemStack(this, 1, i));
}
@Override
public void register(IForgeRegistry<Item> items) {
super.register(items);
}
public void createRecipe() {
for (int i = 0; i < 16; ++i)
RecipeUtils.addShapedRecipe(new ItemStack(this, 1, i), " i ", "ipi", " i ", 'i', inverted ? new ItemStack(Items.IRON_INGOT) : new ItemStack(ItemRegistry.pinkSlime),
'p', new ItemStack(Blocks.STAINED_GLASS_PANE, 1, i));
}
@Override
public void registerRender() {
for (int i = 0; i < 16; ++i)
ModelLoader.setCustomModelResourceLocation(this, i, new ModelResourceLocation(this.getRegistryName().toString() + i, "inventory"));
}
@Override
public String getItemStackDisplayName(ItemStack stack) {
return new TextComponentTranslation("item.fireworksCharge." + EnumDyeColor.byMetadata(stack.getMetadata()).getUnlocalizedName().replaceAll("_", "")).getFormattedText() + " " + super.getItemStackDisplayName(stack);
}
} |
package com.carlosefonseca.common.utils;
import android.os.Build;
import android.util.SparseArray;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.carlosefonseca.common.utils.CodeUtils.LONG_L;
import static com.carlosefonseca.common.utils.CodeUtils.SIDE_T;
@SuppressWarnings("UnusedDeclaration")
public final class ListUtils {
private ListUtils() {}
public static <T> T first(List<T> list) {
return list.get(0);
}
public static <T> T last(List<T> list) {
return list.get(list.size() - 1);
}
public static <T> List<T> firsts(List<T> list, int length) {
return list.subList(0, Math.min(list.size(), length));
}
public static <T> List<T> lasts(List<T> list, int length) {
return list.subList(Math.max(list.size() - length, 0), list.size());
}
/**
* Moves an element to the index 0. If the element doesn't exist or already is at index 0,
* nothing is done to the list.
* Rotates right a subset of the list from index 0 to the element.
*/
public static <T> void moveToTop(List<T> list, T element) {
final int i = list.indexOf(element);
if (i > 0) Collections.rotate(list.subList(0, i + 1), 1);
}
/**
* Returns a list containing all objects.
* @see #list(java.util.Collection[])
*/
@SafeVarargs
public static <T> ArrayList<T> list(T... objects) {
ArrayList<T> list = new ArrayList<>();
Collections.addAll(list, objects);
return list;
}
/**
* Merges elements of all lists into a single list.
* @see #list(Object[])
*/
@SafeVarargs
public static <T> ArrayList<T> merge(Collection<T>... lists) {
ArrayList<T> list = new ArrayList<>();
for (Collection<T> ts : lists) list.addAll(ts);
return list;
}
/**
* Returns a copy of the specified list with object appended to it.
* (Not a copy if original is a List and supports adding).
*/
@SafeVarargs
public static <T,L extends List<T>> L add(Collection<T> list, T... objects) {
if (list instanceof List) {
try {
list.addAll(Arrays.asList(objects));
return (L) list;
} catch (UnsupportedOperationException ignored) {
}
}
final ArrayList<T> list1 = new ArrayList<>(list);
list1.addAll(Arrays.asList(objects));
return (L) list1;
}
public static <T> SparseArray<T> copySparseArray(SparseArray<T> original) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return original.clone();
} else {
SparseArray<T> newArray = new SparseArray<T>(original.size());
for (int i = 0; i < original.size(); i++) {
newArray.put(original.keyAt(i), original.valueAt(i));
}
return newArray;
}
}
/**
* Iterates through the sparse array and adds the contents to the list.
*
* @param list The list that will receive the items.
* @param array The sparse array that contains the elements.
*/
public static <T> List<T> sparseArrayToList(List<T> list, SparseArray<? extends T> array) {
for (int i = 0; i < array.size(); i++) {
list.add(array.valueAt(i));
}
return list;
}
public static void removeNullElements(ArrayList<?> arrayList) {
for (int i = arrayList.size() - 1; i >= 0; i
if (arrayList.get(i) == null) {
arrayList.remove(i);
}
}
}
public static <T> List<T> defaultIfNull(@Nullable List<T> list) {
return list == null ? new ArrayList<T>() : list;
}
public static <T, C extends Collection<T>> ArrayList<T> flatten(Collection<C> listOfLists) {
final ArrayList<T> list = new ArrayList<>();
for (Collection<T> listOfT : listOfLists) list.addAll(listOfT);
return list;
}
public static class ListComparator<T> {
private static final java.lang.String TAG = CodeUtils.getTag(ListComparator.class);
public final List<T> newObjects; // to create
public final List<T> sameObjects; // to do nothing
@Nullable public final List<T> updatedObjects; // to do nothing
public final List<T> oldObjects; // to delete
protected ListComparator(List<T> newObjects, List<T> sameObjects, List<T> oldObjects, @Nullable List<T> updatedObjects) {
this.newObjects = newObjects;
this.sameObjects = sameObjects;
this.updatedObjects = updatedObjects;
this.oldObjects = oldObjects;
}
/**
* Processes two lists and separates the items only on the first, the items only on the second and items on both. If an
* item is on both, uses {@link java.lang.Comparable#compareTo(Object)} to check if the item on the second is greater than
* the one on the first list.
*
* @param <T> Should implement {@link java.lang.Object#equals(Object)}
*/
public static <T extends Comparable<T>> ListComparator<T> computeWithUpdates(Collection<T> existingStuff,
Collection<T> newStuff) {
ArrayList<T> oldObjects = new ArrayList<>(existingStuff);
ArrayList<T> newObjects = new ArrayList<>();
ArrayList<T> updatedObjects = new ArrayList<>();
ArrayList<T> sameObjects = new ArrayList<>();
for (T t : newStuff) {
final int i = oldObjects.indexOf(t);
if (i < 0) {
newObjects.add(t);
} else {
final T oldT = oldObjects.remove(i);
final int compareTo = oldT.compareTo(t);
if (compareTo == 0) {
sameObjects.add(t);
} else if (compareTo > 0) {
updatedObjects.add(t);
} else {
Log.w(TAG, "Existing object " + oldT + " is newer than 'new' object " + t);
}
}
}
return new ListComparator<>(newObjects, sameObjects, oldObjects, updatedObjects);
}
protected void handleEqualObjects(T oldT, T t) {
sameObjects.add(t);
}
/**
* Processes two lists and separates the items only on the first, the items only on the second and items on both.
*
* @param <T> Should implement {@link java.lang.Object#equals(Object)}
* @see {@link #computeWithUpdates(java.util.Collection, java.util.Collection)}
*/
public static <T> ListComparator<T> compute(Collection<T> existingStuff, Collection<T> newStuff) {
ArrayList<T> oldObjects = new ArrayList<>(existingStuff);
ArrayList<T> newObjects = new ArrayList<>();
ArrayList<T> sameObjects = new ArrayList<>();
for (T t : newStuff) {
if (oldObjects.remove(t)) {
sameObjects.add(t);
} else {
newObjects.add(t);
}
}
return new ListComparator<>(newObjects, sameObjects, oldObjects, null);
}
/**
* Same as {@link #compute(java.util.Collection, java.util.Collection)} but on "sameObjects" the ones on the "existing
* stuff" list are returned.
*/
public static <T> ListComparator<T> compute2(Collection<T> existingStuff, Collection<T> newStuff) {
ArrayList<T> oldObjects = new ArrayList<>(existingStuff);
ArrayList<T> newObjects = new ArrayList<>();
ArrayList<T> sameObjects = new ArrayList<>();
for (T t : newStuff) {
final int index = oldObjects.indexOf(t);
if (index >= 0) {
sameObjects.add(oldObjects.remove(index));
} else {
newObjects.add(t);
}
}
return new ListComparator<>(newObjects, sameObjects, oldObjects, null);
}
@Override
public String toString() {
return "ListComparator of " + getTypeName() + "\n" +
SIDE_T + " NEW: " + newObjects + "\n" +
SIDE_T + " SAME: " + sameObjects + "\n" +
LONG_L + " OLD: " + oldObjects;
}
protected String getTypeName() {
final T instance = !newObjects.isEmpty()
? newObjects.get(0)
: !oldObjects.isEmpty() ? oldObjects.get(0) : !sameObjects.isEmpty() ? sameObjects.get(0) : null;
return instance != null ? instance.getClass().getSimpleName() : "<Empty List?>";
}
public boolean hasChanges() {
return !newObjects.isEmpty() || !oldObjects.isEmpty() ||
(updatedObjects != null && !updatedObjects.isEmpty());
}
}
public static class ListComparator2<T extends Comparable<T>> {
private static final java.lang.String TAG = CodeUtils.getTag(ListComparator.class);
public final List<T> newObjects = new ArrayList<>(); // to create
public final List<T> sameObjects = new ArrayList<>(); // to do nothing
public final List<T> updatedObjects = new ArrayList<>(); // to do nothing
public final List<T> oldObjects; // to delete
public ListComparator2(Collection<T> oldItems) {
oldObjects = new ArrayList<>(oldItems);
}
/**
* Processes two lists and separates the items only on the first, the items only on the second and items on both. If an
* item is on both, uses {@link java.lang.Comparable#compareTo(Object)} to check if the item on the second is greater
* than
* the one on the first list.
*/
public ListComparator2<T> compare(Collection<T> newStuff) {
for (T t : newStuff) {
final int i = oldObjects.indexOf(t);
if (i < 0) {
newObjects.add(t);
} else {
// object already exists by equals()
final T oldT = oldObjects.remove(i);
final int compareTo = oldT.compareTo(t);
if (compareTo == 0) {
handleEqualObjects(oldT, t);
} else if (compareTo < 0) { // oldT is less than (new) t
updatedObjects.add(t);
} else {
Log.w(TAG, "Existing object " + oldT + " is newer than 'new' object " + t);
}
}
}
return this;
}
protected void handleEqualObjects(T oldT, T t) {
sameObjects.add(t);
}
@Override
public String toString() {
return "ListComparator of " + getTypeName() + "\n" +
SIDE_T + " NEW: " + newObjects + "\n" +
SIDE_T + " SAME: " + sameObjects + "\n" +
LONG_L + " OLD: " + oldObjects;
}
protected String getTypeName() {
final T instance = !newObjects.isEmpty()
? newObjects.get(0)
: !oldObjects.isEmpty() ? oldObjects.get(0) : !sameObjects.isEmpty() ? sameObjects.get(0) : null;
return instance != null ? instance.getClass().getSimpleName() : "<Empty List?>";
}
}
public interface Id<T> {
T getId();
}
public static <T> ArrayList<T> getIds(Iterable<? extends Id<T>> list) {
final ArrayList<T> integers = new ArrayList<>();
for (Id item : list) //noinspection unchecked
integers.add((T) item.getId());
return integers;
}
public static boolean containsIgnoreCase(Collection<String> list, String string) {
for (String s : list) {
if (s.equalsIgnoreCase(string)) {
return true;
}
}
return false;
}
} |
package com.carlosefonseca.common.utils;
import android.os.Handler;
import android.os.Looper;
import bolts.AggregateException;
import bolts.Continuation;
import bolts.Task;
import org.jetbrains.annotations.Nullable;
public final class TaskUtils {
private static final String TAG = CodeUtils.getTag(TaskUtils.class);
public static final Continuation<Void, Void> LogErrorContinuation = new Continuation<Void, Void>() {
@Override
public Void then(Task<Void> voidTask) throws Exception {
logTaskError(voidTask);
return null;
}
};
public static boolean logTaskError(Task<?> voidTask) {
final Exception error = voidTask.getError();
logAggregateException(error);
return error != null;
}
public static boolean hasErrors(String tag, String msg, Task<String> task) {
final Exception error = task.getError();
if (error != null) {
Log.w(tag, msg);
TaskUtils.logAggregateException(error);
return true;
}
return false;
}
public static void logAggregateException(Exception error) {
if (error != null) {
Log.w(TAG, error);
if (error instanceof AggregateException) {
for (Exception exception : ((AggregateException) error).getErrors()) {
Log.w(TAG, "
Log.w(TAG, exception);
}
}
}
}
private TaskUtils() {}
public static <T> Task<T> runTaskWithTimeout(Task<T> t, int timeout) {
final Task<T>.TaskCompletionSource taskCompletionSource = Task.create();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
taskCompletionSource.trySetError(new RuntimeException("Timeout!"));
}
}, timeout);
t.continueWith(new Continuation<T, Object>() {
@Nullable
@Override
public T then(Task<T> task) throws Exception {
taskCompletionSource.setResult(task.getResult());
return null;
}
});
return taskCompletionSource.getTask();
}
public static <T> Continuation<T, T> getPassThruLogErrorContinuation() {
return new Continuation<T, T>() {
@Override
public T then(Task<T> task) throws Exception {
final Exception error = task.getError();
if (error != null) {
Log.w(TAG, "Errors during task execution", error);
if (error instanceof AggregateException) {
for (Exception exception : ((AggregateException) error).getErrors()) {
Log.w(TAG, exception);
Log.w(TAG, "
}
}
throw error;
} else {
return task.getResult();
}
}
};
}
} |
package com.codingchili.core.Storage;
import io.vertx.core.*;
import io.vertx.core.json.JsonObject;
import java.io.IOException;
import java.util.Optional;
import com.codingchili.core.Configuration.Strings;
import com.codingchili.core.Context.StorageContext;
import com.codingchili.core.Files.JsonFileStore;
/**
* @author Robin Duda
* <p>
* Map backed by a json-file.
*/
public class AsyncJsonMap<Key, Value> implements AsyncStorage<Key, Value> {
private static final String ASYNCJSONMAP_WORKERS = "asyncjsonmap.workers";
private final WorkerExecutor fileWriter;
private JsonObject db;
private StorageContext<Value> context;
public AsyncJsonMap(Future<AsyncStorage<Key, Value>> future, StorageContext<Value> context) {
this.context = context;
this.fileWriter = context.vertx().createSharedWorkerExecutor(ASYNCJSONMAP_WORKERS);
try {
db = JsonFileStore.readObject(context.DB());
} catch (IOException e) {
db = new JsonObject();
context.console().log(Strings.getFileReadError(context.DB()));
}
future.complete(this);
}
@Override
public void get(Key key, Handler<AsyncResult<Value>> handler) {
Optional<Value> value = get(key);
if (value.isPresent()) {
handler.handle(Future.succeededFuture(value.get()));
} else {
handler.handle(Future.succeededFuture());
}
}
@Override
public void put(Key key, Value value, Handler<AsyncResult<Void>> handler) {
put(key, value);
handler.handle(Future.succeededFuture());
}
@Override
public void put(Key key, Value value, long ttl, Handler<AsyncResult<Void>> handler) {
put(key, value, handler);
context.timer(ttl, event -> remove(key));
}
@Override
public void putIfAbsent(Key key, Value value, Handler<AsyncResult<Value>> handler) {
Optional<Value> current = get(key);
if (current.isPresent()) {
handler.handle(Future.succeededFuture(current.get()));
} else {
put(key, value);
handler.handle(Future.succeededFuture());
}
}
@Override
public void putIfAbsent(Key key, Value value, long ttl, Handler<AsyncResult<Value>> handler) {
putIfAbsent(key, value, handler);
context.timer(ttl, event -> remove(key));
}
@Override
public void remove(Key key, Handler<AsyncResult<Value>> handler) {
Optional<Value> current = get(key);
if (current.isPresent()) {
handler.handle(Future.succeededFuture(current.get()));
remove(key);
} else {
handler.handle(Future.succeededFuture());
}
}
@Override
public void removeIfPresent(Key key, Value value, Handler<AsyncResult<Boolean>> handler) {
Optional<Value> current = get(key);
if (current.isPresent() && current.get().equals(value)) {
remove(key);
handler.handle(Future.succeededFuture(true));
} else {
handler.handle(Future.succeededFuture(false));
}
}
@Override
public void replace(Key key, Value value, Handler<AsyncResult<Value>> handler) {
Optional<Value> current = get(key);
if (current.isPresent()) {
handler.handle(Future.succeededFuture(current.get()));
} else {
put(key, value);
handler.handle(Future.succeededFuture());
}
}
@Override
public void replaceIfPresent(Key key, Value oldValue, Value newValue, Handler<AsyncResult<Boolean>> handler) {
Optional<Value> current = get(key);
if (current.isPresent()) {
if (current.get().equals(oldValue)) {
put(key, newValue);
handler.handle(Future.succeededFuture(true));
} else {
handler.handle(Future.succeededFuture(false));
}
} else {
handler.handle(Future.succeededFuture(false));
}
}
@Override
public void clear(Handler<AsyncResult<Void>> handler) {
db.clear();
handler.handle(Future.succeededFuture());
save();
}
@Override
public void size(Handler<AsyncResult<Integer>> handler) {
handler.handle(Future.succeededFuture(db.size()));
}
private Optional<Value> get(Key key) {
Value value = context.toValue(db.getJsonObject(key.toString()));
if (value == null) {
return Optional.empty();
} else {
return Optional.of(value);
}
}
private void put(Key key, Value value) {
db.put(key.toString(), context.toJson(value));
save();
}
private void remove(Key key) {
db.remove(key.toString());
save();
}
private void save() {
fileWriter.executeBlocking(execute -> {
JsonFileStore.writeObject(db, context.DB());
}, true, result -> {
});
}
} |
package com.conveyal.data.census;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.GetObjectRequest;
import java.io.IOException;
import java.io.InputStream;
/**
* A seamless data source based on storage in Amazon S3.
*/
public class S3SeamlessSource extends SeamlessSource {
private static AmazonS3 s3;
public final String region;
public final String bucketName;
public S3SeamlessSource(String region, String bucketName) {
this.region = region;
this.bucketName = bucketName;
this.s3 = AmazonS3ClientBuilder.standard()
.withRegion(region)
.build();
}
@Override
protected InputStream getInputStream(int x, int y) throws IOException {
try {
GetObjectRequest req = new GetObjectRequest(bucketName, String.format("%d/%d.pbf.gz", x, y));
// the LODES bucket is requester-pays.
req.setRequesterPays(true);
return s3.getObject(req).getObjectContent();
} catch (AmazonS3Exception e) {
// there is no data in this tile
if ("NoSuchKey".equals(e.getErrorCode()))
return null;
else
// re-throw, something else is amiss
throw e;
}
}
} |
package com.coremedia.iso.boxes.mdat;
import com.coremedia.iso.BoxParser;
import com.coremedia.iso.ChannelHelper;
import com.coremedia.iso.boxes.Box;
import com.coremedia.iso.boxes.ContainerBox;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import static com.googlecode.mp4parser.util.CastUtils.l2i;
/**
* This box contains the media data. In video tracks, this box would contain video frames. A presentation may
* contain zero or more Media Data Boxes. The actual media data follows the type field; its structure is described
* by the metadata (see {@link com.coremedia.iso.boxes.SampleTableBox}).<br>
* In large presentations, it may be desirable to have more data in this box than a 32-bit size would permit. In this
* case, the large variant of the size field is used.<br>
* There may be any number of these boxes in the file (including zero, if all the media data is in other files). The
* metadata refers to media data by its absolute offset within the file (see {@link com.coremedia.iso.boxes.StaticChunkOffsetBox});
* so Media Data Box headers and free space may easily be skipped, and files without any box structure may
* also be referenced and used.
*/
public final class MediaDataBox implements Box {
private static Logger LOG = Logger.getLogger(MediaDataBox.class.getName());
public static final String TYPE = "mdat";
public static final int BUFFER_SIZE = 10 * 1024 * 1024;
ContainerBox parent;
ByteBuffer header;
// These fields are for the special case of a FileChannel as input.
private FileChannel fileChannel;
private long startPosition;
private long contentSize;
private Map<Long, Reference<ByteBuffer>> cache = new HashMap<Long, Reference<ByteBuffer>>();
/**
* If the whole content is just in one mapped buffer keep a strong reference to it so it is
* not evicted from the cache.
*/
private ByteBuffer content;
public ContainerBox getParent() {
return parent;
}
public void setParent(ContainerBox parent) {
this.parent = parent;
}
public String getType() {
return TYPE;
}
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
if (fileChannel != null) {
assert checkStillOk();
fileChannel.transferTo(startPosition - header.limit(), contentSize + header.limit(), writableByteChannel);
} else {
header.rewind();
writableByteChannel.write(header);
writableByteChannel.write(content);
}
}
/**
* If someone use the same file as source and sink it could the case that
* inserting a few bytes before the mdat results in overwrting data we still
* need to write this mdat here. This method just makes sure that we haven't already
* overwritten the mdat contents.
* @return true if ok
*/
private boolean checkStillOk() {
try {
fileChannel.position(startPosition - header.limit());
ByteBuffer h2 = ByteBuffer.allocate(header.limit());
fileChannel.read(h2);
header.rewind();
h2.rewind();
assert h2.equals(header): "It seems that the content I want to read has already been overwritten.";
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public long getSize() {
long size = header.limit();
size += contentSize;
return size;
}
public void parse(ReadableByteChannel readableByteChannel, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
this.header = header;
this.contentSize = contentSize;
if (readableByteChannel instanceof FileChannel && (contentSize > 100 * 1024)) {
this.fileChannel = ((FileChannel) readableByteChannel);
this.startPosition = ((FileChannel) readableByteChannel).position();
((FileChannel) readableByteChannel).position(((FileChannel) readableByteChannel).position() + contentSize);
} else {
content = ChannelHelper.readFully(readableByteChannel, l2i(contentSize));
cache.put(0l, new SoftReference<ByteBuffer>(content));
}
}
public synchronized ByteBuffer getContent(long offset, int length) {
for (Long chacheEntryOffset : cache.keySet()) {
if (chacheEntryOffset <= offset && offset <= chacheEntryOffset + BUFFER_SIZE) {
ByteBuffer cacheEntry = cache.get(chacheEntryOffset).get();
if ((cacheEntry != null) && ((chacheEntryOffset + cacheEntry.limit()) >= (offset + length))) {
// CACHE HIT
cacheEntry.position((int) (offset - chacheEntryOffset));
ByteBuffer cachedSample = cacheEntry.slice();
cachedSample.limit(length);
return cachedSample;
}
}
}
// CACHE MISS
ByteBuffer cacheEntry;
try {
// Just mapping 10MB at a time. Seems reasonable.
cacheEntry = fileChannel.map(FileChannel.MapMode.READ_ONLY, startPosition + offset, Math.min(BUFFER_SIZE, contentSize - offset));
} catch (IOException e1) {
LOG.fine("Even mapping just 10MB of the source file into the memory failed. " + e1);
throw new RuntimeException(
"Delayed reading of mdat content failed. Make sure not to close " +
"the FileChannel that has been used to create the IsoFile!", e1);
}
cache.put(offset, new SoftReference<ByteBuffer>(cacheEntry));
cacheEntry.position(0);
ByteBuffer cachedSample = cacheEntry.slice();
cachedSample.limit(length);
return cachedSample;
}
public ByteBuffer getHeader() {
return header;
}
} |
//@author A0111875E
package com.epictodo.controller.nlp;
import edu.stanford.nlp.ie.crf.CRFClassifier;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.parser.lexparser.LexicalizedParser;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.time.TimeAnnotator;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NLPLoadEngine {
public StanfordCoreNLP _pipeline;
private static NLPLoadEngine instance = null;
private static final String CLASSIFIER_MODEL = "classifiers/english.muc.7class.distsim.crf.ser.gz";
private static final String ENGLISHPCFG_MODEL = "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz";
public static CRFClassifier<CoreLabel> CLASSIFIER = null;
public LexicalizedParser LEXICAL_PARSER = null;
private Logger _logger = Logger.getLogger("
private PrintStream _err = System.err;
private double _counter = 0;
private final double LOAD_COUNT = 3000;
/**
* This method mutes NLP API Error Messages temporarily
* This works for all console messages
* <p/>
* Usage:
* <p/>
* mute();
*/
public void mute() {
System.setErr(new PrintStream(new OutputStream() {
public void write(int b) {
loadSystem();
}
private void loadSystem() {
_counter++;
if (_counter/LOAD_COUNT == 1){
System.out.println("System loading..");
}else if (_counter/LOAD_COUNT == 0.1){
System.out.println("10%");
}else if (_counter/LOAD_COUNT == 0.25){
System.out.println("25%");
}else if (_counter/LOAD_COUNT == 0.50){
System.out.println("50%");
}else if (_counter/3000 == 0.75){
System.out.println("75%");
}
}
}));
}
/**
* This method restores NLP API Error Messages to be displayed
* This method works for all console messages.
* <p/>
* Usage:
* <p/>
* restore();
*/
public void restore() {
System.setErr(_err);
}
/**
* This method prints the progress bar to be displayed.
* [Hack] to inject into printstream overriding all red warnings on load with progress bar
*
* @param _percent
*/
public static NLPLoadEngine getInstance() {
if (instance == null) {
instance = new NLPLoadEngine();
}
return instance;
}
public NLPLoadEngine() {
this.mute();
Properties _properties = new Properties();
_properties.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref, sentiment");
try {
CLASSIFIER = CRFClassifier.getClassifierNoExceptions(CLASSIFIER_MODEL);
LEXICAL_PARSER = LexicalizedParser.loadModel(ENGLISHPCFG_MODEL);
_pipeline = new StanfordCoreNLP(_properties, true);
_pipeline.addAnnotator(new TimeAnnotator("sutime", _properties));
_logger.log(Level.INFO, "Successfully loaded models.");
} catch (RuntimeException ex) {
_logger.log(Level.SEVERE, "Error loading models.");
throw ex;
}
}
public CRFClassifier<CoreLabel> classifierModel() {
return CLASSIFIER;
}
} |
package com.github.dozedoff.commonj.net;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for downloading binary data from the Internet.
*/
public class GetBinary {
private long contentLenght = 0;
private int offset = 0;
private int failCount = 0;
private int maxRetry = 3;
private int readTimeoutInMilli = 10000;
private ByteBuffer classBuffer;
private final static Logger logger = LoggerFactory.getLogger(GetBinary.class);
public GetBinary() {
classBuffer = ByteBuffer.allocate(15728640); // 15mb
}
public GetBinary(int size) {
classBuffer = ByteBuffer.allocate(size);
}
@Deprecated
/**
* Use getViaHttp instead.
* @param url
* @return
* @throws IOException
*/
public byte[] get(String url) throws IOException {
return get(new URL(url));
}
@Deprecated
/**
* Use getViaHttp instead.
* @param url
* @return
* @throws IOException
*/
public byte[] get(URL url) throws IOException {
BufferedInputStream binary = null;
HttpURLConnection thread = null;
try {
thread = (HttpURLConnection) url.openConnection();
thread.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); // pretend to
// be a
// firefox
// browser
binary = new BufferedInputStream(thread.getInputStream());
classBuffer.clear();
// ByteBuffer bb = ByteBuffer.allocate(15728640); //15mb
int count = 0;
byte[] c = new byte[8192]; // transfer data from input (URL) to output (file) one byte at a time
while ((count = binary.read(c)) != -1) {
classBuffer.put(c, 0, count);
}
classBuffer.flip();
byte[] varBuffer = new byte[classBuffer.limit()];
classBuffer.get(varBuffer);
binary.close();
return varBuffer;
} catch (IOException e) {
throw new IOException("unable to connect to " + url.toString());
} finally {
if (binary != null)
binary.close();
if (thread != null)
thread.disconnect();
}
}
public Long getLenght(URL url) throws IOException, PageLoadException {
HttpURLConnection thread = null;
try {
thread = (HttpURLConnection) url.openConnection();
thread.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); // pretend to
// be a
// firefox
// browser
thread.setRequestMethod("HEAD");
thread.setDoOutput(true);
thread.setReadTimeout(readTimeoutInMilli);
thread.connect();
return Long.valueOf(thread.getHeaderField("Content-Length"));
} catch (NumberFormatException nfe) {
if (thread.getResponseCode() != 200)
throw new PageLoadException(Integer.toString(thread.getResponseCode()), thread.getResponseCode());
throw new NumberFormatException("unable to parse " + url.toString());
} catch (SocketTimeoutException ste) {
throw new SocketTimeoutException(ste.getMessage());
} catch (IOException e) {
throw new IOException("unable to connect to " + url.toString());
} catch (ClassCastException cce) {
logger.warn(cce.getMessage() + ", " + url.toString());
} finally {
if (thread != null)
thread.disconnect();
}
return contentLenght;
}
public Map<String, List<String>> getHeader(URL url) throws IOException {
HttpURLConnection thread = null;
try {
thread = (HttpURLConnection) url.openConnection();
thread.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); // pretend to
return thread.getHeaderFields();
} catch (IOException e) {
throw new IOException("unable to connect to " + url.toString());
} finally {
if (thread != null) {
thread.disconnect();
}
}
}
public byte[] getRange(URL url, int start, long l) throws IOException, PageLoadException {
BufferedInputStream binary = null;
HttpURLConnection httpCon;
try {
httpCon = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
throw new IOException("unable to connect to " + url.toString());
}
try {
httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); // pretend
// to be a
// firefox
// browser
httpCon.setRequestMethod("GET");
httpCon.setDoOutput(true);
httpCon.setRequestProperty("Range", "bytes=" + start + "-" + l);
httpCon.setReadTimeout(readTimeoutInMilli);
httpCon.connect();
binary = new BufferedInputStream(httpCon.getInputStream());
} catch (SocketTimeoutException ste) {
if (httpCon != null) {
httpCon.disconnect();
}
throw new SocketTimeoutException(ste.getMessage());
} catch (IOException e) {
if (httpCon != null) {
httpCon.disconnect();
}
throw new PageLoadException(Integer.toString(httpCon.getResponseCode()), httpCon.getResponseCode());
}
int count = 0;
byte[] c = new byte[8192]; // transfer data from input (URL) to output (file) one byte at a time
try {
while ((count = binary.read(c)) != -1) {
classBuffer.put(c, 0, count);
}
} catch (SocketException se) {
logger.warn("SocketException, http response: " + httpCon.getResponseCode());
if (failCount < maxRetry) {
try {
Thread.sleep(5000);
} catch (Exception ie) {
}
this.offset = classBuffer.position();
httpCon.disconnect();
failCount++;
return getRange(url, offset, contentLenght - 1);
} else {
logger.warn("Buffer position at failure: " + classBuffer.position() + " URL: " + url.toString());
httpCon.disconnect();
throw new SocketException();
}
} finally {
if (binary != null)
binary.close();
if (httpCon != null) {
httpCon.disconnect();
}
}
if (failCount != 0)
logger.info("GetBinary Successful -> " + classBuffer.position() + "/" + contentLenght + ", " + failCount + " tries, "
+ url.toString());
classBuffer.flip();
byte[] varBuffer = new byte[classBuffer.limit()];
classBuffer.get(varBuffer);
classBuffer.clear();
return varBuffer;
}
public byte[] getViaHttp(String url) throws PageLoadException, IOException {
return getViaHttp(new URL(url));
}
public byte[] getViaHttp(URL url) throws IOException, PageLoadException {
Long contentLenght = 0L;
BufferedInputStream binary = null;
HttpURLConnection httpCon = null;
httpCon = connect(url);
if (httpCon.getResponseCode() != 200) {
httpCon.disconnect();
throw new PageLoadException(String.valueOf(httpCon.getResponseCode()), httpCon.getResponseCode());
}
contentLenght = httpCon.getContentLengthLong();
binary = new BufferedInputStream(httpCon.getInputStream());
int count = 0;
byte[] c = new byte[8192]; // transfer data from input (URL) to output (file) one byte at a time
try {
while ((count = binary.read(c)) != -1) {
classBuffer.put(c, 0, count);
}
} catch (SocketException se) { // TODO remove this catch block, it's unused
// try{Thread.sleep(5000);}catch(Exception ie){}
this.offset = classBuffer.position();
if (failCount < maxRetry) {
failCount++;
logger.warn("GetBinary failed, reason: " + se.getLocalizedMessage() + " -> " + classBuffer.position() + "/"
+ contentLenght + " " + url.toString());
httpCon.disconnect();
return getRange(url, offset, contentLenght - 1);
} else {
throw new SocketException();
}
} catch (NullPointerException npe) {
logger.error("NullPointerException in GetBinary.getViaHttp");
return null;
} finally {
if (binary != null)
binary.close();
if (httpCon != null) {
httpCon.disconnect();
}
}
classBuffer.flip();
byte[] varBuffer = new byte[classBuffer.limit()];
classBuffer.get(varBuffer);
classBuffer.clear();
return varBuffer;
}
private HttpURLConnection connect(URL url) throws IOException, ProtocolException {
HttpURLConnection httpCon;
httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0"); // pretend to be
// a firefox
// browser
httpCon.setRequestMethod("GET");
httpCon.setDoOutput(true);
httpCon.setReadTimeout(readTimeoutInMilli);
httpCon.connect();
return httpCon;
}
public int getMaxRetry() {
return maxRetry;
}
public void setMaxRetry(int maxRetry) {
this.maxRetry = maxRetry;
}
public boolean setReadTimeout(int milliSeconds) {
if (milliSeconds >= 0) {
this.readTimeoutInMilli = milliSeconds;
return true;
} else {
return false;
}
}
} |
package com.google.code.beanmatchers;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import java.util.Random;
public final class BeanMatchers {
private static final ValueGeneratorRepository VALUE_GENERATOR_REPOSTITORY;
private static final TypeBasedValueGenerator TYPE_BASED_VALUE_GENERATOR;
static {
Random random = new Random();
VALUE_GENERATOR_REPOSTITORY = new InMemoryValueGeneratorRepository();
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new StringGenerator(), String.class);
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new IntegerGenerator(random), Integer.class, Integer.TYPE);
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new DoubleGenerator(random), Double.class, Double.TYPE);
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new BooleanGenerator(random), Boolean.class, Boolean.TYPE);
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new LongGenerator(random), Long.class, Long.TYPE);
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new FloatGenerator(random), Float.class, Float.TYPE);
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(new ByteGenerator(random), Byte.class, Byte.TYPE);
ArrayTypeBasedValueGenerator arrayValueGenerator = new ArrayTypeBasedValueGenerator();
TYPE_BASED_VALUE_GENERATOR = new DefaultTypeBasedValueGenerator(VALUE_GENERATOR_REPOSTITORY,
new MockingTypeBasedValueGenerator(), new EnumBasedValueGenerator(random), arrayValueGenerator);
arrayValueGenerator.setTypeBaseValueGenerator(TYPE_BASED_VALUE_GENERATOR);
}
private BeanMatchers() {}
@Factory
public static Matcher<Class> hasValidGettersAndSettersFor(String... properties) {
return new InstantiatingMatcherDecorator(isABeanWithValidGettersAndSettersFor(properties));
}
@Factory
public static <T> Matcher<T> isABeanWithValidGettersAndSettersFor(String... properties) {
return new HasValidGettersAndSettersMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties);
}
@Factory
public static Matcher<Class> hasValidGettersAndSettersExcluding(String... properties) {
return new InstantiatingMatcherDecorator(isABeanWithValidGettersAndSettersExcluding(properties));
}
@Factory
public static <T> Matcher<T> isABeanWithValidGettersAndSettersExcluding(String... properties) {
return new HasValidGettersAndSettersExcludingMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties);
}
@Factory
public static Matcher<Class> hasValidGettersAndSetters() {
return hasValidGettersAndSettersExcluding();
}
@Factory
public static <T> Matcher<T> isABeanWithValidGettersAndSetters() {
return isABeanWithValidGettersAndSettersExcluding();
}
@Factory
public static Matcher<Class> hasValidBeanConstructor() {
return new HasValidBeanConstructorMatcher();
}
@Factory
public static Matcher<Class> hasValidBeanHashCode() {
return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR);
}
@Factory
public static Matcher<Class> hasValidBeanHashCodeFor(String... properties) {
return new HasValidBeanHashCodeForMatcher(TYPE_BASED_VALUE_GENERATOR, properties);
}
@Factory
public static Matcher<Class> hasValidBeanHashCodeExcluding(String... properties) {
return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties);
}
@Factory
public static Matcher<Class> hasValidBeanEquals() {
return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR);
}
@Factory
public static Matcher<Class> hasValidBeanEqualsFor(String... properties) {
return new HasValidBeanEqualsForMatcher(TYPE_BASED_VALUE_GENERATOR, properties);
}
@Factory
public static Matcher<Class> hasValidBeanEqualsExcluding(String... properties) {
return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties);
}
@Factory
public static Matcher<Class> hasValidBeanToString() {
return new HasToStringDescribingPropertiesExcludingMatcher(TYPE_BASED_VALUE_GENERATOR);
}
@Factory
public static Matcher<Class> hasValidBeanToStringExcluding(String... properties) {
return new HasToStringDescribingPropertiesExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties);
}
public static <T> void registerValueGenerator(ValueGenerator<T> generator, Class<T> type) {
VALUE_GENERATOR_REPOSTITORY.registerValueGenerator(generator, type);
}
} |
package com.martensigwart.fakeload;
import com.sun.management.OperatingSystemMXBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.List;
/**
* This class acts as the controlling entity of the {@link DefaultSimulationInfrastructure}.
*
* <p>
* The {@code LoadController} is responsible for managing the <b>desired</b> and <b>actual</b> system load.
* The desired system load represents the load the user wants to simulate and the actual system load represents
* the actual system load that is being simulated.
*
* <p>
* All increases and decreases of {@code FakeLoad} requests arriving at {@code DefaultSimulationInfrastructure}
* get propagated to the {@code LoadController}. The {@code LoadController} then uses an instance of type
* {@link SystemLoad} to keep track of the currently desired system load. Within the {@code SystemLoad} instance,
* the load instructions arriving from different {@code FakeLoad}s get aggregated.
*
* <p>
* After the <i>desired</i> system load has been determined by the {@code SystemLoad} instance,
* the {@code LoadController} propagates the desired load information to the individual threads responsible
* for <i>actual</i> load simulation.
*
* <p>
* The {@code LoadController} is also responsible for adjusting the actual system load produced by
* the simulator threads. Whenever a significant deviation between desired target load and actual system load is
* detected, the class adjusts the load slightly in the direction of target. This way the load generated by the
* simulator threads actually reaches the desired level.
*
*
* @author Marten Sigwart
* @since 1.8
* @see DefaultSimulationInfrastructure
* @see SystemLoad
*/
public final class LoadController implements Runnable {
private static final Logger log = LoggerFactory.getLogger(LoadController.class);
private static final OperatingSystemMXBean operatingSystem = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
private static final int SLEEP_PERIOD = 2000;
private static final int CPU_CONTROL_THRESHOLD = 1;
private final SystemLoad systemLoad;
private final List<CpuSimulator> cpuSimulators;
private final MemorySimulator memorySimulator;
private final DiskInputSimulator diskInputSimulator;
private final DiskOutputSimulator diskOutputSimulator;
private final double stepSize;
private final Object lock;
// Set to lower then CPU_CONTROL_THRESHOLD
private long lastCpu = -CPU_CONTROL_THRESHOLD-1;
private long oldDesiredCpu = 0L;
public LoadController(SystemLoad systemLoad, List<CpuSimulator> cpuSimulators, MemorySimulator memorySimulator, DiskInputSimulator diskInputSimulator, DiskOutputSimulator diskOutputSimulator) {
this.systemLoad = systemLoad;
this.cpuSimulators = Collections.unmodifiableList(cpuSimulators);
this.memorySimulator = memorySimulator;
this.diskInputSimulator = diskInputSimulator;
this.diskOutputSimulator = diskOutputSimulator;
this.stepSize = 1.0 / Runtime.getRuntime().availableProcessors();
this.lock = new Object();
}
@Override
public void run() {
log.debug("LoadController - Started");
boolean running = true;
operatingSystem.getProcessCpuLoad(); // the first value reported is always zero
while(running) {
try {
synchronized (lock) {
while (systemLoad.getCpu() == 0) {
log.debug("LoadController - Nothing to control, waiting...");
lock.wait();
log.debug("LoadController - Woke Up");
}
}
Thread.sleep(SLEEP_PERIOD);
controlCpuLoad();
} catch (InterruptedException e) {
log.debug("LoadController - Interrupted");
running = false;
}
}
}
public void increaseSystemLoadBy(FakeLoad load) throws MaximumLoadExceededException {
systemLoad.increaseBy(load);
for (CpuSimulator cpuSim: cpuSimulators) {
cpuSim.setLoad(systemLoad.getCpu());
}
synchronized (lock) {
lock.notify(); // notify thread executing the run method
}
memorySimulator.setLoad(systemLoad.getMemory());
diskInputSimulator.setLoad(systemLoad.getDiskInput());
diskOutputSimulator.setLoad(systemLoad.getDiskOutput());
}
public void decreaseSystemLoadBy(FakeLoad load) {
systemLoad.decreaseBy(load);
for (CpuSimulator cpuSim: cpuSimulators) {
cpuSim.setLoad(systemLoad.getCpu());
}
memorySimulator.setLoad(systemLoad.getMemory());
diskInputSimulator.setLoad(systemLoad.getDiskInput());
diskOutputSimulator.setLoad(systemLoad.getDiskOutput());
}
/**
* Controls and adjusts the <i>actual</i> CPU load produced by CPU simulator threads.
*
* <p>
* CPU load adjustment is done in the following way:
*
* <p>
* First, the desired CPU load is retrieved from the {@link SystemLoad} instance.
* The desired load is compared to the last desired CPU load recorded by the method.
* When the desired load has been adjusted recently and old and new desired load differ,
* the old load is set to the new one and the method returns with no load adjustment
* taking place, as simulator threads might not have had the time to catch up to change
* in desired load yet.
*
* <p>
* When there is no difference between the new and old desired CPU load, the desired
* load is compared to the actual CPU load currently produced by the simulator threads.
* When desired and actual CPU load differ by more than a defined threshold, and actual
* CPU load is <b>not</b> currently changing, CPU load will be adjusted.
*
*/
private void controlCpuLoad() {
long desiredCpu = systemLoad.getCpu();
if (desiredCpu != oldDesiredCpu) {
log.trace("Last desired load: {}, new desired load: {} --> Not adjusting CPU load", oldDesiredCpu, desiredCpu);
oldDesiredCpu = desiredCpu;
return;
}
long actualCpu = (long)(operatingSystem.getProcessCpuLoad() * 100);
log.trace("Desired CPU: {}, Actual CPU: {}, Last CPU: {}", desiredCpu, actualCpu, lastCpu);
long difference = actualCpu - desiredCpu;
if ( Math.abs(difference) > CPU_CONTROL_THRESHOLD &&
Math.abs(lastCpu - actualCpu) <= CPU_CONTROL_THRESHOLD) {
int noOfSteps = (int)(Math.abs(difference) / stepSize);
log.trace("Number of adjustment steps: {}",noOfSteps);
if (difference < 0) { // actual load smaller than desired load
log.trace("Increasing CPU load, difference {}", difference);
increaseCpuSimulatorLoads(1, noOfSteps);
} else {
log.trace("Decreasing CPU load, difference {}", difference);
decreaseCpuSimulatorLoads(1, noOfSteps);
}
}
lastCpu = actualCpu;
}
private void increaseCpuSimulatorLoads(int delta, int noOfSteps) {
for (int i=0; i<noOfSteps; i++) {
CpuSimulator cpuSimulator = cpuSimulators.get(i % cpuSimulators.size());
/*
* Only increase if load is not maxed out.
* Synchronization of simulator is not important here,
* if-statement only to prevent unnecessary calls to increase load.
*/
if (!cpuSimulator.isMaximumLoad()) {
cpuSimulators.get(i % cpuSimulators.size()).increaseLoad(delta);
}
}
}
private void decreaseCpuSimulatorLoads(int delta, int noOfSteps) {
for (int i=0; i<noOfSteps; i++) {
CpuSimulator cpuSimulator = cpuSimulators.get(i % cpuSimulators.size());
/*
* Only decrease if load is not zero.
* Synchronization of simulator is not important here,
* if-statement only to prevent unnecessary calls to decrease load.
*/
if (!cpuSimulator.isZeroLoad()) {
cpuSimulators.get(i % cpuSimulators.size()).decreaseLoad(delta);
}
}
}
public List<CpuSimulator> getCpuSimulators() {
return cpuSimulators;
}
public MemorySimulator getMemorySimulator() {
return memorySimulator;
}
public DiskInputSimulator getDiskInputSimulator() {
return diskInputSimulator;
}
public DiskOutputSimulator getDiskOutputSimulator() {
return diskOutputSimulator;
}
} |
package com.ociweb.pronghorn.iot.i2c;
import java.io.IOException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ociweb.iot.hardware.Hardware;
import com.ociweb.iot.hardware.I2CConnection;
import com.ociweb.pronghorn.iot.AbstractTrafficOrderedStage;
import com.ociweb.pronghorn.iot.schema.I2CCommandSchema;
import com.ociweb.pronghorn.iot.schema.I2CResponseSchema;
import com.ociweb.pronghorn.iot.schema.TrafficAckSchema;
import com.ociweb.pronghorn.iot.schema.TrafficReleaseSchema;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeReader;
import com.ociweb.pronghorn.pipe.PipeWriter;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.util.Appendables;
import com.ociweb.pronghorn.util.Blocker;
import com.ociweb.pronghorn.util.math.PMath;
import com.ociweb.pronghorn.util.math.ScriptedSchedule;
public class I2CJFFIStage extends AbstractTrafficOrderedStage {
private final I2CBacking i2c;
private final Pipe<I2CCommandSchema>[] fromCommandChannels;
private final Pipe<I2CResponseSchema> i2cResponsePipe;
private static final Logger logger = LoggerFactory.getLogger(I2CJFFIStage.class);
private ScriptedSchedule schedule;
private I2CConnection[] inputs = null;
private byte[] workingBuffer;
private int inProgressIdx = 0;
private long blockStartTime = 0;
private int scheduleIdx = 0;
private boolean awaitingResponse = false;
private static final int MAX_ADDR = 127;
private Blocker pollBlocker;
private long readReleaseTime;
private boolean doneReading = false;
private int activePipe =-1;
private long timeOut = 0;
private final int writeTime = 1; //TODO: Writes time out after 1ms. Is this ideal?
//NOTE: on the pi without any RATE value this stage is run every .057 ms, this is how long 1 run takes to complete for the clock., 2 analog sensors.
public I2CJFFIStage(GraphManager graphManager, Pipe<TrafficReleaseSchema>[] goPipe,
Pipe<I2CCommandSchema>[] i2cPayloadPipes,
Pipe<TrafficAckSchema>[] ackPipe,
Pipe<I2CResponseSchema> i2cResponsePipe,
Hardware hardware) {
super(graphManager, hardware, i2cPayloadPipes, goPipe, ackPipe, i2cResponsePipe);
this.i2c = hardware.i2cBacking;
this.fromCommandChannels = i2cPayloadPipes;
this.i2cResponsePipe = i2cResponsePipe;
this.inputs = null==hardware.i2cInputs?new I2CConnection[0]:hardware.i2cInputs;
//force all commands to happen upon publish and release
this.supportsBatchedPublish = false;
this.supportsBatchedRelease = false;
GraphManager.addNota(graphManager, GraphManager.SCHEDULE_RATE, -1, this); //TODO: Give this a concrete time
}
@Override
public void startup(){
super.startup();
workingBuffer = new byte[2048];
logger.debug("Polling "+this.inputs.length+" i2cInput(s)");
int[] schedulePeriods = new int[inputs.length];
for (int i = 0; i < inputs.length; i++) {
schedulePeriods[i] = inputs[i].responseMS;
timeOut = hardware.currentTimeMillis() + writeTime;
while(!i2c.write(inputs[i].address, inputs[i].setup, inputs[i].setup.length) && hardware.currentTimeMillis()<timeOut){};
logger.info("I2C setup {} complete",inputs[i].address);
}
//TODO: add setup for outputs ??
schedule = PMath.buildScriptedSchedule(schedulePeriods);
System.out.println("proposed schedule:"+schedule);
pollBlocker = new Blocker(MAX_ADDR);
blockStartTime = System.currentTimeMillis();
}
@Override
public void run() {
if(blockStartTime == 0){ blockStartTime = System.currentTimeMillis(); }; //TODO: This can be cleaned up
if(System.currentTimeMillis()<blockStartTime){
return; //Enough time has not elapsed to start next block on schedule
}else{
doneReading = false;
//System.out.println("now reading");
}
long tempy = System.currentTimeMillis();
do{
inProgressIdx = schedule.script[scheduleIdx];
scheduleIdx = (scheduleIdx+1) % schedule.script.length;
if(inProgressIdx != -1){ //TODO: I don't know if this is formatted very well having if and while conditionals being the same
//System.out.println("Processing " + inProgressIdx);
sendReadRequest();
//long nsWait = readReleaseTime-System.nanoTime(); //TODO: ReadReleaseTime needs to be dependent on sensor
try {
Thread.sleep(1); //TODO: this changes depending on what we're doing
} catch (InterruptedException e) {
requestShutdown();
return;
}
int len = this.inputs[inProgressIdx].readBytes;
workingBuffer[0] = -2;
byte[] temp =i2c.read(this.inputs[inProgressIdx].address, workingBuffer, len);
if (PipeWriter.tryWriteFragment(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10)) {
PipeWriter.writeInt(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_ADDRESS_11, this.inputs[inProgressIdx].address);
PipeWriter.writeBytes(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12, temp, 0, len, Integer.MAX_VALUE);
PipeWriter.writeLong(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_TIME_13, hardware.currentTimeMillis());
PipeWriter.writeInt(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_REGISTER_14, this.inputs[inProgressIdx].register);
PipeWriter.publishWrites(i2cResponsePipe);
}else{
System.out.println("Pipe full. Deal with it");
}
}
}while(inProgressIdx != -1);
blockStartTime += schedule.commonClock;
if(System.currentTimeMillis()<blockStartTime){
doneReading = true; //can now send outgoing commands
//sendOutgoingCommands(activePipe);
System.out.println("now writing");
}
super.run();
// System.out.println(blockStartTime - System.currentTimeMillis());
// System.out.println(System.currentTimeMillis()-tempy);
// boolean doneWithActiveCommands = false;
// //All poll cycles come first as the highest priority. commands will come second and they can back up on the pipe if needed.
// if (isPollInProgress()) {
// if (!PipeWriter.hasRoomForFragmentOfSize(i2cResponsePipe, Pipe.sizeOf(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10))) {
// return;//no room for response so do not read it now.
// long nsWait = readReleaseTime-System.nanoTime();
// if (nsWait>0) {
// try {
// Thread.sleep(nsWait/1_000_000, (int)(nsWait%1_000_000));
// } catch (InterruptedException e) {
// requestShutdown();
// return;
// int len = this.inputs[inProgressIdx].readBytes;
// workingBuffer[0] = -2;
// byte[] temp =i2c.read(this.inputs[inProgressIdx].address, workingBuffer, len);
// if (-1 == temp[0]) {
// //no data yet with all -1 values
// return;
// } else {
// if (-2 == temp[0]) {
// //no response and none will follow
// //eg the poll failed on this round
// } else {
// if (!PipeWriter.tryWriteFragment(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10)) {
// throw new RuntimeException("should not happen "+i2cResponsePipe);
// PipeWriter.writeInt(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_ADDRESS_11, this.inputs[inProgressIdx].address);
// PipeWriter.writeBytes(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_BYTEARRAY_12, temp, 0, len, Integer.MAX_VALUE);
// PipeWriter.writeLong(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_TIME_13, hardware.currentTimeMillis());
// PipeWriter.writeInt(i2cResponsePipe, I2CResponseSchema.MSG_RESPONSE_10_FIELD_REGISTER_14, this.inputs[inProgressIdx].register);
// PipeWriter.publishWrites(i2cResponsePipe);
// inProgressIdx--;//read next one
// long durationToNextRelease = pollBlocker.durationToNextRelease(hardware.currentTimeMillis(), 1000);
// //we are not waiting for a response so now its time send the commands.
// //will return false if this timed out and we still had work to complete
// doneWithActiveCommands = processReleasedCommands(durationToNextRelease); //no longer than 1 second
// //check if we should begin polling again
// if (isTimeToPoll()) {
// sendReadRequest();
// } while (!doneWithActiveCommands ||
// isPollInProgress() ||
// connectionBlocker.willReleaseInWindow(hardware.currentTimeMillis(),msNearWindow) ||
// pollBlocker.willReleaseInWindow(hardware.currentTimeMillis(), msNearWindow));
}
private boolean isPollInProgress() {
return awaitingResponse && inProgressIdx >= 0;
}
private boolean isTimeToPoll() {
if (inProgressIdx >= 0) {
return true; //still processing each of the input items needed
}
if (this.inputs.length > 0) {
inProgressIdx = this.inputs.length-1;
return true;
} else {
return false;
}
}
private void sendReadRequest() {
//long now = System.currentTimeMillis();
//pollBlocker.releaseBlocks(now);
I2CConnection connection = this.inputs[inProgressIdx];
//if (!pollBlocker.isBlocked(deviceKey(connection))) {
timeOut = hardware.currentTimeMillis() + writeTime;
while(!i2c.write((byte)connection.address, connection.readCmd, connection.readCmd.length) && hardware.currentTimeMillis()<timeOut){};
//readReleaseTime = System.nanoTime()+10_000;//TODO: we may need a different value per twig but this will do for now.
//awaitingResponse = true;
//NOTE: the register may or may not be present and the address may not be enough to go on so we MUST
//pollBlocker.until(deviceKey(connection), now+connection.responseMS);
return;
//if that one was blocked check the next.
//} while (--inProgressIdx >= 0);
}
private int deviceKey(I2CConnection connection) {
return (((int)connection.address)<< 16) | connection.register;
}
protected void processMessagesForPipe(int a) {
sendOutgoingCommands(a);
System.out.println("activePipe = "+a);
}
private void sendOutgoingCommands(int activePipe) {
if(activePipe == -1){
return; //No active pipe selected yet
}
Pipe<I2CCommandSchema> pipe = fromCommandChannels[activePipe];
System.out.println("outgoingCommand");
while ( hasReleaseCountRemaining(activePipe)
&& !isChannelBlocked(activePipe)
&& !connectionBlocker.isBlocked(Pipe.peekInt(pipe, 1)) //peek next address and check that it is not blocking for some time
&& doneReading
&& PipeReader.tryReadFragment(pipe)){
System.out.println("writing");
int msgIdx = PipeReader.getMsgIdx(pipe);
switch(msgIdx){
case I2CCommandSchema.MSG_COMMAND_7:
{
int addr = PipeReader.readInt(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_ADDRESS_12);
byte[] backing = PipeReader.readBytesBackingArray(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
int len = PipeReader.readBytesLength(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
int pos = PipeReader.readBytesPosition(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
int mask = PipeReader.readBytesMask(pipe, I2CCommandSchema.MSG_COMMAND_7_FIELD_BYTEARRAY_2);
assert(!connectionBlocker.isBlocked(addr)): "expected command to not be blocked";
Pipe.copyBytesFromToRing(backing, pos, mask, workingBuffer, 0, Integer.MAX_VALUE, len);
try {
if (logger.isDebugEnabled()) {
logger.debug("{} send command {} {}", activePipe, Appendables.appendArray(new StringBuilder(), '[', backing, pos, mask, ']', len), pipe);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
timeOut = hardware.currentTimeMillis() + writeTime;
while(!i2c.write((byte) addr, workingBuffer, len) && hardware.currentTimeMillis()<timeOut){};
logger.debug("send done");
}
break;
case I2CCommandSchema.MSG_BLOCKCHANNELMS_22:
{
blockChannelDuration(activePipe,PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCHANNELMS_22_FIELD_DURATION_13));
logger.debug("CommandChannel blocked for {} millis ",PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCHANNELMS_22_FIELD_DURATION_13));
}
break;
case I2CCommandSchema.MSG_BLOCKCONNECTIONMS_20:
{
int addr = PipeReader.readInt(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONMS_20_FIELD_ADDRESS_12);
long duration = PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONMS_20_FIELD_DURATION_13);
connectionBlocker.until(addr, hardware.currentTimeMillis() + duration);
logger.debug("I2C addr {} blocked for {} millis {}", addr, duration, pipe);
}
break;
case I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21:
{
int addr = PipeReader.readInt(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21_FIELD_ADDRESS_12);
long time = PipeReader.readLong(pipe, I2CCommandSchema.MSG_BLOCKCONNECTIONUNTIL_21_FIELD_TIMEMS_14);
connectionBlocker.until(addr, time);
logger.debug("I2C addr {} blocked until {} millis {}", addr, time, pipe);
}
break;
case -1 :
requestShutdown();
}
PipeReader.releaseReadLock(pipe);
//only do now after we know its not blocked and was completed
decReleaseCount(activePipe);
}
}
} |
package com.orange.oss.cloudfoundry.cscpi;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.util.Predicates2.retry;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import org.jclouds.cloudstack.CloudStackApi;
import org.jclouds.cloudstack.domain.AsyncCreateResponse;
import org.jclouds.cloudstack.domain.DiskOffering;
import org.jclouds.cloudstack.domain.NIC;
import org.jclouds.cloudstack.domain.Network;
import org.jclouds.cloudstack.domain.NetworkOffering;
import org.jclouds.cloudstack.domain.OSType;
import org.jclouds.cloudstack.domain.ServiceOffering;
import org.jclouds.cloudstack.domain.Tag;
import org.jclouds.cloudstack.domain.Template;
import org.jclouds.cloudstack.domain.TemplateMetadata;
import org.jclouds.cloudstack.domain.VirtualMachine;
import org.jclouds.cloudstack.domain.VirtualMachine.State;
import org.jclouds.cloudstack.domain.Volume;
import org.jclouds.cloudstack.domain.Volume.Type;
import org.jclouds.cloudstack.domain.Zone;
import org.jclouds.cloudstack.features.VolumeApi;
import org.jclouds.cloudstack.options.CreateSnapshotOptions;
import org.jclouds.cloudstack.options.CreateTagsOptions;
import org.jclouds.cloudstack.options.CreateTemplateOptions;
import org.jclouds.cloudstack.options.DeleteTemplateOptions;
import org.jclouds.cloudstack.options.DeployVirtualMachineOptions;
import org.jclouds.cloudstack.options.ListDiskOfferingsOptions;
import org.jclouds.cloudstack.options.ListNetworkOfferingsOptions;
import org.jclouds.cloudstack.options.ListNetworksOptions;
import org.jclouds.cloudstack.options.ListServiceOfferingsOptions;
import org.jclouds.cloudstack.options.ListTagsOptions;
import org.jclouds.cloudstack.options.ListTemplatesOptions;
import org.jclouds.cloudstack.options.ListVirtualMachinesOptions;
import org.jclouds.cloudstack.options.ListVolumesOptions;
import org.jclouds.cloudstack.options.ListZonesOptions;
import org.jclouds.cloudstack.options.RegisterTemplateOptions;
import org.jclouds.cloudstack.predicates.JobComplete;
import org.jclouds.http.HttpResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.orange.oss.cloudfoundry.cscpi.boshregistry.BoshRegistryClient;
import com.orange.oss.cloudfoundry.cscpi.config.CloudStackConfiguration;
import com.orange.oss.cloudfoundry.cscpi.domain.NetworkType;
import com.orange.oss.cloudfoundry.cscpi.domain.Networks;
import com.orange.oss.cloudfoundry.cscpi.domain.ResourcePool;
import com.orange.oss.cloudfoundry.cscpi.exceptions.VMCreationFailedException;
import com.orange.oss.cloudfoundry.cscpi.webdav.WebdavServerAdapter;
public class CPIImpl implements CPI{
private static final String CPI_OS_TYPE = "Other PV (64-bit)";
private static final String CPI_VM_PREFIX = "cpivm-";
private static final String CPI_PERSISTENT_DISK_PREFIX = "cpi-disk-";
private static final String CPI_EPHEMERAL_DISK_PREFIX = "cpi-ephemeral-disk-";
private static Logger logger=LoggerFactory.getLogger(CPIImpl.class);
@Autowired
private CloudStackConfiguration cloudstackConfig;
@Autowired
private CloudStackApi api;
@Autowired
UserDataGenerator userDataGenerator;
@Autowired
VmSettingGenerator vmSettingGenerator;
@Autowired
private WebdavServerAdapter webdav;
@Autowired
private BoshRegistryClient boshRegistry;
private Predicate<String> jobComplete;
/**
* creates a vm.
* take the stemcell_id as cloudstack template name.
* create the vm on the correct network configuration
* static
* vip
* floating
* create an "ephemeral disk" and attach it the the vm
*
* @param agent_id
* @param stemcell_id
* @param resource_pool
* @param networks
* @param disk_locality
* @param env
* @return
* @throws VMCreationFailedException
*/
public String create_vm(String agent_id,
String stemcell_id,
ResourcePool resource_pool,
Networks networks,
List<String> disk_locality,
Map<String,String> env) throws VMCreationFailedException {
String compute_offering=resource_pool.compute_offering;
Assert.isTrue(compute_offering!=null,"Must provide compute offering in vm ressource pool");
String affinityGroup=resource_pool.affinity_group;
if (affinityGroup!=null) {
logger.info("an affinity group {} has been specified for create_vm",affinityGroup);
}
String vmName=CPI_VM_PREFIX+UUID.randomUUID().toString();
logger.info("now creating cloudstack vm");
//cloudstack userdata generation for bootstrap
String userData=this.userDataGenerator.userMetadata(vmName,networks);
this.vmCreation(stemcell_id, compute_offering, networks, vmName,agent_id,userData);
//create ephemeral disk, read the disk size from properties, attach it to the vm.
//NB: if base ROOT disk is large enough, bosh agent can use it to hold swap / ephemeral data. CPI forces an external vol for ephemeral
String ephemeralDiskServiceOfferingName=resource_pool.ephemeral_disk_offering;
if (ephemeralDiskServiceOfferingName==null) {
ephemeralDiskServiceOfferingName=this.cloudstackConfig.defaultEphemeralDiskOffering;
logger.info("no ephemeral_disk_offering specified in cloud_properties. use global CPI default ephemeral disk offering {}",ephemeralDiskServiceOfferingName);
}
logger.debug("ephemeral disk offering is {}",ephemeralDiskServiceOfferingName);
logger.info("now creating ephemeral disk");
int ephemeralDiskSize=resource_pool.disk/1024; //cloudstack size api is Go
String name=CPI_EPHEMERAL_DISK_PREFIX+UUID.randomUUID().toString();
String ephemeralDiskName=this.diskCreate(name,ephemeralDiskSize,ephemeralDiskServiceOfferingName);
//NOW attache the ephemeral disk to the vm (need reboot ?)
//FIXME : placement constraint local disk offering / vm
logger.info("now attaching ephemeral disk {} to cloudstack vm {}",ephemeralDiskName,vmName);
this.diskAttachment(vmName, ephemeralDiskName);
//FIXME: if attach fails, clean both vm and ephemeral disk ??
//FIXME: registry feeding in vmCreation method. refactor here ?
return vmName;
}
/**
* Cloudstack vm creation.
* @param stemcell_id
* @param compute_offering
* @param networks
* @param vmName
* @throws VMCreationFailedException
*/
private void vmCreation(String stemcell_id, String compute_offering,
Networks networks, String vmName,String agent_id,String userData) throws VMCreationFailedException {
Set<Template> matchingTemplates=api.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.name(stemcell_id));
Assert.isTrue(matchingTemplates.size()==1,"Did not find a single template with name "+stemcell_id);
Template stemCellTemplate=matchingTemplates.iterator().next();
String csTemplateId=stemCellTemplate.getId();
logger.info("found cloudstack template {} matching name / stemcell_id {}",csTemplateId,stemcell_id );
String csZoneId = findZoneId();
//find compute offering
Set<ServiceOffering> computeOfferings = api.getOfferingApi().listServiceOfferings(ListServiceOfferingsOptions.Builder.name(compute_offering));
Assert.isTrue(computeOfferings.size()>0, "Unable to find compute offering "+compute_offering);
ServiceOffering so=computeOfferings.iterator().next();
//parse network from cloud_properties
Assert.isTrue(networks.networks.size()==1, "CPI currenly only support 1 network / nic per VM");
String directorNetworkName=networks.networks.keySet().iterator().next();
//NB: directorName must be usefull for vm provisioning ?
com.orange.oss.cloudfoundry.cscpi.domain.Network directorNetwork=networks.networks.values().iterator().next();
String network_name=directorNetwork.cloud_properties.get("name");
//find the network with the provided name
Network network=null;
Set<Network> listNetworks = api.getNetworkApi().listNetworks(ListNetworksOptions.Builder.zoneId(csZoneId));
for (Network n:listNetworks){
if (n.getName().equals(network_name)){
network=n;
}
}
Assert.notNull(network,"Could not find network "+network_name);
Set<NetworkOffering> listNetworkOfferings = api.getOfferingApi().listNetworkOfferings(ListNetworkOfferingsOptions.Builder.zoneId(csZoneId).id(network.getNetworkOfferingId()));
NetworkOffering networkOffering=listNetworkOfferings.iterator().next();
//Requirements, check the provided network, must have a correct prerequisite in offering
// service offering need dhcp (for dhcp bootstrap, and getting vrouter ip, used for metadata access)
// need metadata service for userData
// need dns ?
logger.info("associated Network Offering is {}", networkOffering.getName());
NetworkType netType=directorNetwork.type;
DeployVirtualMachineOptions options=null;
switch (netType)
{
case vip:
case dynamic:
logger.debug("dynamic ip vm creation");
options=DeployVirtualMachineOptions.Builder
.name(vmName)
.networkId(network.getId())
.userData(userData.getBytes())
//.dataDiskSize(dataDiskSize)
;
break;
case manual:
logger.debug("static / manual ip vm creation");
//check ip is available
Assert.isTrue(!this.vmWithIpExists(directorNetwork.ip), "The required IP "+directorNetwork.ip +" is not available");
options=DeployVirtualMachineOptions.Builder
.name(vmName)
.networkId(network.getId())
.userData(userData.getBytes())
//.dataDiskSize(dataDiskSize)
.ipOnDefaultNetwork(directorNetwork.ip)
;
break;
}
logger.info("Now launching VM {} creation !",vmName);
try {
AsyncCreateResponse job = api.getVirtualMachineApi().deployVirtualMachineInZone(csZoneId, so.getId(), csTemplateId, options);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(job.getJobId());
} catch (HttpResponseException hjce){
int statusCode=hjce.getResponse().getStatusCode();
String message=hjce.getResponse().getMessage();
logger.error("Error while creating vm. Status code {}, Message : {} ",statusCode,message);
throw new VMCreationFailedException("Error while creating vm",hjce);
}
VirtualMachine vm = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vmName)).iterator().next();
if (! vm.getState().equals(State.RUNNING)) {
throw new RuntimeException("Not in expected running state:" + vm.getState());
}
//list NICS, check macs.
NIC nic=vm.getNICs().iterator().next();
logger.info("generated NIC : "+nic.toString());
//FIXME: move bosh registry in create_vm (no need of registry for stemcell generation work vms)
//populate bosh registry
logger.info("add vm {} to registry", vmName );
String settings=this.vmSettingGenerator.createsettingForVM(agent_id,vmName,vm,networks);
this.boshRegistry.put(vmName, settings);
logger.info("vm creation completed, now running ! {}");
}
@Override
@Deprecated
public String current_vm_id() {
logger.info("current_vm_id");
//FIXME : deprecated API
//must keep state in CPI with latest changed / created vm ?? Or find current vm running cpi ? by IP / hostname ?
// ==> use local vm meta data server to identify.
// see http://cloudstack-administration.readthedocs.org/en/latest/api.html#user-data-and-meta-data
return null;
}
/**
*
* first try : create a vm from an existing template, stop it, create template from vm, delete work vm
*
* @param image_path
* @param cloud_properties
* @return
*/
@Override
public String create_stemcell(String image_path,
Map<String, String> cloud_properties) {
logger.info("create_stemcell");
//mock mode enables tests with an existing template (copied as a new template)
if (this.cloudstackConfig.mockCreateStemcell){
logger.warn("USING MOCK STEMCELL TRANSFORMATION TO CLOUDSTAK TEMPLATE)");
String stemcellId;
try {
stemcellId = mockTemplateGeneration();
} catch (VMCreationFailedException e) {
throw new RuntimeException(e);
}
return stemcellId;
}
//TODO : template name limited to 32 chars, UUID is longer. use Random for now
Random randomGenerator=new Random();
String stemcellId="cpitemplate-"+randomGenerator.nextInt(100000);
logger.info("Starting to upload stemcell to webdav");
Assert.isTrue(image_path!=null,"create_stemcell: Image Path must not be Null");
File f=new File(image_path);
Assert.isTrue(f.exists(), "create_stemcell: Image Path does not exist :"+image_path);
Assert.isTrue(f.isFile(), "create_stemcell: Image Path exist but is not a file :"+image_path);
String webDavUrl=null;
try {
webDavUrl=this.webdav.pushFile(new FileInputStream(f), stemcellId+".vhd");
} catch (FileNotFoundException e) {
logger.error("Unable to read file");
throw new RuntimeException("Unable to read file",e);
}
logger.debug("template pushed to webdav, url {}",webDavUrl);
//FIXME: find correct os type (PVM 64 bits)
OSType osType=null;
for (OSType ost:api.getGuestOSApi().listOSTypes()){
if (ost.getDescription().equals(CPI_OS_TYPE)) osType=ost;
}
Assert.notNull(osType, "Unable to find OsType");
TemplateMetadata templateMetadata=TemplateMetadata.builder()
.name(stemcellId)
.osTypeId(osType.getId())
.displayText(stemcellId+" : cpi stemcell template")
.build();
RegisterTemplateOptions options=RegisterTemplateOptions.Builder
.bits(64)
.isExtractable(true)
//.isPublic(false) //true is KO
//.isFeatured(false)
//.domainId(domainId)
;
//TODO: get from cloud properties ie from stemcell MANIFEST file ?
String hypervisor="XenServer";
String format="VHD"; // QCOW2, RAW, and VHD.
Set<Template> registredTemplates = api.getTemplateApi().registerTemplate(templateMetadata, format, hypervisor, webDavUrl, findZoneId(), options);
for (Template t: registredTemplates){
logger.debug("registred template "+t.toString());
}
//FIXME: wait for the template to be ready
logger.info("Template successfully registred ! {} - {}",stemcellId);
logger.info("done registering cloudstack template for stemcell {}",stemcellId);
return stemcellId;
}
/**
* Mocktemplate generation : use existing template and copy it as another
*
* @return
*/
private String mockTemplateGeneration() throws VMCreationFailedException {
//String instance_type="Ultra Tiny";
String instance_type="CO1 - Small STD";
//FIXME : should parameter the network offering
String network_name="DefaultIsolatedNetworkOfferingWithSourceNatService";
logger.info("CREATING work vm for template generation");
//map stemcell to cloudstack template concept.
String workVmName="cpi-stemcell-work-"+UUID.randomUUID();
//FIXME : temporay network config (dynamic)
Networks fakeDirectorNetworks=new Networks();
com.orange.oss.cloudfoundry.cscpi.domain.Network net=new com.orange.oss.cloudfoundry.cscpi.domain.Network();
net.type=NetworkType.dynamic;
net.cloud_properties.put("name", "3112 - preprod - back");
net.dns.add("10.234.50.180");
net.dns.add("10.234.71.124");
fakeDirectorNetworks.networks.put("default",net);
this.vmCreation(cloudstackConfig.existingTemplateName, instance_type, fakeDirectorNetworks, workVmName,"fakeagent","fakeuserdata");
VirtualMachine m=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(workVmName)).iterator().next();
logger.info("STOPPING work vm for template generation");
String stopJob=api.getVirtualMachineApi().stopVirtualMachine(m.getId());
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(stopJob);
logger.info("Work vm stopped. now creating template from it its ROOT Volume");
Volume rootVolume=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.virtualMachineId(m.getId()).type(Type.ROOT)).iterator().next();
//hopefully, fist volume is ROOT ?
//FIXME : template name limited to 32 chars, UUID is longer. use Random
Random randomGenerator=new Random();
String stemcellId="cpitemplate-"+randomGenerator.nextInt(100000);
//find correct os type (PVM 64 bits)
OSType osType=null;
for (OSType ost:api.getGuestOSApi().listOSTypes()){
if (ost.getDescription().equals(CPI_OS_TYPE)) osType=ost;
}
Assert.notNull(osType, "Unable to find OsType");
TemplateMetadata templateMetadata=TemplateMetadata.builder()
.name(stemcellId)
.osTypeId(osType.getId())
.volumeId(rootVolume.getId())
.displayText("generated cpi stemcell template")
.build();
CreateTemplateOptions options=CreateTemplateOptions.Builder
.isPublic(true)
.isFeatured(true);
AsyncCreateResponse asyncTemplateCreateJob =api.getTemplateApi().createTemplate(templateMetadata, options);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(asyncTemplateCreateJob.getJobId());
logger.info("Template successfully created ! {} - {}",stemcellId);
logger.info("now cleaning work vm");
String jobId=api.getVirtualMachineApi().destroyVirtualMachine(m.getId());
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(jobId);
logger.info("work vm cleaned work vm");
return stemcellId;
}
@Override
public void delete_stemcell(String stemcell_id) {
logger.info("delete_stemcell");
//FIXME: assert stemcell_id template exists and is unique
Set<Template> listTemplates = api.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.name(stemcell_id));
Assert.isTrue(listTemplates.size()>0,"Could not find any CloudStack Template matching stemcell id "+stemcell_id);
Assert.isTrue(listTemplates.size()==1,"Found multiple CloudStack templates matching stemcell_id "+stemcell_id);
String csTemplateId=listTemplates.iterator().next().getId();
String zoneId=findZoneId();
DeleteTemplateOptions options=DeleteTemplateOptions.Builder.zoneId(zoneId);
AsyncCreateResponse asyncTemplateDeleteJob =api.getTemplateApi().deleteTemplate(csTemplateId, options);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(asyncTemplateDeleteJob.getJobId());
logger.info("stemcell {} successfully deleted",stemcell_id);
}
@Override
public void delete_vm(String vm_id) {
logger.info("delete_vm");
Set<VirtualMachine> vms = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id));
if (vms.size()==0) {
logger.warn("Vm to delete does not exist {}. OK ...",vm_id);
return;
}
Assert.isTrue(vms.size()==1, "delete_vm : Found multiple VMs with name "+vm_id);
VirtualMachine csVm = vms.iterator().next();
String csVmId=csVm.getId();
//stop the vm
String stopJobId=api.getVirtualMachineApi().stopVirtualMachine(csVmId);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(stopJobId);
logger.info("vm {} stopped before destroying");
//remove NIC (free the IP before expunge delay
NIC nic=csVm.getNICs().iterator().next();
logger.info("NIC to delete : {}",nic.toString());
//TODO: can use jclouds to remove the nic?
String jobId=api.getVirtualMachineApi().destroyVirtualMachine(csVmId);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(jobId);
//FIXME : should force expunge VM (bosh usually recreates a vm shortly, expunge is necessary to avoid ip / vols reuse conflicts).
//remove vm_id /settings from bosh registry
logger.info("remove vm {} from registry", vm_id );
this.boshRegistry.delete(vm_id);
//delete ephemeral disk !! Unmount then delete.
Set<Volume> vols=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.type(Type.DATADISK).virtualMachineId(csVmId));
if (vols.size()==0){
logger.warn("No ephemeral disk found while deleting vm {}. Ignoring ...",vm_id);
return;
}
Assert.isTrue(vols.size()==1,"Should have a single data disk mounted (ephemeral disk), found "+vols.size());
Volume ephemeralVol=vols.iterator().next();
Assert.isTrue(ephemeralVol.getName().startsWith(CPI_EPHEMERAL_DISK_PREFIX),"mounted disk is not ephemeral disk. Name is "+ephemeralVol.getName());
//detach disk
AsyncCreateResponse resp=api.getVolumeApi().detachVolume(ephemeralVol.getId());
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(resp.getJobId());
//delete disk
api.getVolumeApi().deleteVolume(ephemeralVol.getId());
logger.info("deleted successfully vm {} and ephemeral disk {}",vm_id,ephemeralVol.getName());
}
@Override
public boolean has_vm(String vm_id) {
logger.info("has_vm ?");
Set<VirtualMachine> listVirtualMachines = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id));
Assert.isTrue(listVirtualMachines.size() <=1, "INCONSISTENCY : multiple vms found for vm_id "+vm_id);
if (listVirtualMachines.size()==0) return false;
return true;
}
@Override
public boolean has_disk(String disk_id) {
logger.info("has_disk ?");
Set<Volume> vols=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK));
Assert.isTrue(vols.size() <=1, "INCONSISTENCY : multiple data volumes found for disk_id "+disk_id);
if (vols.size()==0) return false;
logger.debug("disk {} found in cloudstack", disk_id);
return true;
}
@Override
public void reboot_vm(String vm_id) {
logger.info("reboot_vm");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next();
String rebootJob=api.getVirtualMachineApi().rebootVirtualMachine(vm.getId());
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(rebootJob);
logger.info("done rebooting vm {}",vm_id);
}
/**
* add metadata to the VM. CPI should not rely on the presence of specific ket
*/
@Override
public void set_vm_metadata(String vm_id, Map<String, String> metadata) {
logger.info("set vm metadata");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next();
//set metadatas
setVmMetada(vm_id, metadata, vm);
}
/**
*
* adapter method to cloudstack User Tag API
* @param vm_id cloudstack vm id
* @param metadata map of tag name / value
* @param vm cloudstack VirtualMachine
*/
private void setVmMetada(String vm_id, Map<String, String> metadata,
VirtualMachine vm) {
//NB: must merge with preexisting user tags. delete previous tag
ListTagsOptions listTagOptions=ListTagsOptions.Builder.resourceId(vm.getId()).resourceType(Tag.ResourceType.USER_VM);
Set<Tag> existingTags=api.getTagApi().listTags(listTagOptions);
if (existingTags.size()>0) {
//FIXME: merge change existing tags
logger.warn("VM metadata already set on vm {}.Metadata change not yet implemented by CPI");
return;
}
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
Map<String, String> tags = builder.putAll(metadata).build();
logger.debug(">> adding tags %s to virtualmachine(%s)", tags, vm.getId());
CreateTagsOptions tagOptions = CreateTagsOptions.Builder.resourceIds(vm.getId()).resourceType(Tag.ResourceType.USER_VM).tags(tags);
AsyncCreateResponse tagJob = api.getTagApi().createTags(tagOptions);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(tagJob.getJobId());
logger.info("done settings metadata on vm ",vm_id);
}
/**
* Modify the VM network configuration
* NB: throws NotSupported error for now. => The director will delete the VM and recreate a new One with the desired target conf
* @throws com.orange.oss.cloudfoundry.cscpi.exceptions.NotSupportedException
*/
@Override
public void configure_networks(String vm_id, Networks networks) throws com.orange.oss.cloudfoundry.cscpi.exceptions.NotSupportedException {
logger.info("configure network");
throw new com.orange.oss.cloudfoundry.cscpi.exceptions.NotSupportedException("CPI does not support modifying network yet");
}
@Override
public String create_disk(Integer size, Map<String, String> cloud_properties) {
String diskOfferingName=cloud_properties.get("disk_offering");
Assert.isTrue(diskOfferingName!=null, "no disk_offering attribute specified for disk creation !");
if (diskOfferingName==null){
diskOfferingName=this.cloudstackConfig.defaultDiskOffering;
logger.info("no disk_offering attribute specified for disk creation. use global CPI default disk offering: {}",diskOfferingName);
}
String name=CPI_PERSISTENT_DISK_PREFIX+UUID.randomUUID().toString();
return this.diskCreate(name,size,diskOfferingName);
}
/**
* @param diskOfferingName
* @return
*/
private String diskCreate(String name,int size,String diskOfferingName) {
logger.info("create_disk {} on offering {}",name,diskOfferingName);
//find disk offering
Set<DiskOffering> listDiskOfferings = api.getOfferingApi().listDiskOfferings(ListDiskOfferingsOptions.Builder.name(diskOfferingName));
Assert.isTrue(listDiskOfferings.size()>0, "Unknown Service Offering ! : "+diskOfferingName);
DiskOffering csDiskOffering = listDiskOfferings.iterator().next();
String diskOfferingId=csDiskOffering.getId();
String zoneId=this.findZoneId();
AsyncCreateResponse resp=null;
if (csDiskOffering.isCustomized()){
logger.info("creating disk with specified size (custom size offering)");
resp=api.getVolumeApi().createVolumeFromCustomDiskOfferingInZone(name, diskOfferingId, zoneId, size);
} else {
logger.info("creating disk - ignoring specified size {} (fixed by offering : {} )",size,csDiskOffering.getDiskSize());
resp=api.getVolumeApi().createVolumeFromDiskOfferingInZone(name, diskOfferingId, zoneId);
}
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(resp.getJobId());
logger.info("disk {} successfully created ",name);
return name;
}
@Override
public void delete_disk(String disk_id) {
logger.info("delete_disk");
//FIXME; check disk exists
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK)).iterator().next().getId();
api.getVolumeApi().deleteVolume(csDiskId);
}
@Override
public void attach_disk(String vm_id, String disk_id) {
logger.info("attach disk");
this.diskAttachment(vm_id, disk_id);
//now update registry
String previousSetting=this.boshRegistry.getRaw(vm_id);
String newSetting=this.vmSettingGenerator.updateVmSettingForAttachDisk(previousSetting, disk_id);
this.boshRegistry.put(vm_id, newSetting);
logger.info("==> attach disk updated in bosh registry");
}
/**
* Cloudstack Attachement.
* Used for persistent disks and ephemeral disk
* @param vm_id
* @param disk_id
*/
private void diskAttachment(String vm_id, String disk_id) {
//FIXME; check disk exists
//FIXME: check vm exists
Set<Volume> volumes = api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK));
Assert.isTrue(volumes.size()<2,"attach_disk: Fatal, Found multiple volume with name "+disk_id);
Assert.isTrue(volumes.size()==1,"attach_disk: Unable to find volume "+disk_id);
String csDiskId=volumes.iterator().next().getId();
Set<VirtualMachine> vms = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id));
Assert.isTrue(vms.size()==1, "attach_disk: Unable to find vm "+vm_id);
String csVmId=vms.iterator().next().getId();
//FIXME: with local disk, should check the host and vm host id match ?
VolumeApi vol = this.api.getVolumeApi();
AsyncCreateResponse resp=vol.attachVolume(csDiskId, csVmId);
//TODO: need to restart vm ?
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(resp.getJobId());
logger.info("==> attach disk successfull");
}
@Override
public String snapshot_disk(String disk_id, Map<String, String> metadata) {
logger.info("snapshot disk");
String csDiskId=api.getVolumeApi().getVolume(disk_id).getId();
AsyncCreateResponse async = api.getSnapshotApi().createSnapshot(csDiskId,CreateSnapshotOptions.Builder.domainId("domain"));
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(async.getJobId());
//FIXME
return null;
}
@Override
public void delete_snapshot(String snapshot_id) {
logger.info("delete snapshot");
//TODO
}
@Override
public void detach_disk(String vm_id, String disk_id) {
logger.info("detach disk");
String csDiskId=api.getVolumeApi().listVolumes(ListVolumesOptions.Builder.name(disk_id).type(Type.DATADISK)).iterator().next().getId();
AsyncCreateResponse resp=api.getVolumeApi().detachVolume(csDiskId);
jobComplete = retry(new JobComplete(api), 1200, 3, 5, SECONDS);
jobComplete.apply(resp.getJobId());
logger.info("==> detach disk successfull");
//now update registry
String previousSetting=this.boshRegistry.getRaw(vm_id);
String newSetting=this.vmSettingGenerator.updateVmSettingForDetachDisk(previousSetting, disk_id);
this.boshRegistry.put(vm_id, newSetting);
logger.info("==> attach disk updated in bosh registry");
}
@Override
public List<String> get_disks(String vm_id) {
logger.info("get_disks");
VirtualMachine vm=api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.name(vm_id)).iterator().next();
VolumeApi vol = this.api.getVolumeApi();
Set<Volume> vols=vol.listVolumes(ListVolumesOptions.Builder.virtualMachineId(vm.getId()));
ArrayList<String> disks = new ArrayList<String>();
Iterator<Volume> it=vols.iterator();
while (it.hasNext()){
Volume v=it.next();
//only DATA disk - persistent disk. No ROOT disk,no ephemeral disk ?
if ((v.getType()==Type.DATADISK) && (v.getName().startsWith(CPI_PERSISTENT_DISK_PREFIX))){
String disk_id=v.getName();
disks.add(disk_id);
}
}
return disks;
}
/**
* utility to retrieve cloudstack zoneId
* @return
*/
private String findZoneId() {
//TODO: select the exact zone if multiple available
ListZonesOptions zoneOptions=ListZonesOptions.Builder.available(true);
Set<Zone> zones = api.getZoneApi().listZones(zoneOptions);
Assert.notEmpty(zones, "No Zone available");
Zone zone=zones.iterator().next();
String zoneId = zone.getId();
Assert.isTrue(zone.getName().equals(this.cloudstackConfig.default_zone));
return zoneId;
}
/**
* utility method to check ip conflict
* @param ip
* @return
*/
public boolean vmWithIpExists(String ip) {
logger.debug("check vm exist with ip {}",ip);
Set<VirtualMachine> listVirtualMachines = api.getVirtualMachineApi().listVirtualMachines(ListVirtualMachinesOptions.Builder.zoneId(this.findZoneId()));
boolean ipExists=false;
for (VirtualMachine vm:listVirtualMachines){
String vmIp=vm.getIPAddress();
if ((vmIp!=null)&& (vmIp.equals(ip))){
logger.warn("vm {} already uses ip {}",vm.getName(),ip);
ipExists=true;
}
}
return ipExists;
}
} |
package com.sandwell.JavaSimulation3D;
import java.util.ArrayList;
import java.util.HashMap;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.Color4d;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.BooleanListInput;
import com.sandwell.JavaSimulation.BooleanVector;
import com.sandwell.JavaSimulation.ColourInput;
import com.sandwell.JavaSimulation.DoubleInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.Keyword;
import com.sandwell.JavaSimulation.ProbabilityDistribution;
import com.sandwell.JavaSimulation.Process;
import com.sandwell.JavaSimulation.Tester;
import com.sandwell.JavaSimulation.Vector;
/**
* Class ModelEntity - JavaSimulation3D
*/
public class ModelEntity extends DisplayEntity {
// Breakdowns
@Keyword(desc = "Reliability is defined as:\n" +
" 100% - (plant breakdown time / total operation time)\n " +
"or\n " +
"(Operational Time)/(Breakdown + Operational Time)",
example = "Object1 Reliability { 0.95 }")
private final DoubleInput availability;
protected double hoursForNextFailure; // The number of working hours required before the next breakdown
protected double iATFailure; // inter arrival time between failures
protected boolean breakdownPending; // true when a breakdown is to occur
protected boolean brokendown; // true => entity is presently broken down
protected boolean maintenance; // true => entity is presently in maintenance
protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown
protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance
protected double breakdownStartTime; // Start time of the most recent breakdown
protected double breakdownEndTime; // End time of the most recent breakdown
// Breakdown Probability Distributions
@Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).",
example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution;
@Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).",
example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeIATDistribution;
// Maintenance
@Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.",
example = "Object1 FirstMaintenanceTime { 24 h }")
protected DoubleListInput firstMaintenanceTimes;
@Keyword(desc = "The time between maintenance activities for each maintenance cycle",
example = "Object1 MaintenanceInterval { 168 h }")
protected DoubleListInput maintenanceIntervals;
@Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.",
example = "Object1 MaintenanceDuration { 336 h }")
protected DoubleListInput maintenanceDurations;
protected IntegerVector maintenancePendings; // Number of maintenance periods that are due
@Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " +
"with another planned maintenance event.",
example = "Object1 SkipMaintenanceIfOverlap { TRUE }")
protected BooleanListInput skipMaintenanceIfOverlap;
@Keyword(desc = "A list of objects that share the maintenance schedule with this object. " +
"In order for the maintenance to start, all objects on this list must be available." +
"This keyword is for Handlers and Signal Blocks only.",
example = "Block1 SharedMaintenance { Block2 Block2 }")
private final EntityListInput<ModelEntity> sharedMaintenanceList;
protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information
protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay
// Maintenance based on hours of operations
@Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle",
example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }")
private final DoubleListInput firstMaintenanceOperatingHours;
@Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle",
example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }")
private final DoubleListInput maintenanceOperatingHoursIntervals;
@Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle",
example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }")
private final DoubleListInput maintenanceOperatingHoursDurations;
protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due
protected DoubleVector hoursForNextMaintenanceOperatingHours;
protected double maintenanceStartTime; // Start time of the most recent maintenance
protected double maintenanceEndTime; // End time of the most recent maintenance
protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance
protected double nextMaintenanceDuration; // duration for next maintenance
protected DoubleVector lastScheduledMaintenanceTimes;
@Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " +
"for longer than this time, the maintenance will start even if " +
"there is an object within the lookahead. There must be one entry for each " +
"defined maintenance schedule if DeferMaintenanceLookAhead is used. This" +
"keyword is only used for signal blocks.",
example = "Object1 DeferMaintenanceLimit { 50 50 h }")
private final DoubleListInput deferMaintenanceLimit;
@Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released",
example = "Object1 DowntimeToReleaseEquipment { 1.0 h }")
protected final DoubleInput downtimeToReleaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " +
"then routes/tasks are released before performing the maintenance in the cycle.",
example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }")
protected final BooleanListInput releaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " +
"TRUE, then maintenance in the cycle can start even if the equipment is presently " +
"working.",
example = "Object1 ForceMaintenance { TRUE FALSE FALSE }")
protected final BooleanListInput forceMaintenance;
// Statistics
@Keyword(desc = "If TRUE, then statistics for this object are " +
"included in the main output report.",
example = "Object1 PrintToReport { TRUE }")
private final BooleanInput printToReport;
// States
private static Vector stateList = new Vector( 11, 1 ); // List of valid states
private final HashMap<String, StateRecord> stateMap;
protected double workingHours; // Accumulated working time spent in working states
private double timeOfLastStateChange;
private int numberOfCompletedCycles;
private double startOfCycleTime;
private double maxCycleDur;
private double minCycleDur;
private double totalCompletedCycleHours;
protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity
protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity
private StateRecord presentState; // The present state of the entity
protected FileEntity stateReportFile; // The file to store the state information
// Graphics
protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down
protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance
static {
stateList.addElement( "Idle" );
stateList.addElement( "Working" );
stateList.addElement( "Breakdown" );
stateList.addElement( "Maintenance" );
}
{
maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector());
maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceDurations.setUnits("h");
this.addInput(maintenanceDurations, true, "MaintenanceDuration");
maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector());
maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceIntervals.setUnits("h");
this.addInput(maintenanceIntervals, true, "MaintenanceInterval");
firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector());
firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceTimes.setUnits("h");
this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime");
forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null);
this.addInput(forceMaintenance, true);
releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null);
this.addInput(releaseEquipment, true);
availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d);
this.addInput(availability, true);
downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null);
this.addInput(downtimeIATDistribution, true);
downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null);
this.addInput(downtimeDurationDistribution, true);
downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY);
this.addInput(downtimeToReleaseEquipment, true);
skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector());
this.addInput(skipMaintenanceIfOverlap, true);
deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null);
deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY);
deferMaintenanceLimit.setUnits("h");
this.addInput(deferMaintenanceLimit, true);
sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0));
this.addInput(sharedMaintenanceList, true);
firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector());
firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceOperatingHours.setUnits("h");
this.addInput(firstMaintenanceOperatingHours, true);
maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector());
maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursDurations.setUnits("h");
this.addInput(maintenanceOperatingHoursDurations, true);
maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector());
maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursIntervals.setUnits("h");
this.addInput(maintenanceOperatingHoursIntervals, true);
printToReport = new BooleanInput("PrintToReport", "Report", true);
this.addInput(printToReport, true);
}
public ModelEntity() {
lastHistogramUpdateTime = 0.0;
secondToLastHistogramUpdateTime = 0.0;
hoursForNextFailure = 0.0;
iATFailure = 0.0;
maintenancePendings = new IntegerVector( 1, 1 );
maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 );
hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 );
performMaintenanceAfterShipDelayPending = false;
lastScheduledMaintenanceTimes = new DoubleVector();
breakdownStartTime = 0.0;
breakdownEndTime = Double.POSITIVE_INFINITY;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenanceStartTime = 0.0;
maintenanceEndTime = Double.POSITIVE_INFINITY;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
stateMap = new HashMap<String, StateRecord>();
StateRecord idle = new StateRecord("Idle", 0);
stateMap.put("idle" , idle);
presentState = idle;
timeOfLastStateChange = getCurrentTime();
idle.lastStartTimeInState = getCurrentTime();
idle.secondLastStartTimeInState = getCurrentTime();
initStateMap();
}
/**
* Clear internal properties
*/
public void clearInternalProperties() {
hoursForNextFailure = 0.0;
performMaintenanceAfterShipDelayPending = false;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
}
@Override
public void validate()
throws InputErrorException {
super.validate();
this.validateMaintenance();
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals");
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations");
if( getAvailability() < 1.0 ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!");
}
}
if( downtimeIATDistribution.getValue() != null ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set.");
}
}
if( skipMaintenanceIfOverlap.getValue().size() > 0 )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap");
if( releaseEquipment.getValue() != null )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment");
if( forceMaintenance.getValue() != null ) {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance");
}
if(downtimeDurationDistribution.getValue() != null &&
downtimeDurationDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values");
if(downtimeIATDistribution.getValue() != null &&
downtimeIATDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeIATDistribution cannot allow negative values");
}
@Override
public void earlyInit() {
super.earlyInit();
if( downtimeDurationDistribution.getValue() != null ) {
downtimeDurationDistribution.getValue().initialize();
}
if( downtimeIATDistribution.getValue() != null ) {
downtimeIATDistribution.getValue().initialize();
}
}
public int getNumberOfCompletedCycles() {
return numberOfCompletedCycles;
}
// INPUT
public void validateMaintenance() {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals");
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations");
for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) {
if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) {
throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)",
maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i));
}
}
}
// INITIALIZATION METHODS
public void clearStatistics() {
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() );
}
// Determine the time for the first breakdown event
/*if ( downtimeIATDistribution == null ) {
if( breakdownSeed != 0 ) {
breakdownRandGen.initialiseWith( breakdownSeed );
hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure );
} else {
hoursForNextFailure = getNextBreakdownIAT();
}
}
else {
hoursForNextFailure = getNextBreakdownIAT();
}*/
}
/**
* *!*!*!*! OVERLOAD !*!*!*!*
* Initialize statistics
*/
public void initialize() {
brokendown = false;
maintenance = false;
associatedBreakdown = false;
associatedMaintenance = false;
// Create state trace file if required
if (testFlag(FLAG_TRACESTATE)) {
String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc";
stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
}
workingHours = 0.0;
// Calculate the average downtime duration if distributions are used
double average = 0.0;
if(getDowntimeDurationDistribution() != null)
average = getDowntimeDurationDistribution().getExpectedValue();
// Calculate the average downtime inter-arrival time
if( (getAvailability() == 1.0 || average == 0.0) ) {
iATFailure = 10.0E10;
}
else {
if( getDowntimeIATDistribution() != null ) {
iATFailure = getDowntimeIATDistribution().getExpectedValue();
// Adjust the downtime inter-arrival time to get the specified availability
if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) {
getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this );
iATFailure = getDowntimeIATDistribution().getExpectedValue();
}
}
else {
iATFailure = ( (average / (1.0 - getAvailability())) - average );
}
}
// Determine the time for the first breakdown event
hoursForNextFailure = getNextBreakdownIAT();
this.setPresentState( "Idle" );
brokendown = false;
// Start the maintenance network
if( firstMaintenanceTimes.getValue().size() != 0 ) {
maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 );
lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY );
this.doMaintenanceNetwork();
}
// calculate hours for first operating hours breakdown
for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) );
maintenanceOperatingHoursPendings.add( 0 );
}
}
// ACCESSOR METHODS
/**
* Return the time at which the most recent maintenance is scheduled to end
*/
public double getMaintenanceEndTime() {
return maintenanceEndTime;
}
/**
* Return the time at which a the most recent breakdown is scheduled to end
*/
public double getBreakdownEndTime() {
return breakdownEndTime;
}
public double getTimeOfLastStateChange() {
return timeOfLastStateChange;
}
/**
* Returns the availability proportion.
*/
public double getAvailability() {
return availability.getValue();
}
public DoubleListInput getFirstMaintenanceTimes() {
return firstMaintenanceTimes;
}
public boolean getPrintToReport() {
return printToReport.getValue();
}
/**
* Return true if the entity is working
*/
public boolean isWorking() {
return false;
}
public boolean isBrokendown() {
return brokendown;
}
public boolean isBreakdownPending() {
return breakdownPending;
}
public boolean isInAssociatedBreakdown() {
return associatedBreakdown;
}
public boolean isInMaintenance() {
return maintenance;
}
public boolean isInAssociatedMaintenance() {
return associatedMaintenance;
}
public boolean isInService() {
return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance );
}
public void setBrokendown( boolean bool ) {
brokendown = bool;
this.setPresentState();
}
public void setMaintenance( boolean bool ) {
maintenance = bool;
this.setPresentState();
}
public void setAssociatedBreakdown( boolean bool ) {
associatedBreakdown = bool;
}
public void setAssociatedMaintenance( boolean bool ) {
associatedMaintenance = bool;
}
public ProbabilityDistribution getDowntimeDurationDistribution() {
return downtimeDurationDistribution.getValue();
}
public double getDowntimeToReleaseEquipment() {
return downtimeToReleaseEquipment.getValue();
}
public boolean hasServiceDefined() {
return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null );
}
// HOURS AND STATES
public static class StateRecord {
public final String name;
int index;
double initializationHours;
double totalHours;
double completedCycleHours;
double currentCycleHours;
double lastStartTimeInState;
double secondLastStartTimeInState;
private StateRecord(String state, int i) {
name = state;
index = i;
}
public int getIndex() {
return index;
}
public double getTotalHours() {
return totalHours;
}
public double getCompletedCycleHours() {
return completedCycleHours;
}
public double getCurrentCycleHours() {
return currentCycleHours;
}
public double getLastStartTimeInState() {
return lastStartTimeInState;
}
public double getSecondLastStartTimeInState() {
return secondLastStartTimeInState;
}
@Override
public String toString() {
return name;
}
}
public void initStateMap() {
// Populate the hash map for the states and StateRecord
StateRecord idle = getStateRecordFor("Idle");
stateMap.clear();
for (int i = 0; i < getStateList().size(); i++) {
String state = (String)getStateList().get(i);
if ( state.equals("Idle") ) {
idle.index = i;
continue;
}
StateRecord stateRecord = new StateRecord(state, i);
stateMap.put(state.toLowerCase() , stateRecord);
}
stateMap.put("idle", idle);
timeOfLastStateChange = getCurrentTime();
maxCycleDur = 0.0d;
minCycleDur = Double.POSITIVE_INFINITY;
totalCompletedCycleHours = 0.0d;
startOfCycleTime = getCurrentTime();
}
/**
* Runs after initialization period
*/
public void collectInitializationStats() {
collectPresentHours();
for ( StateRecord each : stateMap.values() ) {
each.initializationHours = each.getTotalHours();
each.totalHours = 0.0d;
each.completedCycleHours = 0.0d;
}
numberOfCompletedCycles = 0;
maxCycleDur = 0.0d;
minCycleDur = Double.POSITIVE_INFINITY;
totalCompletedCycleHours = 0.0d;
}
/**
* Runs when cycle is finished
*/
public void collectCycleStats() {
collectPresentHours();
// finalize cycle for each state record
for ( StateRecord each : stateMap.values() ) {
each.completedCycleHours += each.getCurrentCycleHours();
each.currentCycleHours = 0.0d;
}
numberOfCompletedCycles++;
double dur = getCurrentTime() - startOfCycleTime;
maxCycleDur = Math.max(maxCycleDur, dur);
minCycleDur = Math.min(minCycleDur, dur);
totalCompletedCycleHours += dur;
startOfCycleTime = getCurrentTime();
}
/**
* Clear the current cycle hours, also reset the start of cycle time
*/
protected void clearCurrentCycleHours() {
collectPresentHours();
// clear current cycle hours for each state record
for ( StateRecord each : stateMap.values() )
each.currentCycleHours = 0.0d;
startOfCycleTime = getCurrentTime();
}
/**
* Runs after each report interval
*/
public void clearReportStats() {
collectPresentHours();
// clear totalHours for each state record
for ( StateRecord each : stateMap.values() ) {
each.totalHours = 0.0d;
each.completedCycleHours = 0.0d;
}
numberOfCompletedCycles = 0;
maxCycleDur = 0.0d;
minCycleDur = Double.POSITIVE_INFINITY;
totalCompletedCycleHours = 0.0d;
}
/**
* Update the hours for the present state and set new timeofLastStateChange
*/
private void collectPresentHours() {
double curTime = getCurrentTime();
if (curTime == timeOfLastStateChange)
return;
double duration = curTime - timeOfLastStateChange;
timeOfLastStateChange = curTime;
presentState.totalHours += duration;
presentState.currentCycleHours += duration;
if (this.isWorking())
workingHours += duration;
}
/**
* A callback subclasses can override that is called on each state transition.
*
* The state has not been changed when this is called, so presentState is still
* valid.
*
* @param next the state being transitioned to
*/
public void stateChanged(StateRecord next) {}
/**
* Updates the statistics, then sets the present status to be the specified value.
*/
public void setPresentState( String state ) {
if (presentState.name.equals(state))
return;
StateRecord nextState = this.getStateRecordFor(state);
if (nextState == null)
throw new ErrorException("%s Specified state: %s was not found in the StateList: %s",
this.getInputName(), state, this.getStateList());
if (traceFlag) {
StringBuffer buf = new StringBuffer("setState( ");
buf.append(nextState.name).append(" )");
this.trace(buf.toString());
buf.setLength(0);
buf.append(" Old State = ").append(presentState.name);
this.traceLine(buf.toString());
}
double curTime = getCurrentTime();
if (testFlag(FLAG_TRACESTATE) && curTime != timeOfLastStateChange) {
double duration = curTime - timeOfLastStateChange;
stateReportFile.format("%.5f %s.setState( \"%s\" ) dt = %g\n",
timeOfLastStateChange, this.getInputName(),
presentState.name, duration);
stateReportFile.flush();
}
collectPresentHours();
stateChanged(nextState);
nextState.secondLastStartTimeInState = nextState.getLastStartTimeInState();
nextState.lastStartTimeInState = timeOfLastStateChange;
presentState = nextState;
}
public StateRecord getStateRecordFor(String state) {
return stateMap.get(state.toLowerCase());
}
private StateRecord getStateRecordFor(int index) {
String state = (String)getStateList().get(index);
return getStateRecordFor(state);
}
public double getTotalHoursFor(StateRecord state) {
double hours = state.getTotalHours();
if (presentState == state)
hours += getCurrentTime() - timeOfLastStateChange;
return hours;
}
public double getTotalHoursFor(String state) {
StateRecord rec = getStateRecordFor(state);
return getTotalHoursFor(rec);
}
public double getTotalHoursFor(int index) {
return getTotalHoursFor( (String) getStateList().get(index) );
}
public double getTotalHours() {
double total = getCurrentTime() - timeOfLastStateChange;
for (int i = 0; i < getNumberOfStates(); i++)
total += getStateRecordFor(i).getTotalHours();
return total;
}
public double getCompletedCycleHoursFor(String state) {
return getStateRecordFor(state).getCompletedCycleHours();
}
public double getCompletedCycleHoursFor(int index) {
return getStateRecordFor(index).getCompletedCycleHours();
}
public double getCompletedCycleHours() {
return totalCompletedCycleHours;
}
public double getCurrentCycleHoursFor(StateRecord state) {
double hours = state.getCurrentCycleHours();
if (presentState == state)
hours += getCurrentTime() - timeOfLastStateChange;
return hours;
}
/**
* Returns the amount of time spent in the specified state in current cycle
*/
public double getCurrentCycleHoursFor( String state ) {
StateRecord rec = getStateRecordFor(state);
return getCurrentCycleHoursFor(rec);
}
/**
* Return spent hours for a given state at the index in stateList for current cycle
*/
public double getCurrentCycleHoursFor(int index) {
StateRecord rec = getStateRecordFor(index);
return getCurrentCycleHoursFor(rec);
}
/**
* Return the total hours in current cycle for all the states
*/
public double getCurrentCycleHours() {
double total = getCurrentTime() - timeOfLastStateChange;
for (int i = 0; i < getNumberOfStates(); i++) {
total += getStateRecordFor(i).getCurrentCycleHours();
}
return total;
}
public double getStartCycleTime() {
return startOfCycleTime;
}
/**
* Returns the present state name
*/
public String getPresentState() {
return presentState.name;
}
public StateRecord getState() {
return presentState;
}
public boolean presentStateEquals(String state) {
return getPresentState().equals(state);
}
public boolean presentStateMatches(String state) {
return getPresentState().equalsIgnoreCase(state);
}
public boolean presentStateStartsWith(String prefix) {
return getPresentState().startsWith(prefix);
}
public boolean presentStateEndsWith(String suffix) {
return getPresentState().endsWith(suffix);
}
protected int getPresentStateIndex() {
return presentState.getIndex();
}
public void setPresentState() {}
/**
* Set the last time a histogram was updated for this entity
*/
public void setLastHistogramUpdateTime( double time ) {
secondToLastHistogramUpdateTime = lastHistogramUpdateTime;
lastHistogramUpdateTime = time;
}
/**
* Returns the time from the start of the start state to the start of the end state
*/
public double getTimeFromStartState_ToEndState( String startState, String endState) {
// Determine the index of the start state
StateRecord startStateRec = this.getStateRecordFor(startState);
if (startStateRec == null) {
throw new ErrorException("Specified state: %s was not found in the StateList.", startState);
}
// Determine the index of the end state
StateRecord endStateRec = this.getStateRecordFor(endState);
if (endStateRec == null) {
throw new ErrorException("Specified state: %s was not found in the StateList.", endState);
}
// Is the start time of the end state greater or equal to the start time of the start state?
if (endStateRec.getLastStartTimeInState() >= startStateRec.getLastStartTimeInState()) {
// If either time was not in the present cycle, return NaN
if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ||
startStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the last start time of the start state to the last start time of the end state
return endStateRec.getLastStartTimeInState() - startStateRec.getLastStartTimeInState();
}
else {
// If either time was not in the present cycle, return NaN
if (endStateRec.getLastStartTimeInState() <= lastHistogramUpdateTime ||
startStateRec.getSecondLastStartTimeInState() <= secondToLastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the second to last start time of the start date to the last start time of the end state
return endStateRec.getLastStartTimeInState() - startStateRec.getSecondLastStartTimeInState();
}
}
/**
* Return the commitment
*/
public double getCommitment() {
return 1.0 - this.getFractionOfTimeForState( "Idle" );
}
/**
* Return the fraction of time for the given status
*/
public double getFractionOfTimeForState( String aState ) {
if( getTotalHours() > 0.0 ) {
return ((this.getTotalHoursFor( aState ) / getTotalHours()) );
}
else {
return 0.0;
}
}
/**
* Return the percentage of time for the given status
*/
public double getPercentageOfTimeForState( String aState ) {
if( getTotalHours() > 0.0 ) {
return ((this.getTotalHoursFor( aState ) / getTotalHours()) * 100.0);
}
else {
return 0.0;
}
}
/**
* Returns the number of hours the entity is in use.
* *!*!*!*! OVERLOAD !*!*!*!*
*/
public double getWorkingHours() {
double hours = 0.0d;
if ( this.isWorking() )
hours = getCurrentTime() - timeOfLastStateChange;
return workingHours + hours;
}
public double getMaxCycleDur() {
return maxCycleDur;
}
public double getMinCycleDur() {
return minCycleDur;
}
public Vector getStateList() {
return stateList;
}
/**
* Return total number of states
*/
public int getNumberOfStates() {
return stateMap.size();
}
// MAINTENANCE METHODS
/**
* Perform tasks required before a maintenance period
*/
public void doPreMaintenance() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Start working again following a breakdown or maintenance period
*/
public void restart() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown
*/
public void releaseEquipment() {}
public boolean releaseEquipmentForMaintenanceSchedule( int index ) {
if( releaseEquipment.getValue() == null )
return true;
return releaseEquipment.getValue().get( index );
}
public boolean forceMaintenanceSchedule( int index ) {
if( forceMaintenance.getValue() == null )
return false;
return forceMaintenance.getValue().get( index );
}
/**
* Perform all maintenance schedules that are due
*/
public void doMaintenance() {
// scheduled maintenance
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( this.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.doMaintenance(index);
}
}
// Operating hours maintenance
for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) {
hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index ));
maintenanceOperatingHoursPendings.addAt( 1, index );
this.doMaintenanceOperatingHours(index);
}
}
}
/**
* Perform all the planned maintenance that is due for the given schedule
*/
public void doMaintenance( int index ) {
double wait;
if( masterMaintenanceEntity != null ) {
wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index );
}
else {
wait = this.getMaintenanceDurations().getValue().get( index );
}
if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) {
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
if( masterMaintenanceEntity != null ) {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) );
}
else {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) );
}
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
// Release equipment if necessary
if( this.releaseEquipmentForMaintenanceSchedule( index ) ) {
this.releaseEquipment();
}
while( maintenancePendings.get( index ) != 0 ) {
maintenancePendings.subAt( 1, index );
scheduleWait( wait );
// If maintenance pending goes negative, something is wrong
if( maintenancePendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
this.setPresentState( "Idle" );
maintenance = false;
this.restart();
}
}
/**
* Perform all the planned maintenance that is due
*/
public void doMaintenanceOperatingHours( int index ) {
if(maintenanceOperatingHoursPendings.get( index ) == 0 )
return;
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
maintenanceEndTime = maintenanceStartTime +
(maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index));
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
while( maintenanceOperatingHoursPendings.get( index ) != 0 ) {
//scheduleWait( maintenanceDurations.get( index ) );
scheduleWait( maintenanceEndTime - maintenanceStartTime );
maintenanceOperatingHoursPendings.subAt( 1, index );
// If maintenance pending goes negative, something is wrong
if( maintenanceOperatingHoursPendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
maintenance = false;
this.setPresentState( "Idle" );
this.restart();
}
/**
* Check if a maintenance is due. if so, try to perform the maintenance
*/
public boolean checkMaintenance() {
if( traceFlag ) this.trace( "checkMaintenance()" );
if( checkOperatingHoursMaintenance() ) {
return true;
}
// List of all entities going to maintenance
ArrayList<ModelEntity> sharedMaintenanceEntities;
// This is not a master maintenance entity
if( masterMaintenanceEntity != null ) {
sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList();
}
// This is a master maintenance entity
else {
sharedMaintenanceEntities = getSharedMaintenanceList();
}
// If this entity is in shared maintenance relation with a group of entities
if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) {
// Are all entities in the group ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// For every entity in the shared maintenance list plus the master maintenance entity
for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) {
ModelEntity aModel;
// Locate master maintenance entity( after all entity in shared maintenance list have been taken care of )
if( i == sharedMaintenanceEntities.size() ) {
// This entity is manster maintenance entity
if( masterMaintenanceEntity == null ) {
aModel = this;
}
// This entity is on the shared maintenannce list of the master maintenance entity
else {
aModel = masterMaintenanceEntity;
}
}
// Next entity in the shared maintenance list
else {
aModel = sharedMaintenanceEntities.get( i );
}
// Check for aModel maintenances
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( aModel.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
aModel.startProcess("doMaintenance", index);
}
}
}
return true;
}
else {
return false;
}
}
// This block is maintained indipendently
else {
// Check for maintenances
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
if( this.canStartMaintenance( i ) ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i );
this.startProcess("doMaintenance", i);
return true;
}
}
}
}
return false;
}
/**
* Determine how many hours of maintenance is scheduled between startTime and endTime
*/
public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) {
if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" );
double totalHours = 0.0;
double firstTime = 0.0;
// Add on hours for all pending maintenance
for( int i=0; i < maintenancePendings.size(); i++ ) {
totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i );
}
if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours );
// Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime
for( int i=0; i < maintenancePendings.size(); i++ ) {
// Find the first time that maintenance is scheduled after startTime
firstTime = firstMaintenanceTimes.getValue().get( i );
while( firstTime < startTime ) {
firstTime += maintenanceIntervals.getValue().get( i );
}
if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime );
// Now have the first maintenance start time after startTime
// Add all maintenances that lie in the given interval
while( firstTime < endTime ) {
if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime );
// Add the maintenance
totalHours += maintenanceDurations.getValue().get( i );
// Update the search period
endTime += maintenanceDurations.getValue().get( i );
// Look for next maintenance in new interval
firstTime += maintenanceIntervals.getValue().get( i );
if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) );
}
}
// Return the total hours of maintenance scheduled from startTime to endTime
if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours );
return totalHours;
}
public boolean checkOperatingHoursMaintenance() {
if( traceFlag ) this.trace("checkOperatingHoursMaintenance()");
// Check for maintenances
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
// If the entity is not available, maintenance cannot start
if( ! this.canStartMaintenance( i ) )
continue;
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i )));
maintenanceOperatingHoursPendings.addAt( 1, i );
if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i );
this.startProcess("doMaintenanceOperatingHours", i);
return true;
}
}
return false;
}
/**
* Wrapper method for doMaintenance_Wait.
*/
public void doMaintenanceNetwork() {
this.startProcess("doMaintenanceNetwork_Wait");
}
/**
* Network for planned maintenance.
* This method should be called in the initialize method of the specific entity.
*/
public void doMaintenanceNetwork_Wait() {
// Initialize schedules
for( int i=0; i < maintenancePendings.size(); i++ ) {
maintenancePendings.set( i, 0 );
}
nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue());
nextMaintenanceDuration = 0;
// Find the next maintenance event
int index = 0;
double earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
// Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO)
scheduleLastLIFO();
while( true ) {
double dt = earliestTime - getCurrentTime();
// Wait for the maintenance check time
if( dt > Process.getEventTolerance() ) {
scheduleWait( dt );
}
// Increment the number of maintenances due for the entity
maintenancePendings.addAt( 1, index );
// If this is a master maintenance entity
if (getSharedMaintenanceList().size() > 0) {
// If all the entities on the shared list are ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// Put this entity to maintenance
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
}
// If this entity is maintained independently
else {
// Do maintenance if possible
if( ! this.isInService() && this.canStartMaintenance( index ) ) {
// if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() );
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
// Keep track of the time the maintenance was attempted
else {
lastScheduledMaintenanceTimes.set( index, getCurrentTime() );
// If skipMaintenance was defined, cancel the maintenance
if( this.shouldSkipMaintenance( index ) ) {
// if a different maintenance is due, cancel this maintenance
boolean cancelMaintenance = false;
for( int i=0; i < maintenancePendings.size(); i++ ) {
if( i != index ) {
if( maintenancePendings.get( i ) > 0 ) {
cancelMaintenance = true;
break;
}
}
}
if( cancelMaintenance || this.isInMaintenance() ) {
maintenancePendings.subAt( 1, index );
}
}
// Do a check after the limit has expired
if( this.getDeferMaintenanceLimit( index ) > 0.0 ) {
this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) );
}
}
}
// Determine the next maintenance time
nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index );
// Find the next maintenance event
index = 0;
earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
}
}
public double getDeferMaintenanceLimit( int index ) {
if( deferMaintenanceLimit.getValue() == null )
return 0.0d;
return deferMaintenanceLimit.getValue().get( index );
}
public void scheduleCheckMaintenance( double wait ) {
scheduleWait( wait );
this.checkMaintenance();
}
public boolean shouldSkipMaintenance( int index ) {
if( skipMaintenanceIfOverlap.getValue().size() == 0 )
return false;
return skipMaintenanceIfOverlap.getValue().get( index );
}
/**
* Return TRUE if there is a pending maintenance for any schedule
*/
public boolean isMaintenancePending() {
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
return true;
}
}
for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
return true;
}
}
return false;
}
public boolean isForcedMaintenancePending() {
if( forceMaintenance.getValue() == null )
return false;
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) {
return true;
}
}
return false;
}
public ArrayList<ModelEntity> getSharedMaintenanceList () {
return sharedMaintenanceList.getValue();
}
public IntegerVector getMaintenancePendings () {
return maintenancePendings;
}
public DoubleListInput getMaintenanceDurations() {
return maintenanceDurations;
}
/**
* Return the start of the next scheduled maintenance time if not in maintenance,
* or the start of the current scheduled maintenance time if in maintenance
*/
public double getNextMaintenanceStartTime() {
if( nextMaintenanceTimes == null )
return Double.POSITIVE_INFINITY;
else
return nextMaintenanceTimes.getMin();
}
/**
* Return the duration of the next maintenance event (assuming only one pending)
*/
public double getNextMaintenanceDuration() {
return nextMaintenanceDuration;
}
// Shows if an Entity would ever go on service
public boolean hasServiceScheduled() {
if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) {
return true;
}
return false;
}
public void setMasterMaintenanceBlock( ModelEntity aModel ) {
masterMaintenanceEntity = aModel;
}
// BREAKDOWN METHODS
/**
* No Comments Given.
*/
public void calculateTimeOfNextFailure() {
hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT());
}
/**
* Activity Network for Breakdowns.
*/
public void doBreakdown() {
}
/**
* Prints the header for the entity's state list.
* @return bottomLine contains format for each column of the bottom line of the group report
*/
public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) {
IntegerVector bottomLine = new IntegerVector();
if( getStateList().size() != 0 ) {
anOut.putStringTabs( "Name", 1 );
bottomLine.add( ReportAgent.BLANK );
int doLoop = getStateList().size();
for( int x = 0; x < doLoop; x++ ) {
String state = (String)getStateList().get( x );
anOut.putStringTabs( state, 1 );
bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC );
}
anOut.newLine();
}
return bottomLine;
}
/**
* Print the entity's name and percentage of hours spent in each state.
* @return columnValues are the values for each column in the group report (0 if the value is a String)
*/
public DoubleVector printUtilizationOn( FileEntity anOut ) {
double total;
DoubleVector columnValues = new DoubleVector();
total = getTotalHours();
if (total == 0.0d)
return columnValues;
anOut.format("%s\t", getName());
columnValues.add(0.0d);
// print fraction of time per state
for (int i = 0; i < getStateList().size(); i++) {
String state = (String) getStateList().get(i);
StateRecord rec = getStateRecordFor(state);
double hoursFraction = 0.0d;
if (rec != null)
hoursFraction = getTotalHoursFor(rec)/total;
anOut.format("%.1f%%\t", hoursFraction * 100.0d);
columnValues.add(hoursFraction);
}
anOut.format("%n");
return columnValues;
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean isAvailable() {
throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." );
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartMaintenance( int index ) {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartForcedMaintenance() {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean areAllEntitiesAvailable() {
throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." );
}
/**
* Return the time of the next breakdown duration
*/
public double getBreakdownDuration() {
// if( traceFlag ) this.trace( "getBreakdownDuration()" );
// If a distribution was specified, then select a duration randomly from the distribution
if ( getDowntimeDurationDistribution() != null ) {
return getDowntimeDurationDistribution().nextValue();
}
else {
return 0.0;
}
}
/**
* Return the time of the next breakdown IAT
*/
public double getNextBreakdownIAT() {
if( getDowntimeIATDistribution() != null ) {
return getDowntimeIATDistribution().nextValue();
}
else {
return iATFailure;
}
}
public double getHoursForNextFailure() {
return hoursForNextFailure;
}
public void setHoursForNextFailure( double hours ) {
hoursForNextFailure = hours;
}
/**
Returns a vector of strings describing the ModelEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
@Override
public Vector getInfo() {
Vector info = super.getInfo();
info.add( String.format("Present State\t%s", getPresentState()) );
return info;
}
protected DoubleVector getMaintenanceOperatingHoursIntervals() {
return maintenanceOperatingHoursIntervals.getValue();
}
protected double getMaintenanceOperatingHoursDurationFor(int index) {
return maintenanceOperatingHoursDurations.getValue().get(index);
}
protected ProbabilityDistribution getDowntimeIATDistribution() {
return downtimeIATDistribution.getValue();
}
} |
package com.sandwell.JavaSimulation3D;
import com.jaamsim.ui.FrameBox;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.Util;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MouseInputListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
/**
* Class to display information about model objects. <br>
* displays the results of getInfo for an object
*/
public class PropertyBox extends FrameBox {
private static PropertyBox myInstance; // only one instance allowed to be open
private Entity currentEntity;
private int presentPage;
private final IntegerVector presentLineByPage = new IntegerVector();
private final JTabbedPane jTabbedFrame = new JTabbedPane();
private boolean ignoreStateChange = false;
public PropertyBox() {
super( "Property Viewer" );
setDefaultCloseOperation(FrameBox.HIDE_ON_CLOSE);
jTabbedFrame.setPreferredSize( new Dimension( 800, 400 ) );
// Register a change listener
jTabbedFrame.addChangeListener(new ChangeListener() {
// This method is called whenever the selected tab changes
@Override
public void stateChanged(ChangeEvent evt) {
if( ! ignoreStateChange ) {
presentPage = jTabbedFrame.getSelectedIndex();
updateValues();
}
}
});
getContentPane().add( jTabbedFrame );
setSize( 300, 150 );
setLocation(0, 110);
pack();
}
private JScrollPane getPropTable() {
final JTable propTable = new AjustToLastColumnTable(0, 3);
int totalWidth = jTabbedFrame.getWidth();
propTable.getColumnModel().getColumn( 2 ).setWidth( totalWidth / 2 );
propTable.getColumnModel().getColumn( 1 ).setWidth( totalWidth / 5 );
propTable.getColumnModel().getColumn( 0 ).setWidth( 3 * totalWidth / 10 );
propTable.getColumnModel().getColumn( 0 ).setHeaderValue( "Property" );
propTable.getColumnModel().getColumn( 1 ).setHeaderValue( "Type" );
propTable.getColumnModel().getColumn( 2 ).setHeaderValue( "Value" );
propTable.getColumnModel().getColumn(0).setCellRenderer(FrameBox.colRenderer);
propTable.getColumnModel().getColumn(1).setCellRenderer(FrameBox.colRenderer);
propTable.getColumnModel().getColumn(2).setCellRenderer(FrameBox.colRenderer);
propTable.getTableHeader().setFont(FrameBox.boldFont);
propTable.getTableHeader().setReorderingAllowed(false);
propTable.addMouseListener( new MouseInputListener() {
@Override
public void mouseEntered( MouseEvent e ) {
}
@Override
public void mouseClicked( MouseEvent e ) {
// Left double click
if( e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1 ) {
// Get the index of the row the user has clicked on
int row = propTable.getSelectedRow();
int column = propTable.getSelectedColumn();
String name = propTable.getValueAt(row, column).toString();
// Remove HTML
name = name.replaceAll( "<html>", "").replace( "<p>", "" ).replace( "<align=top>", "" ).replace("<br>", "" ).trim();
Entity entity = Input.tryParseEntity(name, Entity.class);
// An Entity Name
if( entity != null ) {
FrameBox.setSelectedEntity(entity);
}
}
}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {}
@Override
public void mousePressed( MouseEvent e ) {
// Right Mouse Button
if( e.getButton() == MouseEvent.BUTTON3 ) {
// get the coordinates of the mouse click
Point p = e.getPoint();
// get the row index that contains that coordinate
int row = propTable.rowAtPoint( p );
// Not get focused on the cell
if( row < 0 ) {
return;
}
String type = propTable.getValueAt(row, 1).toString();
// Remove HTML
type = type.replaceAll( "<html>", "").replaceAll( "<p>", "" ).replaceAll( "<align=top>", "" ).replaceAll("<br>", "" ).trim();
// A list of entities
if( type.equalsIgnoreCase("Vector") || type.equalsIgnoreCase("ArrayList")) {
// Define a popup menu
JPopupMenu popupMenu = new JPopupMenu( );
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Entity entity = Input.tryParseEntity(e.getActionCommand(), Entity.class);
FrameBox.setSelectedEntity(entity);
}
};
// Split the values in the list
String value = propTable.getValueAt(row, 2).toString();
value = value.replaceAll( "<html>", "").replaceAll( "<p>", "" ).replaceAll( "<align=top>", "" ).replaceAll("<br>", "" ).trim();
String[] items = value.split( " " );
for( int i = 0; i < items.length; i++ ) {
String each = items[ i ].replace( ",", "");
each = each.replace("[", "");
each = each.replace("]", "");
Entity entity = Input.tryParseEntity(each, Entity.class);
// This item is an entity
if( entity != null ) {
// Add the entity to the popup menu
JMenuItem item = new JMenuItem( entity.getName() );
item.addActionListener( actionListener );
popupMenu.add( item );
}
}
// Show the popup menu if it has items
if( popupMenu.getComponentCount() > 0 ) {
popupMenu.show( e.getComponent(), e.getX(), e.getY() );
}
}
}
}
});
JScrollPane jScrollPane = new JScrollPane(propTable);
return jScrollPane;
}
@Override
public void setEntity( Entity entity ) {
if(currentEntity == entity || ! this.isVisible())
return;
// Prevent stateChanged() method of jTabbedFrame to reenter this method
if( ignoreStateChange ) {
return;
}
ignoreStateChange = true;
if (entity == null) {
setTitle("Property Viewer");
presentPage = 0;
currentEntity = entity;
jTabbedFrame.removeAll();
ignoreStateChange = false;
return;
}
ArrayList<ClassFields> cFields = getFields(entity);
// A different class has been selected, or no previous value for currentEntity
if(currentEntity == null || currentEntity.getClass() != entity.getClass()) {
presentPage = 0;
presentLineByPage.clear();
// Remove the tabs for new selected entity
jTabbedFrame.removeAll();
}
currentEntity = entity;
// Create tabs if they do not exist yet
if( jTabbedFrame.getTabCount() == 0 ) {
for( int i = 0; i < cFields.size(); i++ ) {
// The properties in the current page
ClassFields cf = cFields.get(i);
jTabbedFrame.addTab(cf.klass.getSimpleName(), getPropTable());
JTable propTable = (JTable)(((JScrollPane)jTabbedFrame.getComponentAt(i)).getViewport().getComponent(0));
((javax.swing.table.DefaultTableModel)propTable.getModel()).setRowCount(cf.fields.size());
// populate property and type columns for this propTable
for( int j = 0; j < cf.fields.size(); j++ ) {
propTable.setValueAt(cf.fields.get(j).getName(), j, 0);
propTable.setValueAt(cf.fields.get(j).getType().getSimpleName(), j, 1);
}
}
}
ignoreStateChange = false;
updateValues();
}
@Override
public void updateValues() {
if(currentEntity == null || ! this.isVisible())
return;
setTitle(String.format("Property Viewer - %s", currentEntity));
ClassFields cf = getFields(currentEntity).get( presentPage );
JTable propTable = (JTable)(((JScrollPane)jTabbedFrame.getComponentAt(presentPage)).getViewport().getComponent(0));
// Print value column for current page
for( int i = 0; i < cf.fields.size(); i++ ) {
String[] record = getField(currentEntity, cf.fields.get(i)).split( "\t" );
// Value column
if( record.length > 2 ) {
// Number of items for an appendable property
int numberOfItems = 1;
for( int l = 0; l < record[2].length() - 1 ; l++ ) {
// Items are separated by "},"
if( record[2].substring( l, l + 2 ).equalsIgnoreCase( "},") ) {
numberOfItems++;
}
}
// If the property is not appendable, then check for word wrapping
if( numberOfItems == 1 ) {
// Set the row height for this entry
int stringLengthInPixel = Util.getPixelWidthOfString_ForFont( record[2].trim(), propTable.getFont() );
double lines = (double) stringLengthInPixel / ((double) propTable.getColumnModel().getColumn( 2 ).getWidth() );
// Adjustment
if( lines > 1 ){
lines *= 1.1 ;
}
int numberOfLines = (int) Math.ceil( lines );
String lineBreaks = "";
// Only if there are not too many lines
if( numberOfLines < 10 ) {
int height = (numberOfLines - 1 ) * (int) (propTable.getRowHeight() * 0.9) + propTable.getRowHeight(); // text height is about 90% of the row height
propTable.setRowHeight( i, height );
// Add extra line breaks to the end of the string to shift the entry to the top of the row
// (Jtable should do this with <align=top>, but this does not work)
for( int j = 0; j < numberOfLines; j++ ) {
lineBreaks = lineBreaks + "<br>";
}
// Set the value
String value = "null";
if( ! record[2].equalsIgnoreCase( "<null>" ) ) {
value = record[2];
}
propTable.setValueAt( "<html> <p> <align=top>" + " " + value + lineBreaks, i, 2 );
}
else {
propTable.setValueAt( numberOfLines + " rows is too large to be displayed!", i, 2 );
}
}
// If the property is appendable, then add line breaks after each item
else if( numberOfItems <= 50 ) {
// Set the row height for this entry
int height = (numberOfItems - 1 ) * (int) (propTable.getRowHeight() * 0.9) + propTable.getRowHeight(); // text height is about 90% of the row height
propTable.setRowHeight( i, height );
// Set the entry
String str = record[2].replaceAll( "},", "}<br>" ); // Replace the brace and comma with a brace and line break
propTable.setValueAt( "<html>" + str, i, 2 );
}
// Do not print an appendable entry that requires too many rows
else {
propTable.setValueAt( numberOfItems + " rows is too large to be displayed!", i, 2 );
}
}
}
}
/**
* Returns the only instance of the property box
*/
public synchronized static PropertyBox getInstance() {
if (myInstance == null)
myInstance = new PropertyBox();
return myInstance;
}
@Override
public void dispose() {
myInstance = null;
super.dispose();
}
private static String getField(Object obj, java.lang.reflect.Field field) {
StringBuilder fieldString = new StringBuilder();
try {
// save the field's accessibility, reset after reading
boolean accessible = field.isAccessible();
field.setAccessible(true);
// get the name and type for the property
fieldString.append(field.getName());
fieldString.append("\t");
fieldString.append(field.getType().getSimpleName());
fieldString.append("\t");
fieldString.append(propertyFormatObject(field.get(obj)));
// set the access for this field to what it originally was
field.setAccessible(accessible);
}
catch( SecurityException e ) {
System.out.println( e );
}
catch( IllegalAccessException e ) {
System.out.println( e );
}
return fieldString.toString();
}
private static class ClassFields implements Comparator<Field> {
final Class<?> klass;
final ArrayList<Field> fields;
ClassFields(Class<?> aKlass) {
klass = aKlass;
Field[] myFields = klass.getDeclaredFields();
fields = new ArrayList<Field>(myFields.length);
for (Field each : myFields) {
String name = each.getName();
// Static variables are all capitalized (ignore them)
if (name.toUpperCase().equals(name))
continue;
fields.add(each);
}
Collections.sort(fields, this);
}
@Override
public int compare(Field f1, Field f2) {
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
private static ArrayList<ClassFields> getFields(Entity object) {
if (object == null)
return new ArrayList<ClassFields>(0);
return getFields(object.getClass());
}
private static ArrayList<ClassFields> getFields(Class<?> klass) {
if (klass == null || klass.getSuperclass() == null)
return new ArrayList<ClassFields>();
ArrayList<ClassFields> cFields = getFields(klass.getSuperclass());
cFields.add(new ClassFields(klass));
return cFields;
}
private static String propertyFormatObject( Object value ) {
if (value == null)
return "<null>";
if (value instanceof Entity)
return ((Entity)value).getInputName();
if (value instanceof double[])
return Arrays.toString((double[])value);
try {
return value.toString();
}
catch (ConcurrentModificationException e) {
return "";
}
}
} |
package org.xcri.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.junit.Test;
import org.xcri.Namespaces;
import org.xcri.core.Catalog;
import org.xcri.exceptions.InvalidElementException;
import org.xcri.types.DescriptiveTextType;
public class DescriptionTest {
/**
* If a Descriptive Text Element has an @href attribute, the Producer
* MUST NOT include any text content or child elements.
*/
@Test
public void linkedDescription() throws JDOMException, IOException, InvalidElementException{
Catalog catalog = new Catalog();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader("<catalog xmlns=\""+Namespaces.XCRI_NAMESPACE+"\" xmlns:mlo=\""+Namespaces.MLO_NAMESPACE+"\" xmlns:dc=\""+Namespaces.DC_NAMESPACE+"\" xmlns:xsi=\""+Namespaces.XSI_NAMESPACE+"\"><provider><dc:description href=\"http://xcri.org/test\"></dc:description></provider></catalog>"));
catalog.fromXml(document);
assertEquals("http://xcri.org/test", catalog.getProviders()[0].getDescriptions()[0].getHref());
assertEquals("", catalog.getProviders()[0].getDescriptions()[0].getValue());
assertEquals("http://xcri.org/test", catalog.getProviders()[0].getDescriptions()[0].toXml().getAttributeValue("href"));
assertEquals("", catalog.getProviders()[0].getDescriptions()[0].toXml().getText());
}
/**
* The content of a Descriptive Text Element MUST be one of either:
* Empty
* Plain unescaped text content
* Valid XHTML 1.0 content
*/
@Test
public void xhtmlContent() throws JDOMException, IOException, InvalidElementException{
String content =
"<div xmlns=\"http:
"<p>This module shows how to take an existing presentation and modify it and how to create " +
"your own presentations. No knowledge of PowerPoint is assumed.</p>" +
"<p>The topics covered are:" +
"<ul>" +
"<li>Using and modifying an existing PowerPoint presentation</li> " +
"<li>Creating a simple presentation</li> " +
"<li>Making use of themes and schemes supplied with PowerPoint</li> " +
"<li>The PowerPoint views</li> " +
"<li>Printing and saving your presentation</li>" +
"</ul>" +
"</p> " +
"</div>";
Catalog catalog = new Catalog();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader("<catalog xmlns=\""+Namespaces.XCRI_NAMESPACE+"\" xmlns:dc=\""+Namespaces.DC_NAMESPACE+"\"><provider><dc:description>"+content+"</dc:description></provider></catalog>"));
catalog.fromXml(document);
assertEquals(content, catalog.getProviders()[0].getDescriptions()[0].getValue());
assertNotNull(catalog.getProviders()[0].getDescriptions()[0].toXml().getChild("div", Namespaces.XHTML_NAMESPACE_NS));
}
/**
* If a Descriptive Text Element has an @href attribute and the <description>
* element contains either text content or child elements, an Aggregator MUST
* treat the element as in error and ignore the element.
*/
@Test
public void both() throws JDOMException, IOException, InvalidElementException{
Catalog catalog = new Catalog();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader("<catalog xmlns=\""+Namespaces.XCRI_NAMESPACE+"\" xmlns:mlo=\""+Namespaces.MLO_NAMESPACE+"\" xmlns:dc=\""+Namespaces.DC_NAMESPACE+"\" xmlns:xsi=\""+Namespaces.XSI_NAMESPACE+"\"><provider><dc:description href=\"http://xcri.org/test\">text content</dc:description></provider></catalog>"));
catalog.fromXml(document);
assertEquals(0, catalog.getProviders()[0].getDescriptions().length);
}
/**
* TODO Encoding schemes: Use of vocabularies for types of Descriptive Text Elements is encouraged.
*/
/**
* TODO Length: Aggregators MAY choose to truncate long Descriptive Text Element content; a
* suggested maximum length is 4000 characters.
*/
/**
* Use of images: Images SHOULD NOT be referenced from within the Descriptive Text Element
* element by Producers as these are unlikely to be presented by Aggregators; potentially
* an image tag can be used to execute cross-site scripting (XSS) attacks. Instead, any
* image SHOULD be provided separately using the XCRI image element.
*/
/**
* Safe use of XHTML: See the section on Security Considerations for guidance.
* Aggregators SHOULD pay particular attention to the security of the IMG, SCRIPT,
* EMBED, OBJECT, FRAME, FRAMESET, IFRAME, META, and LINK elements, but other
* elements might also have negative security properties.
* @throws InvalidElementException
* @throws IOException
* @throws JDOMException
*/
@Test
public void contentWarnings() throws JDOMException, IOException, InvalidElementException{
assertTrue(hasContentWarning("<img/>"));
assertTrue(hasContentWarning("<script>nasty code</script>"));
assertTrue(hasContentWarning("<embed>nasty embed</embed>"));
assertTrue(hasContentWarning("<object>nasty object</object>"));
assertTrue(hasContentWarning("<frame>nasty thing</frame>"));
assertTrue(hasContentWarning("<frameset>nasty thing</frameset>"));
assertTrue(hasContentWarning("<meta>nasty thing</meta>"));
assertTrue(hasContentWarning("<link>nasty thing</link>"));
}
private boolean hasContentWarning(String content) throws JDOMException, IOException, InvalidElementException{
Logger logger = Logger.getLogger(DescriptiveTextType.class.getName());
Formatter formatter = new SimpleFormatter();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Handler handler = new StreamHandler(out, formatter);
logger.addHandler(handler);
try {
Catalog catalog = new Catalog();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader("<catalog xmlns=\""+Namespaces.XCRI_NAMESPACE+"\" xmlns:dc=\""+Namespaces.DC_NAMESPACE+"\"><dc:description><div xmlns=\"http:
catalog.fromXml(document);
handler.flush();
String logMsg = out.toString();
assertNotNull(logMsg);
if(logMsg.contains("description : content contains potentially dangerous XHTML")) return true;
} finally {
logger.removeHandler(handler);
}
return false;
}
@Test
public void sanitize() throws JDOMException, IOException, InvalidElementException{
String content = "<p>Hello World</p><script>nasty script</script><p>Goodbye</p>";
Catalog catalog = new Catalog();
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader("<catalog xmlns=\""+Namespaces.XCRI_NAMESPACE+"\" xmlns:dc=\""+Namespaces.DC_NAMESPACE+"\"><dc:description><div xmlns=\"http:
catalog.fromXml(document);
assertEquals("<div xmlns=\"http:
}
/**
* Inheritance: Descriptive Text Elements and any refinements are inheritable. See the
* section on inheritance for more guidance.
*
* TESTED IN OTHER CLASSES
*/
} |
package com.semantico.rigel;
import java.util.List;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableListMultimap.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.semantico.rigel.ContentRepository.JoinQueryBuilder.PartOne;
import com.semantico.rigel.ContentRepository.JoinQueryBuilder.PartTwo;
import com.semantico.rigel.fields.Field;
import com.semantico.rigel.filters.Filter;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.Group;
import org.apache.solr.client.solrj.response.GroupCommand;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.*;
public final class ContentRepositoryImpl<T extends ContentItem> implements
ContentRepository<T> {
private static final Logger LOG = LoggerFactory
.getLogger(ContentRepository.class);
private final SolrServer solr;
private final ContentItemFactory contentItemFactory;
private final ContentItem.Schema<T> schema;
private final METHOD method;
public ContentRepositoryImpl(SolrServer solr,
ContentItemFactory contentItemFactory, METHOD method,
ContentItem.Schema<T> schema) {
this.solr = checkNotNull(solr);
this.contentItemFactory = checkNotNull(contentItemFactory);
this.method = checkNotNull(method);
this.schema = schema;
}
@Override
public IdQueryBuilder<T> id(String id) {
checkArgument(id != null && !id.isEmpty());
return new IdQueryBuilderImpl(id);
}
public class IdQueryBuilderImpl implements IdQueryBuilder<T> {
private final SolrQuery q;
private boolean forceType;
public IdQueryBuilderImpl(String id) {
this.forceType = false;
this.q = new SolrQuery(Filter.on(schema.id.getField(), id).toSolrFormat());
q.setRows(1);
q.setRequestHandler("fetch");
}
@Override
public IdQueryBuilder<T> forceType() {
forceType = true;
return this;
}
@Override
public Optional<T> get() {
ImmutableList<T> items;
if (forceType) {
items = getContentItemsForQueryForced(q);
} else {
items = getContentItemsForQuery(q);
}
T contentItem = (items.size() > 0) ? items.get(0) : null;
return Optional.fromNullable(contentItem);
}
}
@Override
public IdsQueryBuilder<T> ids(String... ids) {
for (String id : ids) {
checkArgument(id != null && !id.isEmpty());
}
return new IdsQueryBuilderImpl(ids);
}
@Override
public IdsQueryBuilder<T> ids(Collection<String> ids) {
return ids(ids.toArray(new String[ids.size()]));
}
private class IdsQueryBuilderImpl implements IdsQueryBuilder<T> {
private String[] ids;
private boolean forceType;
public IdsQueryBuilderImpl(String... ids) {
this.forceType = false;
this.ids = ids;
}
@Override
public IdsQueryBuilder<T> forceType() {
forceType = true;
return this;
}
@Override
public ImmutableMap<String, Optional<T>> get() {
if (ids.length == 0) {
return ImmutableMap.of();
}
Set<Filter> filters = Sets.newHashSet();
for (String id : ids) {
filters.add(Filter.on(schema.id.getField(), id));
}
SolrQuery q = new SolrQuery(Filter.or(filters).toSolrFormat());
q.setRows(Integer.MAX_VALUE);
q.setRequestHandler("fetch");
ImmutableList<T> items;
if (forceType) {
items = getContentItemsForQueryForced(q);
} else {
items = getContentItemsForQuery(q);
}
Map<String, Optional<T>> map = Maps.newHashMap();
for (T item : items) {
map.put(item.getId(), Optional.of(item));
}
for (String id : ids) {
if (!map.containsKey(id)) {
map.put(id, Optional.<T> absent());
}
}
return ImmutableMap.copyOf(map);
}
}
@Override
public AllQueryBuilder<T> all() {
return new AllQueryBuilderImpl();
}
protected SolrQuery buildAllQuery() {
SolrQuery q = new SolrQuery("*:*");
q.addFilterQuery(Filter.and(schema.getFilters()).toSolrFormat());
q.setRows(Integer.MAX_VALUE);
q.setRequestHandler("fetch");
return q;
}
public ImmutableList<Count> getValuesForField(Field<?> field) {
SolrQuery sq = buildValuesForFieldsQuery(field);
QueryResponse rsp = querySolr(sq);
FacetField facetField = rsp.getFacetField(field.getFieldName());
return ImmutableList.copyOf(facetField.getValues());
}
public ImmutableListMultimap<Field<?>, Count> getValuesForFields(
Field<?>... fields) {
SolrQuery sq = buildValuesForFieldsQuery(fields);
QueryResponse rsp = querySolr(sq);
ImmutableListMultimap.Builder<Field<?>, Count> results = ImmutableListMultimap
.builder();
for (Field<?> field : fields) {
FacetField facetField = rsp.getFacetField(field.getFieldName());
results.putAll(field, facetField.getValues());
}
return results.build();
}
protected SolrQuery buildValuesForFieldsQuery(Field<?>... fields) {
SolrQuery q = buildAllQuery();
q.setFacet(true);
for (Field<?> field : fields) {
q.addFacetField(field.getFieldName());
}
q.setRows(0);
return q;
}
private final class AllQueryBuilderImpl implements AllQueryBuilder<T> {
private SolrQuery q;
private boolean forceType;
private QueryHook hook;
public AllQueryBuilderImpl() {
q = buildAllQuery();
forceType = false;
hook = null;
}
@Override
public AllQueryBuilder<T> filterBy(Filter... filters) {
q.addFilterQuery(Filter.and(filters).toSolrFormat());
return this;
}
@Override
public AllQueryBuilder<T> orderBy(Field<?> field, ORDER order) {
q.addSort(field.getFieldName(), order);
return this;
}
@Override
public AllQueryBuilder<T> limit(int count) {
q.setRows(count);
return this;
}
@Override
public AllQueryBuilder<T> customQuery(QueryHook hook) {
this.hook = hook;
return this;
}
@Override
public AllQueryBuilder<T> forceType() {
forceType = true;
return this;
}
@Override
public ImmutableList<T> get() {
processQueryHook();
if (forceType) {
return getContentItemsForQueryForced(q);
} else {
return getContentItemsForQuery(q);
}
}
private void processQueryHook() {
if (hook == null) {
return;
}
SolrQuery combined = new SolrQuery();
hook.perform(combined);
if (!forceType) {
//if the content item type isnt forced then we cant limit the fields
//potentially any field could be used by the content item factory to
//determine the type
combined.remove("fl");
}
combined.add(q);
q = combined;
}
}
@Override
public JoinQueryBuilder.PartOne<T> joinFrom(Field<?> field) {
return new JoinQueryBuilderPart1(field);
}
private class JoinQueryBuilderPart1 implements JoinQueryBuilder.PartOne<T> {
//Fields are public, dirty, but users are only exposed to the interface
public Field<?> fromField;
public Field<?> toField;
public Filter sourceFilter;
public JoinQueryBuilderPart1(Field<?> field) {
this.fromField = field;
}
@Override
public PartOne<T> filterBy(Filter... filters) {
if (sourceFilter != null) {
throw new RuntimeException("multiple filterBy statements not supported for the source filter");
//you can join them together with and / or into one filter if you want
}
this.sourceFilter = Filter.and(filters);
return this;
}
@Override
public PartTwo<T> to(Field<?> field) {
this.toField = field;
return new JoinQueryBuilderPart2(this);
}
}
private class JoinQueryBuilderPart2 implements JoinQueryBuilder.PartTwo<T> {
private SolrQuery q;
private boolean forceType;
public JoinQueryBuilderPart2(JoinQueryBuilderPart1 partOne) {
forceType = false;
q = new SolrQuery();
q.setQuery(String.format("{!join from=%s to=%s}%s",
partOne.fromField.getFieldName(),
partOne.toField.getFieldName(),
partOne.sourceFilter == null ? "*:*" : partOne.sourceFilter.toSolrFormat()));
q.addFilterQuery(Filter.and(schema.getFilters()).toSolrFormat());
}
@Override
public PartTwo<T> filterBy(Filter... filters) {
q.addFilterQuery(Filter.and(filters).toSolrFormat());
return this;
}
@Override
public PartTwo<T> forceType() {
forceType = true;
return this;
}
@Override
public ImmutableList<T> get() {
if (forceType) {
return getContentItemsForQueryForced(q);
} else {
return getContentItemsForQuery(q);
}
}
}
@Override
public GroupQueryBuilder<T> groupBy(Field<?> groupField) {
return new GroupQueryBuilderImpl(groupField);
}
private class GroupQueryBuilderImpl implements GroupQueryBuilder<T> {
private boolean forceType;
private SolrQuery q;
public GroupQueryBuilderImpl(Field<?> groupField) {
this.forceType = false;
this.q = new SolrQuery("*:*");
q.set("group", true);
q.set("group.field", groupField.getFieldName());
q.addFilterQuery(Filter.and(schema.getFilters()).toSolrFormat());
}
@Override
public GroupQueryBuilder<T> filterBy(Filter... filters) {
q.addFilterQuery(Filter.and(filters).toSolrFormat());
return this;
}
@Override
public GroupQueryBuilder<T> orderGroupsBy(Field<?> field, ORDER order) {
q.setSort(field.getFieldName(), order);
return this;
}
@Override
public GroupQueryBuilder<T> limitGroups(int count) {
q.setRows(count);
return this;
}
@Override
public GroupQueryBuilder<T> orderWithinGroupBy(Field<?> field, ORDER order) {
q.set("group.sort", String.format("%s %s", field.getFieldName(), order));
return this;
}
@Override
public GroupQueryBuilder<T> limitResultsPerGroup(int count) {
q.set("group.limit", count);
return this;
}
@Override
public GroupQueryBuilder<T> forceType() {
this.forceType = true;
return this;
}
@Override
public ImmutableListMultimap<String, T> get() {
QueryResponse response = querySolr(q);
GroupCommand command = response.getGroupResponse().getValues().get(0);
Builder<String, T> builder = ImmutableListMultimap.builder();
for (Group group : command.getValues()) {
String key = group.getGroupValue();
if (forceType) {
List<T> items = contentItemFactory.fromDocumentList(group.getResult(), schema);
builder.putAll(key, items);
} else {
List<? extends ContentItem> items = contentItemFactory.fromDocumentList(group.getResult());
for (ContentItem item : items) {
builder.put(key, doCast(item));
}
}
}
return builder.build();
}
}
//@Override
//public <R> FieldQueryBuilder<R> distinctValues(Field<R> facetField) {
//// TODO IMPLEMENT ME
//return null;
private ImmutableList<T> getContentItemsForQueryForced(SolrQuery q) {
QueryResponse response = querySolr(q);
return contentItemFactory.fromResponse(response, schema);
}
private ImmutableList<T> getContentItemsForQuery(SolrQuery q) {
QueryResponse response = querySolr(q);
List<? extends ContentItem> items = contentItemFactory.fromResponse(response);
ImmutableList.Builder<T> b = ImmutableList.<T>builder();
for (ContentItem item : items) {
b.add(doCast(item));
}
return b.build();
}
private QueryResponse querySolr(SolrQuery q) {
LOG.info("Solr Query: " + q.toString());
try {
return solr.query(q, method);
} catch (SolrServerException ex) {
throw new RuntimeException(ex);
}
}
private final T doCast(ContentItem item) {
try {
return (T) item;
} catch (ClassCastException e) {
throw new UnexpectedTypeException("Unexpected content item returned from solr query", e);
}
}
public static class UnexpectedTypeException extends RuntimeException {
public UnexpectedTypeException(String message, Exception cause) {
super(message, cause);
}
}
} |
package com.srinivas.systemutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import com.srinivas.systemutils.exceptions.SystemInteractionException;
/**
* Class that executes console commands and gets and puts input and output.
*
* @author Srinivas
* v
*/
public class ConsoleUtilities {
private static ProcessBuilder s_builder = new ProcessBuilder();
private static final String LINE_SEPARATOR = "\n";
private static final File ORIGIN_DIR = new File(
System.getProperty("user.dir"));
/**
* Checks correctness of String parameters.
* @param value the String that must be verified
*/
private static void checkParam(final String value) {
if (value == null || value.equals("")) {
throw new IllegalArgumentException("Value cannot be null or empty");
}
}
/**
* Sets the working directory to execute commands in.
* Makes the directory if it doesn't exist.
* @param path the path to the directory
*/
public static void setWorkingDirectory(final String path) {
checkParam(path);
File executionPath = new File(path);
executionPath.mkdirs();
s_builder.directory(executionPath);
}
/**
* Reset working dir
* Makes the directory if it doesn't exist.
*/
public static void resetWorkingDirectory() {
s_builder.directory(ORIGIN_DIR);
}
/**
* Capture a Process output.
*
* @param process process whose output must be caught
* @throws IOException when the stream could not be read
* @return result an Array of strings separated by the newline character
* containing the process output
*/
private static String[] gobbleOutputStream(final Process process)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String intermediateResult = builder.toString();
String result[] = intermediateResult.split(LINE_SEPARATOR);
return result;
}
/**
* Capture a Process error stream.
*
* @param process process whose output must be caught
* @throws IOException
* @return result an Array of strings separated by the newline character
* containing the process error stream
*/
private static String[] gobbleErrorStream(final Process process)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String intermediateResult = builder.toString();
String result[] = intermediateResult.split(LINE_SEPARATOR);
return result;
}
/**
* Method will execute a system command. Fails when command writes to error
* stream.
*
* @param command A command object to execute
* @return command the command with it's execution details set.
* @throws IOException when the process builder cannot execute the command
*/
public static Command exec(final Command command) throws IOException,
InterruptedException {
checkParam(command.getCommand());
String cmdParts[] = command.getCommand().split(" ");
s_builder.command(cmdParts);
Process process = s_builder.start();
process.waitFor();
command.setOutput(gobbleOutputStream(process));
command.setErrorContents(gobbleErrorStream(process));
if (command.getErrorContents().length > 1) {
command.setStatus(ProcessCode.FAILURE);
} else {
command.setStatus(ProcessCode.SUCCESS);
}
return command;
}
/**
* Method will execute a system command. Error stream is not a failure
* criterion.
*
* @param command A command object to execute
* @return command the command with it's execution details set.
* @throws IOException when the process builder cannot execute the command
*/
public static Command execDisregardingErrorStream(final Command command)
throws IOException, InterruptedException {
checkParam(command.getCommand());
String cmdParts[] = command.getCommand().split(" ");
s_builder.command(cmdParts);
Process process = s_builder.start();
process.waitFor();
command.setOutput(gobbleOutputStream(process));
command.setErrorContents(gobbleErrorStream(process));
return command;
}
/**
* Method will execute a system command. Reads streams before process
* finishes. May result in race conditions.
*
* @param command A command object to execute
* @return command the command with it's execution details set.
* @throws IOException when the process builder cannot execute the command
*/
public static Command execUnSafe(final Command command) throws IOException,
InterruptedException {
checkParam(command.getCommand());
String cmdParts[] = command.getCommand().split(" ");
s_builder.command(cmdParts);
Process process = s_builder.start();
command.setOutput(gobbleOutputStream(process));
command.setErrorContents(gobbleErrorStream(process));
if (command.getErrorContents().length > 0) {
command.setStatus(ProcessCode.FAILURE);
} else {
command.setStatus(ProcessCode.SUCCESS);
}
return command;
}
/**
* Method will execute a system command. Reads streams before process
* finishes. May result in race conditions. Disregards Error stream as a
* criterion.
*
* @param command A command object to execute
* @return command the command with it's execution details set.
* @throws IOException when the process builder cannot execute the command
*/
public static Command execUnSafeDisregardingErrorStream(
final Command command) throws IOException, InterruptedException {
checkParam(command.getCommand());
String cmdParts[] = command.getCommand().split(" ");
s_builder.command(cmdParts);
Process process = s_builder.start();
command.setOutput(gobbleOutputStream(process));
command.setErrorContents(gobbleErrorStream(process));
return command;
}
/**
* Write to standard output.
*
* @param message the string to output
*/
// TODO: add verification
public static void sOut(final String message) {
checkParam(message);
System.out.println(message);
}
/**
* Write to standard output. No newline character.
*
* @param message the string to output
*/
// TODO: add verification
public static void sDump(final String message) {
checkParam(message);
System.out.print(message);
}
/**
* Write to standard error.
*
* @param message the string to output
*/
// TODO: add verification
public static void sErr(final String message) {
checkParam(message);
System.err.println(message);
}
/**
* Reads some input. It's up to the user to cast it to the write type. This
* provides more flexibility.
*
* @return inputVal a string containing the values the user input
* @throws IOException when the input stream could not be read.
*/
public static String sIn() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputVal = br.readLine();
return inputVal;
}
} |
package com.vaguehope.onosendai.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.net.Uri;
import com.vaguehope.onosendai.config.Account;
import com.vaguehope.onosendai.provider.ServiceRef;
import com.vaguehope.onosendai.util.ArrayHelper;
public class OutboxTweet {
private final Long uid;
private final String accountId;
private final List<String> svcMetas;
private final String body;
private final String inReplyToSid;
private final Uri attachment;
private final String lastError;
public OutboxTweet (final Account account, final Set<ServiceRef> svcs, final String body, final String inReplyToSid, final Uri attachment) {
this(null, account.getId(), svcsToList(svcs), body, inReplyToSid, attachment, null);
}
public OutboxTweet (final Long uid, final String accountId, final String svcMetas, final String body, final String inReplyToSid, final String attachment, final String lastError) {
this(uid, accountId, svcsStrToList(svcMetas), body, inReplyToSid, safeParseUri(attachment), lastError);
}
public OutboxTweet (final OutboxTweet ot, final String lastError) {
this(ot.getUid(), ot.getAccountId(), ot.getSvcMetasList(), ot.getBody(), ot.getInReplyToSid(), ot.getAttachment(), lastError);
}
private OutboxTweet (final Long uid, final String accountId, final List<String> svcMetas, final String body, final String inReplyToSid, final Uri attachment, final String lastError) {
this.uid = uid;
this.accountId = accountId;
this.svcMetas = Collections.unmodifiableList(svcMetas);
this.body = body;
this.inReplyToSid = inReplyToSid;
this.attachment = attachment;
this.lastError = lastError;
}
public Long getUid () {
return this.uid;
}
public String getAccountId () {
return this.accountId;
}
public List<String> getSvcMetasList () {
return this.svcMetas;
}
public String getSvcMetasStr () {
return svcsListToStr(this.svcMetas);
}
public Set<ServiceRef> getSvcMetasParsed () {
return svcsListToParsed(getSvcMetasList());
}
public String getBody () {
return this.body;
}
public String getInReplyToSid () {
return this.inReplyToSid;
}
public Uri getAttachment () {
return this.attachment;
}
public String getAttachmentStr () {
return this.attachment != null ? this.attachment.toString() : null;
}
@Override
public String toString () {
return new StringBuilder()
.append("OutboxTweet{").append(this.uid)
.append(",").append(this.accountId)
.append(",").append(this.getAttachmentStr())
.append(",").append(this.body)
.append(",").append(this.inReplyToSid)
.append(",").append(this.getAttachmentStr())
.append(",").append(this.getLastError())
.append("}").toString();
}
private static Uri safeParseUri (final String s) {
if (s == null) return null;
return Uri.parse(s);
}
private static List<String> svcsToList (final Set<ServiceRef> svcs) {
final List<String> l = new ArrayList<String>();
for (final ServiceRef svc : svcs) {
l.add(svc.toServiceMeta());
}
return l;
}
private static String svcsListToStr (final List<String> svcMetasList) {
return ArrayHelper.join(svcMetasList, "|");
}
private static List<String> svcsStrToList (final String svcMetasStr) {
return Arrays.asList(svcMetasStr.split("\\|"));
}
private static Set<ServiceRef> svcsListToParsed (final List<String> svcList) {
final Set<ServiceRef> ret = new HashSet<ServiceRef>();
for (String meta : svcList) {
ret.add(ServiceRef.parseServiceMeta(meta));
}
return ret;
}
public String getLastError () {
return this.lastError;
}
} |
package com.vaguehope.onosendai.storage;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.vaguehope.onosendai.C;
import com.vaguehope.onosendai.config.Column;
import com.vaguehope.onosendai.model.Meta;
import com.vaguehope.onosendai.model.MetaType;
import com.vaguehope.onosendai.model.ScrollState;
import com.vaguehope.onosendai.model.Tweet;
import com.vaguehope.onosendai.util.LogWrapper;
public class DbAdapter implements DbInterface {
private static final String DB_NAME = "tweets";
private static final int DB_VERSION = 11;
private final LogWrapper log = new LogWrapper("DB"); // TODO make static?
private final Context mCtx;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final List<TwUpdateListener> twUpdateListeners = new ArrayList<TwUpdateListener>();
private static class DatabaseHelper extends SQLiteOpenHelper {
private final LogWrapper log = new LogWrapper("DBH");
DatabaseHelper (final Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate (final SQLiteDatabase db) {
db.execSQL(TBL_TW_CREATE);
db.execSQL(TBL_TW_CREATE_INDEX);
db.execSQL(TBL_TM_CREATE);
db.execSQL(TBL_TM_CREATE_INDEX);
db.execSQL(TBL_SC_CREATE);
db.execSQL(TBL_KV_CREATE);
db.execSQL(TBL_KV_CREATE_INDEX);
}
@Override
public void onUpgrade (final SQLiteDatabase db, final int oldVersion, final int newVersion) {
if (oldVersion < 8) { // NOSONAR not a magic number.
this.log.w("Upgrading database from version %d to %d, which will destroy all old data.", oldVersion, newVersion);
db.execSQL("DROP INDEX IF EXISTS " + TBL_TM_INDEX);
db.execSQL("DROP TABLE IF EXISTS " + TBL_TM);
db.execSQL("DROP INDEX IF EXISTS " + TBL_TW_INDEX);
db.execSQL("DROP TABLE IF EXISTS " + TBL_TW);
db.execSQL("DROP TABLE IF EXISTS " + TBL_SC);
onCreate(db);
}
else {
this.log.w("Upgrading database from version %d to %d...", oldVersion, newVersion);
if (oldVersion < 9) { // NOSONAR not a magic number.
this.log.w("Adding column %s...", TBL_TM_TITLE);
db.execSQL("ALTER TABLE " + TBL_TM + " ADD COLUMN " + TBL_TM_TITLE + " text;");
}
if (oldVersion < 10) { // NOSONAR not a magic number.
this.log.w("Creating table %s...", TBL_KV);
db.execSQL(TBL_KV_CREATE);
this.log.w("Creating index %s...", TBL_KV_INDEX);
db.execSQL(TBL_KV_CREATE_INDEX);
}
if (oldVersion < 11) { // NOSONAR not a magic number.
this.log.w("Adding column %s...", TBL_SC_TIME);
db.execSQL("ALTER TABLE " + TBL_SC + " ADD COLUMN " + TBL_SC_TIME + " integer;");
}
}
}
}
public DbAdapter (final Context ctx) {
this.mCtx = ctx;
}
public void open () {
this.mDbHelper = new DatabaseHelper(this.mCtx);
this.mDb = this.mDbHelper.getWritableDatabase();
}
public void close () {
this.mDb.close();
this.mDbHelper.close();
}
public boolean checkDbOpen () {
if (this.mDb == null) {
this.log.e("aborting because mDb==null.");
return false;
}
if (!this.mDb.isOpen()) {
this.log.d("mDb was not open; opeing it...");
open();
}
return true;
}
// Tweets.
private static final String TBL_TW = "tw";
private static final String TBL_TW_ID = "_id";
private static final String TBL_TW_COLID = "colid";
private static final String TBL_TW_SID = "sid";
private static final String TBL_TW_TIME = "time";
private static final String TBL_TW_USERNAME = "uname";
private static final String TBL_TW_FULLNAME = "fname";
private static final String TBL_TW_BODY = "body";
private static final String TBL_TW_AVATAR = "avatar";
private static final String TBL_TW_CREATE = "create table " + TBL_TW + " ("
+ TBL_TW_ID + " integer primary key autoincrement,"
+ TBL_TW_COLID + " integer,"
+ TBL_TW_SID + " text,"
+ TBL_TW_TIME + " integer,"
+ TBL_TW_USERNAME + " text,"
+ TBL_TW_FULLNAME + " text,"
+ TBL_TW_BODY + " text,"
+ TBL_TW_AVATAR + " text,"
+ "UNIQUE(" + TBL_TW_COLID + ", " + TBL_TW_SID + ") ON CONFLICT REPLACE"
+ ");";
private static final String TBL_TW_INDEX = TBL_TW + "_idx";
private static final String TBL_TW_CREATE_INDEX = "CREATE INDEX " + TBL_TW_INDEX + " ON " + TBL_TW + "(" + TBL_TW_SID + "," + TBL_TW_TIME + ");";
private static final String TBL_TM = "tm";
private static final String TBL_TM_ID = "_id";
private static final String TBL_TM_TWID = "twid";
private static final String TBL_TM_TYPE = "type";
private static final String TBL_TM_DATA = "data";
private static final String TBL_TM_TITLE = "title";
private static final String TBL_TM_CREATE = "create table " + TBL_TM + " ("
+ TBL_TM_ID + " integer primary key autoincrement,"
+ TBL_TM_TWID + " integer,"
+ TBL_TM_TYPE + " integer,"
+ TBL_TM_DATA + " text,"
+ TBL_TM_TITLE + " text,"
+ "FOREIGN KEY (" + TBL_TM_TWID + ") REFERENCES " + TBL_TW + " (" + TBL_TW_ID + ") ON DELETE CASCADE,"
+ "UNIQUE(" + TBL_TM_TWID + ", " + TBL_TM_TYPE + "," + TBL_TM_DATA + "," + TBL_TM_TITLE + ") ON CONFLICT IGNORE"
+ ");";
private static final String TBL_TM_INDEX = TBL_TM + "_idx";
private static final String TBL_TM_CREATE_INDEX = "CREATE INDEX " + TBL_TM_INDEX + " ON " + TBL_TM + "(" + TBL_TM_TWID + ");";
@Override
public void storeTweets (final Column column, final List<Tweet> tweets) {
// Clear old data.
this.mDb.beginTransaction();
try {
final int n = this.mDb.delete(TBL_TW,
TBL_TW_COLID + "=? AND " + TBL_TW_ID + " NOT IN (SELECT " + TBL_TW_ID + " FROM " + TBL_TW +
" WHERE " + TBL_TW_COLID + "=?" +
" ORDER BY " + TBL_TW_TIME +
" DESC LIMIT " + C.DATA_TW_MAX_COL_ENTRIES + ")",
new String[] { String.valueOf(column.getId()), String.valueOf(column.getId()) });
this.log.d("Deleted %d rows from %s column %d.", n, TBL_TW, column.getId());
this.mDb.setTransactionSuccessful();
}
finally {
this.mDb.endTransaction();
}
this.mDb.beginTransaction();
try {
final ContentValues values = new ContentValues();
for (final Tweet tweet : tweets) {
values.clear();
values.put(TBL_TW_COLID, column.getId());
values.put(TBL_TW_SID, tweet.getSid());
values.put(TBL_TW_TIME, tweet.getTime());
values.put(TBL_TW_USERNAME, tweet.getUsername());
values.put(TBL_TW_FULLNAME, tweet.getFullname());
values.put(TBL_TW_BODY, tweet.getBody());
values.put(TBL_TW_AVATAR, tweet.getAvatarUrl());
final long uid = this.mDb.insertWithOnConflict(TBL_TW, null, values, SQLiteDatabase.CONFLICT_IGNORE);
final List<Meta> metas = tweet.getMetas();
if (metas != null) {
for (final Meta meta : metas) {
values.clear();
values.put(TBL_TM_TWID, uid);
values.put(TBL_TM_TYPE, meta.getType().getId());
values.put(TBL_TM_DATA, meta.getData());
if (meta.getTitle() != null) values.put(TBL_TM_TITLE, meta.getTitle());
this.mDb.insertWithOnConflict(TBL_TM, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
}
}
this.mDb.setTransactionSuccessful();
}
finally {
this.mDb.endTransaction();
}
notifyTwListeners(column.getId());
}
@Override
public void deleteTweet (final Column column, final Tweet tweet) {
this.mDb.beginTransaction();
try {
this.mDb.delete(TBL_TW, TBL_TW_COLID + "=? AND " + TBL_TW_SID + "=?",
new String[] { String.valueOf(column.getId()), String.valueOf(tweet.getSid()) });
this.log.d("Deleted tweet %s from %s column %d.", tweet.getSid(), TBL_TW, column.getId());
this.mDb.setTransactionSuccessful();
}
finally {
this.mDb.endTransaction();
}
notifyTwListeners(column.getId());
}
@Override
public void deleteTweets (final Column column) {
this.mDb.beginTransaction();
try {
this.mDb.delete(TBL_TW, TBL_TW_COLID + "=?", new String[] { String.valueOf(column.getId()) });
this.log.d("Deleted tweets from %s column %d.", TBL_TW, column.getId());
this.mDb.setTransactionSuccessful();
}
finally {
this.mDb.endTransaction();
}
notifyTwListeners(column.getId());
}
@Override
public List<Tweet> getTweets (final int columnId, final int numberOf) {
return getTweets(TBL_TW_COLID + "=?", new String[] { String.valueOf(columnId) }, numberOf);
}
@Override
public List<Tweet> getTweets (final int columnId, final int numberOf, final int[] excludeColumnIds) {
if (excludeColumnIds == null || excludeColumnIds.length < 1) return getTweets(columnId, numberOf);
final StringBuilder where = new StringBuilder()
.append(TBL_TW_COLID).append("=?")
.append(" AND ").append(TBL_TW_SID)
.append(" NOT IN (SELECT ").append(TBL_TW_SID)
.append(" FROM ").append(TBL_TW)
.append(" WHERE ");
final String[] whereArgs = new String[1 + excludeColumnIds.length];
whereArgs[0] = String.valueOf(columnId);
for (int i = 0; i < excludeColumnIds.length; i++) {
if (i > 0) where.append(" OR ");
where.append(TBL_TW_COLID).append("=?");
whereArgs[i + 1] = String.valueOf(excludeColumnIds[i]);
}
where.append(")");
return getTweets(where.toString(), whereArgs, numberOf);
}
private List<Tweet> getTweets (final String where, final String[] whereArgs, final int numberOf) {
if (!checkDbOpen()) return null;
List<Tweet> ret = new ArrayList<Tweet>();
Cursor c = null;
try {
c = this.mDb.query(true, TBL_TW,
new String[] { TBL_TW_ID, TBL_TW_SID, TBL_TW_USERNAME, TBL_TW_FULLNAME, TBL_TW_BODY, TBL_TW_TIME, TBL_TW_AVATAR },
where, whereArgs,
null, null,
TBL_TW_TIME + " desc", String.valueOf(numberOf));
if (c != null && c.moveToFirst()) {
final int colId = c.getColumnIndex(TBL_TW_ID);
final int colSid = c.getColumnIndex(TBL_TW_SID);
final int colUesrname = c.getColumnIndex(TBL_TW_USERNAME);
final int colFullname = c.getColumnIndex(TBL_TW_FULLNAME);
final int colBody = c.getColumnIndex(TBL_TW_BODY);
final int colTime = c.getColumnIndex(TBL_TW_TIME);
final int colAvatar = c.getColumnIndex(TBL_TW_AVATAR);
ret = new ArrayList<Tweet>();
do {
final long uid = c.getLong(colId);
final String sid = c.getString(colSid);
final String username = c.getString(colUesrname);
final String fullname = c.getString(colFullname);
final String body = c.getString(colBody);
final long time = c.getLong(colTime);
final String avatar = c.getString(colAvatar);
ret.add(new Tweet(uid, sid, username, fullname, body, time, avatar, null));
}
while (c.moveToNext());
}
}
finally {
if (c != null) c.close();
}
return ret;
}
@Override
public Tweet getTweetDetails (final String tweetSid) {
return getTweetDetails(TBL_TW_SID + "=?", new String[] { tweetSid });
}
@Override
public Tweet getTweetDetails (final int columnId, final Tweet tweet) {
return getTweetDetails(columnId, tweet.getSid());
}
@Override
public Tweet getTweetDetails (final int columnId, final String tweetSid) {
return getTweetDetails(TBL_TW_COLID + "=? AND " + TBL_TW_SID + "=?",
new String[] { String.valueOf(columnId), tweetSid });
}
@Override
public Tweet getTweetDetails (final long tweetUid) {
return getTweetDetails(TBL_TW_ID + "=?", new String[] { String.valueOf(tweetUid) });
}
private Tweet getTweetDetails (final String selection, final String[] selectionArgs) {
if (!checkDbOpen()) return null;
Tweet ret = null;
Cursor c = null;
Cursor d = null;
try {
c = this.mDb.query(true, TBL_TW,
new String[] { TBL_TW_ID, TBL_TW_SID, TBL_TW_USERNAME, TBL_TW_FULLNAME, TBL_TW_BODY, TBL_TW_TIME, TBL_TW_AVATAR },
selection, selectionArgs,
null, null, null, null);
if (c != null && c.moveToFirst()) {
final int colId = c.getColumnIndex(TBL_TW_ID);
final int colSid = c.getColumnIndex(TBL_TW_SID);
final int colUesrname = c.getColumnIndex(TBL_TW_USERNAME);
final int colFullname = c.getColumnIndex(TBL_TW_FULLNAME);
final int colBody = c.getColumnIndex(TBL_TW_BODY);
final int colTime = c.getColumnIndex(TBL_TW_TIME);
final int colAvatar = c.getColumnIndex(TBL_TW_AVATAR);
final long uid = c.getLong(colId);
final String sid = c.getString(colSid);
final String username = c.getString(colUesrname);
final String fullname = c.getString(colFullname);
final String body = c.getString(colBody);
final long time = c.getLong(colTime);
final String avatar = c.getString(colAvatar);
List<Meta> metas = null;
try {
d = this.mDb.query(true, TBL_TM,
new String[] { TBL_TM_TYPE, TBL_TM_DATA, TBL_TM_TITLE },
TBL_TM_TWID + "=?",
new String[] { String.valueOf(uid) },
null, null, null, null);
if (d != null && d.moveToFirst()) {
final int colType = d.getColumnIndex(TBL_TM_TYPE);
final int colData = d.getColumnIndex(TBL_TM_DATA);
final int colTitle = d.getColumnIndex(TBL_TM_TITLE);
metas = new ArrayList<Meta>();
do {
final int typeId = d.getInt(colType);
final String data = d.getString(colData);
final String title = d.getString(colTitle);
metas.add(new Meta(MetaType.parseId(typeId), data, title));
}
while (d.moveToNext());
}
}
finally {
if (d != null) d.close();
}
ret = new Tweet(uid, sid, username, fullname, body, time, avatar, metas);
}
}
finally {
if (c != null) c.close();
}
return ret;
}
@Override
public int getScrollUpCount (final Column column) {
return getScrollUpCount(column.getId(), column.getExcludeColumnIds(), null);
}
@Override
public int getScrollUpCount (final int columnId, final int[] excludeColumnIds, final ScrollState scroll) {
if (!checkDbOpen()) return -1;
final StringBuilder where = new StringBuilder()
.append(TBL_TW_COLID).append("=?")
.append(" AND ").append(TBL_TW_TIME).append(">?");
final String[] whereArgs = new String[2 + (excludeColumnIds != null ? excludeColumnIds.length : 0)];
whereArgs[0] = String.valueOf(columnId);
// TODO integrate into query?
final ScrollState fscroll = scroll != null ? scroll : getScroll(columnId);
if (fscroll == null) return 0; // Columns is probably empty.
final Tweet tweet = getTweetDetails(fscroll.getItemId());
if (tweet == null) return 0; // Columns is probably empty.
whereArgs[1] = String.valueOf(tweet.getTime());
if (excludeColumnIds != null && excludeColumnIds.length > 0) {
where.append(" AND ").append(TBL_TW_SID)
.append(" NOT IN (SELECT ").append(TBL_TW_SID)
.append(" FROM ").append(TBL_TW)
.append(" WHERE ");
for (int i = 0; i < excludeColumnIds.length; i++) {
if (i > 0) where.append(" OR ");
where.append(TBL_TW_COLID).append("=?");
whereArgs[2 + i] = String.valueOf(excludeColumnIds[i]);
}
where.append(")");
}
return (int) DatabaseUtils.queryNumEntries(this.mDb, TBL_TW, where.toString(), whereArgs);
}
private void notifyTwListeners (final int columnId) {
for (final TwUpdateListener l : this.twUpdateListeners) {
l.columnChanged(columnId);
}
}
@Override
public void addTwUpdateListener (final TwUpdateListener listener) {
this.twUpdateListeners.add(listener);
}
@Override
public void removeTwUpdateListener (final TwUpdateListener listener) {
this.twUpdateListeners.remove(listener);
}
// Scrolls.
private static final String TBL_SC = "sc";
private static final String TBL_SC_ID = "_id";
private static final String TBL_SC_COLID = "colid";
private static final String TBL_SC_ITEMID = "itemid";
private static final String TBL_SC_TOP = "top";
private static final String TBL_SC_TIME = "time";
private static final String TBL_SC_CREATE = "create table " + TBL_SC + " ("
+ TBL_SC_ID + " integer primary key autoincrement,"
+ TBL_SC_COLID + " integer,"
+ TBL_SC_ITEMID + " integer,"
+ TBL_SC_TOP + " integer,"
+ TBL_SC_TIME + " integer,"
+ "UNIQUE(" + TBL_SC_COLID + ") ON CONFLICT REPLACE" +
");";
@Override
public void storeScroll (final int columnId, final ScrollState state) {
if (state == null) return;
this.mDb.beginTransaction();
try {
final ContentValues values = new ContentValues();
values.put(TBL_SC_COLID, columnId);
values.put(TBL_SC_ITEMID, state.getItemId());
values.put(TBL_SC_TOP, state.getTop());
values.put(TBL_SC_TIME, state.getItemTime());
this.mDb.insertWithOnConflict(TBL_SC, null, values, SQLiteDatabase.CONFLICT_REPLACE);
this.mDb.setTransactionSuccessful();
}
finally {
this.mDb.endTransaction();
}
this.log.d("Stored scroll for col %d: %s", columnId, state);
}
@Override
public ScrollState getScroll (final int columnId) {
if (!checkDbOpen()) return null;
ScrollState ret = null;
Cursor c = null;
try {
c = this.mDb.query(true, TBL_SC,
new String[] { TBL_SC_ITEMID, TBL_SC_TOP, TBL_SC_TIME },
TBL_TW_COLID + "=?", new String[] { String.valueOf(columnId) },
null, null, null, null);
if (c != null && c.moveToFirst()) {
final int colItemId = c.getColumnIndex(TBL_SC_ITEMID);
final int colTop = c.getColumnIndex(TBL_SC_TOP);
final int colTime = c.getColumnIndex(TBL_SC_TIME);
final long itemId = c.getLong(colItemId);
final int top = c.getInt(colTop);
final long time = c.getLong(colTime);
ret = new ScrollState(itemId, top, time);
}
}
finally {
if (c != null) c.close();
}
this.log.d("Read scroll for col %d: %s", columnId, ret);
return ret;
}
private static final String TBL_KV = "kv";
private static final String TBL_KV_ID = "_id";
private static final String TBL_KV_KEY = "key";
private static final String TBL_KV_VAL = "val";
private static final String TBL_KV_CREATE = "create table " + TBL_KV + " ("
+ TBL_KV_ID + " integer primary key autoincrement,"
+ TBL_KV_KEY + " text,"
+ TBL_KV_VAL + " text,"
+ "UNIQUE(" + TBL_KV_KEY + ") ON CONFLICT REPLACE" +
");";
private static final String TBL_KV_INDEX = TBL_KV + "_idx";
private static final String TBL_KV_CREATE_INDEX = "CREATE INDEX " + TBL_KV_INDEX + " ON " + TBL_KV + "(" + TBL_KV_KEY + ");";
@Override
public void storeValue (final String key, final String value) {
this.mDb.beginTransaction();
try {
final ContentValues values = new ContentValues();
values.put(TBL_KV_KEY, key);
values.put(TBL_KV_VAL, value);
this.mDb.insertWithOnConflict(TBL_KV, null, values, SQLiteDatabase.CONFLICT_REPLACE);
this.mDb.setTransactionSuccessful();
}
finally {
this.mDb.endTransaction();
}
if (value == null) {
this.log.d("Stored KV: '%s' = null.", key);
}
else {
this.log.d("Stored KV: '%s' = '%s'.", key, value);
}
}
@Override
public String getValue (final String key) {
if (!checkDbOpen()) return null;
String ret = null;
Cursor c = null;
try {
c = this.mDb.query(true, TBL_KV,
new String[] { TBL_KV_VAL },
TBL_KV_KEY + "=?", new String[] { key },
null, null, null, null);
if (c != null && c.moveToFirst()) {
final int colVal = c.getColumnIndex(TBL_KV_VAL);
ret = c.getString(colVal);
}
}
finally {
if (c != null) c.close();
}
if (ret == null) {
this.log.d("Read KV: '%s' = null.", key);
}
else {
this.log.d("Read KV: '%s' = '%s'.", key, ret);
}
return ret;
}
} |
package crazypants.enderio.machines.config;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import crazypants.enderio.base.config.Config.Section;
import crazypants.enderio.base.config.ValueFactory;
import crazypants.enderio.base.config.ValueFactory.IValue;
import crazypants.enderio.machines.EnderIOMachines;
import crazypants.enderio.machines.config.config.ClientConfig;
import crazypants.enderio.machines.config.config.CombustionGenConfig;
import crazypants.enderio.machines.config.config.KillerJoeConfig;
import crazypants.enderio.machines.config.config.SolarConfig;
import crazypants.enderio.machines.config.config.SoulBinderConfig;
import crazypants.enderio.machines.config.config.SpawnerConfig;
import crazypants.enderio.machines.config.config.TankConfig;
import crazypants.enderio.machines.config.config.VacuumConfig;
import crazypants.enderio.machines.config.config.VatConfig;
import crazypants.enderio.machines.config.config.WeatherConfig;
import crazypants.enderio.machines.config.config.ZombieGenConfig;
@ParametersAreNonnullByDefault // Not the right one, but eclipse knows only 3 null annotations anyway, so it's ok
public final class Config {
public static final Section sectionCapacitor = new Section("", "capacitor");
public static final ValueFactory F = new ValueFactory(EnderIOMachines.MODID);
public static final IValue<Boolean> registerRecipes = new IValue<Boolean>() {
@Override
public @Nonnull Boolean get() {
return crazypants.enderio.base.config.Config.registerRecipes;
}
};
public static final IValue<Float> explosionResistantBlockHardness = new IValue<Float>() {
@Override
public @Nonnull Float get() {
return crazypants.enderio.base.config.Config.EXPLOSION_RESISTANT;
}
};
public static void load() {
// force sub-configs to be classloaded with the main config
ClientConfig.F.getClass();
CombustionGenConfig.F.getClass();
KillerJoeConfig.F.getClass();
SolarConfig.F.getClass();
SoulBinderConfig.F.getClass();
SpawnerConfig.F.getClass();
TankConfig.F.getClass();
VacuumConfig.F.getClass();
VatConfig.F.getClass();
WeatherConfig.F.getClass();
ZombieGenConfig.F.getClass();
}
} |
package de.idrinth.waraddonclient.service;
import de.idrinth.waraddonclient.Config;
import de.idrinth.waraddonclient.Utils;
import java.io.File;
import java.io.IOException;
import de.idrinth.waraddonclient.model.TrustManager;
public class Request {
private static final String BASE_URL = "https://tools.idrinth.de/";
private volatile boolean requestActive;
private org.apache.http.impl.client.CloseableHttpClient client;
private final javax.net.ssl.SSLContext sslContext;
private final FileLogger logger;
public Request(TrustManager manager, FileLogger logger) {
this.logger = logger;
sslContext = org.apache.http.ssl.SSLContextBuilder.create().loadTrustMaterial(
manager.getKeyStore(),
manager
).build();
}
public javax.json.JsonArray getAddonList() throws IOException {
org.apache.http.HttpResponse response = executionHandler(new org.apache.http.client.methods.HttpGet(BASE_URL + "addon-api/"));
javax.json.JsonArray data = javax.json.Json.createReader(response.getEntity().getContent()).readArray();
client.close();
return data;
}
public java.io.InputStream getAddonDownload(String url) throws IOException {
org.apache.http.HttpResponse response = executionHandler(new org.apache.http.client.methods.HttpGet(BASE_URL + "addons/" + url));
return response.getEntity().getContent();
}
private synchronized org.apache.http.HttpResponse executionHandler(org.apache.http.client.methods.HttpRequestBase uri) throws IOException {
uri.setConfig(org.apache.http.client.config.RequestConfig.DEFAULT);
uri.setHeader("User-Agent", "IdrinthsWARAddonClient/" + Config.getVersion());
uri.setHeader("Cache-Control", "no-cache");
while (requestActive) {
Utils.sleep(150, logger);
}
requestActive = true;
client = org.apache.http.impl.client.HttpClientBuilder.create()
.useSystemProperties()
.setSSLContext(sslContext)
.build();
org.apache.http.HttpResponse response = client.execute(uri);
if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
requestActive = false;
throw new java.net.ConnectException(response.getStatusLine().getReasonPhrase());
}
requestActive = false;
return response;
}
public boolean upload(String url, File file) {
org.apache.http.client.methods.HttpPost request = new org.apache.http.client.methods.HttpPost(url);
request.setEntity(new org.apache.http.entity.FileEntity(file));
try {
boolean wasSuccess = executionHandler(request) != null;
client.close();
return wasSuccess;
} catch (IOException exception) {
logger.error(exception);
}
return false;
}
public String getVersion() {
org.apache.http.client.methods.HttpGet request = new org.apache.http.client.methods.HttpGet("https://api.github.com/repos/Idrinth/WARAddonClient/releases/latest");
org.apache.http.HttpResponse response = executionHandler(request);
String version = "";
try {
if (response != null) {
javax.json.JsonObject data = javax.json.Json.createReader(response.getEntity().getContent()).readObject();
version = data.getString("tag_name");
}
client.close();
} catch (java.io.IOException exception) {
logger.error(exception);
}
return version;
}
} |
package edu.harvard.iq.dataverse;
import edu.harvard.iq.dataverse.api.SearchFields;
import edu.harvard.iq.dataverse.datavariable.DataVariable;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Named;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
@Stateless
@Named
public class IndexServiceBean {
private static final Logger logger = Logger.getLogger(IndexServiceBean.class.getCanonicalName());
@EJB
DataverseServiceBean dataverseService;
@EJB
DatasetServiceBean datasetService;
// List<String> advancedSearchFields = new ArrayList<>();
// List<String> notAdvancedSearchFields = new ArrayList<>();
public String indexAll() {
/**
* @todo allow for configuration of hostname and port
*/
SolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
logger.info("deleting all Solr documents before a complete re-index");
try {
server.deleteByQuery("*:*");// CAUTION: deletes everything!
} catch (SolrServerException | IOException ex) {
return ex.toString();
}
try {
server.commit();
} catch (SolrServerException | IOException ex) {
return ex.toString();
}
List<Dataverse> dataverses = dataverseService.findAll();
int dataverseIndexCount = 0;
for (Dataverse dataverse : dataverses) {
logger.info("indexing dataverse " + dataverseIndexCount + " of " + dataverses.size() + ": " + indexDataverse(dataverse));
dataverseIndexCount++;
}
int datasetIndexCount = 0;
List<Dataset> datasets = datasetService.findAll();
for (Dataset dataset : datasets) {
datasetIndexCount++;
logger.info("indexing dataset " + datasetIndexCount + " of " + datasets.size() + ": " + indexDataset(dataset));
}
// logger.info("advanced search fields: " + advancedSearchFields);
// logger.info("not advanced search fields: " + notAdvancedSearchFields);
logger.info("done iterating through all datasets");
return dataverseIndexCount + " dataverses" + " and " + datasetIndexCount + " datasets indexed\n";
}
public String indexDataverse(Dataverse dataverse) {
Dataverse rootDataverse = dataverseService.findRootDataverse();
Collection<SolrInputDocument> docs = new ArrayList<>();
SolrInputDocument solrInputDocument = new SolrInputDocument();
solrInputDocument.addField(SearchFields.ID, "dataverse_" + dataverse.getId());
solrInputDocument.addField(SearchFields.ENTITY_ID, dataverse.getId());
solrInputDocument.addField(SearchFields.TYPE, "dataverses");
solrInputDocument.addField(SearchFields.NAME, dataverse.getName());
solrInputDocument.addField(SearchFields.NAME_SORT, dataverse.getName());
solrInputDocument.addField(SearchFields.DESCRIPTION, dataverse.getDescription());
// logger.info("dataverse affiliation: " + dataverse.getAffiliation());
if (dataverse.getAffiliation() != null && !dataverse.getAffiliation().isEmpty()) {
/**
* @todo: stop using affiliation as category
*/
// solrInputDocument.addField(SearchFields.CATEGORY, dataverse.getAffiliation());
solrInputDocument.addField(SearchFields.AFFILIATION, dataverse.getAffiliation());
}
// checking for NPE is important so we can create the root dataverse
if (rootDataverse != null && !dataverse.equals(rootDataverse)) {
// important when creating root dataverse
if (dataverse.getOwner() != null) {
solrInputDocument.addField(SearchFields.PARENT_ID, dataverse.getOwner().getId());
solrInputDocument.addField(SearchFields.PARENT_NAME, dataverse.getOwner().getName());
}
}
List<String> dataversePathSegmentsAccumulator = new ArrayList<>();
List<String> dataverseSegments = findPathSegments(dataverse, dataversePathSegmentsAccumulator);
List<String> dataversePaths = getDataversePathsFromSegments(dataverseSegments);
if (dataversePaths.size() > 0) {
// logger.info(dataverse.getName() + " size " + dataversePaths.size());
dataversePaths.remove(dataversePaths.size() - 1);
}
solrInputDocument.addField(SearchFields.SUBTREE, dataversePaths);
docs.add(solrInputDocument);
/**
* @todo allow for configuration of hostname and port
*/
SolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
try {
if (dataverse.getId() != null) {
server.add(docs);
} else {
logger.info("WARNING: indexing of a dataverse with no id attempted");
}
} catch (SolrServerException | IOException ex) {
return ex.toString();
}
try {
server.commit();
} catch (SolrServerException | IOException ex) {
return ex.toString();
}
return "indexed dataverse " + dataverse.getId() + ":" + dataverse.getAlias();
}
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
Collection<SolrInputDocument> docs = new ArrayList<>();
List<String> dataversePathSegmentsAccumulator = new ArrayList<>();
List<String> dataverseSegments = new ArrayList<>();
try {
dataverseSegments = findPathSegments(dataset.getOwner(), dataversePathSegmentsAccumulator);
} catch (Exception ex) {
logger.info("failed to find dataverseSegments for dataversePaths for " + SearchFields.SUBTREE + ": " + ex);
}
List<String> dataversePaths = getDataversePathsFromSegments(dataverseSegments);
SolrInputDocument solrInputDocument = new SolrInputDocument();
solrInputDocument.addField(SearchFields.ID, "dataset_" + dataset.getId());
solrInputDocument.addField(SearchFields.ENTITY_ID, dataset.getId());
solrInputDocument.addField(SearchFields.TYPE, "datasets");
if (dataset.getEditVersion() != null) {
for (DatasetFieldValue datasetFieldValue : dataset.getEditVersion().getDatasetFieldValues()) {
DatasetField datasetField = datasetFieldValue.getDatasetField();
String title = datasetField.getTitle();
String name = datasetField.getName();
Long id = datasetField.getId();
String idDashTitle = id + "-" + title;
String idDashName = id + "-" + name;
// logger.info(idDashTitle);
// logger.info(name + ": " + datasetFieldValue.getStrValue());
String solrField = datasetField.getSolrField();
if (datasetFieldValue.getStrValue() != null && !datasetFieldValue.getStrValue().isEmpty() && solrField != null) {
logger.info("indexing " + datasetFieldValue.getDatasetField().getName() + ":" + datasetFieldValue.getStrValue() + " into " + solrField);
if (solrField.endsWith("_i")) {
String dateAsString = datasetFieldValue.getStrValue();
logger.info("date as string: " + dateAsString);
if (dateAsString != null && !dateAsString.isEmpty()) {
SimpleDateFormat inputDateyyyy = new SimpleDateFormat("yyyy", Locale.ENGLISH);
try {
/**
* @todo when bean validation is working we
* won't have to convert strings into dates
*/
logger.info("Trying to convert " + dateAsString + " to a YYYY date from dataset " + dataset.getId());
Date dateAsDate = inputDateyyyy.parse(dateAsString);
SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy");
String datasetFieldFlaggedAsDate = yearOnly.format(dateAsDate);
logger.info("YYYY only: " + datasetFieldFlaggedAsDate);
solrInputDocument.addField(solrField, Integer.parseInt(datasetFieldFlaggedAsDate));
} catch (Exception ex) {
logger.info("unable to convert " + dateAsString + " into YYYY format and couldn't index it (" + datasetField.getName() + ")");
}
}
} else {
// _s (dynamic string) and all other Solr fields
if (datasetFieldValue.getDatasetField().getName().equals("authorAffiliation")) {
/**
* @todo think about how to tie the fact that this
* needs to be multivalued (_ss) because a
* multivalued facet (authorAffilition_ss) is being
* collapsed into here at index time. The business
* logic to determine if a data-driven metadata
* field should be indexed into Solr as a single or
* multiple value lives in the getSolrField() method
* of DatasetField.java
*/
solrField = SearchFields.AFFILIATION;
} else if (datasetFieldValue.getDatasetField().getName().equals("title")) {
// datasets have titles not names but index title under name as well so we can sort datasets by name along dataverses and files
solrInputDocument.addField(SearchFields.NAME_SORT, datasetFieldValue.getStrValue());
}
solrInputDocument.addField(solrField, datasetFieldValue.getStrValue());
}
}
/**
* @todo: review all code below... commented out old indexing of
* hard coded fields. Also, should we respect the
* isAdvancedSearchField boolean?
*/
// if (datasetField.isAdvancedSearchField()) {
// advancedSearchFields.add(idDashName);
// logger.info(idDashName + " is an advanced search field (" + title + ")");
// if (name.equals(DatasetFieldConstant.title)) {
// String toIndexTitle = datasetFieldValue.getStrValue();
// if (toIndexTitle != null && !toIndexTitle.isEmpty()) {
// solrInputDocument.addField(SearchFields.TITLE, toIndexTitle);
// } else if (name.equals(DatasetFieldConstant.authorName)) {
// String toIndexAuthor = datasetFieldValue.getStrValue();
// if (toIndexAuthor != null && !toIndexAuthor.isEmpty()) {
// solrInputDocument.addField(SearchFields.AUTHOR_STRING, toIndexAuthor);
// } else if (name.equals(DatasetFieldConstant.productionDate)) {
// String toIndexProductionDateString = datasetFieldValue.getStrValue();
// if (toIndexProductionDateString != null && !toIndexProductionDateString.isEmpty()) {
// SimpleDateFormat inputDateyyyy = new SimpleDateFormat("yyyy", Locale.ENGLISH);
// try {
// logger.info("Trying to convert " + toIndexProductionDateString + " to a YYYY date from dataset " + dataset.getId());
// Date productionDate = inputDateyyyy.parse(toIndexProductionDateString);
// SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy");
// String productionYear = yearOnly.format(productionDate);
// logger.info("YYYY only: " + productionYear);
// solrInputDocument.addField(SearchFields.PRODUCTION_DATE_YEAR_ONLY, Integer.parseInt(productionYear));
// solrInputDocument.addField(SearchFields.PRODUCTION_DATE_ORIGINAL, productionDate);
// } catch (Exception ex) {
// logger.info("unable to convert " + toIndexProductionDateString + " into YYYY format");
// /**
// * @todo: DRY! this is the same as above!
// */
// } else if (name.equals(DatasetFieldConstant.distributionDate)) {
// String toIndexdistributionDateString = datasetFieldValue.getStrValue();
// if (toIndexdistributionDateString != null && !toIndexdistributionDateString.isEmpty()) {
// SimpleDateFormat inputDateyyyy = new SimpleDateFormat("yyyy", Locale.ENGLISH);
// try {
// logger.info("Trying to convert " + toIndexdistributionDateString + " to a YYYY date from dataset " + dataset.getId());
// Date distributionDate = inputDateyyyy.parse(toIndexdistributionDateString);
// SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy");
// String distributionYear = yearOnly.format(distributionDate);
// logger.info("YYYY only: " + distributionYear);
// solrInputDocument.addField(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, Integer.parseInt(distributionYear));
// solrInputDocument.addField(SearchFields.DISTRIBUTION_DATE_ORIGINAL, distributionDate);
// } catch (Exception ex) {
// logger.info("unable to convert " + toIndexdistributionDateString + " into YYYY format");
// } else if (name.equals(DatasetFieldConstant.keywordValue)) {
// String toIndexKeyword = datasetFieldValue.getStrValue();
// if (toIndexKeyword != null && !toIndexKeyword.isEmpty()) {
// solrInputDocument.addField(SearchFields.KEYWORD, toIndexKeyword);
// } else if (name.equals(DatasetFieldConstant.distributorName)) {
// String toIndexDistributor = datasetFieldValue.getStrValue();
// if (toIndexDistributor != null && !toIndexDistributor.isEmpty()) {
// solrInputDocument.addField(SearchFields.DISTRIBUTOR, toIndexDistributor);
// } else if (name.equals(DatasetFieldConstant.description)) {
// String toIndexDescription = datasetFieldValue.getStrValue();
// if (toIndexDescription != null && !toIndexDescription.isEmpty()) {
// solrInputDocument.addField(SearchFields.DESCRIPTION, toIndexDescription);
// } else {
// notAdvancedSearchFields.add(idDashName);
// logger.info(idDashName + " is not an advanced search field (" + title + ")");
}
}
solrInputDocument.addField(SearchFields.SUBTREE, dataversePaths);
solrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataset.getOwner().getName());
solrInputDocument.addField(SearchFields.PARENT_ID, dataset.getOwner().getId());
solrInputDocument.addField(SearchFields.PARENT_NAME, dataset.getOwner().getName());
docs.add(solrInputDocument);
List<DataFile> files = dataset.getFiles();
for (DataFile dataFile : files) {
SolrInputDocument datafileSolrInputDocument = new SolrInputDocument();
datafileSolrInputDocument.addField(SearchFields.ID, "datafile_" + dataFile.getId());
datafileSolrInputDocument.addField(SearchFields.ENTITY_ID, dataFile.getId());
datafileSolrInputDocument.addField(SearchFields.TYPE, "files");
datafileSolrInputDocument.addField(SearchFields.NAME, dataFile.getName());
datafileSolrInputDocument.addField(SearchFields.NAME_SORT, dataFile.getName());
datafileSolrInputDocument.addField(SearchFields.FILE_TYPE_MIME, dataFile.getContentType());
datafileSolrInputDocument.addField(SearchFields.FILE_TYPE, dataFile.getContentType().split("/")[0]);
datafileSolrInputDocument.addField(SearchFields.DESCRIPTION, dataFile.getDescription());
datafileSolrInputDocument.addField(SearchFields.SUBTREE, dataversePaths);
datafileSolrInputDocument.addField(SearchFields.HOST_DATAVERSE, dataFile.getOwner().getOwner().getName());
// datafileSolrInputDocument.addField(SearchFields.PARENT_NAME, dataFile.getDataset().getTitle());
datafileSolrInputDocument.addField(SearchFields.PARENT_ID, dataFile.getOwner().getId());
if (!dataFile.getOwner().getLatestVersion().getTitle().isEmpty()) {
datafileSolrInputDocument.addField(SearchFields.PARENT_NAME, dataFile.getOwner().getLatestVersion().getTitle());
}
// If this is a tabular data file -- i.e., if there are data
// variables associated with this file, we index the variable
// names and labels:
if (dataFile.isTabularData()) {
List<DataVariable> variables = dataFile.getDataTable().getDataVariables();
String variableNamesToIndex = null;
String variableLabelsToIndex = null;
for (DataVariable var : variables) {
// Hard-coded search fields, for now:
// TODO: immediately: define these as constants in SearchFields;
// TODO: eventually: review, decide how datavariables should
// be handled for indexing purposes. (should it be a fixed
// setup, defined in the code? should it be flexible? unlikely
// that this needs to be domain-specific... since these data
// variables are quite specific to tabular data, which in turn
// is something social science-specific...
// anyway -- needs to be reviewed. -- L.A. 4.0alpha1
if (var.getName() != null && !var.getName().equals("")) {
if (variableNamesToIndex == null) {
variableNamesToIndex = var.getName();
} else {
variableNamesToIndex = variableNamesToIndex + " " + var.getName();
}
}
if (var.getLabel() != null && !var.getLabel().equals("")) {
if (variableLabelsToIndex == null) {
variableLabelsToIndex = var.getLabel();
} else {
variableLabelsToIndex = variableLabelsToIndex + " " + var.getLabel();
}
}
}
if (variableNamesToIndex != null) {
logger.info("indexing " + variableNamesToIndex.length() + " bytes");
datafileSolrInputDocument.addField("varname_s", variableNamesToIndex);
}
if (variableLabelsToIndex != null) {
logger.info("indexing " + variableLabelsToIndex.length() + " bytes");
datafileSolrInputDocument.addField("varlabel_s", variableLabelsToIndex);
}
}
// And if the file has indexable file-level metadata associated
// with it, we'll index that too:
List<FileMetadataFieldValue> fileMetadataFieldValues = dataFile.getFileMetadataFieldValues();
if (fileMetadataFieldValues != null && fileMetadataFieldValues.size() > 0) {
for (int j = 0; j < fileMetadataFieldValues.size(); j++) {
String fieldValue = fileMetadataFieldValues.get(j).getStrValue();
FileMetadataField fmf = fileMetadataFieldValues.get(j).getFileMetadataField();
String fileMetadataFieldName = fmf.getName();
String fileMetadataFieldFormatName = fmf.getFileFormatName();
String fieldName = fileMetadataFieldFormatName + "-" + fileMetadataFieldName + "_s";
datafileSolrInputDocument.addField(fieldName, fieldValue);
}
}
docs.add(datafileSolrInputDocument);
}
/**
* @todo allow for configuration of hostname and port
*/
SolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
try {
server.add(docs);
} catch (SolrServerException | IOException ex) {
return ex.toString();
}
try {
server.commit();
} catch (SolrServerException | IOException ex) {
return ex.toString();
}
return "indexed dataset " + dataset.getId(); // + ":" + dataset.getTitle();
}
public List<String> findPathSegments(Dataverse dataverse, List<String> segments) {
if (!dataverseService.findRootDataverse().equals(dataverse)) {
// important when creating root dataverse
if (dataverse.getOwner() != null) {
findPathSegments(dataverse.getOwner(), segments);
}
segments.add(dataverse.getAlias());
return segments;
} else {
// base case
return segments;
}
}
List<String> getDataversePathsFromSegments(List<String> dataversePathSegments) {
List<String> subtrees = new ArrayList<>();
for (int i = 0; i < dataversePathSegments.size(); i++) {
StringBuilder pathBuilder = new StringBuilder();
int numSegments = dataversePathSegments.size();
for (int j = 0; j < numSegments; j++) {
if (j <= i) {
pathBuilder.append("/" + dataversePathSegments.get(j));
}
}
subtrees.add(pathBuilder.toString());
}
return subtrees;
}
} |
package exnihilocreatio.recipes.defaults;
import exnihilocreatio.ExNihiloCreatio;
import exnihilocreatio.ModBlocks;
import exnihilocreatio.ModFluids;
import exnihilocreatio.ModItems;
import exnihilocreatio.blocks.BlockSieve.MeshType;
import exnihilocreatio.config.ModConfig;
import exnihilocreatio.items.ItemResource;
import exnihilocreatio.items.ore.ItemOre;
import exnihilocreatio.items.seeds.ItemSeedBase;
import exnihilocreatio.registries.manager.ExNihiloRegistryManager;
import exnihilocreatio.registries.registries.*;
import exnihilocreatio.registries.types.Meltable;
import exnihilocreatio.texturing.Color;
import exnihilocreatio.util.BlockInfo;
import exnihilocreatio.util.ItemInfo;
import exnihilocreatio.util.Util;
import lombok.Getter;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.oredict.OreDictionary;
import java.util.LinkedHashMap;
import java.util.Map;
public class ExNihilo implements IRecipeDefaults {
@Getter
public String MODID = ExNihiloCreatio.MODID;
@Override
public void registerCompost(CompostRegistry registry) {
BlockInfo dirtState = new BlockInfo(Blocks.DIRT);
registry.register("treeSapling", 0.125f, dirtState);
registry.register("treeLeaves", 0.125f, dirtState);
registry.register("flower", 0.1f, dirtState);
registry.register("fish", 0.15f, dirtState);
registry.register("listAllmeatcooked", 0.20f, dirtState);
registry.register(new ItemInfo(Items.ROTTEN_FLESH), 0.1f, dirtState, new Color("C45631"));
registry.register(new ItemInfo(Items.SPIDER_EYE), 0.08f, dirtState, new Color("963E44"));
registry.register(new ItemInfo(Items.WHEAT), 0.08f, dirtState, new Color("E3E162"));
registry.register(new ItemInfo(Items.WHEAT_SEEDS), 0.08f, dirtState, new Color("35A82A"));
registry.register(new ItemInfo(Items.BREAD), 0.16f, dirtState, new Color("D1AF60"));
registry.register(new BlockInfo(Blocks.BROWN_MUSHROOM), 0.10f, dirtState, new Color("CFBFB6"));
registry.register(new BlockInfo(Blocks.RED_MUSHROOM), 0.10f, dirtState, new Color("D6A8A5"));
registry.register(new ItemInfo(Items.PUMPKIN_PIE), 0.16f, dirtState, new Color("E39A6D"));
registry.register(new ItemInfo(Items.PORKCHOP), 0.2f, dirtState, new Color("FFA091"));
registry.register(new ItemInfo(Items.BEEF), 0.2f, dirtState, new Color("FF4242"));
registry.register(new ItemInfo(Items.CHICKEN), 0.2f, dirtState, new Color("FFE8E8"));
registry.register(new ItemInfo(ModItems.resources, ItemResource.getMetaFromName(ItemResource.SILKWORM)), 0.04f, dirtState, new Color("ff9966"));
registry.register(new ItemInfo(ModItems.cookedSilkworm), 0.04f, dirtState, new Color("cc6600"));
registry.register(new ItemInfo(Items.APPLE), 0.10f, dirtState, new Color("FFF68F"));
registry.register(new ItemInfo(Items.MELON), 0.04f, dirtState, new Color("FF443B"));
registry.register(new BlockInfo(Blocks.MELON_BLOCK), 1.0f / 6, dirtState, new Color("FF443B"));
registry.register(new BlockInfo(Blocks.PUMPKIN), 1.0f / 6, dirtState, new Color("FFDB66"));
registry.register(new BlockInfo(Blocks.LIT_PUMPKIN), 1.0f / 6, dirtState, new Color("FFDB66"));
registry.register(new BlockInfo(Blocks.CACTUS), 0.10f, dirtState, new Color("DEFFB5"));
registry.register(new ItemInfo(Items.CARROT), 0.08f, dirtState, new Color("FF9B0F"));
registry.register(new ItemInfo(Items.POTATO), 0.08f, dirtState, new Color("FFF1B5"));
registry.register(new ItemInfo(Items.BAKED_POTATO), 0.08f, dirtState, new Color("FFF1B5"));
registry.register(new ItemInfo(Items.POISONOUS_POTATO), 0.08f, dirtState, new Color("E0FF8A"));
registry.register(new BlockInfo(Blocks.WATERLILY.getDefaultState()), 0.10f, dirtState, new Color("269900"));
registry.register(new BlockInfo(Blocks.VINE.getDefaultState()), 0.10f, dirtState, new Color("23630E"));
registry.register(new BlockInfo(Blocks.TALLGRASS, 1), 0.08f, dirtState, new Color("23630E"));
registry.register(new ItemInfo(Items.EGG), 0.08f, dirtState, new Color("FFFA66"));
registry.register(new ItemInfo(Items.NETHER_WART), 0.10f, dirtState, new Color("FF2B52"));
registry.register(new ItemInfo(Items.REEDS), 0.08f, dirtState, new Color("9BFF8A"));
registry.register(new ItemInfo(Items.STRING), 0.04f, dirtState, Util.whiteColor);
//Register any missed items
registry.register("listAllfruit", 0.10f, dirtState, new Color("35A82A"));
registry.register("listAllveggie", 0.10f, dirtState, new Color("FFF1B5"));
registry.register("listAllGrain", 0.08f, dirtState, new Color("E3E162"));
registry.register("listAllseed", 0.08f, dirtState, new Color("35A82A"));
registry.register("listAllmeatraw", 0.15f, dirtState, new Color("FFA091"));
}
@Override
public void registerCrook(CrookRegistry registry) {
registry.register("treeLeaves", ItemResource.getResourceStack(ItemResource.SILKWORM), 0.1f, 0f);
}
@Override
public void registerSieve(SieveRegistry registry) {
//Stone Pebble
registry.register("dirt", new ItemInfo(ModItems.pebbles), getDropChance(1f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles), getDropChance(1f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles), getDropChance(0.5f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles), getDropChance(0.5f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles), getDropChance(0.1f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles), getDropChance(0.1f), MeshType.STRING.getID());
//Granite Pebble
registry.register("dirt", new ItemInfo(ModItems.pebbles, 1), getDropChance(0.5f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles, 1), getDropChance(0.1f), MeshType.STRING.getID());
//Diorite Pebble
registry.register("dirt", new ItemInfo(ModItems.pebbles, 2), getDropChance(0.5f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles, 2), getDropChance(0.1f), MeshType.STRING.getID());
//Andesite Pebble
registry.register("dirt", new ItemInfo(ModItems.pebbles, 3), getDropChance(0.5f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(ModItems.pebbles, 3), getDropChance(0.1f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(Items.WHEAT_SEEDS), getDropChance(0.7f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(Items.MELON_SEEDS), getDropChance(0.35f), MeshType.STRING.getID());
registry.register("dirt", new ItemInfo(Items.PUMPKIN_SEEDS), getDropChance(0.35f), MeshType.STRING.getID());
//Ancient Spores
registry.register("dirt", new ItemInfo(ModItems.resources, 3), getDropChance(0.05f), MeshType.STRING.getID());
//Grass Seeds
registry.register("dirt", new ItemInfo(ModItems.resources, 4), getDropChance(0.05f), MeshType.STRING.getID());
registry.register("sand", new ItemInfo(Items.DYE, 3), getDropChance(0.03f), MeshType.STRING.getID());
registry.register("sand", new ItemInfo(Items.PRISMARINE_SHARD), getDropChance(0.02f), MeshType.DIAMOND.getID());
registry.register("gravel", new ItemInfo(Items.FLINT), getDropChance(0.25f), MeshType.FLINT.getID());
registry.register("gravel", new ItemInfo(Items.COAL), getDropChance(0.125f), MeshType.FLINT.getID());
registry.register("gravel", new ItemInfo(Items.DYE, 4), getDropChance(0.05f), MeshType.FLINT.getID());
registry.register("gravel", new ItemInfo(Items.DIAMOND), getDropChance(0.008f), MeshType.IRON.getID());
registry.register("gravel", new ItemInfo(Items.EMERALD), getDropChance(0.008f), MeshType.IRON.getID());
registry.register("gravel", new ItemInfo(Items.DIAMOND), getDropChance(0.016f), MeshType.DIAMOND.getID());
registry.register("gravel", new ItemInfo(Items.EMERALD), getDropChance(0.016f), MeshType.DIAMOND.getID());
registry.register(new BlockInfo(Blocks.SOUL_SAND), new ItemInfo(Items.QUARTZ), getDropChance(1f), MeshType.FLINT.getID());
registry.register(new BlockInfo(Blocks.SOUL_SAND), new ItemInfo(Items.QUARTZ), getDropChance(0.33f), MeshType.FLINT.getID());
registry.register(new BlockInfo(Blocks.SOUL_SAND), new ItemInfo(Items.NETHER_WART), getDropChance(0.1f), MeshType.STRING.getID());
registry.register(new BlockInfo(Blocks.SOUL_SAND), new ItemInfo(Items.GHAST_TEAR), getDropChance(0.02f), MeshType.DIAMOND.getID());
registry.register(new BlockInfo(Blocks.SOUL_SAND), new ItemInfo(Items.QUARTZ), getDropChance(1f), MeshType.DIAMOND.getID());
registry.register(new BlockInfo(Blocks.SOUL_SAND), new ItemInfo(Items.QUARTZ), getDropChance(0.8f), MeshType.DIAMOND.getID());
registry.register("dust", new ItemInfo(Items.DYE, 15), getDropChance(0.2f), MeshType.STRING.getID());
registry.register("dust", new ItemInfo(Items.GUNPOWDER), getDropChance(0.07f), MeshType.STRING.getID());
registry.register("dust", new ItemInfo(Items.REDSTONE), getDropChance(0.125f), MeshType.IRON.getID());
registry.register("dust", new ItemInfo(Items.REDSTONE), getDropChance(0.25f), MeshType.DIAMOND.getID());
registry.register("dust", new ItemInfo(Items.GLOWSTONE_DUST), getDropChance(0.0625f), MeshType.IRON.getID());
registry.register("dust", new ItemInfo(Items.BLAZE_POWDER), getDropChance(0.05f), MeshType.IRON.getID());
// Custom Ores for other mods
OreRegistry oreRegistry = ExNihiloRegistryManager.ORE_REGISTRY;
// Gold from nether rack
ItemOre gold = oreRegistry.getOreItem("gold");
if (gold != null) {
registry.register(new BlockInfo(ModBlocks.netherrackCrushed), new ItemInfo(gold, 0), getDropChance(0.25f), MeshType.FLINT.getID());
registry.register(new BlockInfo(ModBlocks.netherrackCrushed), new ItemInfo(gold, 0), getDropChance(0.25f), MeshType.IRON.getID());
registry.register(new BlockInfo(ModBlocks.netherrackCrushed), new ItemInfo(gold, 0), getDropChance(0.4f), MeshType.DIAMOND.getID());
}
// All default Ores
for (ItemOre ore : oreRegistry.getItemOreRegistry()) {
if (oreRegistry.getSieveBlackList().contains(ore)) continue;
registry.register("gravel", new ItemInfo(ore), getDropChance(0.07f), MeshType.FLINT.getID());
registry.register("gravel", new ItemInfo(ore), getDropChance(0.1f), MeshType.IRON.getID());
registry.register("gravel", new ItemInfo(ore), getDropChance(0.2f), MeshType.DIAMOND.getID());
}
// Seeds
for (ItemSeedBase seed : ModItems.itemSeeds) {
registry.register("dirt", new ItemInfo(seed), getDropChance(0.05f), MeshType.STRING.getID());
}
getLeavesSapling().forEach((leaves, sapling) -> {
BlockLeaves blockLeaves = ((BlockLeaves) Block.getBlockFromItem(leaves.getItemStack().getItem()));
float chance = blockLeaves.getSaplingDropChance(blockLeaves.getDefaultState()) / 100f;
registry.register(leaves, sapling, Math.min(chance * 1, 1.0f), MeshType.STRING.getID());
registry.register(leaves, sapling, Math.min(chance * 2, 1.0f), MeshType.FLINT.getID());
registry.register(leaves, sapling, Math.min(chance * 3, 1.0f), MeshType.IRON.getID());
registry.register(leaves, sapling, Math.min(chance * 4, 1.0f), MeshType.DIAMOND.getID());
//Apple
registry.register(leaves, new ItemInfo(Items.APPLE), 0.05f, MeshType.STRING.getID());
registry.register(leaves, new ItemInfo(Items.APPLE), 0.10f, MeshType.FLINT.getID());
registry.register(leaves, new ItemInfo(Items.APPLE), 0.15f, MeshType.IRON.getID());
registry.register(leaves, new ItemInfo(Items.APPLE), 0.20f, MeshType.DIAMOND.getID());
//Golden Apple
registry.register(leaves, new ItemInfo(Items.GOLDEN_APPLE), 0.001f, MeshType.STRING.getID());
registry.register(leaves, new ItemInfo(Items.GOLDEN_APPLE), 0.003f, MeshType.FLINT.getID());
registry.register(leaves, new ItemInfo(Items.GOLDEN_APPLE), 0.005f, MeshType.IRON.getID());
registry.register(leaves, new ItemInfo(Items.GOLDEN_APPLE), 0.01f, MeshType.DIAMOND.getID());
//Silk Worm
registry.register(leaves, new ItemInfo(ItemResource.getResourceStack(ItemResource.SILKWORM)), 0.025f, MeshType.STRING.getID());
registry.register(leaves, new ItemInfo(ItemResource.getResourceStack(ItemResource.SILKWORM)), 0.05f, MeshType.FLINT.getID());
registry.register(leaves, new ItemInfo(ItemResource.getResourceStack(ItemResource.SILKWORM)), 0.1f, MeshType.IRON.getID());
registry.register(leaves, new ItemInfo(ItemResource.getResourceStack(ItemResource.SILKWORM)), 0.2f, MeshType.DIAMOND.getID());
});
}
@Override
public void registerHammer(HammerRegistry registry) {
registry.register("cobblestone", new ItemStack(Blocks.GRAVEL, 1), 0, 1.0F, 0.0F);
registry.register("gravel", new ItemStack(Blocks.SAND, 1), 0, 1.0F, 0.0F);
registry.register("sand", new ItemStack(ModBlocks.dust, 1), 0, 1.0F, 0.0F);
registry.register("netherrack", new ItemStack(ModBlocks.netherrackCrushed, 1), 0, 1.0F, 0.0F);
registry.register("endstone", new ItemStack(ModBlocks.endstoneCrushed, 1), 0, 1.0F, 0.0F);
registry.register("stoneAndesite", new ItemStack(ModBlocks.crushedAndesite), 0, 1f, 0);
registry.register("stoneGranite", new ItemStack(ModBlocks.crushedGranite), 0, 1f, 0);
registry.register("stoneDiorite", new ItemStack(ModBlocks.crushedDiorite), 0, 1f, 0);
registry.register("crushedGranite", new ItemStack(Blocks.SAND, 1, 1), 0, 1.0f, 0.0f);
// Hammer concrete into concrete powder
for (int meta = 0; meta < 16; meta++)
registry.register(BlockInfo.getStateFromMeta(Blocks.CONCRETE, meta), new ItemStack(Blocks.CONCRETE_POWDER, 1, meta), 1, 1.0f, 0.0f);
}
@Override
public void registerHeat(HeatRegistry registry) {
// Vanilla fluids are weird, the "flowing" variant is simply a temporary state of checking if it can flow.
// So, once the lava has spread out all the way, it will all actually be "still" lava.
// Thanks Mojang <3
registry.register(new BlockInfo(Blocks.FLOWING_LAVA), 3);
registry.register(new BlockInfo(Blocks.LAVA), 3);
registry.register(new BlockInfo(Blocks.FIRE), 4);
registry.register(new BlockInfo(Blocks.TORCH), 1);
}
@Override
public void registerBarrelLiquidBlacklist(BarrelLiquidBlacklistRegistry registry) {
registry.register(ModBlocks.barrelWood.getTier(), "lava");
registry.register(ModBlocks.barrelWood.getTier(), "fire_water");
registry.register(ModBlocks.barrelWood.getTier(), "rocket_fuel");
registry.register(ModBlocks.barrelWood.getTier(), "pyrotheum");
}
@Override
public void registerFluidOnTop(FluidOnTopRegistry registry) {
registry.register(FluidRegistry.LAVA, FluidRegistry.WATER, new BlockInfo(Blocks.OBSIDIAN.getDefaultState()));
registry.register(FluidRegistry.WATER, FluidRegistry.LAVA, new BlockInfo(Blocks.COBBLESTONE.getDefaultState()));
}
@Override
public void registerOreChunks(OreRegistry registry) {
registry.register("gold", new Color("FFFF00"), new ItemInfo(Items.GOLD_INGOT, 0));
registry.register("iron", new Color("BF8040"), new ItemInfo(Items.IRON_INGOT, 0));
//TODO: Better way, will most likely never grab as it is just called before many mods init their oredict
if (!OreDictionary.getOres("oreCopper").isEmpty()) {
registry.register("copper", new Color("FF9933"), null);
}
if (!OreDictionary.getOres("oreTin").isEmpty()) {
registry.register("tin", new Color("E6FFF2"), null);
}
if (!OreDictionary.getOres("oreAluminium").isEmpty() || !OreDictionary.getOres("oreAluminum").isEmpty()) {
registry.register("aluminium", new Color("BFBFBF"), null);
}
if (!OreDictionary.getOres("oreLead").isEmpty()) {
registry.register("lead", new Color("330066"), null);
}
if (!OreDictionary.getOres("oreSilver").isEmpty()) {
registry.register("silver", new Color("F2F2F2"), null);
}
if (!OreDictionary.getOres("oreNickel").isEmpty()) {
registry.register("nickel", new Color("FFFFCC"), null);
}
if (!OreDictionary.getOres("oreUranium").isEmpty()) {
registry.register("uranium", new Color("4E5B43"), null);
}
}
@Override
public void registerFluidTransform(FluidTransformRegistry registry) {
registry.register("water", "witchwater", 12000, new BlockInfo[]{new BlockInfo(Blocks.MYCELIUM.getDefaultState())}, new BlockInfo[]{new BlockInfo(Blocks.BROWN_MUSHROOM.getDefaultState()), new BlockInfo(Blocks.RED_MUSHROOM.getDefaultState())});
}
@Override
public void registerFluidBlockTransform(FluidBlockTransformerRegistry registry) {
registry.register(FluidRegistry.WATER, "dust", new ItemInfo(new ItemStack(Blocks.CLAY)));
registry.register(FluidRegistry.LAVA, "dustRedstone", new ItemInfo(new ItemStack(Blocks.NETHERRACK)));
registry.register(FluidRegistry.LAVA, "dustGlowstone", new ItemInfo(new ItemStack(Blocks.END_STONE)));
registry.register(ModFluids.fluidWitchwater, "sand", new ItemInfo(new ItemStack(Blocks.SOUL_SAND)));
if (FluidRegistry.isFluidRegistered("milk")){
registry.register(FluidRegistry.getFluid("milk"), new ItemInfo(new ItemStack(Blocks.BROWN_MUSHROOM)), new ItemInfo(new ItemStack(Blocks.SLIME_BLOCK)), "Slime");
registry.register(FluidRegistry.getFluid("milk"), new ItemInfo(new ItemStack(Blocks.RED_MUSHROOM)), new ItemInfo(new ItemStack(Blocks.SLIME_BLOCK)), "Slime");
}
// Vanilla Concrete
for (int meta = 0; meta < 16; meta++)
registry.register(FluidRegistry.WATER, new ItemInfo(new ItemStack(Blocks.CONCRETE_POWDER, 1, meta)), new ItemInfo(new ItemStack(Blocks.CONCRETE, 1, meta)));
}
@Override
public void registerFluidItemFluid(FluidItemFluidRegistry registry) {
registry.register(FluidRegistry.WATER, new ItemInfo(ItemResource.getResourceStack(ItemResource.ANCIENT_SPORES)), ModFluids.fluidWitchwater);
}
@Override
public void registerCrucibleStone(CrucibleRegistry registry) {
registry.register("cobblestone", FluidRegistry.LAVA, 250);
registry.register("stone", FluidRegistry.LAVA, 250);
registry.register("gravel", FluidRegistry.LAVA, 200);
registry.register("sand", FluidRegistry.LAVA, 100);
registry.register(new BlockInfo(ModBlocks.dust.getDefaultState()), FluidRegistry.LAVA, 50);
// 1:1 Back to lava
registry.register("netherrack", FluidRegistry.LAVA, 1000);
registry.register("obsidian", FluidRegistry.LAVA, 1000);
}
@Override
public void registerCrucibleWood(CrucibleRegistry registry) {
Meltable water = new Meltable(FluidRegistry.WATER.getName(), 250, new BlockInfo(Blocks.LEAVES, 0));
registry.register("treeLeaves", FluidRegistry.WATER, 250);
registry.register("treeSapling", water);
registry.register("listAllfruit", water);
registry.register("listAllveggie", water);
registry.register(new ItemInfo(Blocks.SAPLING, 0), water);
registry.register(new ItemInfo(Blocks.SAPLING, 1), water.copy().setTextureOverride(new BlockInfo(Blocks.LEAVES, 1)));
registry.register(new ItemInfo(Blocks.SAPLING, 2), water.copy().setTextureOverride(new BlockInfo(Blocks.LEAVES, 2)));
registry.register(new ItemInfo(Blocks.SAPLING, 3), water.copy().setTextureOverride(new BlockInfo(Blocks.LEAVES, 3)));
registry.register(new ItemInfo(Blocks.SAPLING, 4), water.copy().setTextureOverride(new BlockInfo(Blocks.LEAVES2, 0)));
registry.register(new ItemInfo(Blocks.SAPLING, 5), water.copy().setTextureOverride(new BlockInfo(Blocks.LEAVES2, 1)));
registry.register(new ItemInfo(Items.APPLE), water);
}
@Override
public void registerMilk(MilkEntityRegistry registry) {
registry.register("Cow", "milk", 10, 20);
}
private float getDropChance(float chance) {
if (ModConfig.world.isSkyWorld)
return chance;
else return chance / 100f * (float) ModConfig.world.normalDropPercent;
}
public static Map<BlockInfo, BlockInfo> getLeavesSapling(){
Map<BlockInfo, BlockInfo> saplingMap = new LinkedHashMap<>();
saplingMap.put(new BlockInfo(Blocks.LEAVES, 0), new BlockInfo(Blocks.SAPLING, 0));
saplingMap.put(new BlockInfo(Blocks.LEAVES, 1), new BlockInfo(Blocks.SAPLING, 1));
saplingMap.put(new BlockInfo(Blocks.LEAVES, 2), new BlockInfo(Blocks.SAPLING, 2));
saplingMap.put(new BlockInfo(Blocks.LEAVES, 3), new BlockInfo(Blocks.SAPLING, 3));
saplingMap.put(new BlockInfo(Blocks.LEAVES2, 0), new BlockInfo(Blocks.SAPLING, 4));
saplingMap.put(new BlockInfo(Blocks.LEAVES2, 1), new BlockInfo(Blocks.SAPLING, 5));
return saplingMap;
}
} |
package fr.foodlimit.api.scheduled;
import fr.foodlimit.api.food.FoodService;
import fr.foodlimit.api.shared.models.Food;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.tomcat.jni.Local;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Iterator;
@Component
@ConfigurationProperties("onesignal")
public class ScheduledTasks {
@Autowired
FoodService foodService;
private String url;
private String apiKey;
private String appGoogleId;
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
@Scheduled(cron="25 17 * * *")
public void notifyAllUsersWithExpiredFoodsIn3Days() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
for (Iterator<Food> i = foodService.getFoods().iterator(); i.hasNext();) {
Food food = i.next();
if(LocalDate.now().plusDays(3).isAfter(food.getDlc())){
this.sendNotif(httpClient, food);
}
}
httpClient.close();
}
private void sendNotif(HttpClient httpClient, Food food) throws IOException {
try {
// Build request
HttpPost request = new HttpPost(url);
// Headers
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", apiKey);
// Body
JSONObject json = new JSONObject();
json.put("app_id", appGoogleId);
json.put("headings", new JSONObject().put("en", "FOOD-LIMIT"));
json.put("contents", new JSONObject().put("en", "Votre aliment '"+food.getName()+"' arrive à sa date de péremption !"));
json.put("filters", new JSONArray().put(
new JSONObject()
.put("field", "tag")
.put("key", "username")
.put("relation", "=")
.put("value", food.getUser().getUsername())
));
StringEntity body = new StringEntity(json.toString());
request.setEntity(body);
// Execute
httpClient.execute(request);
log.info(request.toString());
} catch (Exception ex) {
log.error(ex.getMessage());
}
}
} |
package ge.edu.freeuni.sdp.arkanoid;
import ge.edu.freeuni.sdp.arkanoid.model.*;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Size;
import java.util.ArrayList;
import java.util.List;
class LevelRegistry {
static List<Level> getLevels(Size size) {
List<Level> levels = new ArrayList<>();
Level levelTestGray = new Level(
"Test Level gray brick",
"Test Level gray brick.",
new GrayTestLevelBuilder(size));
Level autoPaddleLevel = new Level(
"Test #12 Autopilot Capsule",
"This level is a test for #12 Autopilot Capsule feature.",
new TestACapsuleLevelBuilder(size));
Level levelVerySimple = new Level(
"Test #3 Expand Capsule",
"This level is a test for #3 Expand Capsule feature.",
new TestECapsuleLevelBuilder(size));
Level level1 = new Level(
"Level 1",
"Destruct the wall. No power-ups.",
new Level1Builder(size));
Level levelSinkingWall = new Level(
"Level 2 Sinking Wall",
"Wall is sinking. Make sure it doesn't reach you.",
new SinkingWallLevelBuilder(size));
Level levelScrollingWall = new Level(
"Level 3 Scrolling Wall",
"Wall is scrolling. Make sure it doesnt reach left bound.",
new ScrollingWallLevelBuilder(size));
Level levelBombBricksDemo = new Level(
"Level Bomb Bricks Demo",
"Approximately 20% of bricks are bombs. If bomb is hit, " +
"it explodes neighbours within radius of 2 bricks" +
"(bomb bricks are Blue)",
new LevelBombBricksDemoBuilder(size)
);
Level levelClearDemo = new Level(
"Simulate level clear",
"Contains one brick which is hit when the game starts",
new LevelSingleBrickBuilder(size)
);
Level levelGameEndDemo = new Level(
"Simulate game finish",
"Contains one brick which is hit when the game starts",
new LevelSingleBrickBuilder(size)
);
Level levelBreakCapsuleDemo = new Level(
"Level Break Capsule Demo",
"This level is a test for BreakCapsule thus half of the " +
"bricks contains BreakCapsule",
new LevelBreakCapsuleBuilder(size)
);
levels.add(autoPaddleLevel);
Level levelWithLives = new Level(
"P Capsule",
"Contains one brick which is hit when the game starts",
new FrameBuilderWithLives(size)
);
Level levelBoss = new Level(
"Level Boss",
"Monster contains every capsule in the game",
new LevelBossBuilder(size)
);
Level DisruptionCapsuleLevel = new Level(
"Test Disruption Capsule",
"This level is a test for #12 Autopilot Capsule feature.",
new TestDCapsuleLevelBuilder(size));
Level levelWormhole = new Level(
"Level Wormhole",
"This level contains two portals",
new LevelWormholeBuilder(size)
);
Level levelKillCapsuleDemo = new Level(
"Kill Capsule!",
"Bricks contain killer capsules, that you must avoid",
new LevelKillCapsuleBuilder(size)
);
Level levelLaserCapsuleDemo = new Level(
"Laser Capsule!",
"laser capsules generate laser beam if catched by paddle",
new TestLCapsuleLevelBuilder(size)
);
levels.add(levelTestGray);
levels.add(levelClearDemo);
levels.add(levelVerySimple);
levels.add(level1);
levels.add(levelBreakCapsuleDemo);
levels.add(levelSinkingWall);
levels.add(levelScrollingWall);
levels.add(levelBombBricksDemo);
levels.add(levelGameEndDemo);
levels.add(levelWithLives);
levels.add(levelBoss);
levels.add(DisruptionCapsuleLevel);
levels.add(levelWormhole);
levels.add(levelKillCapsuleDemo);
levels.add(levelLaserCapsuleDemo);
return levels;
}
} |
package harmony.mastermind.logic.commands;
import java.util.ArrayList;
import java.util.Stack;
import harmony.mastermind.storage.StorageMemory;
import harmony.mastermind.memory.GenericMemory;
import harmony.mastermind.memory.Memory;
public class History {
private static ArrayList<GenericMemory> current = null;
private static Stack<ArrayList<GenericMemory>> back = new Stack<ArrayList<GenericMemory>>();
private static Stack<ArrayList<GenericMemory>> forward = new Stack<ArrayList<GenericMemory>>();
//@@author A0143378Y
// Creates a snapshot of changes in the memory and moves previous state into the back stack. forward stack is reinitialized
public static void advance(Memory memory) {
forward = new Stack<ArrayList<GenericMemory>>();
back.push(current);
current = new ArrayList<GenericMemory>();
duplicateMemory(memory);
}
//@@author A0143378Y
// Duplicates memory into the current ArrayList
private static void duplicateMemory(Memory memory) {
for (int i = 0; i< memory.getSize(); i++) { // Duplicating of memory into snapshot
current.add(new GenericMemory(memory.get(i).getType(),
memory.get(i).getName(),
memory.get(i).getDescription(),
memory.get(i).getStart(),
memory.get(i).getEnd(),
memory.get(i).getState()));
}
}
/*
* Unused code:
* Reason: For future implementations of Memory
//@@author A0143378Y-unused
// Retrieves most recent snapshot in the forward stack and swap it with current memory. Current memory gets pushed into back stack
public static void redo(Memory memory) {
if (forward.isEmpty() || (forward.peek() == null)) {
System.out.println("Nothing to redo!");
return;
}
redoMemorySwap(memory);
StorageMemory.saveToStorage(memory);
System.out.println("Redo successful.");
}
//@@author A0143378Y
// Swaps memory used for redo
private static void redoMemorySwap(Memory memory) {
assert forward.size() > 0;
back.push(current);
current = forward.pop();
memory.setList(current);
}
//@@author A0143378Y
// Retrieves most recent snapshot in the back stack and swap it with current memory. Current memory gets pushed into forward stack
public static void undo(Memory memory) {
if (back.isEmpty() || (back.peek() == null)) {
System.out.println("Nothing to undo!");
return;
}
ArrayList<GenericMemory> temp = duplicateTemp(memory);
undoMemorySwap(memory, temp);
StorageMemory.saveToStorage(memory);
System.out.println("Undo successful.");
}
//@@author A0143378Y
// Swaps memory used for undo
private static void undoMemorySwap(Memory memory, ArrayList<GenericMemory> temp) {
forward.push(temp);
current = back.pop();
assert current != null;
memory.setList(current);
}
//@@author A0143378Y
// Duplicate current memory into temp ArrayList
private static ArrayList<GenericMemory> duplicateTemp(Memory memory) {
ArrayList<GenericMemory> temp = new ArrayList<GenericMemory>(); // Duplicating of memory into forward stack
for (int i = 0; i < memory.getSize(); i++) {
temp.add(new GenericMemory(memory.get(i).getType(),
memory.get(i).getName(),
memory.get(i).getDescription(),
memory.get(i).getStart(),
memory.get(i).getEnd(),
memory.get(i).getState()));
}
return temp;
}
*/
} |
package hudson.plugins.disk_usage;
import hudson.Plugin;
import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Job;
import hudson.model.Jobs;
import hudson.model.ManagementLink;
import hudson.triggers.Trigger;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.ServletException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* Entry point of the the plugin.
*
* @author dvrzalik
* @plugin
*/
public class DiskUsagePlugin extends Plugin {
//trigger disk usage thread each 60 minutes
public static final int COUNT_INTERVAL_MINUTES = 60;
private transient final DiskUsageThread duThread = new DiskUsageThread();
private static DiskUsage diskUsageSum;
public void start() throws Exception {
ManagementLink.LIST.add(new ManagementLink() {
public final String[] COLUMNS = new String[]{"Project name", "Builds", "Workspace"};
public String getIconFileName() {
return "/plugin/disk-usage/icons/diskusage48.png";
}
public String getDisplayName() {
return "Disk usage";
}
public String getUrlName() {
return "plugin/disk-usage/";
}
public String getDescription() {
return "Displays per-project disk usage";
}
});
Jobs.PROPERTIES.add(DiskUsageProperty.DESCRIPTOR);
Trigger.timer.scheduleAtFixedRate(duThread, 1000*60*COUNT_INTERVAL_MINUTES, 1000*60*COUNT_INTERVAL_MINUTES);
}
/**
* @return DiskUsage for given project (shortcut for the view). Never null.
*/
public static DiskUsage getDiskUsage(Job project) {
ProjectDiskUsageAction action = project.getAction(ProjectDiskUsageAction.class);
if (action != null) {
return action.getDiskUsage();
}
return new DiskUsage(0, 0);
}
//Another shortcut
public static String getProjectUrl(Job project) {
return Util.encode(project.getAbsoluteUrl());
}
/**
* @return Project list sorted by occupied disk space
*/
public static List getProjectList() {
Comparator<AbstractProject> comparator = new Comparator<AbstractProject>() {
public int compare(AbstractProject o1, AbstractProject o2) {
DiskUsage du1 = getDiskUsage(o1);
DiskUsage du2 = getDiskUsage(o2);
long result = du2.wsUsage + du2.buildUsage - du1.wsUsage - du1.buildUsage;
if(result > 0) return 1;
if(result < 0) return -1;
return 0;
}
};
List<AbstractProject> projectList = Util.createSubList(Hudson.getInstance().getItems(), AbstractProject.class);
Collections.sort(projectList, comparator);
//calculate sum
DiskUsage sum = new DiskUsage(0, 0);
for(AbstractProject project: projectList) {
DiskUsage du = getDiskUsage(project);
sum.buildUsage += du.buildUsage;
sum.wsUsage += du.wsUsage;
}
diskUsageSum = sum;
return projectList;
}
public static DiskUsage getDiskUsageSum() {
return diskUsageSum;
}
public void doRecordDiskUsage(StaplerRequest req, StaplerResponse res) throws ServletException, IOException {
duThread.doRun();
res.forwardToPreviousPage(req);
}
} |
package in.twizmwaz.cardinal.command;
import com.google.common.base.Optional;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.NestedCommand;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.LocalizedChatMessage;
import in.twizmwaz.cardinal.chat.UnlocalizedChatMessage;
import in.twizmwaz.cardinal.event.TeamNameChangeEvent;
import in.twizmwaz.cardinal.match.MatchState;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import in.twizmwaz.cardinal.util.ChatUtil;
import in.twizmwaz.cardinal.util.Teams;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TeamCommands {
@Command(aliases = {"force"}, desc = "Forces a player onto the team specified.", usage = "<player> <team>", min = 2)
@CommandPermissions("cardinal.team.force")
public static void force(final CommandContext cmd, CommandSender sender) throws CommandException {
if (Bukkit.getPlayer(cmd.getString(0)) != null) {
Optional<TeamModule> team = Teams.getTeamByName(cmd.getJoinedStrings(1));
if (team.isPresent()) {
if (!team.get().contains(Bukkit.getPlayer(cmd.getString(0)))) {
team.get().add(Bukkit.getPlayer(cmd.getString(0)), true, false);
sender.sendMessage(team.get().getColor() + Bukkit.getPlayer(cmd.getString(0)).getName() + ChatColor.GRAY + " forced to " + team.get().getCompleteName());
} else
throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_ALREADY_ON_TEAM,
Teams.getTeamByPlayer(Bukkit.getPlayer(cmd.getString(0))).get().getColor() + Bukkit.getPlayer(cmd.getString(0)).getName() + ChatColor.RED,
Teams.getTeamByPlayer(Bukkit.getPlayer(cmd.getString(0))).get().getCompleteName()).getMessage(((Player) sender).getLocale()));
} else {
throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_NO_TEAM_MATCH).getMessage(ChatUtil.getLocale(sender)));
}
} else {
throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_NO_PLAYER_MATCH).getMessage(ChatUtil.getLocale(sender)));
}
}
@Command(aliases = {"alias"}, desc = "Renames a the team specified.", usage = "<team> <name>", min = 2)
@CommandPermissions("cardinal.team.alias")
public static void alias(final CommandContext cmd, CommandSender sender) throws CommandException {
Optional<TeamModule> team = Teams.getTeamByName(cmd.getString(0));
if (team.isPresent()) {
String msg = cmd.getJoinedStrings(1);
String locale = ChatUtil.getLocale(sender);
ChatUtil.getGlobalChannel().sendMessage(ChatColor.GRAY + new LocalizedChatMessage(ChatConstant.GENERIC_TEAM_ALIAS, team.get().getCompleteName() + ChatColor.GRAY, team.get().getColor() + msg + ChatColor.GRAY).getMessage(locale));
team.get().setName(msg);
Bukkit.getServer().getPluginManager().callEvent(new TeamNameChangeEvent(team.get()));
} else {
throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_NO_TEAM_MATCH).getMessage(ChatUtil.getLocale(sender)));
}
}
@Command(aliases = {"shuffle"}, desc = "Shuffles the teams.")
@CommandPermissions("cardinal.team.shuffle")
public static void shuffle(final CommandContext cmd, CommandSender sender) throws CommandException {
if (GameHandler.getGameHandler().getMatch().getState().equals(MatchState.WAITING) || GameHandler.getGameHandler().getMatch().getState().equals(MatchState.STARTING)) {
List<Player> playersToShuffle = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers()) {
if (Teams.getTeamByPlayer(player).isPresent()) {
if (!Teams.getTeamByPlayer(player).get().isObserver()) {
playersToShuffle.add(player);
TeamModule observers = Teams.getTeamById("observers").get();
observers.add(player, true, false);
}
}
}
while (playersToShuffle.size() > 0) {
Player player = playersToShuffle.get(new Random().nextInt(playersToShuffle.size()));
Optional<TeamModule> team = Teams.getTeamWithFewestPlayers(GameHandler.getGameHandler().getMatch());
if (team.isPresent()) team.get().add(player, true);
playersToShuffle.remove(player);
}
String locale = ChatUtil.getLocale(sender);
sender.sendMessage(ChatColor.GREEN + new LocalizedChatMessage(ChatConstant.GENERIC_TEAM_SHUFFLE).getMessage(locale));
} else {
throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_NO_SHUFFLE).getMessage(ChatUtil.getLocale(sender)));
}
}
@Command(aliases = {"size"}, desc = "Changes the specified team's size.", usage = "<team> <size>", min = 2)
@CommandPermissions("cardinal.team.size")
public static void size(final CommandContext cmd, CommandSender sender) throws CommandException {
Optional<TeamModule> team = Teams.getTeamByName(cmd.getString(0));
if (team.isPresent()) {
team.get().setMaxOverfill(Integer.parseInt(cmd.getString(1)));
team.get().setMax(Integer.parseInt(cmd.getString(1)));
sender.sendMessage(new LocalizedChatMessage(ChatConstant.GENERIC_TEAM_SIZE_CHANGED, Teams.getTeamByName(cmd.getString(0)).get().getCompleteName() + ChatColor.WHITE, ChatColor.AQUA + cmd.getString(1)).getMessage(ChatUtil.getLocale(sender)));
} else {
throw new CommandException(new LocalizedChatMessage(ChatConstant.ERROR_NO_TEAM_MATCH).getMessage(ChatUtil.getLocale(sender)));
}
}
@Command(aliases = {"myteam", "mt"}, desc = "Shows what team you are on", min = 0, max = 0)
public static void myTeam(final CommandContext cmd, CommandSender sender) throws CommandException {
if (sender instanceof Player) {
Optional<TeamModule> team = Teams.getTeamByPlayer((Player) sender);
if (team.isPresent()) {
sender.sendMessage(new UnlocalizedChatMessage(ChatColor.GRAY + "{0}", new LocalizedChatMessage(ChatConstant.GENERIC_ON_TEAM, team.get().getCompleteName())).getMessage(((Player) sender).getLocale()));
}
}
}
public static class TeamParentCommand {
@Command(aliases = {"team"}, desc = "Manage the teams in the match.")
@NestedCommand({TeamCommands.class})
public static void team(final CommandContext args, CommandSender sender) throws CommandException {
}
}
} |
package io.github.yas99en.mojo.script;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.List;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Executes scripts
*/
@Mojo(name = "execute")
public class ExecuteMojo extends AbstractMojo {
private static Pattern urlPattern = Pattern.compile("^jar:.*|^http:
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession session;
@Parameter(defaultValue = "javascript")
private String engine;
@Parameter(property="scriptmvn.arguments")
private String[] arguments;
@Parameter
private List<String> scriptFiles;
@Parameter
private String scriptFile;
@Parameter(property="scriptmvn.script")
private String script;
@Parameter(defaultValue = "true")
private boolean globalProject;
@Parameter(defaultValue = "true")
private boolean globalSettings;
@Parameter(defaultValue = "true")
private boolean globalLog;
@Parameter(defaultValue = "mvn")
private String prefix;
private Log log;
public void execute() throws MojoExecutionException {
log = getLog();
try {
evaluate();
} catch (ScriptException e) {
throw new MojoExecutionException(e.getMessage(), e);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
} catch (RuntimeException e) {
if(e.getCause() instanceof MojoExecutionException) {
throw (MojoExecutionException)e.getCause();
} else {
throw e;
}
}
}
private void evaluate() throws ScriptException, IOException, MojoExecutionException {
ScriptEngineManager manager = new ScriptEngineManager();
log.info("engine: " + engine);
ScriptEngine eng = manager.getEngineByName(engine);
if(eng == null) {
throw new MojoExecutionException("engine not found for: " + engine);
}
Mvn mvn = new Mvn(session, log);
setUpGlobals(eng, mvn);
if(arguments == null) {
arguments = new String[0];
}
if(scriptFiles != null) {
evalScriptFiles(eng, mvn, scriptFiles, arguments);
}
if(scriptFile != null) {
evalScriptFile(eng, mvn, scriptFile, arguments);
}
if(script != null) {
evalScript(eng, mvn, script, arguments);
}
}
private void setUpGlobals(ScriptEngine eng, Mvn mvn) {
log.debug("prefix: "+prefix);
if(!prefix.isEmpty()) {
eng.put(prefix, mvn);
}
if(globalProject) {
eng.put("project", mvn.project);
}
if(globalSettings) {
eng.put("settings", mvn.settings);
}
if(globalLog) {
eng.put("log", mvn.log);
}
}
private static void evalScript(ScriptEngine eng, Mvn mvn, String script, String[] arguments) throws ScriptException {
String pomXml = new File(mvn.project.getBasedir(), "pom.xml").getAbsolutePath();
mvn.setScriptFile(pomXml);
eng.put(ScriptEngine.FILENAME, pomXml);
mvn.setArguments(arguments.clone());
eng.put(ScriptEngine.ARGV, arguments.clone());
eng.eval(script);
}
private static void evalScriptFile(ScriptEngine eng, Mvn mvn, String scriptFile, String[] arguments)
throws IOException, ScriptException {
mvn.setArguments(arguments.clone());
eng.put(ScriptEngine.ARGV, arguments.clone());
InputStream in = null;
if(urlPattern.matcher(scriptFile).matches()) {
URL url = new URL(scriptFile);
mvn.log.debug(url);
mvn.setScriptFile(scriptFile);
eng.put(ScriptEngine.FILENAME, scriptFile);
in = url.openStream();
} else {
File file = new File(scriptFile);
if(!file.isAbsolute()) {
file = new File(mvn.project.getBasedir(), scriptFile);
}
mvn.log.debug(file);
mvn.setScriptFile(file.getAbsolutePath());
eng.put(ScriptEngine.FILENAME, file.getAbsolutePath());
in = new FileInputStream(file);
}
Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
try {
eng.eval(reader);
} finally {
try {
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
private static void evalScriptFiles(ScriptEngine eng, Mvn mvn,
List<String> scriptFiles, String[] arguments) throws IOException, ScriptException {
for(String scriptFile: scriptFiles) {
evalScriptFile(eng, mvn, scriptFile, arguments);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.