diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/jreunion/src/main/java/org/reunionemu/jreunion/server/PacketFactory.java b/jreunion/src/main/java/org/reunionemu/jreunion/server/PacketFactory.java
index 4f1caaa..3bd882c 100644
--- a/jreunion/src/main/java/org/reunionemu/jreunion/server/PacketFactory.java
+++ b/jreunion/src/main/java/org/reunionemu/jreunion/server/PacketFactory.java
@@ -1,1277 +1,1277 @@
package org.reunionemu.jreunion.server;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import org.reunionemu.jreunion.game.Effectable;
import org.reunionemu.jreunion.game.Equipment;
import org.reunionemu.jreunion.game.Equipment.Slot;
//import org.reunionemu.jreunion.game.items.pet.PetEquipment;
//import org.reunionemu.jreunion.game.items.pet.PetEquipment.PetSlot;
import org.reunionemu.jreunion.game.items.pet.PetEquipment;
import org.reunionemu.jreunion.game.items.pet.PetEquipment.PetSlot;
import org.reunionemu.jreunion.game.npc.Merchant;
import org.reunionemu.jreunion.game.npc.NpcShop;
import org.reunionemu.jreunion.game.ExchangeItem;
import org.reunionemu.jreunion.game.InventoryItem;
import org.reunionemu.jreunion.game.Item;
import org.reunionemu.jreunion.game.LivingObject;
import org.reunionemu.jreunion.game.Npc;
import org.reunionemu.jreunion.game.Party;
import org.reunionemu.jreunion.game.Pet;
import org.reunionemu.jreunion.game.Player;
import org.reunionemu.jreunion.game.Position;
import org.reunionemu.jreunion.game.QuickSlotItem;
import org.reunionemu.jreunion.game.RoamingItem;
import org.reunionemu.jreunion.game.Skill;
import org.reunionemu.jreunion.game.StashItem;
import org.reunionemu.jreunion.game.VendorItem;
import org.reunionemu.jreunion.game.WorldObject;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
public class PacketFactory {
public static enum Type{
FAIL,
INFO,
OK,
OUT,
GO_WORLD,
GOTO,
PARTY_DISBAND,
HOUR,
IN_CHAR,
SAY,
IN_ITEM,
DROP,
IN_NPC,
AT,
PLACE,
S_CHAR,
WALK,
SOCIAL,
COMBAT,
JUMP,
LEVELUP,
STATUS,
EFFECT,
CHAR_REMOVE,
CHAR_WEAR,
ATTACK,
ATTACK_VITAL,
SKILLLEVEL,
PICKUP,
PICK,
SHOP_RATE,
SHOP_ITEM,
SUCCESS,
MSG,
STASH,
STASH_TO,
STASH_FROM,
STASH_GET,
STASH_PUT,
STASH_END,
INVEN,
SKILLLEVEL_ALL,
A_,
SKILL,
MULTI_SHOT,
QUICK,
WEARING,
UPGRADE,
QT,
KILL,
Q_EX,
WISPER,
SECONDATTACK,
SAV,
K,
ICHANGE,
CHIP_EXCHANGE,
SKY,
UPDATE_ITEM,
USQ, // old 2007 client
UQ_ITEM,
MT_ITEM,
AV,
PSTATUS,
MYPET,
PARTY_REQUEST,
PARTY_SECESSION,
PARTY_LIST,
PARTY_MEMBER,
PARTY_INFO,
PARTY_CHANGE,
P_KEEP,
IN_PET,
EXTRA,
G_POS_START,
G_POS_BODY,
G_POS_END,
EVENTNOTICE,
GUILD_SAY,
GUILD_LEVEL,
GUILD_GRADE,
GUILD_NAME,
EXCH,
EXCH_ASK,
EXCH_START,
EXCH_INVEN_TO,
EXCH_INVEN_FROM,
EXCH_MONEY
}
public static String createPacket(Type packetType, Object... args) {
switch (packetType) {
case FAIL:
String message = "";
for(Object o: args){
message+=" "+o;
}
return "fail"+message;
case INFO:
String infomsg = "";
for(Object o: args){
infomsg+=" "+o;
}
return "info"+infomsg;
case OK:
return "OK";
case GO_WORLD:
if(args.length>0){
LocalMap map = (LocalMap)args[0];
int unknown = args.length>1?(Integer)args[1]:0;
InetSocketAddress address = map.getAddress();
return "go_world "+address.getAddress().getHostAddress()+" "+address.getPort()+" " + map.getId()+" "+unknown;
}
break;
case GOTO:
if(args.length>0){
Position position = (Position)args[0];
return "goto " + position.getX() + " " + position.getY() + " "+position.getZ()+" "
+ (position.getRotation()*1000)/1000;
}
break;
case EVENTNOTICE:
if(args.length>0){
String msg = "";
for(Object o: args){
msg+=" "+o;
}
return "event"+msg;
}
break;
case PARTY_DISBAND:
return "party disband";
case HOUR:
if(args.length>0){
int hour = (Integer)args[0];
return "hour " + hour;
}
break;
case IN_CHAR:
if(args.length>0){
Player player = (Player)args[0];
boolean warping = false;
if(args.length>1){
warping = (Boolean)args[1];
}
int combat = player.isInCombat() ? 1 : 0;
Equipment eq = player.getEquipment();
String packetData = warping?"appear ":"in ";
packetData += "c " + player.getEntityId() + " " + player.getName()
+ " " + player.getRace().value() + " " + player.getSex().ordinal() + " "
+ player.getHairStyle() + " " + player.getPosition().getX()
+ " " + player.getPosition().getY() + " "
+ player.getPosition().getZ() + " "
+ player.getPosition().getRotation() + " " + eq.getTypeId(Slot.HELMET) + " "
+ eq.getTypeId(Slot.CHEST) + " " + eq.getTypeId(Slot.PANTS) + " " + eq.getTypeId(Slot.SHOULDER) + " "
+ eq.getTypeId(Slot.BOOTS) + " " + eq.getTypeId(Slot.OFFHAND) + " " + eq.getTypeId(Slot.MAINHAND) + " "
+ player.getPercentageHp() + " " + combat + " 0 0 0 0 0 0";
// in char [UniqueID] [Name] [Race] [Gender] [HairStyle] [XPos]
// [YPos] [ZPos] [Rotation] [Helm] [Armor] [Pants] [ShoulderMount]
// [Boots] [Shield] [Weapon] [Hp%] [CombatMode] 0 0 0 [Boosted] [PKMode]
// 0 [Guild]
// [MemberType] 1
if(player.getGuildId() != 0)
{
String[] guildLevelText = {"","Member","","","","","","Sub-General","General","Sub-Master","Master"};
packetData += " "+player.getGuildName()+" "+guildLevelText[(int) player.getGuildLvl()]+" "+player.getGuildLvl();
}
return packetData;
}
break;
case OUT:
if(args.length>0){
WorldObject object = (WorldObject)args[0];
return "out "+getObjectType(object)+" " + object.getEntityId();
}
break;
case SAY:
if(args.length>0){
String text = (String)args[0];
Player from = null;
if(args.length>1){
from = (Player)args[1];
}
if(from==null) {
return "say "+ -1 +" "+text;
} else {
if(args.length == 2){
boolean admin = from.getAdminState() == 255;
String name = from.getName();
if(admin)
name = "<GM>"+name;
return "say "+from.getEntityId()+" "+name+" " + text + " "+(admin ? 1 : 0);
}
}
}
break;
case GUILD_SAY:
if(args.length>0){
String text = (String)args[0];
Player from = (Player)args[1];
return "say "+from.getEntityId()+" *GUILD*"+from.getName()+" "+text;
}
break;
case GUILD_NAME:
if(args.length == 1){
Player player = (Player)args[0];
return "guild_name "+player.getEntityId()+" "+player.getGuildName();
}
break;
case GUILD_GRADE:
if(args.length == 1){
String[] guildLevelText = {"","Member","","","","","","Sub-General","General","Sub-Master","Master"};
Player player = (Player)args[0];
return "guild_grade "+player.getEntityId()+" 0 "+guildLevelText[(int) player.getGuildLvl()] + " "+player.getGuildLvl();
}
break;
case GUILD_LEVEL:
if(args.length == 1){
Player player = (Player)args[0];
return "guild_level "+player.getGuildLvl();
}
break;
case WISPER:
if(args.length == 3)
{
String text = (String)args[0];
Player player = (Player)args[1];
String direction = (String)args[2];
return "say "+player.getEntityId()+" "+direction+player.getName()+" " + text + " "+((player.getAdminState() >= 200) ? 1 : 0);
}
break;
case DROP:
if(args.length>0){
RoamingItem roamingItem = (RoamingItem)args[0];
Position position = roamingItem.getPosition();
Item<?> item = roamingItem.getItem();
return "drop " + item.getEntityId() + " " + item.getType().getTypeId() + " "
+ position.getX() + " " + position.getY() + " " + position.getZ() + " "+position.getRotation()
+" " + item.getGemNumber() + " "+ item.getExtraStats()+ " " + item.getUnknown1() + " " + item.getUnknown2();
}
break;
case IN_ITEM:
if(args.length>0){
RoamingItem roamingItem = (RoamingItem)args[0];
Item<?> item = roamingItem.getItem();
Position position = roamingItem.getPosition();
return "in item " + item.getEntityId() + " " + item.getType().getTypeId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation() + " " + item.getGemNumber()
+ " " + item.getExtraStats()+ " " + item.getUnknown1() + " " + item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case IN_NPC:
if(args.length>0){
Npc<?> npc = (Npc<?>)args[0];
Boolean spawn = false;
if(args.length>1){
spawn = (Boolean)args[1];
}
int percentageHp = (int)(((double)npc.getHp()/ (double)npc.getMaxHp())* 100);
Position npcPosition = npc.getPosition();
return "in n " + npc.getEntityId() + " " + npc.getType().getTypeId()
+ " " + npcPosition.getX() + " "
+ npcPosition.getY() + " "+npcPosition.getZ()+" "
+ npcPosition.getRotation() + " "
+ percentageHp + " "
+ npc.getMutantType() + " " + npc.getUnknown1() + " "
+ npc.getType().getNeoProgmare() + " " + npc.getUnknown2() + " "+ (spawn ? 1 : 0) + " "
+ npc.getUnknown3();
}
break;
case AT:
if(args.length>0){
Player player = (Player)args[0];
return
"at " + player.getEntityId() + " "
+ player.getPosition().getX() + " " + player.getPosition().getY() + " "
+ player.getPosition().getZ() + " " + (float)player.getPosition().getRotation();
}
break;
case PLACE:
if(args.length>1){
Player player = (Player)args[0];
Position position = player.getPosition();
int unknown = (Integer)args[1];
return "p c " + player.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation() + " "
+ unknown + " " + (player.isRunning()?1:0);
}
break;
case S_CHAR:
if(args.length>0){
Player player = (Player)args[0];
Position position = player.getPosition();
return "s c " + player.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation();
}
break;
case WALK:
if(args.length>1){
LivingObject livingObject = (LivingObject)args[0];
Position position = (Position)args[1];
return "w "+getObjectType(livingObject)+" " + livingObject.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + (livingObject.isRunning()?1:0);
}
break;
case SUCCESS:
return "success";
case SOCIAL:
if(args.length>1){
Player player = (Player)args[0];
int emotionId = (Integer)args[1];
return "social char " + player.getEntityId() + " "
+ emotionId;
}
break;
case SKILLLEVEL_ALL:
if(args.length>0){
String packetData = "skilllevel_all";
Player player = (Player)args[0];
for(Skill skill: player.getSkills().keySet()) {
packetData += " " + skill.getId() + " " + player.getSkillLevel(skill);
}
return packetData;
}
break;
case A_:
if(args.length>1){
String type = (String)args[0];
Object value = args[1];
return "a_" + type + " " + value;
}
break;
case COMBAT:
if(args.length>0){
Player player = (Player)args[0];
return "combat " + player.getEntityId() + " " + (player.isInCombat()?1:0);
}
break;
case JUMP:
if(args.length>0){
Player player = (Player)args[0];
return "jump " + player.getPosition().getX() + " "
+ player.getPosition().getY() + " "
+ player.getEntityId();
}
break;
case LEVELUP:
if(args.length>0){
Player player = (Player)args[0];
return "levelup " + player.getEntityId();
}
break;
case STATUS:
if(args.length>1){
int id = (Integer)args[0];
long arg1 = (Long)args[1];
long arg2 = 0;
if(args.length > 2){
arg2 = (Long)args[2];
}
return "status " + id + " " + arg1 + " " + arg2;
}
break;
case MSG:
if(args.length>0){
String msg = (String)args[0];
return "msg "+msg;
}
break;
case EFFECT: //attack skill
if(args.length>2){
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
Skill skill = (Skill)args[2];
int unknown1 = (Integer)args[3];
int unknown2 = (Integer)args[4];
int unknown3 = (Integer)args[5];
return "effect " + skill.getId() + " "+getObjectType(source)+" "
+ source.getEntityId() + " "+getObjectType(target)+" " + target.getEntityId() + " "
+ target.getPercentageHp() + " " + source.getDmgType() + " "
+ unknown1 + " " + unknown2 + " " +unknown3;
// S> effect [SkillID] [n/c] [1STEntityId] [n/c] [2NDEntityID] [RemainingHP%] [Critical] 0 0 0
}
break;
case SECONDATTACK: //or Subattack
//sa c 547782 c 589654 0 3 0 0 40
if(args.length == 3)
{
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
int skillId = (Integer)args[2];
return "sa "+getObjectType(source)+" "+source.getEntityId()+" "+getObjectType(target)+" "
+target.getEntityId()+" "+target.getPercentageHp()+" "+source.getDmgType()+" 0 0 "+skillId;
}
break;
case SAV:
//sav n 26128 75 2 0 4900 3
if(args.length == 5)
{
LivingObject target = (LivingObject) args[0];
int damageType = (Integer)args[1];
int unknown1 = (Integer)args[2];
int itemStatusRemain = (Integer)args[3];
int unknown2 = (Integer)args[4];
return "sav "+ (target==null ? -1 : getObjectType(target)) + " "
+ (target==null ? -1 : target.getEntityId()) + " "
+ (target==null ? -1 : target.getPercentageHp()) + " "
+ damageType + " "
+ unknown1 + " "
+ itemStatusRemain + " "
+ unknown2;
}
break;
case SKILL: //self usable skill
if(args.length>1){
LivingObject source = (LivingObject) args[0];
Skill skill = (Skill)args[1];
return "skill " + ((Effectable)skill).getEffectModifier() + " char "+ source.getEntityId() + " "
+skill.getId();
// S> skill [Duration/Activated] char [CharID] [SkillID]
}
break;
case CHAR_REMOVE:
if(args.length>1){
Player player = (Player)args[0];
Slot slot = (Slot)args[1];
return "char_remove " + player.getEntityId() + " " + slot.value();
}
break;
case CHAR_WEAR:
if(args.length>1){
Player player = (Player)args[0];
Slot slot = (Slot)args[1];
Item<?> item = (Item<?>)args[2];
return "char_wear " + player.getEntityId() + " " + slot.value() + " "
+ item.getType().getTypeId() + " " + item.getGemNumber();
}
break;
case ATTACK:
if(args.length>1){
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
int isCritical = (Integer)args[2];
return "attack " + getObjectType(source) + " "
+ source.getEntityId() + " " + getObjectType(target)
+ " " + target.getEntityId() + " "
+ target.getPercentageHp() + " " + isCritical
+ " 0 0 0 0";
// S> attack c [CharEntityID] npc [NpcEntityID] [RemainHP%] [isCritical] 0 0 0 0
}
break;
case ATTACK_VITAL:
if(args.length>0){
LivingObject target = (LivingObject)args[0];
return
"attack_vital "+getObjectType(target)+" " + target.getEntityId() + " "
+ target.getPercentageHp() + " 0 0";
}
break;
case SKILLLEVEL:
if(args.length>1){
Skill skill = (Skill)args[0];
int currentSkillLevel = (Integer)args[1];
return "skilllevel " + skill.getId() + " " + currentSkillLevel;
}
break;
case PICKUP:
if(args.length>0){
Player player = (Player)args[0];
return "pickup " + player.getEntityId();
}
break;
case PICK:
if(args.length>0){
InventoryItem invItem = (InventoryItem)args[0];
Item<?> item = invItem.getItem();
return "pick " + item.getEntityId() + " " + item.getType().getTypeId() + " "
+ invItem.getPosition().getPosX()+" "+invItem.getPosition().getPosY() + " "
+ invItem.getPosition().getTab()+" " + item.getGemNumber() + " "
+ item.getExtraStats() + " " + item.getUnknown1() + " " + item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case SHOP_RATE:
if(args.length>0){
NpcShop npcShop = (NpcShop)args[0];
return "shop_rate " + npcShop.getBuyRate() + " "+ npcShop.getSellRate();
}
break;
case SHOP_ITEM:
if(args.length>0){
VendorItem vendorItem = (VendorItem)args[0];
return "shop_item " + vendorItem.getType();
}
break;
case STASH:
if(args.length>1){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash " + slot + " 0 " + (item.getGemNumber()/100) + " 0 0";
else
return "stash "
+ slot + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity + " "
+ item.getUnknown2();
}
break;
case STASH_TO:
if(args.length>1){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash_to "
+ slot + " 0 "
+ (item.getGemNumber()/100) + " 0";
else
return "stash_to "
+ slot + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity + " "
+ item.getUnknown2();
}
break;
case STASH_FROM:
if(args.length>0){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash_from "
+ slot + " 0 "
+ (item.getGemNumber()/100) + " 0";
else
return "stash_from "
+ slot + " "
+ item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity;
}
break;
case STASH_GET:
if(args.length>0){
List<int[]> itemList = (List<int[]>)args[0];
int itemTypeId = (Integer)args[1];
int inventoryTab = (Integer)args[2];
int unknown2 = (Integer)args[3];
int slot = (Integer)args[4];
int itemQuantity = (Integer)args[5];
int unknown1 = 1;
String packet = "stash_get "
+ unknown1 + " "
+ itemTypeId + " "
+ inventoryTab + " "
+ unknown2 + " "
+ slot + " "
+ itemQuantity;
for(int[] itemData : itemList){
packet += " " + itemData[0] + " "
+ itemData[1] + " "
+ itemData[2];
}
return packet;
}
break;
case STASH_PUT:
if(args.length>1){
//stash_put [?] [TypeId] [InvTab] [StashTab] [StashPos] [ItemAmmount] [InvPosX] [InvPosY]
int itemTypeId = (Integer)args[0];
int invTab = (Integer)args[1];
int stashTab = (Integer)args[2];
int stashPos = (Integer)args[3];
int itemAmmount = (Integer)args[4];
int[] itemsData = (int[])args[5];
int index = 3;
String packet = "stash_put 1 "
+ itemTypeId + " "
+ invTab + " "
+ stashTab + " "
+ stashPos + " "
+ itemAmmount;
while(index < itemsData.length){
packet += " " + itemsData[index++];
}
return packet;
}
break;
case STASH_END:
return "stash_end";
case INVEN:
if(args.length > 0){
InventoryItem invItem = (InventoryItem)args[0];
int version = (Integer)args[1];
Item<?> item = invItem.getItem();
return "inven " + invItem.getPosition().getTab() + " "
+ item.getEntityId() + " " + item.getType().getTypeId() + " " + invItem.getPosition().getPosX() + " "
+ invItem.getPosition().getPosY() + " " + item.getGemNumber() + " " + item.getExtraStats() + " "
+ item.getUnknown1() + (version >= 2000 ? " " + item.getUnknown2() + " " + item.getUnknown3() : "");
}
break;
case MULTI_SHOT: //human semi-automatic skill
if(args.length >= 1){
String source = (String) args[0]; //me or char
int numberOfShots = (Integer) args[1];
String charId = args.length == 3 ? (String) args[2]+" " : "";
return "multi_shot "+source+" " +charId+""+numberOfShots;
// S> multi_shot me [numberOfShots]
// S> multi_shot char [charID] [numberOfShots]
}
break;
case QUICK:
if(args.length > 0){
QuickSlotItem qsItem = (QuickSlotItem)args[0];
Item<?> item = qsItem.getItem();
return "quick " + qsItem.getPosition().getSlot() + " "
+ item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1();
}
break;
case UPGRADE:
if(args.length > 0){
Item<?> item = (Item<?>) args[0];
Slot slot = (Slot) args[1];
int upgraderesult = (Integer) args[2];
return "upgrade " + upgraderesult + " "
+ slot.value() + " "
+ item.getEntityId() + " "
+ item.getGemNumber();
}
break;
case KILL:
if(args.length > 0){ //Kill is used on 2007+ client
LivingObject target = (LivingObject) args[0];
return "kill " +getObjectType(target)+ " " + target.getEntityId() + "\n";
}
break;
case WEARING:
if(args.length > 0){
Equipment eq = (Equipment)args[0];
int version = (Integer)args[1];
/*
* [entity] [typeid] [gemnumber] [extrast] [unknown1] [unknown 2] [unknown 3] [cur_dur] [max_dur]
* 1524774 318 2 0 0 0 0 4449 4453
*
* wearing
* 1524774 318 2 0 0 0 0 4449 4453 [Helmet] 0
* 1524775 333 9 0 0 0 0 4322 4509 [Armor] 1
* 1524776 351 15 0 0 0 0 3778 4029 [Pants] 2
* 1524777 196 0 0 0 0 0 0 0 [Cloak] 3
* 1524778 373 3 0 0 0 0 3113 3203 [Shoes] 4
* 1524779 121 6 0 0 0 0 0 0 [Shield] 5
* 1524780 445 6 1 0 0 0 0 0 [Necklace] 6
* -1 -1 0 0 0 0 0 0 0 [Ring] 7
* 1524781 455 1 1 0 0 0 0 0 [Bracelet] 8
* -1 -1 0 0 0 0 0 0 0 [Weapon] 9
* -1 -1 0 0 0 0 0 0 0 [?] 10 PET1 ?
* -1 -1 0 0 0 0 0 0 0 [?] 11 PET2 ?
*
*/
return "wearing " + eq.getEntityId(Slot.HELMET) + " " + eq.getTypeId(Slot.HELMET) + " "
+ eq.getGemNumber(Slot.HELMET) + " " + eq.getExtraStats(Slot.HELMET) + " "
+ eq.getUnknown1(Slot.HELMET) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.HELMET) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.HELMET) + " " : "")
+ eq.getDurability(Slot.HELMET) + " " + eq.getMaxDurability(Slot.HELMET) + " "
+ eq.getEntityId(Slot.CHEST) + " " + eq.getTypeId(Slot.CHEST) + " "
+ eq.getGemNumber(Slot.CHEST) + " " + eq.getExtraStats(Slot.CHEST) + " "
+ eq.getUnknown1(Slot.CHEST) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.CHEST) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.CHEST) + " " :"")
+ eq.getDurability(Slot.CHEST) + " " + eq.getMaxDurability(Slot.CHEST) + " "
+ eq.getEntityId(Slot.PANTS) + " " + eq.getTypeId(Slot.PANTS) + " "
+ eq.getGemNumber(Slot.PANTS) + " " + eq.getExtraStats(Slot.PANTS) + " "
+ eq.getUnknown1(Slot.PANTS) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.PANTS) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.PANTS) + " " : "")
+ eq.getDurability(Slot.PANTS) + " " + eq.getMaxDurability(Slot.PANTS) + " "
+ eq.getEntityId(Slot.SHOULDER) + " " + eq.getTypeId(Slot.SHOULDER) + " "
+ eq.getGemNumber(Slot.SHOULDER) + " " + eq.getExtraStats(Slot.SHOULDER) + " "
+ eq.getUnknown1(Slot.SHOULDER) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.SHOULDER) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.SHOULDER) + " " : "")
+ eq.getDurability(Slot.SHOULDER) + " " + eq.getMaxDurability(Slot.SHOULDER) + " "
+ eq.getEntityId(Slot.BOOTS) + " " + eq.getTypeId(Slot.BOOTS)
+ " " + eq.getGemNumber(Slot.BOOTS) + " " + eq.getExtraStats(Slot.BOOTS) + " "
+ eq.getUnknown1(Slot.BOOTS) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.BOOTS) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.BOOTS) + " " : "")
+ eq.getDurability(Slot.BOOTS) + " " + eq.getMaxDurability(Slot.BOOTS) + " "
+ eq.getEntityId(Slot.OFFHAND) + " " + eq.getTypeId(Slot.OFFHAND) + " "
+ eq.getGemNumber(Slot.OFFHAND) + " " + eq.getExtraStats(Slot.OFFHAND) + " "
+ eq.getUnknown1(Slot.OFFHAND) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.OFFHAND) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.OFFHAND) + " " : "")
+ eq.getDurability(Slot.OFFHAND) + " " + eq.getMaxDurability(Slot.OFFHAND) + " "
+ eq.getEntityId(Slot.NECKLACE) + " " + eq.getTypeId(Slot.NECKLACE) + " "
+ eq.getGemNumber(Slot.NECKLACE) + " " + eq.getExtraStats(Slot.NECKLACE) + " "
+ eq.getUnknown1(Slot.NECKLACE) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.NECKLACE) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.NECKLACE) + " " : "")
+ eq.getDurability(Slot.NECKLACE) + " " + eq.getMaxDurability(Slot.NECKLACE) + " "
+ eq.getEntityId(Slot.RING) + " " + eq.getTypeId(Slot.RING) + " "
+ eq.getGemNumber(Slot.RING) + " " + eq.getExtraStats(Slot.RING) + " "
+ eq.getUnknown1(Slot.RING) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.RING) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.RING) + " " : "")
+ eq.getDurability(Slot.RING) + " " + eq.getMaxDurability(Slot.RING) + " "
+ eq.getEntityId(Slot.BRACELET) + " " + eq.getTypeId(Slot.BRACELET) + " "
+ eq.getGemNumber(Slot.BRACELET) + " " + eq.getExtraStats(Slot.BRACELET) + " "
+ eq.getUnknown1(Slot.BRACELET) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.BRACELET) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.BRACELET) + " " : "")
+ eq.getDurability(Slot.BRACELET) + " " + eq.getMaxDurability(Slot.BRACELET) + " "
+ eq.getEntityId(Slot.MAINHAND) + " " + eq.getTypeId(Slot.MAINHAND) + " "
+ eq.getGemNumber(Slot.MAINHAND) + " " + eq.getExtraStats(Slot.MAINHAND) + " "
+ eq.getUnknown1(Slot.MAINHAND) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.MAINHAND) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.MAINHAND) + " " : "")
+ eq.getDurability(Slot.MAINHAND) + " " + eq.getMaxDurability(Slot.MAINHAND)
+ " -1 -1 0 0 0 0 0 0 0"
+ " -1 -1 0 0 0 0 0 0 0";
}
break;
case QT:
if(args.length > 0){
String packetData = (String) args[0];
return "qt " + packetData + "\n";
}
break;
case Q_EX:
if(args.length > 0){
Integer limeAmmount = (Integer) args[0];
return "q_ex " + limeAmmount + "\n";
}
break;
case K:
if(args.length > 0){
int isActivated = (Integer) args[0];
LivingObject livingObject = (LivingObject) args[1];
int typeId = (Integer) args[2];
return "k "+isActivated+" "+getObjectType(livingObject)+" "+livingObject.getEntityId()+" "+typeId;
}
break;
case ICHANGE:
if(args.length > 0){
Item<?> oldItem = (Item<?>) args[0];
Item<?> newItem = (Item<?>) args[1];
if(oldItem == null || newItem == null)
return "ichange 0 0 0 0 0 0 0 0";
else {
return "ichange "
+ oldItem.getEntityId() + " "
+ newItem.getEntityId() + " "
+ newItem.getType().getTypeId() + " "
+ newItem.getGemNumber() + " "
+ newItem.getExtraStats() + " 0 0 0";
}
}
break;
case CHIP_EXCHANGE:
if(args.length > 0){
int gemTraderType = (Integer) args[0];
String betResult = (String) args[1];
Item<?> item = (Item<?>) args[2];
String serverBet = ((String) args[3]);
if(item == null)
return "chip_exchange "+gemTraderType+" ok "+betResult+"-1 "+serverBet;
else
return "chip_exchange "+gemTraderType+" ok "+betResult+""
+item.getType().getTypeId()+" "+serverBet+""+item.getEntityId();
}
break;
case SKY:
if(args.length == 2){
Player player = (Player) args[0];
int state = (Integer) args[1];
return "sky "+player.getEntityId()+" "+state;
}
break;
case UPDATE_ITEM:
if(args.length > 0){
Item<?> item = (Item<?>) args[0];
int upgraderesult = (Integer) args[1];
return "update_item " + item.getEntityId() +" "+ upgraderesult + " "
+ item.getGemNumber() + " "
+ item.getExtraStats();
}
break;
case USQ:
if(args.length > 0){
String type = (String) args[0];
int quickSlotPosition = (Integer) args[1];
int equipmentPosition = (Integer) args[2];
Item<?> item = (Item<?>) args[3];
int equipmentGemNumber = item.getGemNumber();
int equipmentExtraStatus = item.getExtraStats();
return "usq " + type + " " + quickSlotPosition +" "
+ equipmentPosition + " "
+ equipmentGemNumber + " "
+ equipmentExtraStatus;
}
break;
case UQ_ITEM:
if(args.length > 0){
int updateResult = (Integer) args[0]; //need confirmation about this
int quickSlotPosition = (Integer) args[1];
int itemEntityId = (Integer) args[2];
String serverPacket = "uq_item " + updateResult + " " + quickSlotPosition
+ " " + itemEntityId;
if (args.length == 4) {
int unknown = (Integer) args[3];
serverPacket += " " + unknown;
}
if (args.length == 6) {
int gemNumber = (Integer) args[3];
int extraStats = (Integer) args[4];
int unknown = (Integer) args[5];
serverPacket += " " + gemNumber + " " + extraStats + " " + unknown;
}
return serverPacket;
}
break;
case MT_ITEM:
if(args.length > 0){
int updateResult = (Integer) args[0];
int quickSlotPosition = (Integer) args[1];
int itemEntityId = (Integer) args[2];
int unknown = (Integer) args[2];
return "mt_item " + updateResult + " " + quickSlotPosition + " "
+ itemEntityId + " " + unknown;
}
break;
case AV:
if(args.length > 0){
LivingObject victim = (LivingObject) args[0];
int damageType = (Integer) args[1];
return "av " + getObjectType(victim) + " " + victim.getEntityId() + " "
+ victim.getPercentageHp() + " " + damageType + " 0";
}
break;
case PARTY_REQUEST:
if(args.length > 0){
Party party = (Party)args[0];
Player leader = party.getLeader();
String packet = "party request 0 "+leader.getEntityId()+" "+leader.getName();
for(Player member : party.getMembers()){
packet += " "+member.getEntityId()+" "+member.getName();
}
return packet += " "+party.getExpOption()+" "+party.getItemOption();
}
break;
case PARTY_SECESSION:
if(args.length > 0){
int entityId = (Integer)args[0];
return "party secession "+ entityId;
}
break;
case PARTY_LIST:
if(args.length > 0){
int membersAmmount = (Integer)args[0];
return "party list "+ membersAmmount;
}
break;
case PARTY_MEMBER:
if(args.length > 0){
Player member = (Player)args[0];
return "party member "+ member.getEntityId()+" "+member.getName();
}
break;
case PARTY_INFO:
if(args.length > 0){
Player member = (Player)args[0];
return "party info "+ member.getEntityId()+" "+member.getHp()+" "+member.getMaxHp();
}
break;
case PARTY_CHANGE:
if(args.length > 0){
int optionPosition = (Integer)args[0];
int optionValue = (Integer)args[1];
return "party change "+optionPosition+" "+optionValue;
}
break;
case PSTATUS:
if(args.length>1){
int id = (Integer)args[0];
long arg1 = (Long)args[1];
long arg2 = (Long)args[2];
int arg3 = (Integer)args[3];
return "pstatus " + id + " " + arg1 + " " + arg2 + " " + arg3;
}
break;
case MYPET:
if(args.length == 1){
if(((String)args[0]).equals("del")){
return "mypet del";
}
} else if(args.length == 2){
Player player = (Player)args[0];
Pet pet = (Pet)args[1];
PetEquipment equipment = pet.getEquipment();
return "mypet "
+ pet.getEntityId() + " "
+ pet.getName() + " "
+ (player.getClient().getVersion()>=2000 ? "0 " : "")
+ pet.getPosition().getX() + " "
+ pet.getPosition().getY() + " "
+ (pet.getPosition().getRotation()*1000)/1000 + " "
+ equipment.getTypeId(PetSlot.HORN) + " "
+ equipment.getTypeId(PetSlot.HEAD) + " "
+ equipment.getTypeId(PetSlot.BODY) + " "
+ equipment.getTypeId(PetSlot.WING) + " "
+ equipment.getTypeId(PetSlot.FOOT) + " "
+ equipment.getTypeId(PetSlot.TAIL) + " "
+ pet.getHp() + " "
+ pet.getMaxHp();
}
break;
case P_KEEP:
if(args.length == 2){
String pKeepType = (String)args[0];
Pet pet = (Pet)args[1];
if(pKeepType.equals("fail")){
int timeRemain = pet.getBreederTimer() + 60; //we add 60 to have the correct minutes value
return "p_keep fail " + timeRemain;
} else if(pKeepType.equals("info")){
//p_keep info [PetName] [isStored] [Level] [Stamina] [Loyalty] [Satiety] [LimeCharge] [TimeLeft(seconds)]
return "p_keep info " + pet.getName() + " "
+ (pet.getState() == 2 ? 1 : 0) + " "
+ pet.getLevel() + " "
+ pet.getMaxHp() + " "
+ pet.getLoyalty() + " "
+ pet.getSatiety() + " "
+ (pet.getState() == 2 ? 15000 : 0) +" 0";
}
}
break;
case IN_PET:
if(args.length>0){
Player player = (Player)args[0];
boolean warping = (Boolean)args[1];
Pet pet = player.getPet();
PetEquipment equipment = pet.getEquipment();
return (warping ? "ap " : "in ")
+"p " + pet.getEntityId() + " "
+ pet.getName() + " "
+ (player.getClient().getVersion()>=2000 ? "0 " : "")
+ pet.getPosition().getX() + " "
+ pet.getPosition().getY() + " "
+ pet.getPosition().getRotation() + " "
+ equipment.getTypeId(PetSlot.HORN) + " "
+ equipment.getTypeId(PetSlot.HEAD) + " "
+ equipment.getTypeId(PetSlot.BODY) + " "
+ equipment.getTypeId(PetSlot.WING) + " "
+ equipment.getTypeId(PetSlot.FOOT) + " "
+ equipment.getTypeId(PetSlot.TAIL) + " 100 14 "
+ player.getName() + " " +
+ player.isMeta();
//in p [PetEntityId] [PetName] 0 [PetPosX] [PetPosY] [PetRotation]
//[PetHornType] [PetHeadType] [PetBodyType] [PetWingType] [PetFootType] [PetTailType]
//100 14 [PlayerName] 0
}
break;
case EXTRA:
if(args.length==1){
Item<?> item = (Item<?>)args[0];
return "extra " + item.getEntityId() + " " + item.getType().getTypeId() + " " + item.getGemNumber() + " "
+ item.getExtraStats() + " " + item.getUnknown1() + " " + item.getUnknown2() + " "
+ item.getUnknown3();
}
break;
case G_POS_START:
if(args.length == 0){
return "g_pos start";
}
break;
case G_POS_BODY:
if(args.length == 1){
Player player = (Player)args[0];
return "g_pos body "+player.getEntityId()+" "+player.getName()+" "+player.getPosition().getX()+" "+player.getPosition().getY();
}
break;
case G_POS_END:
if(args.length == 0){
return "g_pos end";
}
break;
case EXCH:
if(args.length==1){
String exchType = (String)args[0]; /* TYPES:
* cancel
* trade
* disable
*/
return "exch " + exchType;
}
break;
case EXCH_ASK:
if(args.length==1){
Player source = (Player)args[0];
return "exch_ask "+source.getName();
}
break;
case EXCH_START:
if(args.length==1){
Player player = (Player)args[0];
return "exch_start "+player.getName()+" "+player.getLevel();
}
break;
case EXCH_INVEN_TO:
if(args.length==1){
ExchangeItem exchangeItem = (ExchangeItem)args[0];
Item<?> item = exchangeItem.getItem();
return "exch_inven_to " + item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ exchangeItem.getPosition().getPosX() + " "
+ exchangeItem.getPosition().getPosY() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats()+ " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case EXCH_INVEN_FROM:
if(args.length==1){
ExchangeItem exchangeItem = (ExchangeItem)args[0];
return "exch_inven_from " + exchangeItem.getPosition().getPosX() + " "
+ exchangeItem.getPosition().getPosY();
}
break;
case EXCH_MONEY:
if(args.length==1){
- long money = (long)args[0];
+ long money = (Long)args[0];
return "exch_money "+money;
}
break;
default:
throw new UnsupportedOperationException();
}
throw new RuntimeException("Invalid parameters for "+packetType+" message");
}
private static String getObjectType(WorldObject object){
if (object instanceof Player){
return "c";
}
else if(object instanceof RoamingItem){
return "i";
}
else if (object instanceof Npc) {
return "n";
}
else if (object instanceof Pet) {
return "p";
}
throw new RuntimeException("Invalid Object: "+object);
}
public PacketFactory() {
super();
}
}
| true | true | public static String createPacket(Type packetType, Object... args) {
switch (packetType) {
case FAIL:
String message = "";
for(Object o: args){
message+=" "+o;
}
return "fail"+message;
case INFO:
String infomsg = "";
for(Object o: args){
infomsg+=" "+o;
}
return "info"+infomsg;
case OK:
return "OK";
case GO_WORLD:
if(args.length>0){
LocalMap map = (LocalMap)args[0];
int unknown = args.length>1?(Integer)args[1]:0;
InetSocketAddress address = map.getAddress();
return "go_world "+address.getAddress().getHostAddress()+" "+address.getPort()+" " + map.getId()+" "+unknown;
}
break;
case GOTO:
if(args.length>0){
Position position = (Position)args[0];
return "goto " + position.getX() + " " + position.getY() + " "+position.getZ()+" "
+ (position.getRotation()*1000)/1000;
}
break;
case EVENTNOTICE:
if(args.length>0){
String msg = "";
for(Object o: args){
msg+=" "+o;
}
return "event"+msg;
}
break;
case PARTY_DISBAND:
return "party disband";
case HOUR:
if(args.length>0){
int hour = (Integer)args[0];
return "hour " + hour;
}
break;
case IN_CHAR:
if(args.length>0){
Player player = (Player)args[0];
boolean warping = false;
if(args.length>1){
warping = (Boolean)args[1];
}
int combat = player.isInCombat() ? 1 : 0;
Equipment eq = player.getEquipment();
String packetData = warping?"appear ":"in ";
packetData += "c " + player.getEntityId() + " " + player.getName()
+ " " + player.getRace().value() + " " + player.getSex().ordinal() + " "
+ player.getHairStyle() + " " + player.getPosition().getX()
+ " " + player.getPosition().getY() + " "
+ player.getPosition().getZ() + " "
+ player.getPosition().getRotation() + " " + eq.getTypeId(Slot.HELMET) + " "
+ eq.getTypeId(Slot.CHEST) + " " + eq.getTypeId(Slot.PANTS) + " " + eq.getTypeId(Slot.SHOULDER) + " "
+ eq.getTypeId(Slot.BOOTS) + " " + eq.getTypeId(Slot.OFFHAND) + " " + eq.getTypeId(Slot.MAINHAND) + " "
+ player.getPercentageHp() + " " + combat + " 0 0 0 0 0 0";
// in char [UniqueID] [Name] [Race] [Gender] [HairStyle] [XPos]
// [YPos] [ZPos] [Rotation] [Helm] [Armor] [Pants] [ShoulderMount]
// [Boots] [Shield] [Weapon] [Hp%] [CombatMode] 0 0 0 [Boosted] [PKMode]
// 0 [Guild]
// [MemberType] 1
if(player.getGuildId() != 0)
{
String[] guildLevelText = {"","Member","","","","","","Sub-General","General","Sub-Master","Master"};
packetData += " "+player.getGuildName()+" "+guildLevelText[(int) player.getGuildLvl()]+" "+player.getGuildLvl();
}
return packetData;
}
break;
case OUT:
if(args.length>0){
WorldObject object = (WorldObject)args[0];
return "out "+getObjectType(object)+" " + object.getEntityId();
}
break;
case SAY:
if(args.length>0){
String text = (String)args[0];
Player from = null;
if(args.length>1){
from = (Player)args[1];
}
if(from==null) {
return "say "+ -1 +" "+text;
} else {
if(args.length == 2){
boolean admin = from.getAdminState() == 255;
String name = from.getName();
if(admin)
name = "<GM>"+name;
return "say "+from.getEntityId()+" "+name+" " + text + " "+(admin ? 1 : 0);
}
}
}
break;
case GUILD_SAY:
if(args.length>0){
String text = (String)args[0];
Player from = (Player)args[1];
return "say "+from.getEntityId()+" *GUILD*"+from.getName()+" "+text;
}
break;
case GUILD_NAME:
if(args.length == 1){
Player player = (Player)args[0];
return "guild_name "+player.getEntityId()+" "+player.getGuildName();
}
break;
case GUILD_GRADE:
if(args.length == 1){
String[] guildLevelText = {"","Member","","","","","","Sub-General","General","Sub-Master","Master"};
Player player = (Player)args[0];
return "guild_grade "+player.getEntityId()+" 0 "+guildLevelText[(int) player.getGuildLvl()] + " "+player.getGuildLvl();
}
break;
case GUILD_LEVEL:
if(args.length == 1){
Player player = (Player)args[0];
return "guild_level "+player.getGuildLvl();
}
break;
case WISPER:
if(args.length == 3)
{
String text = (String)args[0];
Player player = (Player)args[1];
String direction = (String)args[2];
return "say "+player.getEntityId()+" "+direction+player.getName()+" " + text + " "+((player.getAdminState() >= 200) ? 1 : 0);
}
break;
case DROP:
if(args.length>0){
RoamingItem roamingItem = (RoamingItem)args[0];
Position position = roamingItem.getPosition();
Item<?> item = roamingItem.getItem();
return "drop " + item.getEntityId() + " " + item.getType().getTypeId() + " "
+ position.getX() + " " + position.getY() + " " + position.getZ() + " "+position.getRotation()
+" " + item.getGemNumber() + " "+ item.getExtraStats()+ " " + item.getUnknown1() + " " + item.getUnknown2();
}
break;
case IN_ITEM:
if(args.length>0){
RoamingItem roamingItem = (RoamingItem)args[0];
Item<?> item = roamingItem.getItem();
Position position = roamingItem.getPosition();
return "in item " + item.getEntityId() + " " + item.getType().getTypeId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation() + " " + item.getGemNumber()
+ " " + item.getExtraStats()+ " " + item.getUnknown1() + " " + item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case IN_NPC:
if(args.length>0){
Npc<?> npc = (Npc<?>)args[0];
Boolean spawn = false;
if(args.length>1){
spawn = (Boolean)args[1];
}
int percentageHp = (int)(((double)npc.getHp()/ (double)npc.getMaxHp())* 100);
Position npcPosition = npc.getPosition();
return "in n " + npc.getEntityId() + " " + npc.getType().getTypeId()
+ " " + npcPosition.getX() + " "
+ npcPosition.getY() + " "+npcPosition.getZ()+" "
+ npcPosition.getRotation() + " "
+ percentageHp + " "
+ npc.getMutantType() + " " + npc.getUnknown1() + " "
+ npc.getType().getNeoProgmare() + " " + npc.getUnknown2() + " "+ (spawn ? 1 : 0) + " "
+ npc.getUnknown3();
}
break;
case AT:
if(args.length>0){
Player player = (Player)args[0];
return
"at " + player.getEntityId() + " "
+ player.getPosition().getX() + " " + player.getPosition().getY() + " "
+ player.getPosition().getZ() + " " + (float)player.getPosition().getRotation();
}
break;
case PLACE:
if(args.length>1){
Player player = (Player)args[0];
Position position = player.getPosition();
int unknown = (Integer)args[1];
return "p c " + player.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation() + " "
+ unknown + " " + (player.isRunning()?1:0);
}
break;
case S_CHAR:
if(args.length>0){
Player player = (Player)args[0];
Position position = player.getPosition();
return "s c " + player.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation();
}
break;
case WALK:
if(args.length>1){
LivingObject livingObject = (LivingObject)args[0];
Position position = (Position)args[1];
return "w "+getObjectType(livingObject)+" " + livingObject.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + (livingObject.isRunning()?1:0);
}
break;
case SUCCESS:
return "success";
case SOCIAL:
if(args.length>1){
Player player = (Player)args[0];
int emotionId = (Integer)args[1];
return "social char " + player.getEntityId() + " "
+ emotionId;
}
break;
case SKILLLEVEL_ALL:
if(args.length>0){
String packetData = "skilllevel_all";
Player player = (Player)args[0];
for(Skill skill: player.getSkills().keySet()) {
packetData += " " + skill.getId() + " " + player.getSkillLevel(skill);
}
return packetData;
}
break;
case A_:
if(args.length>1){
String type = (String)args[0];
Object value = args[1];
return "a_" + type + " " + value;
}
break;
case COMBAT:
if(args.length>0){
Player player = (Player)args[0];
return "combat " + player.getEntityId() + " " + (player.isInCombat()?1:0);
}
break;
case JUMP:
if(args.length>0){
Player player = (Player)args[0];
return "jump " + player.getPosition().getX() + " "
+ player.getPosition().getY() + " "
+ player.getEntityId();
}
break;
case LEVELUP:
if(args.length>0){
Player player = (Player)args[0];
return "levelup " + player.getEntityId();
}
break;
case STATUS:
if(args.length>1){
int id = (Integer)args[0];
long arg1 = (Long)args[1];
long arg2 = 0;
if(args.length > 2){
arg2 = (Long)args[2];
}
return "status " + id + " " + arg1 + " " + arg2;
}
break;
case MSG:
if(args.length>0){
String msg = (String)args[0];
return "msg "+msg;
}
break;
case EFFECT: //attack skill
if(args.length>2){
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
Skill skill = (Skill)args[2];
int unknown1 = (Integer)args[3];
int unknown2 = (Integer)args[4];
int unknown3 = (Integer)args[5];
return "effect " + skill.getId() + " "+getObjectType(source)+" "
+ source.getEntityId() + " "+getObjectType(target)+" " + target.getEntityId() + " "
+ target.getPercentageHp() + " " + source.getDmgType() + " "
+ unknown1 + " " + unknown2 + " " +unknown3;
// S> effect [SkillID] [n/c] [1STEntityId] [n/c] [2NDEntityID] [RemainingHP%] [Critical] 0 0 0
}
break;
case SECONDATTACK: //or Subattack
//sa c 547782 c 589654 0 3 0 0 40
if(args.length == 3)
{
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
int skillId = (Integer)args[2];
return "sa "+getObjectType(source)+" "+source.getEntityId()+" "+getObjectType(target)+" "
+target.getEntityId()+" "+target.getPercentageHp()+" "+source.getDmgType()+" 0 0 "+skillId;
}
break;
case SAV:
//sav n 26128 75 2 0 4900 3
if(args.length == 5)
{
LivingObject target = (LivingObject) args[0];
int damageType = (Integer)args[1];
int unknown1 = (Integer)args[2];
int itemStatusRemain = (Integer)args[3];
int unknown2 = (Integer)args[4];
return "sav "+ (target==null ? -1 : getObjectType(target)) + " "
+ (target==null ? -1 : target.getEntityId()) + " "
+ (target==null ? -1 : target.getPercentageHp()) + " "
+ damageType + " "
+ unknown1 + " "
+ itemStatusRemain + " "
+ unknown2;
}
break;
case SKILL: //self usable skill
if(args.length>1){
LivingObject source = (LivingObject) args[0];
Skill skill = (Skill)args[1];
return "skill " + ((Effectable)skill).getEffectModifier() + " char "+ source.getEntityId() + " "
+skill.getId();
// S> skill [Duration/Activated] char [CharID] [SkillID]
}
break;
case CHAR_REMOVE:
if(args.length>1){
Player player = (Player)args[0];
Slot slot = (Slot)args[1];
return "char_remove " + player.getEntityId() + " " + slot.value();
}
break;
case CHAR_WEAR:
if(args.length>1){
Player player = (Player)args[0];
Slot slot = (Slot)args[1];
Item<?> item = (Item<?>)args[2];
return "char_wear " + player.getEntityId() + " " + slot.value() + " "
+ item.getType().getTypeId() + " " + item.getGemNumber();
}
break;
case ATTACK:
if(args.length>1){
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
int isCritical = (Integer)args[2];
return "attack " + getObjectType(source) + " "
+ source.getEntityId() + " " + getObjectType(target)
+ " " + target.getEntityId() + " "
+ target.getPercentageHp() + " " + isCritical
+ " 0 0 0 0";
// S> attack c [CharEntityID] npc [NpcEntityID] [RemainHP%] [isCritical] 0 0 0 0
}
break;
case ATTACK_VITAL:
if(args.length>0){
LivingObject target = (LivingObject)args[0];
return
"attack_vital "+getObjectType(target)+" " + target.getEntityId() + " "
+ target.getPercentageHp() + " 0 0";
}
break;
case SKILLLEVEL:
if(args.length>1){
Skill skill = (Skill)args[0];
int currentSkillLevel = (Integer)args[1];
return "skilllevel " + skill.getId() + " " + currentSkillLevel;
}
break;
case PICKUP:
if(args.length>0){
Player player = (Player)args[0];
return "pickup " + player.getEntityId();
}
break;
case PICK:
if(args.length>0){
InventoryItem invItem = (InventoryItem)args[0];
Item<?> item = invItem.getItem();
return "pick " + item.getEntityId() + " " + item.getType().getTypeId() + " "
+ invItem.getPosition().getPosX()+" "+invItem.getPosition().getPosY() + " "
+ invItem.getPosition().getTab()+" " + item.getGemNumber() + " "
+ item.getExtraStats() + " " + item.getUnknown1() + " " + item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case SHOP_RATE:
if(args.length>0){
NpcShop npcShop = (NpcShop)args[0];
return "shop_rate " + npcShop.getBuyRate() + " "+ npcShop.getSellRate();
}
break;
case SHOP_ITEM:
if(args.length>0){
VendorItem vendorItem = (VendorItem)args[0];
return "shop_item " + vendorItem.getType();
}
break;
case STASH:
if(args.length>1){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash " + slot + " 0 " + (item.getGemNumber()/100) + " 0 0";
else
return "stash "
+ slot + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity + " "
+ item.getUnknown2();
}
break;
case STASH_TO:
if(args.length>1){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash_to "
+ slot + " 0 "
+ (item.getGemNumber()/100) + " 0";
else
return "stash_to "
+ slot + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity + " "
+ item.getUnknown2();
}
break;
case STASH_FROM:
if(args.length>0){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash_from "
+ slot + " 0 "
+ (item.getGemNumber()/100) + " 0";
else
return "stash_from "
+ slot + " "
+ item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity;
}
break;
case STASH_GET:
if(args.length>0){
List<int[]> itemList = (List<int[]>)args[0];
int itemTypeId = (Integer)args[1];
int inventoryTab = (Integer)args[2];
int unknown2 = (Integer)args[3];
int slot = (Integer)args[4];
int itemQuantity = (Integer)args[5];
int unknown1 = 1;
String packet = "stash_get "
+ unknown1 + " "
+ itemTypeId + " "
+ inventoryTab + " "
+ unknown2 + " "
+ slot + " "
+ itemQuantity;
for(int[] itemData : itemList){
packet += " " + itemData[0] + " "
+ itemData[1] + " "
+ itemData[2];
}
return packet;
}
break;
case STASH_PUT:
if(args.length>1){
//stash_put [?] [TypeId] [InvTab] [StashTab] [StashPos] [ItemAmmount] [InvPosX] [InvPosY]
int itemTypeId = (Integer)args[0];
int invTab = (Integer)args[1];
int stashTab = (Integer)args[2];
int stashPos = (Integer)args[3];
int itemAmmount = (Integer)args[4];
int[] itemsData = (int[])args[5];
int index = 3;
String packet = "stash_put 1 "
+ itemTypeId + " "
+ invTab + " "
+ stashTab + " "
+ stashPos + " "
+ itemAmmount;
while(index < itemsData.length){
packet += " " + itemsData[index++];
}
return packet;
}
break;
case STASH_END:
return "stash_end";
case INVEN:
if(args.length > 0){
InventoryItem invItem = (InventoryItem)args[0];
int version = (Integer)args[1];
Item<?> item = invItem.getItem();
return "inven " + invItem.getPosition().getTab() + " "
+ item.getEntityId() + " " + item.getType().getTypeId() + " " + invItem.getPosition().getPosX() + " "
+ invItem.getPosition().getPosY() + " " + item.getGemNumber() + " " + item.getExtraStats() + " "
+ item.getUnknown1() + (version >= 2000 ? " " + item.getUnknown2() + " " + item.getUnknown3() : "");
}
break;
case MULTI_SHOT: //human semi-automatic skill
if(args.length >= 1){
String source = (String) args[0]; //me or char
int numberOfShots = (Integer) args[1];
String charId = args.length == 3 ? (String) args[2]+" " : "";
return "multi_shot "+source+" " +charId+""+numberOfShots;
// S> multi_shot me [numberOfShots]
// S> multi_shot char [charID] [numberOfShots]
}
break;
case QUICK:
if(args.length > 0){
QuickSlotItem qsItem = (QuickSlotItem)args[0];
Item<?> item = qsItem.getItem();
return "quick " + qsItem.getPosition().getSlot() + " "
+ item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1();
}
break;
case UPGRADE:
if(args.length > 0){
Item<?> item = (Item<?>) args[0];
Slot slot = (Slot) args[1];
int upgraderesult = (Integer) args[2];
return "upgrade " + upgraderesult + " "
+ slot.value() + " "
+ item.getEntityId() + " "
+ item.getGemNumber();
}
break;
case KILL:
if(args.length > 0){ //Kill is used on 2007+ client
LivingObject target = (LivingObject) args[0];
return "kill " +getObjectType(target)+ " " + target.getEntityId() + "\n";
}
break;
case WEARING:
if(args.length > 0){
Equipment eq = (Equipment)args[0];
int version = (Integer)args[1];
/*
* [entity] [typeid] [gemnumber] [extrast] [unknown1] [unknown 2] [unknown 3] [cur_dur] [max_dur]
* 1524774 318 2 0 0 0 0 4449 4453
*
* wearing
* 1524774 318 2 0 0 0 0 4449 4453 [Helmet] 0
* 1524775 333 9 0 0 0 0 4322 4509 [Armor] 1
* 1524776 351 15 0 0 0 0 3778 4029 [Pants] 2
* 1524777 196 0 0 0 0 0 0 0 [Cloak] 3
* 1524778 373 3 0 0 0 0 3113 3203 [Shoes] 4
* 1524779 121 6 0 0 0 0 0 0 [Shield] 5
* 1524780 445 6 1 0 0 0 0 0 [Necklace] 6
* -1 -1 0 0 0 0 0 0 0 [Ring] 7
* 1524781 455 1 1 0 0 0 0 0 [Bracelet] 8
* -1 -1 0 0 0 0 0 0 0 [Weapon] 9
* -1 -1 0 0 0 0 0 0 0 [?] 10 PET1 ?
* -1 -1 0 0 0 0 0 0 0 [?] 11 PET2 ?
*
*/
return "wearing " + eq.getEntityId(Slot.HELMET) + " " + eq.getTypeId(Slot.HELMET) + " "
+ eq.getGemNumber(Slot.HELMET) + " " + eq.getExtraStats(Slot.HELMET) + " "
+ eq.getUnknown1(Slot.HELMET) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.HELMET) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.HELMET) + " " : "")
+ eq.getDurability(Slot.HELMET) + " " + eq.getMaxDurability(Slot.HELMET) + " "
+ eq.getEntityId(Slot.CHEST) + " " + eq.getTypeId(Slot.CHEST) + " "
+ eq.getGemNumber(Slot.CHEST) + " " + eq.getExtraStats(Slot.CHEST) + " "
+ eq.getUnknown1(Slot.CHEST) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.CHEST) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.CHEST) + " " :"")
+ eq.getDurability(Slot.CHEST) + " " + eq.getMaxDurability(Slot.CHEST) + " "
+ eq.getEntityId(Slot.PANTS) + " " + eq.getTypeId(Slot.PANTS) + " "
+ eq.getGemNumber(Slot.PANTS) + " " + eq.getExtraStats(Slot.PANTS) + " "
+ eq.getUnknown1(Slot.PANTS) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.PANTS) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.PANTS) + " " : "")
+ eq.getDurability(Slot.PANTS) + " " + eq.getMaxDurability(Slot.PANTS) + " "
+ eq.getEntityId(Slot.SHOULDER) + " " + eq.getTypeId(Slot.SHOULDER) + " "
+ eq.getGemNumber(Slot.SHOULDER) + " " + eq.getExtraStats(Slot.SHOULDER) + " "
+ eq.getUnknown1(Slot.SHOULDER) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.SHOULDER) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.SHOULDER) + " " : "")
+ eq.getDurability(Slot.SHOULDER) + " " + eq.getMaxDurability(Slot.SHOULDER) + " "
+ eq.getEntityId(Slot.BOOTS) + " " + eq.getTypeId(Slot.BOOTS)
+ " " + eq.getGemNumber(Slot.BOOTS) + " " + eq.getExtraStats(Slot.BOOTS) + " "
+ eq.getUnknown1(Slot.BOOTS) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.BOOTS) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.BOOTS) + " " : "")
+ eq.getDurability(Slot.BOOTS) + " " + eq.getMaxDurability(Slot.BOOTS) + " "
+ eq.getEntityId(Slot.OFFHAND) + " " + eq.getTypeId(Slot.OFFHAND) + " "
+ eq.getGemNumber(Slot.OFFHAND) + " " + eq.getExtraStats(Slot.OFFHAND) + " "
+ eq.getUnknown1(Slot.OFFHAND) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.OFFHAND) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.OFFHAND) + " " : "")
+ eq.getDurability(Slot.OFFHAND) + " " + eq.getMaxDurability(Slot.OFFHAND) + " "
+ eq.getEntityId(Slot.NECKLACE) + " " + eq.getTypeId(Slot.NECKLACE) + " "
+ eq.getGemNumber(Slot.NECKLACE) + " " + eq.getExtraStats(Slot.NECKLACE) + " "
+ eq.getUnknown1(Slot.NECKLACE) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.NECKLACE) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.NECKLACE) + " " : "")
+ eq.getDurability(Slot.NECKLACE) + " " + eq.getMaxDurability(Slot.NECKLACE) + " "
+ eq.getEntityId(Slot.RING) + " " + eq.getTypeId(Slot.RING) + " "
+ eq.getGemNumber(Slot.RING) + " " + eq.getExtraStats(Slot.RING) + " "
+ eq.getUnknown1(Slot.RING) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.RING) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.RING) + " " : "")
+ eq.getDurability(Slot.RING) + " " + eq.getMaxDurability(Slot.RING) + " "
+ eq.getEntityId(Slot.BRACELET) + " " + eq.getTypeId(Slot.BRACELET) + " "
+ eq.getGemNumber(Slot.BRACELET) + " " + eq.getExtraStats(Slot.BRACELET) + " "
+ eq.getUnknown1(Slot.BRACELET) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.BRACELET) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.BRACELET) + " " : "")
+ eq.getDurability(Slot.BRACELET) + " " + eq.getMaxDurability(Slot.BRACELET) + " "
+ eq.getEntityId(Slot.MAINHAND) + " " + eq.getTypeId(Slot.MAINHAND) + " "
+ eq.getGemNumber(Slot.MAINHAND) + " " + eq.getExtraStats(Slot.MAINHAND) + " "
+ eq.getUnknown1(Slot.MAINHAND) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.MAINHAND) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.MAINHAND) + " " : "")
+ eq.getDurability(Slot.MAINHAND) + " " + eq.getMaxDurability(Slot.MAINHAND)
+ " -1 -1 0 0 0 0 0 0 0"
+ " -1 -1 0 0 0 0 0 0 0";
}
break;
case QT:
if(args.length > 0){
String packetData = (String) args[0];
return "qt " + packetData + "\n";
}
break;
case Q_EX:
if(args.length > 0){
Integer limeAmmount = (Integer) args[0];
return "q_ex " + limeAmmount + "\n";
}
break;
case K:
if(args.length > 0){
int isActivated = (Integer) args[0];
LivingObject livingObject = (LivingObject) args[1];
int typeId = (Integer) args[2];
return "k "+isActivated+" "+getObjectType(livingObject)+" "+livingObject.getEntityId()+" "+typeId;
}
break;
case ICHANGE:
if(args.length > 0){
Item<?> oldItem = (Item<?>) args[0];
Item<?> newItem = (Item<?>) args[1];
if(oldItem == null || newItem == null)
return "ichange 0 0 0 0 0 0 0 0";
else {
return "ichange "
+ oldItem.getEntityId() + " "
+ newItem.getEntityId() + " "
+ newItem.getType().getTypeId() + " "
+ newItem.getGemNumber() + " "
+ newItem.getExtraStats() + " 0 0 0";
}
}
break;
case CHIP_EXCHANGE:
if(args.length > 0){
int gemTraderType = (Integer) args[0];
String betResult = (String) args[1];
Item<?> item = (Item<?>) args[2];
String serverBet = ((String) args[3]);
if(item == null)
return "chip_exchange "+gemTraderType+" ok "+betResult+"-1 "+serverBet;
else
return "chip_exchange "+gemTraderType+" ok "+betResult+""
+item.getType().getTypeId()+" "+serverBet+""+item.getEntityId();
}
break;
case SKY:
if(args.length == 2){
Player player = (Player) args[0];
int state = (Integer) args[1];
return "sky "+player.getEntityId()+" "+state;
}
break;
case UPDATE_ITEM:
if(args.length > 0){
Item<?> item = (Item<?>) args[0];
int upgraderesult = (Integer) args[1];
return "update_item " + item.getEntityId() +" "+ upgraderesult + " "
+ item.getGemNumber() + " "
+ item.getExtraStats();
}
break;
case USQ:
if(args.length > 0){
String type = (String) args[0];
int quickSlotPosition = (Integer) args[1];
int equipmentPosition = (Integer) args[2];
Item<?> item = (Item<?>) args[3];
int equipmentGemNumber = item.getGemNumber();
int equipmentExtraStatus = item.getExtraStats();
return "usq " + type + " " + quickSlotPosition +" "
+ equipmentPosition + " "
+ equipmentGemNumber + " "
+ equipmentExtraStatus;
}
break;
case UQ_ITEM:
if(args.length > 0){
int updateResult = (Integer) args[0]; //need confirmation about this
int quickSlotPosition = (Integer) args[1];
int itemEntityId = (Integer) args[2];
String serverPacket = "uq_item " + updateResult + " " + quickSlotPosition
+ " " + itemEntityId;
if (args.length == 4) {
int unknown = (Integer) args[3];
serverPacket += " " + unknown;
}
if (args.length == 6) {
int gemNumber = (Integer) args[3];
int extraStats = (Integer) args[4];
int unknown = (Integer) args[5];
serverPacket += " " + gemNumber + " " + extraStats + " " + unknown;
}
return serverPacket;
}
break;
case MT_ITEM:
if(args.length > 0){
int updateResult = (Integer) args[0];
int quickSlotPosition = (Integer) args[1];
int itemEntityId = (Integer) args[2];
int unknown = (Integer) args[2];
return "mt_item " + updateResult + " " + quickSlotPosition + " "
+ itemEntityId + " " + unknown;
}
break;
case AV:
if(args.length > 0){
LivingObject victim = (LivingObject) args[0];
int damageType = (Integer) args[1];
return "av " + getObjectType(victim) + " " + victim.getEntityId() + " "
+ victim.getPercentageHp() + " " + damageType + " 0";
}
break;
case PARTY_REQUEST:
if(args.length > 0){
Party party = (Party)args[0];
Player leader = party.getLeader();
String packet = "party request 0 "+leader.getEntityId()+" "+leader.getName();
for(Player member : party.getMembers()){
packet += " "+member.getEntityId()+" "+member.getName();
}
return packet += " "+party.getExpOption()+" "+party.getItemOption();
}
break;
case PARTY_SECESSION:
if(args.length > 0){
int entityId = (Integer)args[0];
return "party secession "+ entityId;
}
break;
case PARTY_LIST:
if(args.length > 0){
int membersAmmount = (Integer)args[0];
return "party list "+ membersAmmount;
}
break;
case PARTY_MEMBER:
if(args.length > 0){
Player member = (Player)args[0];
return "party member "+ member.getEntityId()+" "+member.getName();
}
break;
case PARTY_INFO:
if(args.length > 0){
Player member = (Player)args[0];
return "party info "+ member.getEntityId()+" "+member.getHp()+" "+member.getMaxHp();
}
break;
case PARTY_CHANGE:
if(args.length > 0){
int optionPosition = (Integer)args[0];
int optionValue = (Integer)args[1];
return "party change "+optionPosition+" "+optionValue;
}
break;
case PSTATUS:
if(args.length>1){
int id = (Integer)args[0];
long arg1 = (Long)args[1];
long arg2 = (Long)args[2];
int arg3 = (Integer)args[3];
return "pstatus " + id + " " + arg1 + " " + arg2 + " " + arg3;
}
break;
case MYPET:
if(args.length == 1){
if(((String)args[0]).equals("del")){
return "mypet del";
}
} else if(args.length == 2){
Player player = (Player)args[0];
Pet pet = (Pet)args[1];
PetEquipment equipment = pet.getEquipment();
return "mypet "
+ pet.getEntityId() + " "
+ pet.getName() + " "
+ (player.getClient().getVersion()>=2000 ? "0 " : "")
+ pet.getPosition().getX() + " "
+ pet.getPosition().getY() + " "
+ (pet.getPosition().getRotation()*1000)/1000 + " "
+ equipment.getTypeId(PetSlot.HORN) + " "
+ equipment.getTypeId(PetSlot.HEAD) + " "
+ equipment.getTypeId(PetSlot.BODY) + " "
+ equipment.getTypeId(PetSlot.WING) + " "
+ equipment.getTypeId(PetSlot.FOOT) + " "
+ equipment.getTypeId(PetSlot.TAIL) + " "
+ pet.getHp() + " "
+ pet.getMaxHp();
}
break;
case P_KEEP:
if(args.length == 2){
String pKeepType = (String)args[0];
Pet pet = (Pet)args[1];
if(pKeepType.equals("fail")){
int timeRemain = pet.getBreederTimer() + 60; //we add 60 to have the correct minutes value
return "p_keep fail " + timeRemain;
} else if(pKeepType.equals("info")){
//p_keep info [PetName] [isStored] [Level] [Stamina] [Loyalty] [Satiety] [LimeCharge] [TimeLeft(seconds)]
return "p_keep info " + pet.getName() + " "
+ (pet.getState() == 2 ? 1 : 0) + " "
+ pet.getLevel() + " "
+ pet.getMaxHp() + " "
+ pet.getLoyalty() + " "
+ pet.getSatiety() + " "
+ (pet.getState() == 2 ? 15000 : 0) +" 0";
}
}
break;
case IN_PET:
if(args.length>0){
Player player = (Player)args[0];
boolean warping = (Boolean)args[1];
Pet pet = player.getPet();
PetEquipment equipment = pet.getEquipment();
return (warping ? "ap " : "in ")
+"p " + pet.getEntityId() + " "
+ pet.getName() + " "
+ (player.getClient().getVersion()>=2000 ? "0 " : "")
+ pet.getPosition().getX() + " "
+ pet.getPosition().getY() + " "
+ pet.getPosition().getRotation() + " "
+ equipment.getTypeId(PetSlot.HORN) + " "
+ equipment.getTypeId(PetSlot.HEAD) + " "
+ equipment.getTypeId(PetSlot.BODY) + " "
+ equipment.getTypeId(PetSlot.WING) + " "
+ equipment.getTypeId(PetSlot.FOOT) + " "
+ equipment.getTypeId(PetSlot.TAIL) + " 100 14 "
+ player.getName() + " " +
+ player.isMeta();
//in p [PetEntityId] [PetName] 0 [PetPosX] [PetPosY] [PetRotation]
//[PetHornType] [PetHeadType] [PetBodyType] [PetWingType] [PetFootType] [PetTailType]
//100 14 [PlayerName] 0
}
break;
case EXTRA:
if(args.length==1){
Item<?> item = (Item<?>)args[0];
return "extra " + item.getEntityId() + " " + item.getType().getTypeId() + " " + item.getGemNumber() + " "
+ item.getExtraStats() + " " + item.getUnknown1() + " " + item.getUnknown2() + " "
+ item.getUnknown3();
}
break;
case G_POS_START:
if(args.length == 0){
return "g_pos start";
}
break;
case G_POS_BODY:
if(args.length == 1){
Player player = (Player)args[0];
return "g_pos body "+player.getEntityId()+" "+player.getName()+" "+player.getPosition().getX()+" "+player.getPosition().getY();
}
break;
case G_POS_END:
if(args.length == 0){
return "g_pos end";
}
break;
case EXCH:
if(args.length==1){
String exchType = (String)args[0]; /* TYPES:
* cancel
* trade
* disable
*/
return "exch " + exchType;
}
break;
case EXCH_ASK:
if(args.length==1){
Player source = (Player)args[0];
return "exch_ask "+source.getName();
}
break;
case EXCH_START:
if(args.length==1){
Player player = (Player)args[0];
return "exch_start "+player.getName()+" "+player.getLevel();
}
break;
case EXCH_INVEN_TO:
if(args.length==1){
ExchangeItem exchangeItem = (ExchangeItem)args[0];
Item<?> item = exchangeItem.getItem();
return "exch_inven_to " + item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ exchangeItem.getPosition().getPosX() + " "
+ exchangeItem.getPosition().getPosY() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats()+ " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case EXCH_INVEN_FROM:
if(args.length==1){
ExchangeItem exchangeItem = (ExchangeItem)args[0];
return "exch_inven_from " + exchangeItem.getPosition().getPosX() + " "
+ exchangeItem.getPosition().getPosY();
}
break;
case EXCH_MONEY:
if(args.length==1){
long money = (long)args[0];
return "exch_money "+money;
}
break;
default:
throw new UnsupportedOperationException();
}
throw new RuntimeException("Invalid parameters for "+packetType+" message");
}
| public static String createPacket(Type packetType, Object... args) {
switch (packetType) {
case FAIL:
String message = "";
for(Object o: args){
message+=" "+o;
}
return "fail"+message;
case INFO:
String infomsg = "";
for(Object o: args){
infomsg+=" "+o;
}
return "info"+infomsg;
case OK:
return "OK";
case GO_WORLD:
if(args.length>0){
LocalMap map = (LocalMap)args[0];
int unknown = args.length>1?(Integer)args[1]:0;
InetSocketAddress address = map.getAddress();
return "go_world "+address.getAddress().getHostAddress()+" "+address.getPort()+" " + map.getId()+" "+unknown;
}
break;
case GOTO:
if(args.length>0){
Position position = (Position)args[0];
return "goto " + position.getX() + " " + position.getY() + " "+position.getZ()+" "
+ (position.getRotation()*1000)/1000;
}
break;
case EVENTNOTICE:
if(args.length>0){
String msg = "";
for(Object o: args){
msg+=" "+o;
}
return "event"+msg;
}
break;
case PARTY_DISBAND:
return "party disband";
case HOUR:
if(args.length>0){
int hour = (Integer)args[0];
return "hour " + hour;
}
break;
case IN_CHAR:
if(args.length>0){
Player player = (Player)args[0];
boolean warping = false;
if(args.length>1){
warping = (Boolean)args[1];
}
int combat = player.isInCombat() ? 1 : 0;
Equipment eq = player.getEquipment();
String packetData = warping?"appear ":"in ";
packetData += "c " + player.getEntityId() + " " + player.getName()
+ " " + player.getRace().value() + " " + player.getSex().ordinal() + " "
+ player.getHairStyle() + " " + player.getPosition().getX()
+ " " + player.getPosition().getY() + " "
+ player.getPosition().getZ() + " "
+ player.getPosition().getRotation() + " " + eq.getTypeId(Slot.HELMET) + " "
+ eq.getTypeId(Slot.CHEST) + " " + eq.getTypeId(Slot.PANTS) + " " + eq.getTypeId(Slot.SHOULDER) + " "
+ eq.getTypeId(Slot.BOOTS) + " " + eq.getTypeId(Slot.OFFHAND) + " " + eq.getTypeId(Slot.MAINHAND) + " "
+ player.getPercentageHp() + " " + combat + " 0 0 0 0 0 0";
// in char [UniqueID] [Name] [Race] [Gender] [HairStyle] [XPos]
// [YPos] [ZPos] [Rotation] [Helm] [Armor] [Pants] [ShoulderMount]
// [Boots] [Shield] [Weapon] [Hp%] [CombatMode] 0 0 0 [Boosted] [PKMode]
// 0 [Guild]
// [MemberType] 1
if(player.getGuildId() != 0)
{
String[] guildLevelText = {"","Member","","","","","","Sub-General","General","Sub-Master","Master"};
packetData += " "+player.getGuildName()+" "+guildLevelText[(int) player.getGuildLvl()]+" "+player.getGuildLvl();
}
return packetData;
}
break;
case OUT:
if(args.length>0){
WorldObject object = (WorldObject)args[0];
return "out "+getObjectType(object)+" " + object.getEntityId();
}
break;
case SAY:
if(args.length>0){
String text = (String)args[0];
Player from = null;
if(args.length>1){
from = (Player)args[1];
}
if(from==null) {
return "say "+ -1 +" "+text;
} else {
if(args.length == 2){
boolean admin = from.getAdminState() == 255;
String name = from.getName();
if(admin)
name = "<GM>"+name;
return "say "+from.getEntityId()+" "+name+" " + text + " "+(admin ? 1 : 0);
}
}
}
break;
case GUILD_SAY:
if(args.length>0){
String text = (String)args[0];
Player from = (Player)args[1];
return "say "+from.getEntityId()+" *GUILD*"+from.getName()+" "+text;
}
break;
case GUILD_NAME:
if(args.length == 1){
Player player = (Player)args[0];
return "guild_name "+player.getEntityId()+" "+player.getGuildName();
}
break;
case GUILD_GRADE:
if(args.length == 1){
String[] guildLevelText = {"","Member","","","","","","Sub-General","General","Sub-Master","Master"};
Player player = (Player)args[0];
return "guild_grade "+player.getEntityId()+" 0 "+guildLevelText[(int) player.getGuildLvl()] + " "+player.getGuildLvl();
}
break;
case GUILD_LEVEL:
if(args.length == 1){
Player player = (Player)args[0];
return "guild_level "+player.getGuildLvl();
}
break;
case WISPER:
if(args.length == 3)
{
String text = (String)args[0];
Player player = (Player)args[1];
String direction = (String)args[2];
return "say "+player.getEntityId()+" "+direction+player.getName()+" " + text + " "+((player.getAdminState() >= 200) ? 1 : 0);
}
break;
case DROP:
if(args.length>0){
RoamingItem roamingItem = (RoamingItem)args[0];
Position position = roamingItem.getPosition();
Item<?> item = roamingItem.getItem();
return "drop " + item.getEntityId() + " " + item.getType().getTypeId() + " "
+ position.getX() + " " + position.getY() + " " + position.getZ() + " "+position.getRotation()
+" " + item.getGemNumber() + " "+ item.getExtraStats()+ " " + item.getUnknown1() + " " + item.getUnknown2();
}
break;
case IN_ITEM:
if(args.length>0){
RoamingItem roamingItem = (RoamingItem)args[0];
Item<?> item = roamingItem.getItem();
Position position = roamingItem.getPosition();
return "in item " + item.getEntityId() + " " + item.getType().getTypeId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation() + " " + item.getGemNumber()
+ " " + item.getExtraStats()+ " " + item.getUnknown1() + " " + item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case IN_NPC:
if(args.length>0){
Npc<?> npc = (Npc<?>)args[0];
Boolean spawn = false;
if(args.length>1){
spawn = (Boolean)args[1];
}
int percentageHp = (int)(((double)npc.getHp()/ (double)npc.getMaxHp())* 100);
Position npcPosition = npc.getPosition();
return "in n " + npc.getEntityId() + " " + npc.getType().getTypeId()
+ " " + npcPosition.getX() + " "
+ npcPosition.getY() + " "+npcPosition.getZ()+" "
+ npcPosition.getRotation() + " "
+ percentageHp + " "
+ npc.getMutantType() + " " + npc.getUnknown1() + " "
+ npc.getType().getNeoProgmare() + " " + npc.getUnknown2() + " "+ (spawn ? 1 : 0) + " "
+ npc.getUnknown3();
}
break;
case AT:
if(args.length>0){
Player player = (Player)args[0];
return
"at " + player.getEntityId() + " "
+ player.getPosition().getX() + " " + player.getPosition().getY() + " "
+ player.getPosition().getZ() + " " + (float)player.getPosition().getRotation();
}
break;
case PLACE:
if(args.length>1){
Player player = (Player)args[0];
Position position = player.getPosition();
int unknown = (Integer)args[1];
return "p c " + player.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation() + " "
+ unknown + " " + (player.isRunning()?1:0);
}
break;
case S_CHAR:
if(args.length>0){
Player player = (Player)args[0];
Position position = player.getPosition();
return "s c " + player.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + position.getRotation();
}
break;
case WALK:
if(args.length>1){
LivingObject livingObject = (LivingObject)args[0];
Position position = (Position)args[1];
return "w "+getObjectType(livingObject)+" " + livingObject.getEntityId() + " " + position.getX()
+ " " + position.getY() + " " + position.getZ() + " " + (livingObject.isRunning()?1:0);
}
break;
case SUCCESS:
return "success";
case SOCIAL:
if(args.length>1){
Player player = (Player)args[0];
int emotionId = (Integer)args[1];
return "social char " + player.getEntityId() + " "
+ emotionId;
}
break;
case SKILLLEVEL_ALL:
if(args.length>0){
String packetData = "skilllevel_all";
Player player = (Player)args[0];
for(Skill skill: player.getSkills().keySet()) {
packetData += " " + skill.getId() + " " + player.getSkillLevel(skill);
}
return packetData;
}
break;
case A_:
if(args.length>1){
String type = (String)args[0];
Object value = args[1];
return "a_" + type + " " + value;
}
break;
case COMBAT:
if(args.length>0){
Player player = (Player)args[0];
return "combat " + player.getEntityId() + " " + (player.isInCombat()?1:0);
}
break;
case JUMP:
if(args.length>0){
Player player = (Player)args[0];
return "jump " + player.getPosition().getX() + " "
+ player.getPosition().getY() + " "
+ player.getEntityId();
}
break;
case LEVELUP:
if(args.length>0){
Player player = (Player)args[0];
return "levelup " + player.getEntityId();
}
break;
case STATUS:
if(args.length>1){
int id = (Integer)args[0];
long arg1 = (Long)args[1];
long arg2 = 0;
if(args.length > 2){
arg2 = (Long)args[2];
}
return "status " + id + " " + arg1 + " " + arg2;
}
break;
case MSG:
if(args.length>0){
String msg = (String)args[0];
return "msg "+msg;
}
break;
case EFFECT: //attack skill
if(args.length>2){
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
Skill skill = (Skill)args[2];
int unknown1 = (Integer)args[3];
int unknown2 = (Integer)args[4];
int unknown3 = (Integer)args[5];
return "effect " + skill.getId() + " "+getObjectType(source)+" "
+ source.getEntityId() + " "+getObjectType(target)+" " + target.getEntityId() + " "
+ target.getPercentageHp() + " " + source.getDmgType() + " "
+ unknown1 + " " + unknown2 + " " +unknown3;
// S> effect [SkillID] [n/c] [1STEntityId] [n/c] [2NDEntityID] [RemainingHP%] [Critical] 0 0 0
}
break;
case SECONDATTACK: //or Subattack
//sa c 547782 c 589654 0 3 0 0 40
if(args.length == 3)
{
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
int skillId = (Integer)args[2];
return "sa "+getObjectType(source)+" "+source.getEntityId()+" "+getObjectType(target)+" "
+target.getEntityId()+" "+target.getPercentageHp()+" "+source.getDmgType()+" 0 0 "+skillId;
}
break;
case SAV:
//sav n 26128 75 2 0 4900 3
if(args.length == 5)
{
LivingObject target = (LivingObject) args[0];
int damageType = (Integer)args[1];
int unknown1 = (Integer)args[2];
int itemStatusRemain = (Integer)args[3];
int unknown2 = (Integer)args[4];
return "sav "+ (target==null ? -1 : getObjectType(target)) + " "
+ (target==null ? -1 : target.getEntityId()) + " "
+ (target==null ? -1 : target.getPercentageHp()) + " "
+ damageType + " "
+ unknown1 + " "
+ itemStatusRemain + " "
+ unknown2;
}
break;
case SKILL: //self usable skill
if(args.length>1){
LivingObject source = (LivingObject) args[0];
Skill skill = (Skill)args[1];
return "skill " + ((Effectable)skill).getEffectModifier() + " char "+ source.getEntityId() + " "
+skill.getId();
// S> skill [Duration/Activated] char [CharID] [SkillID]
}
break;
case CHAR_REMOVE:
if(args.length>1){
Player player = (Player)args[0];
Slot slot = (Slot)args[1];
return "char_remove " + player.getEntityId() + " " + slot.value();
}
break;
case CHAR_WEAR:
if(args.length>1){
Player player = (Player)args[0];
Slot slot = (Slot)args[1];
Item<?> item = (Item<?>)args[2];
return "char_wear " + player.getEntityId() + " " + slot.value() + " "
+ item.getType().getTypeId() + " " + item.getGemNumber();
}
break;
case ATTACK:
if(args.length>1){
LivingObject source = (LivingObject) args[0];
LivingObject target = (LivingObject)args[1];
int isCritical = (Integer)args[2];
return "attack " + getObjectType(source) + " "
+ source.getEntityId() + " " + getObjectType(target)
+ " " + target.getEntityId() + " "
+ target.getPercentageHp() + " " + isCritical
+ " 0 0 0 0";
// S> attack c [CharEntityID] npc [NpcEntityID] [RemainHP%] [isCritical] 0 0 0 0
}
break;
case ATTACK_VITAL:
if(args.length>0){
LivingObject target = (LivingObject)args[0];
return
"attack_vital "+getObjectType(target)+" " + target.getEntityId() + " "
+ target.getPercentageHp() + " 0 0";
}
break;
case SKILLLEVEL:
if(args.length>1){
Skill skill = (Skill)args[0];
int currentSkillLevel = (Integer)args[1];
return "skilllevel " + skill.getId() + " " + currentSkillLevel;
}
break;
case PICKUP:
if(args.length>0){
Player player = (Player)args[0];
return "pickup " + player.getEntityId();
}
break;
case PICK:
if(args.length>0){
InventoryItem invItem = (InventoryItem)args[0];
Item<?> item = invItem.getItem();
return "pick " + item.getEntityId() + " " + item.getType().getTypeId() + " "
+ invItem.getPosition().getPosX()+" "+invItem.getPosition().getPosY() + " "
+ invItem.getPosition().getTab()+" " + item.getGemNumber() + " "
+ item.getExtraStats() + " " + item.getUnknown1() + " " + item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case SHOP_RATE:
if(args.length>0){
NpcShop npcShop = (NpcShop)args[0];
return "shop_rate " + npcShop.getBuyRate() + " "+ npcShop.getSellRate();
}
break;
case SHOP_ITEM:
if(args.length>0){
VendorItem vendorItem = (VendorItem)args[0];
return "shop_item " + vendorItem.getType();
}
break;
case STASH:
if(args.length>1){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash " + slot + " 0 " + (item.getGemNumber()/100) + " 0 0";
else
return "stash "
+ slot + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity + " "
+ item.getUnknown2();
}
break;
case STASH_TO:
if(args.length>1){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash_to "
+ slot + " 0 "
+ (item.getGemNumber()/100) + " 0";
else
return "stash_to "
+ slot + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity + " "
+ item.getUnknown2();
}
break;
case STASH_FROM:
if(args.length>0){
StashItem stashItem = (StashItem)args[0];
int itemQuantity = (Integer)args[1];
Item<?> item = stashItem.getItem();
int slot = stashItem.getStashPosition().getSlot();
if(slot == 12)
return "stash_from "
+ slot + " 0 "
+ (item.getGemNumber()/100) + " 0";
else
return "stash_from "
+ slot + " "
+ item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability() + " "
+ itemQuantity;
}
break;
case STASH_GET:
if(args.length>0){
List<int[]> itemList = (List<int[]>)args[0];
int itemTypeId = (Integer)args[1];
int inventoryTab = (Integer)args[2];
int unknown2 = (Integer)args[3];
int slot = (Integer)args[4];
int itemQuantity = (Integer)args[5];
int unknown1 = 1;
String packet = "stash_get "
+ unknown1 + " "
+ itemTypeId + " "
+ inventoryTab + " "
+ unknown2 + " "
+ slot + " "
+ itemQuantity;
for(int[] itemData : itemList){
packet += " " + itemData[0] + " "
+ itemData[1] + " "
+ itemData[2];
}
return packet;
}
break;
case STASH_PUT:
if(args.length>1){
//stash_put [?] [TypeId] [InvTab] [StashTab] [StashPos] [ItemAmmount] [InvPosX] [InvPosY]
int itemTypeId = (Integer)args[0];
int invTab = (Integer)args[1];
int stashTab = (Integer)args[2];
int stashPos = (Integer)args[3];
int itemAmmount = (Integer)args[4];
int[] itemsData = (int[])args[5];
int index = 3;
String packet = "stash_put 1 "
+ itemTypeId + " "
+ invTab + " "
+ stashTab + " "
+ stashPos + " "
+ itemAmmount;
while(index < itemsData.length){
packet += " " + itemsData[index++];
}
return packet;
}
break;
case STASH_END:
return "stash_end";
case INVEN:
if(args.length > 0){
InventoryItem invItem = (InventoryItem)args[0];
int version = (Integer)args[1];
Item<?> item = invItem.getItem();
return "inven " + invItem.getPosition().getTab() + " "
+ item.getEntityId() + " " + item.getType().getTypeId() + " " + invItem.getPosition().getPosX() + " "
+ invItem.getPosition().getPosY() + " " + item.getGemNumber() + " " + item.getExtraStats() + " "
+ item.getUnknown1() + (version >= 2000 ? " " + item.getUnknown2() + " " + item.getUnknown3() : "");
}
break;
case MULTI_SHOT: //human semi-automatic skill
if(args.length >= 1){
String source = (String) args[0]; //me or char
int numberOfShots = (Integer) args[1];
String charId = args.length == 3 ? (String) args[2]+" " : "";
return "multi_shot "+source+" " +charId+""+numberOfShots;
// S> multi_shot me [numberOfShots]
// S> multi_shot char [charID] [numberOfShots]
}
break;
case QUICK:
if(args.length > 0){
QuickSlotItem qsItem = (QuickSlotItem)args[0];
Item<?> item = qsItem.getItem();
return "quick " + qsItem.getPosition().getSlot() + " "
+ item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats() + " "
+ item.getUnknown1();
}
break;
case UPGRADE:
if(args.length > 0){
Item<?> item = (Item<?>) args[0];
Slot slot = (Slot) args[1];
int upgraderesult = (Integer) args[2];
return "upgrade " + upgraderesult + " "
+ slot.value() + " "
+ item.getEntityId() + " "
+ item.getGemNumber();
}
break;
case KILL:
if(args.length > 0){ //Kill is used on 2007+ client
LivingObject target = (LivingObject) args[0];
return "kill " +getObjectType(target)+ " " + target.getEntityId() + "\n";
}
break;
case WEARING:
if(args.length > 0){
Equipment eq = (Equipment)args[0];
int version = (Integer)args[1];
/*
* [entity] [typeid] [gemnumber] [extrast] [unknown1] [unknown 2] [unknown 3] [cur_dur] [max_dur]
* 1524774 318 2 0 0 0 0 4449 4453
*
* wearing
* 1524774 318 2 0 0 0 0 4449 4453 [Helmet] 0
* 1524775 333 9 0 0 0 0 4322 4509 [Armor] 1
* 1524776 351 15 0 0 0 0 3778 4029 [Pants] 2
* 1524777 196 0 0 0 0 0 0 0 [Cloak] 3
* 1524778 373 3 0 0 0 0 3113 3203 [Shoes] 4
* 1524779 121 6 0 0 0 0 0 0 [Shield] 5
* 1524780 445 6 1 0 0 0 0 0 [Necklace] 6
* -1 -1 0 0 0 0 0 0 0 [Ring] 7
* 1524781 455 1 1 0 0 0 0 0 [Bracelet] 8
* -1 -1 0 0 0 0 0 0 0 [Weapon] 9
* -1 -1 0 0 0 0 0 0 0 [?] 10 PET1 ?
* -1 -1 0 0 0 0 0 0 0 [?] 11 PET2 ?
*
*/
return "wearing " + eq.getEntityId(Slot.HELMET) + " " + eq.getTypeId(Slot.HELMET) + " "
+ eq.getGemNumber(Slot.HELMET) + " " + eq.getExtraStats(Slot.HELMET) + " "
+ eq.getUnknown1(Slot.HELMET) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.HELMET) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.HELMET) + " " : "")
+ eq.getDurability(Slot.HELMET) + " " + eq.getMaxDurability(Slot.HELMET) + " "
+ eq.getEntityId(Slot.CHEST) + " " + eq.getTypeId(Slot.CHEST) + " "
+ eq.getGemNumber(Slot.CHEST) + " " + eq.getExtraStats(Slot.CHEST) + " "
+ eq.getUnknown1(Slot.CHEST) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.CHEST) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.CHEST) + " " :"")
+ eq.getDurability(Slot.CHEST) + " " + eq.getMaxDurability(Slot.CHEST) + " "
+ eq.getEntityId(Slot.PANTS) + " " + eq.getTypeId(Slot.PANTS) + " "
+ eq.getGemNumber(Slot.PANTS) + " " + eq.getExtraStats(Slot.PANTS) + " "
+ eq.getUnknown1(Slot.PANTS) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.PANTS) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.PANTS) + " " : "")
+ eq.getDurability(Slot.PANTS) + " " + eq.getMaxDurability(Slot.PANTS) + " "
+ eq.getEntityId(Slot.SHOULDER) + " " + eq.getTypeId(Slot.SHOULDER) + " "
+ eq.getGemNumber(Slot.SHOULDER) + " " + eq.getExtraStats(Slot.SHOULDER) + " "
+ eq.getUnknown1(Slot.SHOULDER) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.SHOULDER) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.SHOULDER) + " " : "")
+ eq.getDurability(Slot.SHOULDER) + " " + eq.getMaxDurability(Slot.SHOULDER) + " "
+ eq.getEntityId(Slot.BOOTS) + " " + eq.getTypeId(Slot.BOOTS)
+ " " + eq.getGemNumber(Slot.BOOTS) + " " + eq.getExtraStats(Slot.BOOTS) + " "
+ eq.getUnknown1(Slot.BOOTS) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.BOOTS) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.BOOTS) + " " : "")
+ eq.getDurability(Slot.BOOTS) + " " + eq.getMaxDurability(Slot.BOOTS) + " "
+ eq.getEntityId(Slot.OFFHAND) + " " + eq.getTypeId(Slot.OFFHAND) + " "
+ eq.getGemNumber(Slot.OFFHAND) + " " + eq.getExtraStats(Slot.OFFHAND) + " "
+ eq.getUnknown1(Slot.OFFHAND) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.OFFHAND) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.OFFHAND) + " " : "")
+ eq.getDurability(Slot.OFFHAND) + " " + eq.getMaxDurability(Slot.OFFHAND) + " "
+ eq.getEntityId(Slot.NECKLACE) + " " + eq.getTypeId(Slot.NECKLACE) + " "
+ eq.getGemNumber(Slot.NECKLACE) + " " + eq.getExtraStats(Slot.NECKLACE) + " "
+ eq.getUnknown1(Slot.NECKLACE) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.NECKLACE) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.NECKLACE) + " " : "")
+ eq.getDurability(Slot.NECKLACE) + " " + eq.getMaxDurability(Slot.NECKLACE) + " "
+ eq.getEntityId(Slot.RING) + " " + eq.getTypeId(Slot.RING) + " "
+ eq.getGemNumber(Slot.RING) + " " + eq.getExtraStats(Slot.RING) + " "
+ eq.getUnknown1(Slot.RING) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.RING) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.RING) + " " : "")
+ eq.getDurability(Slot.RING) + " " + eq.getMaxDurability(Slot.RING) + " "
+ eq.getEntityId(Slot.BRACELET) + " " + eq.getTypeId(Slot.BRACELET) + " "
+ eq.getGemNumber(Slot.BRACELET) + " " + eq.getExtraStats(Slot.BRACELET) + " "
+ eq.getUnknown1(Slot.BRACELET) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.BRACELET) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.BRACELET) + " " : "")
+ eq.getDurability(Slot.BRACELET) + " " + eq.getMaxDurability(Slot.BRACELET) + " "
+ eq.getEntityId(Slot.MAINHAND) + " " + eq.getTypeId(Slot.MAINHAND) + " "
+ eq.getGemNumber(Slot.MAINHAND) + " " + eq.getExtraStats(Slot.MAINHAND) + " "
+ eq.getUnknown1(Slot.MAINHAND) + " "
//+ (version >= 2000 ? eq.getUnknown2(Slot.MAINHAND) + " " : "")
//+ (version >= 2000 ? eq.getUnknown3(Slot.MAINHAND) + " " : "")
+ eq.getDurability(Slot.MAINHAND) + " " + eq.getMaxDurability(Slot.MAINHAND)
+ " -1 -1 0 0 0 0 0 0 0"
+ " -1 -1 0 0 0 0 0 0 0";
}
break;
case QT:
if(args.length > 0){
String packetData = (String) args[0];
return "qt " + packetData + "\n";
}
break;
case Q_EX:
if(args.length > 0){
Integer limeAmmount = (Integer) args[0];
return "q_ex " + limeAmmount + "\n";
}
break;
case K:
if(args.length > 0){
int isActivated = (Integer) args[0];
LivingObject livingObject = (LivingObject) args[1];
int typeId = (Integer) args[2];
return "k "+isActivated+" "+getObjectType(livingObject)+" "+livingObject.getEntityId()+" "+typeId;
}
break;
case ICHANGE:
if(args.length > 0){
Item<?> oldItem = (Item<?>) args[0];
Item<?> newItem = (Item<?>) args[1];
if(oldItem == null || newItem == null)
return "ichange 0 0 0 0 0 0 0 0";
else {
return "ichange "
+ oldItem.getEntityId() + " "
+ newItem.getEntityId() + " "
+ newItem.getType().getTypeId() + " "
+ newItem.getGemNumber() + " "
+ newItem.getExtraStats() + " 0 0 0";
}
}
break;
case CHIP_EXCHANGE:
if(args.length > 0){
int gemTraderType = (Integer) args[0];
String betResult = (String) args[1];
Item<?> item = (Item<?>) args[2];
String serverBet = ((String) args[3]);
if(item == null)
return "chip_exchange "+gemTraderType+" ok "+betResult+"-1 "+serverBet;
else
return "chip_exchange "+gemTraderType+" ok "+betResult+""
+item.getType().getTypeId()+" "+serverBet+""+item.getEntityId();
}
break;
case SKY:
if(args.length == 2){
Player player = (Player) args[0];
int state = (Integer) args[1];
return "sky "+player.getEntityId()+" "+state;
}
break;
case UPDATE_ITEM:
if(args.length > 0){
Item<?> item = (Item<?>) args[0];
int upgraderesult = (Integer) args[1];
return "update_item " + item.getEntityId() +" "+ upgraderesult + " "
+ item.getGemNumber() + " "
+ item.getExtraStats();
}
break;
case USQ:
if(args.length > 0){
String type = (String) args[0];
int quickSlotPosition = (Integer) args[1];
int equipmentPosition = (Integer) args[2];
Item<?> item = (Item<?>) args[3];
int equipmentGemNumber = item.getGemNumber();
int equipmentExtraStatus = item.getExtraStats();
return "usq " + type + " " + quickSlotPosition +" "
+ equipmentPosition + " "
+ equipmentGemNumber + " "
+ equipmentExtraStatus;
}
break;
case UQ_ITEM:
if(args.length > 0){
int updateResult = (Integer) args[0]; //need confirmation about this
int quickSlotPosition = (Integer) args[1];
int itemEntityId = (Integer) args[2];
String serverPacket = "uq_item " + updateResult + " " + quickSlotPosition
+ " " + itemEntityId;
if (args.length == 4) {
int unknown = (Integer) args[3];
serverPacket += " " + unknown;
}
if (args.length == 6) {
int gemNumber = (Integer) args[3];
int extraStats = (Integer) args[4];
int unknown = (Integer) args[5];
serverPacket += " " + gemNumber + " " + extraStats + " " + unknown;
}
return serverPacket;
}
break;
case MT_ITEM:
if(args.length > 0){
int updateResult = (Integer) args[0];
int quickSlotPosition = (Integer) args[1];
int itemEntityId = (Integer) args[2];
int unknown = (Integer) args[2];
return "mt_item " + updateResult + " " + quickSlotPosition + " "
+ itemEntityId + " " + unknown;
}
break;
case AV:
if(args.length > 0){
LivingObject victim = (LivingObject) args[0];
int damageType = (Integer) args[1];
return "av " + getObjectType(victim) + " " + victim.getEntityId() + " "
+ victim.getPercentageHp() + " " + damageType + " 0";
}
break;
case PARTY_REQUEST:
if(args.length > 0){
Party party = (Party)args[0];
Player leader = party.getLeader();
String packet = "party request 0 "+leader.getEntityId()+" "+leader.getName();
for(Player member : party.getMembers()){
packet += " "+member.getEntityId()+" "+member.getName();
}
return packet += " "+party.getExpOption()+" "+party.getItemOption();
}
break;
case PARTY_SECESSION:
if(args.length > 0){
int entityId = (Integer)args[0];
return "party secession "+ entityId;
}
break;
case PARTY_LIST:
if(args.length > 0){
int membersAmmount = (Integer)args[0];
return "party list "+ membersAmmount;
}
break;
case PARTY_MEMBER:
if(args.length > 0){
Player member = (Player)args[0];
return "party member "+ member.getEntityId()+" "+member.getName();
}
break;
case PARTY_INFO:
if(args.length > 0){
Player member = (Player)args[0];
return "party info "+ member.getEntityId()+" "+member.getHp()+" "+member.getMaxHp();
}
break;
case PARTY_CHANGE:
if(args.length > 0){
int optionPosition = (Integer)args[0];
int optionValue = (Integer)args[1];
return "party change "+optionPosition+" "+optionValue;
}
break;
case PSTATUS:
if(args.length>1){
int id = (Integer)args[0];
long arg1 = (Long)args[1];
long arg2 = (Long)args[2];
int arg3 = (Integer)args[3];
return "pstatus " + id + " " + arg1 + " " + arg2 + " " + arg3;
}
break;
case MYPET:
if(args.length == 1){
if(((String)args[0]).equals("del")){
return "mypet del";
}
} else if(args.length == 2){
Player player = (Player)args[0];
Pet pet = (Pet)args[1];
PetEquipment equipment = pet.getEquipment();
return "mypet "
+ pet.getEntityId() + " "
+ pet.getName() + " "
+ (player.getClient().getVersion()>=2000 ? "0 " : "")
+ pet.getPosition().getX() + " "
+ pet.getPosition().getY() + " "
+ (pet.getPosition().getRotation()*1000)/1000 + " "
+ equipment.getTypeId(PetSlot.HORN) + " "
+ equipment.getTypeId(PetSlot.HEAD) + " "
+ equipment.getTypeId(PetSlot.BODY) + " "
+ equipment.getTypeId(PetSlot.WING) + " "
+ equipment.getTypeId(PetSlot.FOOT) + " "
+ equipment.getTypeId(PetSlot.TAIL) + " "
+ pet.getHp() + " "
+ pet.getMaxHp();
}
break;
case P_KEEP:
if(args.length == 2){
String pKeepType = (String)args[0];
Pet pet = (Pet)args[1];
if(pKeepType.equals("fail")){
int timeRemain = pet.getBreederTimer() + 60; //we add 60 to have the correct minutes value
return "p_keep fail " + timeRemain;
} else if(pKeepType.equals("info")){
//p_keep info [PetName] [isStored] [Level] [Stamina] [Loyalty] [Satiety] [LimeCharge] [TimeLeft(seconds)]
return "p_keep info " + pet.getName() + " "
+ (pet.getState() == 2 ? 1 : 0) + " "
+ pet.getLevel() + " "
+ pet.getMaxHp() + " "
+ pet.getLoyalty() + " "
+ pet.getSatiety() + " "
+ (pet.getState() == 2 ? 15000 : 0) +" 0";
}
}
break;
case IN_PET:
if(args.length>0){
Player player = (Player)args[0];
boolean warping = (Boolean)args[1];
Pet pet = player.getPet();
PetEquipment equipment = pet.getEquipment();
return (warping ? "ap " : "in ")
+"p " + pet.getEntityId() + " "
+ pet.getName() + " "
+ (player.getClient().getVersion()>=2000 ? "0 " : "")
+ pet.getPosition().getX() + " "
+ pet.getPosition().getY() + " "
+ pet.getPosition().getRotation() + " "
+ equipment.getTypeId(PetSlot.HORN) + " "
+ equipment.getTypeId(PetSlot.HEAD) + " "
+ equipment.getTypeId(PetSlot.BODY) + " "
+ equipment.getTypeId(PetSlot.WING) + " "
+ equipment.getTypeId(PetSlot.FOOT) + " "
+ equipment.getTypeId(PetSlot.TAIL) + " 100 14 "
+ player.getName() + " " +
+ player.isMeta();
//in p [PetEntityId] [PetName] 0 [PetPosX] [PetPosY] [PetRotation]
//[PetHornType] [PetHeadType] [PetBodyType] [PetWingType] [PetFootType] [PetTailType]
//100 14 [PlayerName] 0
}
break;
case EXTRA:
if(args.length==1){
Item<?> item = (Item<?>)args[0];
return "extra " + item.getEntityId() + " " + item.getType().getTypeId() + " " + item.getGemNumber() + " "
+ item.getExtraStats() + " " + item.getUnknown1() + " " + item.getUnknown2() + " "
+ item.getUnknown3();
}
break;
case G_POS_START:
if(args.length == 0){
return "g_pos start";
}
break;
case G_POS_BODY:
if(args.length == 1){
Player player = (Player)args[0];
return "g_pos body "+player.getEntityId()+" "+player.getName()+" "+player.getPosition().getX()+" "+player.getPosition().getY();
}
break;
case G_POS_END:
if(args.length == 0){
return "g_pos end";
}
break;
case EXCH:
if(args.length==1){
String exchType = (String)args[0]; /* TYPES:
* cancel
* trade
* disable
*/
return "exch " + exchType;
}
break;
case EXCH_ASK:
if(args.length==1){
Player source = (Player)args[0];
return "exch_ask "+source.getName();
}
break;
case EXCH_START:
if(args.length==1){
Player player = (Player)args[0];
return "exch_start "+player.getName()+" "+player.getLevel();
}
break;
case EXCH_INVEN_TO:
if(args.length==1){
ExchangeItem exchangeItem = (ExchangeItem)args[0];
Item<?> item = exchangeItem.getItem();
return "exch_inven_to " + item.getEntityId() + " "
+ item.getType().getTypeId() + " "
+ exchangeItem.getPosition().getPosX() + " "
+ exchangeItem.getPosition().getPosY() + " "
+ item.getGemNumber() + " "
+ item.getExtraStats()+ " "
+ item.getUnknown1() + " "
+ item.getDurability() + " "
+ item.getType().getMaxDurability();
}
break;
case EXCH_INVEN_FROM:
if(args.length==1){
ExchangeItem exchangeItem = (ExchangeItem)args[0];
return "exch_inven_from " + exchangeItem.getPosition().getPosX() + " "
+ exchangeItem.getPosition().getPosY();
}
break;
case EXCH_MONEY:
if(args.length==1){
long money = (Long)args[0];
return "exch_money "+money;
}
break;
default:
throw new UnsupportedOperationException();
}
throw new RuntimeException("Invalid parameters for "+packetType+" message");
}
|
diff --git a/src/cytoscape/plugin/JarUtil.java b/src/cytoscape/plugin/JarUtil.java
index 3ec141869..40d7444b9 100644
--- a/src/cytoscape/plugin/JarUtil.java
+++ b/src/cytoscape/plugin/JarUtil.java
@@ -1,144 +1,144 @@
package cytoscape.plugin;
/*
Copyright (c) 2010, The Cytoscape Consortium (www.cytoscape.org)
The Cytoscape Consortium is:
- Institute for Systems Biology
- University of California San Diego
- Memorial Sloan-Kettering Cancer Center
- Institut Pasteur
- Agilent Technologies
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import cytoscape.util.URLUtil;
import cytoscape.util.ZipUtil;
import java.util.zip.ZipFile;
/**
* A utility class designed to capture methods used by multiple classes.
*/
class JarUtil {
/**
* Bug 2055 changing regexp used to match jars
* Was "\\w+\\.jar", which seemed unecessarily restrictive
*/
static final String MATCH_JAR_REGEXP = ".*\\.jar$";
/**
* Iterate through all class files, return the subclass of CytoscapePlugin.
* Similar to CytoscapeInit, however only plugins with manifest files that
* describe the class of the CytoscapePlugin are valid.
*/
static String getPluginClass(String fileName, PluginInfo.FileType type) throws IOException {
String pluginClassName = null;
try {
switch (type) {
case JAR:
JarFile jar = new JarFile(fileName);
try {
pluginClassName = getManifestAttribute(jar.getManifest());
} finally {
if (jar != null)
jar.close();
}
break;
case ZIP:
List<ZipEntry> Entries = ZipUtil.getAllFiles(fileName, MATCH_JAR_REGEXP);
if (Entries.size() <= 0) {
String[] filePath = fileName.split("/");
fileName = filePath[filePath.length - 1];
throw new IOException( fileName +
" does not contain any jar files or is not a zip file.");
}
ZipFile zf = null;
try {
zf = new ZipFile(fileName);
for (ZipEntry entry : Entries) {
String entryName = entry.getName();
InputStream is = null;
try {
JarInputStream jis = null;
is = ZipUtil.readFile(zf, entryName);
try {
jis = new JarInputStream(is);
pluginClassName = getManifestAttribute(jis.getManifest());
} finally {
if (jis != null)
jis.close();
}
} finally {
if (is != null)
is.close();
}
}
} finally {
if (zf != null)
zf.close();
}
}
} catch (Exception e) {
- throw new IOException(e);
+ throw new IOException(e.toString());
}
return pluginClassName;
}
/*
* Gets the manifest file value for the Cytoscape-Plugin attribute
*/
static String getManifestAttribute(Manifest m) {
String value = null;
if (m != null) {
value = m.getMainAttributes().getValue("Cytoscape-Plugin");
}
return value;
}
}
| true | true | static String getPluginClass(String fileName, PluginInfo.FileType type) throws IOException {
String pluginClassName = null;
try {
switch (type) {
case JAR:
JarFile jar = new JarFile(fileName);
try {
pluginClassName = getManifestAttribute(jar.getManifest());
} finally {
if (jar != null)
jar.close();
}
break;
case ZIP:
List<ZipEntry> Entries = ZipUtil.getAllFiles(fileName, MATCH_JAR_REGEXP);
if (Entries.size() <= 0) {
String[] filePath = fileName.split("/");
fileName = filePath[filePath.length - 1];
throw new IOException( fileName +
" does not contain any jar files or is not a zip file.");
}
ZipFile zf = null;
try {
zf = new ZipFile(fileName);
for (ZipEntry entry : Entries) {
String entryName = entry.getName();
InputStream is = null;
try {
JarInputStream jis = null;
is = ZipUtil.readFile(zf, entryName);
try {
jis = new JarInputStream(is);
pluginClassName = getManifestAttribute(jis.getManifest());
} finally {
if (jis != null)
jis.close();
}
} finally {
if (is != null)
is.close();
}
}
} finally {
if (zf != null)
zf.close();
}
}
} catch (Exception e) {
throw new IOException(e);
}
return pluginClassName;
}
| static String getPluginClass(String fileName, PluginInfo.FileType type) throws IOException {
String pluginClassName = null;
try {
switch (type) {
case JAR:
JarFile jar = new JarFile(fileName);
try {
pluginClassName = getManifestAttribute(jar.getManifest());
} finally {
if (jar != null)
jar.close();
}
break;
case ZIP:
List<ZipEntry> Entries = ZipUtil.getAllFiles(fileName, MATCH_JAR_REGEXP);
if (Entries.size() <= 0) {
String[] filePath = fileName.split("/");
fileName = filePath[filePath.length - 1];
throw new IOException( fileName +
" does not contain any jar files or is not a zip file.");
}
ZipFile zf = null;
try {
zf = new ZipFile(fileName);
for (ZipEntry entry : Entries) {
String entryName = entry.getName();
InputStream is = null;
try {
JarInputStream jis = null;
is = ZipUtil.readFile(zf, entryName);
try {
jis = new JarInputStream(is);
pluginClassName = getManifestAttribute(jis.getManifest());
} finally {
if (jis != null)
jis.close();
}
} finally {
if (is != null)
is.close();
}
}
} finally {
if (zf != null)
zf.close();
}
}
} catch (Exception e) {
throw new IOException(e.toString());
}
return pluginClassName;
}
|
diff --git a/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java b/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java
index 865c2cdb..647fc99d 100644
--- a/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java
+++ b/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritTaskDataHandler.java
@@ -1,211 +1,215 @@
/*********************************************************************
* Copyright (c) 2010 Sony Ericsson/ST Ericsson and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sony Ericsson/ST Ericsson - initial API and implementation
* Tasktop Technologies - improvements
* GitHub, Inc. - fixes for bug 354753
* Sascha Scholz (SAP) - improvements
*********************************************************************/
package org.eclipse.mylyn.internal.gerrit.core;
import java.util.Date;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.mylyn.internal.gerrit.core.client.GerritChange;
import org.eclipse.mylyn.internal.gerrit.core.client.GerritClient;
import org.eclipse.mylyn.internal.gerrit.core.client.GerritException;
import org.eclipse.mylyn.internal.gerrit.core.client.JSonSupport;
import org.eclipse.mylyn.tasks.core.IRepositoryPerson;
import org.eclipse.mylyn.tasks.core.ITaskMapping;
import org.eclipse.mylyn.tasks.core.RepositoryResponse;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskDataHandler;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskSchema.Field;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskCommentMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import com.google.gerrit.common.data.AccountInfo;
import com.google.gerrit.common.data.ChangeDetail;
import com.google.gerrit.common.data.ChangeInfo;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.ChangeMessage;
/**
* @author Mikael Kober
* @author Thomas Westling
* @author Steffen Pingel
* @author Kevin Sawicki
*/
public class GerritTaskDataHandler extends AbstractTaskDataHandler {
public static String dateToString(Date date) {
if (date == null) {
return ""; //$NON-NLS-1$
} else {
return date.getTime() + ""; //$NON-NLS-1$
}
}
private final GerritConnector connector;
public GerritTaskDataHandler(GerritConnector connector) {
this.connector = connector;
}
public TaskData createTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor) {
TaskData data = new TaskData(getAttributeMapper(repository), GerritConnector.CONNECTOR_KIND,
repository.getRepositoryUrl(), taskId);
initializeTaskData(repository, data, null, monitor);
return data;
}
public TaskData createPartialTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor) {
TaskData data = new TaskData(getAttributeMapper(repository), GerritConnector.CONNECTOR_KIND,
repository.getRepositoryUrl(), taskId);
GerritQueryResultSchema.getDefault().initialize(data);
return data;
}
@Override
public TaskAttributeMapper getAttributeMapper(TaskRepository repository) {
return new TaskAttributeMapper(repository);
}
/**
* Retrieves task data for the given review from repository.
*/
public TaskData getTaskData(TaskRepository repository, String taskId, IProgressMonitor monitor)
throws CoreException {
try {
GerritClient client = connector.getClient(repository);
client.refreshConfigOnce(monitor);
boolean anonymous = client.isAnonymous();
String id = null;
if (!anonymous) {
id = getAccountId(client, repository, monitor);
}
GerritChange review = client.getChange(taskId, monitor);
int reviewId = review.getChangeDetail().getChange().getId().get();
TaskData taskData = createTaskData(repository, Integer.toString(reviewId), monitor);
updateTaskData(repository, taskData, review, !anonymous, id);
return taskData;
} catch (GerritException e) {
throw connector.toCoreException(repository, e);
}
}
/**
* Get account id for repository
*
* @param client
* @param repository
* @param monitor
* @return account id or null if not found
* @throws GerritException
*/
protected String getAccountId(GerritClient client, TaskRepository repository, IProgressMonitor monitor)
throws GerritException {
String id = repository.getProperty(GerritConnector.KEY_REPOSITORY_ACCOUNT_ID);
if (id == null) {
Account account = client.getAccount(monitor);
if (account != null) {
id = account.getId().toString();
repository.setProperty(GerritConnector.KEY_REPOSITORY_ACCOUNT_ID, id);
}
}
return id;
}
@Override
public boolean initializeTaskData(TaskRepository repository, TaskData taskData, ITaskMapping initializationData,
IProgressMonitor monitor) {
GerritTaskSchema.getDefault().initialize(taskData);
return true;
}
@Override
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData,
Set<TaskAttribute> oldAttributes, IProgressMonitor monitor) throws CoreException {
throw new UnsupportedOperationException();
}
public void updateTaskData(TaskRepository repository, TaskData data, GerritChange review, boolean canPublish,
String accountId) {
GerritTaskSchema schema = GerritTaskSchema.getDefault();
ChangeDetail changeDetail = review.getChangeDetail();
Change change = changeDetail.getChange();
AccountInfo owner = changeDetail.getAccounts().get(change.getOwner());
updateTaskData(repository, data, new ChangeInfo(change));
setAttributeValue(data, schema.BRANCH, change.getDest().get());
setAttributeValue(data, schema.OWNER, GerritUtil.getUserLabel(owner));
setAttributeValue(data, schema.UPLOADED, dateToString(change.getCreatedOn()));
setAttributeValue(data, schema.DESCRIPTION, changeDetail.getDescription());
int i = 1;
String accountName = repository.getUserName();
for (ChangeMessage message : changeDetail.getMessages()) {
TaskCommentMapper mapper = new TaskCommentMapper();
if (message.getAuthor() != null) {
AccountInfo author = changeDetail.getAccounts().get(message.getAuthor());
String userName;
String id = author.getId().toString();
if (id.equals(accountId) && accountName != null) {
userName = accountName;
} else {
String email = author.getPreferredEmail();
userName = (email != null) ? email : id;
}
IRepositoryPerson person = repository.createPerson(userName);
person.setName(author.getFullName());
mapper.setAuthor(person);
+ } else {
+ // messages without an author are from Gerrit itself
+ IRepositoryPerson person = repository.createPerson("Gerrit Code Review");
+ mapper.setAuthor(person);
}
mapper.setText(message.getMessage());
mapper.setCreationDate(message.getWrittenOn());
mapper.setNumber(i);
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + i);
mapper.applyTo(attribute);
i++;
}
JSonSupport json = new JSonSupport();
setAttributeValue(data, schema.OBJ_REVIEW, json.getGson().toJson(review));
setAttributeValue(data, schema.CAN_PUBLISH, Boolean.toString(canPublish));
}
public void updateTaskData(TaskRepository repository, TaskData data, ChangeInfo changeInfo) {
GerritQueryResultSchema schema = GerritQueryResultSchema.getDefault();
setAttributeValue(data, schema.KEY, changeInfo.getKey().abbreviate());
setAttributeValue(data, schema.PROJECT, changeInfo.getProject().getName());
setAttributeValue(data, schema.SUMMARY, changeInfo.getSubject());
setAttributeValue(data, schema.STATUS, changeInfo.getStatus().toString());
setAttributeValue(data, schema.URL, connector.getTaskUrl(repository.getUrl(), data.getTaskId()));
setAttributeValue(data, schema.UPDATED, dateToString(changeInfo.getLastUpdatedOn()));
setAttributeValue(data, schema.CHANGE_ID, changeInfo.getKey().get());
if (changeInfo.getStatus() != null && changeInfo.getStatus().isClosed()) {
setAttributeValue(data, schema.COMPLETED, dateToString(changeInfo.getLastUpdatedOn()));
}
}
/**
* Convenience method to set the value of a given Attribute in the given {@link TaskData}.
*/
private TaskAttribute setAttributeValue(TaskData data, Field gerritAttribut, String value) {
TaskAttribute attribute = data.getRoot().getAttribute(gerritAttribut.getKey());
if (value != null) {
attribute.setValue(value);
}
return attribute;
}
}
| true | true | public void updateTaskData(TaskRepository repository, TaskData data, GerritChange review, boolean canPublish,
String accountId) {
GerritTaskSchema schema = GerritTaskSchema.getDefault();
ChangeDetail changeDetail = review.getChangeDetail();
Change change = changeDetail.getChange();
AccountInfo owner = changeDetail.getAccounts().get(change.getOwner());
updateTaskData(repository, data, new ChangeInfo(change));
setAttributeValue(data, schema.BRANCH, change.getDest().get());
setAttributeValue(data, schema.OWNER, GerritUtil.getUserLabel(owner));
setAttributeValue(data, schema.UPLOADED, dateToString(change.getCreatedOn()));
setAttributeValue(data, schema.DESCRIPTION, changeDetail.getDescription());
int i = 1;
String accountName = repository.getUserName();
for (ChangeMessage message : changeDetail.getMessages()) {
TaskCommentMapper mapper = new TaskCommentMapper();
if (message.getAuthor() != null) {
AccountInfo author = changeDetail.getAccounts().get(message.getAuthor());
String userName;
String id = author.getId().toString();
if (id.equals(accountId) && accountName != null) {
userName = accountName;
} else {
String email = author.getPreferredEmail();
userName = (email != null) ? email : id;
}
IRepositoryPerson person = repository.createPerson(userName);
person.setName(author.getFullName());
mapper.setAuthor(person);
}
mapper.setText(message.getMessage());
mapper.setCreationDate(message.getWrittenOn());
mapper.setNumber(i);
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + i);
mapper.applyTo(attribute);
i++;
}
JSonSupport json = new JSonSupport();
setAttributeValue(data, schema.OBJ_REVIEW, json.getGson().toJson(review));
setAttributeValue(data, schema.CAN_PUBLISH, Boolean.toString(canPublish));
}
| public void updateTaskData(TaskRepository repository, TaskData data, GerritChange review, boolean canPublish,
String accountId) {
GerritTaskSchema schema = GerritTaskSchema.getDefault();
ChangeDetail changeDetail = review.getChangeDetail();
Change change = changeDetail.getChange();
AccountInfo owner = changeDetail.getAccounts().get(change.getOwner());
updateTaskData(repository, data, new ChangeInfo(change));
setAttributeValue(data, schema.BRANCH, change.getDest().get());
setAttributeValue(data, schema.OWNER, GerritUtil.getUserLabel(owner));
setAttributeValue(data, schema.UPLOADED, dateToString(change.getCreatedOn()));
setAttributeValue(data, schema.DESCRIPTION, changeDetail.getDescription());
int i = 1;
String accountName = repository.getUserName();
for (ChangeMessage message : changeDetail.getMessages()) {
TaskCommentMapper mapper = new TaskCommentMapper();
if (message.getAuthor() != null) {
AccountInfo author = changeDetail.getAccounts().get(message.getAuthor());
String userName;
String id = author.getId().toString();
if (id.equals(accountId) && accountName != null) {
userName = accountName;
} else {
String email = author.getPreferredEmail();
userName = (email != null) ? email : id;
}
IRepositoryPerson person = repository.createPerson(userName);
person.setName(author.getFullName());
mapper.setAuthor(person);
} else {
// messages without an author are from Gerrit itself
IRepositoryPerson person = repository.createPerson("Gerrit Code Review");
mapper.setAuthor(person);
}
mapper.setText(message.getMessage());
mapper.setCreationDate(message.getWrittenOn());
mapper.setNumber(i);
TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + i);
mapper.applyTo(attribute);
i++;
}
JSonSupport json = new JSonSupport();
setAttributeValue(data, schema.OBJ_REVIEW, json.getGson().toJson(review));
setAttributeValue(data, schema.CAN_PUBLISH, Boolean.toString(canPublish));
}
|
diff --git a/examples/photoalbum/source/ejb/src/main/java/org/richfaces/photoalbum/domain/Image.java b/examples/photoalbum/source/ejb/src/main/java/org/richfaces/photoalbum/domain/Image.java
index 8d33e689..3fcf8435 100644
--- a/examples/photoalbum/source/ejb/src/main/java/org/richfaces/photoalbum/domain/Image.java
+++ b/examples/photoalbum/source/ejb/src/main/java/org/richfaces/photoalbum/domain/Image.java
@@ -1,530 +1,530 @@
/**
* License Agreement.
*
* JBoss RichFaces - Ajax4jsf Component Library
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* Image.java
* Last modified by: $Author$
* $Revision$ $Date$
*/
package org.richfaces.photoalbum.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.annotations.OrderBy;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.richfaces.photoalbum.service.ActionTools;
@NamedQueries({
@NamedQuery(
name = "tag-byName",
query = "select m from MetaTag m where m.tag =:tag"
),
@NamedQuery(
name = "tag-popular",
query = "select new MetaTag(m.id, m.tag) from MetaTag m join m.images img group by m.id, m.tag order by count(img) desc"
),
@NamedQuery(
name = "user-shelves",
query = "select distinct s from Shelf s where (s.shared = true and s.owner.preDefined = true) order by s.name"
),
@NamedQuery(
name = "image-exist",
query = "select i from Image i where i.path = :path and i.album = :album"
),
@NamedQuery(
name = "image-countIdenticalImages",
query = "select count(i) from Image i where i.path like :path and i.album = :album"
),
@NamedQuery(
name = "tag-suggest",
query = "select m from MetaTag m where lower(m.tag) like :tag"
)})
/**
* Class for representing Image Entity
* EJB3 Entity Bean
*
* @author Andrey Markhel
*/
@Entity
@Name("image")
@Scope(ScopeType.CONVERSATION)
@AutoCreate
public class Image implements Serializable {
private static final long serialVersionUID = -7042878411608396483L;
@Id
@GeneratedValue
private Long id;
@ManyToMany
private List<MetaTag> imageTags = new ArrayList<MetaTag>();
@OrderBy(clause = "date asc")
@OneToMany(cascade = CascadeType.REMOVE, mappedBy = "image")
// @Fetch(FetchMode.SUBSELECT)
private List<Comment> comments = new ArrayList<Comment>();
@NotNull
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
private Album album;
@NotNull
@NotEmpty
@Length(min = 3, max = 200)
@Column(length = 255, nullable = false)
private String name;
@Transient
private boolean covering;
@NotNull
@NotEmpty
@Length(min = 3)
@Column(length = 1024, nullable = false)
private String path;
@Column(length = 255)
private String cameraModel;
private int height;
private double size;
private int width;
@Temporal(TemporalType.TIMESTAMP)
private Date uploaded;
@NotNull
@NotEmpty
@Length(min = 3)
@Column(length = 1024)
private String description;
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@NotNull
private boolean allowComments;
private Boolean showMetaInfo = true;
@Transient
private boolean visited;
/*
* Comma separated tags value
* */
@Transient
private String meta = "";
/**
* Getter for property preDefined
*
* @return is this shelf is predefined
*/
public boolean isPreDefined() {
return getAlbum().isPreDefined();
}
// ********************** Accessor Methods ********************** //
public Boolean getShowMetaInfo() {
return showMetaInfo;
}
public void setShowMetaInfo(final Boolean showMetaInfo) {
this.showMetaInfo = showMetaInfo;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Getter for property path.
* Represent file-system structure, relative at uploadRoot dir(determined at startup, by default is system temp dir)
* Usually is user.GetLogin() + SLASH + image.getAlbum().getId() + SLASH + fileName,
* for example "amarkhel/15/coolPicture.jpg"
*
* @return relative path of image
*/
public String getPath() {
return path;
}
/**
* Setter for property path
*
* @param path - relative path to image
*/
public void setPath(String path) {
this.path = path;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
this.album = album;
}
public List<Comment> getComments() {
return comments;
}
public List<MetaTag> getImageTags() {
return imageTags;
}
/**
* Setter for property meta
*
* @param meta - string representation of metatags, associated to image. Used at jsf page.
*/
public void setMeta(String meta) {
this.meta = meta;
}
/**
* Getter for property meta
*
* @return string representation of metatags, associated to image. Used at jsf page.
*/
public String getMetaString() {
return meta;
}
public String getCameraModel() {
return cameraModel;
}
public void setCameraModel(String cameraModel) {
this.cameraModel = cameraModel;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
/**
* Getter for property size
*
* @return size of image in KB
*/
public double getSize() {
return size;
}
/**
* setter for property size
*
* @param size - size of image in KB
*/
public void setSize(double size) {
this.size = size;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
/**
* Getter for property uploaded
*
* @return date of upload to site of this image
*/
public Date getUploaded() {
return uploaded;
}
/**
* setter for property uploaded
*
* @param uploaded - date of upload
*/
public void setUploaded(Date uploaded) {
this.uploaded = uploaded;
}
/**
* Getter for property allowComments. If true, other user may comment this image.
*
* @return is other users may comment this image
*/
public boolean isAllowComments() {
return allowComments;
}
/**
* @param allowComments the allowComments to set
*/
public void setAllowComments(boolean allowComments) {
this.allowComments = allowComments;
}
/**
* @return if this image is covering for containing album
*/
public boolean isCovering() {
return covering;
}
public void setImageTags(final List<MetaTag> imageTags) {
this.imageTags = imageTags;
}
/**
* @param covering - determine if this image is covering for containing album
*/
public void setCovering(boolean covering) {
this.covering = covering;
}
/**
* Getter for property visited
*
* @return boolean value, that indicated is user visit this image already
*/
public boolean isVisited() {
return visited;
}
/**
* Setter for property visited
*
* @param visited - boolean value, that indicated is user visit this image already
*/
public void setVisited(boolean visited) {
this.visited = visited;
}
/**
* Determine if this image should be marked as new(on jsf page, for example in tree)
*
* @return boolean value, that indicated is this image should be marked as new
*/
public boolean isNew() {
if (!visited) {
return this.getUploaded().after(ActionTools.getRecentlyDate());
}
return false;
}
//---------------------------Business methods
/**
* Add comment to this image.
*
* @param comment - comment to add
*/
public void addComment(Comment comment) {
if (comment == null) {
throw new IllegalArgumentException("Null comment!");
}
comment.setImage(this);
comments.add(comment);
}
/**
* Remove comment from list of comments, belongs to that image.
*
* @param comment - comment to delete
*/
public void removeComment(Comment comment) {
if (comment == null) {
throw new IllegalArgumentException("Null comment");
}
if (comment.getImage().equals(this)) {
comment.setImage(null);
comments.remove(comment);
} else {
throw new IllegalArgumentException("Comment not belongs to this image");
}
}
/**
* Add metatag to this image.
*
* @param metatag - metatag to add
*/
public void addMetaTag(MetaTag metatag) {
if (metatag == null) {
throw new IllegalArgumentException("Null metatag!");
}
if (!imageTags.contains(metatag)) {
metatag.addImage(this);
imageTags.add(metatag);
}
}
/**
* Remove metatag from list of metatag, associated to that image.
*
* @param metatag - metatag to delete
*/
public void removeMetaTag(MetaTag metatag) {
if (metatag == null) {
throw new IllegalArgumentException("Null metatag!");
}
if (imageTags.contains(metatag)) {
metatag.removeImage(this);
imageTags.remove(metatag);
}
}
/**
* Return MetaTag object by string representation
*
* @param s - string representation of metatag
*/
public MetaTag getTagByName(String s) {
for (MetaTag t : imageTags) {
if (t.getTag().equals(s)) {
return t;
}
}
return null;
}
/**
* Return Comma separated tag value for presentation in view
*/
public String getMeta() {
final StringBuilder s = new StringBuilder();
for (MetaTag tag : this.imageTags) {
s.append(tag.getTag()).append(", ");
}
//Remove ',' from end
if (s.length() >= 2) {
s.delete(s.length() - 2, s.length());
}
return s.toString();
}
/**
* Return relative path of this image in file-system(relative to uploadRoot parameter)
*/
public String getFullPath() {
if (getAlbum().getPath() == null) {
return null;
}
return getAlbum().getPath() + this.path;
}
public User getOwner() {
return getAlbum().getOwner();
}
public boolean isOwner(User user) {
return user != null && user.equals(getOwner());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
- if (obj == null || getClass() != obj.getClass()) {
+ if (obj == null) {
return false;
}
final Image image = (Image) obj;
return (id == null ? image.getId() == null : id.equals(image.getId()))
&& (path == null ? image.getPath() == null : path.equals(image.getPath()));
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (path != null ? path.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "{id : "+getId()+", name : "+getName()+"}";
}
}
| true | true | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Image image = (Image) obj;
return (id == null ? image.getId() == null : id.equals(image.getId()))
&& (path == null ? image.getPath() == null : path.equals(image.getPath()));
}
| public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
final Image image = (Image) obj;
return (id == null ? image.getId() == null : id.equals(image.getId()))
&& (path == null ? image.getPath() == null : path.equals(image.getPath()));
}
|
diff --git a/src/org/dynasoar/Bootstrap.java b/src/org/dynasoar/Bootstrap.java
index 23e99f0..e6c0909 100644
--- a/src/org/dynasoar/Bootstrap.java
+++ b/src/org/dynasoar/Bootstrap.java
@@ -1,44 +1,44 @@
package org.dynasoar;
import org.dynasoar.config.Configuration;
import org.dynasoar.monitor.NodeMonitor;
import org.dynasoar.service.ServiceMonitor;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
/**
* Initializes and starts up the application.
*
* @author Rakshit Menpara
*/
public class Bootstrap {
private static Logger logger = Logger.getLogger(Bootstrap.class);
public static void main(String args[]) {
logger.info("Starting up DynaSOAr Server...");
// Set up a simple configuration that logs on the console.
BasicConfigurator.configure();
// Check if configuration path is specified as a parameter
- if (args.length > 2) {
- String path = args[2];
+ if (args.length > 0) {
+ String path = args[0];
// Read configuration file
Configuration.readConfiguration(path);
} else {
// Read configuration file
Configuration.readConfiguration();
}
// Start up ServiceMonitor
ServiceMonitor.start();
// Start up NodeMonitor
NodeMonitor.start();
logger.info("Initialization complete. DynaSOAr is running.");
}
}
| true | true | public static void main(String args[]) {
logger.info("Starting up DynaSOAr Server...");
// Set up a simple configuration that logs on the console.
BasicConfigurator.configure();
// Check if configuration path is specified as a parameter
if (args.length > 2) {
String path = args[2];
// Read configuration file
Configuration.readConfiguration(path);
} else {
// Read configuration file
Configuration.readConfiguration();
}
// Start up ServiceMonitor
ServiceMonitor.start();
// Start up NodeMonitor
NodeMonitor.start();
logger.info("Initialization complete. DynaSOAr is running.");
}
| public static void main(String args[]) {
logger.info("Starting up DynaSOAr Server...");
// Set up a simple configuration that logs on the console.
BasicConfigurator.configure();
// Check if configuration path is specified as a parameter
if (args.length > 0) {
String path = args[0];
// Read configuration file
Configuration.readConfiguration(path);
} else {
// Read configuration file
Configuration.readConfiguration();
}
// Start up ServiceMonitor
ServiceMonitor.start();
// Start up NodeMonitor
NodeMonitor.start();
logger.info("Initialization complete. DynaSOAr is running.");
}
|
diff --git a/atlas-web/src/main/java/uk/ac/ebi/gxa/plot/AssayProperties.java b/atlas-web/src/main/java/uk/ac/ebi/gxa/plot/AssayProperties.java
index 17e082c3e..0a070d40d 100644
--- a/atlas-web/src/main/java/uk/ac/ebi/gxa/plot/AssayProperties.java
+++ b/atlas-web/src/main/java/uk/ac/ebi/gxa/plot/AssayProperties.java
@@ -1,103 +1,103 @@
/*
* Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.plot;
import ae3.model.ExperimentalFactorsCompactData;
import ae3.model.SampleCharacteristicsCompactData;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import uk.ac.ebi.gxa.netcdf.reader.NetCDFDescriptor;
import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static com.google.common.io.Closeables.closeQuietly;
/**
* Loads assay properties in order to convert into JSON. Used by assay tooltips on the experiment page.
* Not appropriate for using in the backend services.
*
* @author Olga Melnichuk
* Date: 03/05/2011
*/
public class AssayProperties {
private List<ExperimentalFactorsCompactData> efs = Lists.newArrayList();
private List<SampleCharacteristicsCompactData> scs = Lists.newArrayList();
public Collection<ExperimentalFactorsCompactData> getEfs() {
return Collections.unmodifiableCollection(efs);
}
public Collection<SampleCharacteristicsCompactData> getScs() {
return Collections.unmodifiableCollection(scs);
}
protected AssayProperties load(NetCDFProxy proxy, Function<String, String> nameConverter) throws IOException {
efs = Lists.newArrayList();
scs = Lists.newArrayList();
String[] factors = proxy.getFactors();
String[] sampleCharacteristics = proxy.getCharacteristics();
int[][] s2a = proxy.getSamplesToAssays();
for (String f : factors) {
String[] vals = proxy.getFactorValues(f);
ExperimentalFactorsCompactData d = new ExperimentalFactorsCompactData(
nameConverter.apply(f), vals.length);
for (int i = 0; i < vals.length; i++) {
d.addEfv(vals[i], i);
}
efs.add(d);
}
for (String s : sampleCharacteristics) {
String[] vals = proxy.getCharacteristicValues(s);
SampleCharacteristicsCompactData d = new SampleCharacteristicsCompactData(
- nameConverter.apply(s), vals.length);
+ nameConverter.apply(s), s2a[0].length);
for (int i = 0; i < vals.length; i++) {
d.addScv(vals[i], i);
for (int j = s2a[i].length - 1; j >= 0; j--) {
if (s2a[i][j] > 0) {
- d.addMapping(j, i);
+ d.addMapping(i, j);
}
}
}
scs.add(d);
}
return this;
}
public static AssayProperties create(NetCDFDescriptor proxyDescr, Function<String, String> nameConverter) throws IOException {
NetCDFProxy proxy = null;
try {
proxy = proxyDescr.createProxy();
return (new AssayProperties()).load(proxy, nameConverter);
} finally {
closeQuietly(proxy);
}
}
}
| false | true | protected AssayProperties load(NetCDFProxy proxy, Function<String, String> nameConverter) throws IOException {
efs = Lists.newArrayList();
scs = Lists.newArrayList();
String[] factors = proxy.getFactors();
String[] sampleCharacteristics = proxy.getCharacteristics();
int[][] s2a = proxy.getSamplesToAssays();
for (String f : factors) {
String[] vals = proxy.getFactorValues(f);
ExperimentalFactorsCompactData d = new ExperimentalFactorsCompactData(
nameConverter.apply(f), vals.length);
for (int i = 0; i < vals.length; i++) {
d.addEfv(vals[i], i);
}
efs.add(d);
}
for (String s : sampleCharacteristics) {
String[] vals = proxy.getCharacteristicValues(s);
SampleCharacteristicsCompactData d = new SampleCharacteristicsCompactData(
nameConverter.apply(s), vals.length);
for (int i = 0; i < vals.length; i++) {
d.addScv(vals[i], i);
for (int j = s2a[i].length - 1; j >= 0; j--) {
if (s2a[i][j] > 0) {
d.addMapping(j, i);
}
}
}
scs.add(d);
}
return this;
}
| protected AssayProperties load(NetCDFProxy proxy, Function<String, String> nameConverter) throws IOException {
efs = Lists.newArrayList();
scs = Lists.newArrayList();
String[] factors = proxy.getFactors();
String[] sampleCharacteristics = proxy.getCharacteristics();
int[][] s2a = proxy.getSamplesToAssays();
for (String f : factors) {
String[] vals = proxy.getFactorValues(f);
ExperimentalFactorsCompactData d = new ExperimentalFactorsCompactData(
nameConverter.apply(f), vals.length);
for (int i = 0; i < vals.length; i++) {
d.addEfv(vals[i], i);
}
efs.add(d);
}
for (String s : sampleCharacteristics) {
String[] vals = proxy.getCharacteristicValues(s);
SampleCharacteristicsCompactData d = new SampleCharacteristicsCompactData(
nameConverter.apply(s), s2a[0].length);
for (int i = 0; i < vals.length; i++) {
d.addScv(vals[i], i);
for (int j = s2a[i].length - 1; j >= 0; j--) {
if (s2a[i][j] > 0) {
d.addMapping(i, j);
}
}
}
scs.add(d);
}
return this;
}
|
diff --git a/src/main/java/info/somethingodd/OddItem/configuration/OddItemGroup.java b/src/main/java/info/somethingodd/OddItem/configuration/OddItemGroup.java
index f31dd8f..49d3188 100644
--- a/src/main/java/info/somethingodd/OddItem/configuration/OddItemGroup.java
+++ b/src/main/java/info/somethingodd/OddItem/configuration/OddItemGroup.java
@@ -1,258 +1,260 @@
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package info.somethingodd.OddItem.configuration;
import info.somethingodd.OddItem.OddItem;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* @author Gordon Pettey ([email protected])
*/
public class OddItemGroup implements ConfigurationSerializable, Iterable<ItemStack> {
private List<ItemStack> itemStacks;
private List<String> items;
private Map<String, Object> data;
private Set<String> aliases;
public OddItemGroup(Map<String, Object> serialized) {
data = ((ConfigurationSection) serialized.get("data")).getValues(false);
items = (List<String>) serialized.get("items");
itemStacks = new ArrayList<ItemStack>();
aliases = new TreeSet<String>(OddItem.ALPHANUM_COMPARATOR);
- aliases.addAll((Collection<String>) serialized.get("aliases"));
+ if (serialized.containsKey("aliases")) {
+ aliases.addAll((Collection<String>) serialized.get("aliases"));
+ }
for (String item : items) {
ItemStack itemStack;
try {
if (item.contains(",")) {
itemStack = OddItem.getItemStack(item.substring(0, item.indexOf(",")));
itemStack.setAmount(Integer.valueOf(item.substring(item.indexOf(",") + 1)));
} else {
itemStack = OddItem.getItemStack(item);
itemStack.setAmount(1);
}
itemStacks.add(itemStack);
} catch (IllegalArgumentException e2) {
Bukkit.getLogger().warning("Invalid item \"" + item + "\" in groups.yml (" + items.toString() + ")");
}
}
}
/**
* Gets all aliases for the group
* @return Collection of aliases
*/
public Collection<String> getAliases() {
return Collections.unmodifiableCollection(aliases);
}
/**
* Gets group data
* @return Map of data
*/
public Map<String, Object> getData() {
return data;
}
/**
* Get data by key
* @param key key to retrieve
* @return data
*/
public Object getData(String key) {
if (!data.containsKey(key))
return null;
return data.get(key);
}
/**
* Get data by second-level key
* @param key top-level key
* @param key2 second-level key
* @return data
*/
public Object getData(String key, String key2) {
ConfigurationSection configurationSection = (ConfigurationSection) getData(key);
if (configurationSection == null)
return null;
return configurationSection.get(key2);
}
/**
* Get int by key
* @param key top-level key
* @return data
*/
public Integer getInt(String key) {
return (Integer) getData(key);
}
/**
* Get int by second-level key
* @param key top-level key
* @param key2 second-level key
* @return data
*/
public Integer getInt(String key, String key2) {
return (Integer) getData(key, key2);
}
/**
* Get String by key
* @param key top-level key
* @return data
*/
public String getString(String key) {
return (String) data.get(key);
}
/**
* Get String by second-level key
* @param key top-level key
* @param key2 second-level key
* @return data
*/
public String getString(String key, String key2) {
return (String) getData(key, key2);
}
/**
* Get List\<String\> by key
* @param key top-level key
* @return data
*/
public List<String> getStringList(String key) {
return (List<String>) data.get(key);
}
/**
* Get List\<String\></String\> by second-level key
* @param key top-level key
* @param key2 second-level key
* @return data
*/
public List<String> getStringList(String key, String key2) {
return (List<String>) getData(key, key2);
}
/**
* Get double by key
* @param key top-level key
* @return data
*/
public double getDouble(String key) {
return (Double) getData(key);
}
/**
* Get double by second-level key
* @param key top-level key
* @param key2 second-level key
* @return data
*/
public double getDouble(String key, String key2) {
return (Double) getData(key, key2);
}
/**
* Get ConfigurationSection by second-level key
* @param key top-level key
* @return data
*/
public ConfigurationSection getConfigurationSection(String key) {
return (ConfigurationSection) getData(key);
}
/**
* Checks for top-level data key
* @param key key to check
* @return whether group contains data key
*/
public boolean match(String key) {
for (String k : data.keySet())
if (k.equals(key))
return true;
return false;
}
/**
* Checks for second-level data key
* @param key top-level key to check
* @param key2 second-level key to check
* @return whether group contains key2 inside key1 in data
*/
public boolean match(String key, String key2) {
for (Object x : data.values()) {
if (x instanceof MemorySection)
return ((MemorySection) x).getValues(false).containsKey("key2");
if (x instanceof Map)
return ((Map) x).containsKey(key2);
if (x instanceof List)
return ((List) x).contains(key2);
}
return false;
}
public String toString() {
StringBuilder str = new StringBuilder("OddItemGroup");
str.append("{");
str.append("items=").append(items.toString());
str.append(",");
str.append("data=").append(data.toString());
str.append("}\n");
return str.toString();
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> serialized = new TreeMap<String, Object>(OddItem.ALPHANUM_COMPARATOR);
serialized.put("items", items);
serialized.put("data", data);
return serialized;
}
public static OddItemGroup deserialize(Map<String, Object> serialized) {
return new OddItemGroup(serialized);
}
public static OddItemGroup valueOf(Map<String, Object> serialized) {
return new OddItemGroup(serialized);
}
public Collection<ItemStack> getItems() {
return Collections.unmodifiableCollection(itemStacks);
}
public ItemStack get(int index) {
return itemStacks.get(index);
}
@Override
public Iterator<ItemStack> iterator() {
return Collections.unmodifiableList(itemStacks).iterator();
}
}
| true | true | public OddItemGroup(Map<String, Object> serialized) {
data = ((ConfigurationSection) serialized.get("data")).getValues(false);
items = (List<String>) serialized.get("items");
itemStacks = new ArrayList<ItemStack>();
aliases = new TreeSet<String>(OddItem.ALPHANUM_COMPARATOR);
aliases.addAll((Collection<String>) serialized.get("aliases"));
for (String item : items) {
ItemStack itemStack;
try {
if (item.contains(",")) {
itemStack = OddItem.getItemStack(item.substring(0, item.indexOf(",")));
itemStack.setAmount(Integer.valueOf(item.substring(item.indexOf(",") + 1)));
} else {
itemStack = OddItem.getItemStack(item);
itemStack.setAmount(1);
}
itemStacks.add(itemStack);
} catch (IllegalArgumentException e2) {
Bukkit.getLogger().warning("Invalid item \"" + item + "\" in groups.yml (" + items.toString() + ")");
}
}
}
| public OddItemGroup(Map<String, Object> serialized) {
data = ((ConfigurationSection) serialized.get("data")).getValues(false);
items = (List<String>) serialized.get("items");
itemStacks = new ArrayList<ItemStack>();
aliases = new TreeSet<String>(OddItem.ALPHANUM_COMPARATOR);
if (serialized.containsKey("aliases")) {
aliases.addAll((Collection<String>) serialized.get("aliases"));
}
for (String item : items) {
ItemStack itemStack;
try {
if (item.contains(",")) {
itemStack = OddItem.getItemStack(item.substring(0, item.indexOf(",")));
itemStack.setAmount(Integer.valueOf(item.substring(item.indexOf(",") + 1)));
} else {
itemStack = OddItem.getItemStack(item);
itemStack.setAmount(1);
}
itemStacks.add(itemStack);
} catch (IllegalArgumentException e2) {
Bukkit.getLogger().warning("Invalid item \"" + item + "\" in groups.yml (" + items.toString() + ")");
}
}
}
|
diff --git a/karaf/tooling/features-maven-plugin/src/main/java/org/apache/felix/karaf/tooling/features/GenerateFeaturesXmlMojo.java b/karaf/tooling/features-maven-plugin/src/main/java/org/apache/felix/karaf/tooling/features/GenerateFeaturesXmlMojo.java
index 85d4647ca..d8ce42da5 100644
--- a/karaf/tooling/features-maven-plugin/src/main/java/org/apache/felix/karaf/tooling/features/GenerateFeaturesXmlMojo.java
+++ b/karaf/tooling/features-maven-plugin/src/main/java/org/apache/felix/karaf/tooling/features/GenerateFeaturesXmlMojo.java
@@ -1,578 +1,578 @@
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.felix.karaf.tooling.features;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidArtifactRTException;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.metadata.ResolutionGroup;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.DefaultArtifactCollector;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException;
import org.apache.maven.shared.dependency.tree.traversal.DependencyNodeVisitor;
import org.osgi.impl.bundle.obr.resource.Manifest;
import org.osgi.impl.bundle.obr.resource.ManifestEntry;
import org.osgi.impl.bundle.obr.resource.VersionRange;
/**
* Generates the features XML file
*
* @version $Revision: 1.1 $
* @goal generate-features-xml
* @phase compile
* @execute phase="compile"
* @requiresDependencyResolution runtime
* @inheritByDefault true
* @description Generates the features XML file
*/
@SuppressWarnings("unchecked")
public class GenerateFeaturesXmlMojo extends MojoSupport {
protected static final String SEPARATOR = "/";
/**
* The dependency tree builder to use.
*
* @component
* @required
* @readonly
*/
private DependencyTreeBuilder dependencyTreeBuilder;
/**
* The file to generate
*
* @parameter default-value="${project.build.directory}/classes/feature.xml"
*/
private File outputFile;
/**
* The artifact type for attaching the generated file to the project
*
* @parameter default-value="xml"
*/
private String attachmentArtifactType = "xml";
/**
* The artifact classifier for attaching the generated file to the project
*
* @parameter default-value="features"
*/
private String attachmentArtifactClassifier = "features";
/**
* The kernel version for which to generate the bundle
*
* @parameter
*/
private String kernelVersion;
/*
* A list of packages exported by the kernel
*/
private Map<String, VersionRange> kernelExports = new HashMap<String, VersionRange>();
/**
* A file containing the list of bundles
*
* @parameter
*/
private File bundles;
/*
* A set of known bundles
*/
private Set<String> knownBundles = new HashSet<String>();
/*
* A list of exports by the bundles
*/
private Map<String, Map<VersionRange, Artifact>> bundleExports = new HashMap<String, Map<VersionRange, Artifact>>();
/*
* The set of system exports
*/
private List<String> systemExports = new LinkedList<String>();
/*
* These bundles are the features that will be built
*/
private Map<Artifact, Feature> features = new HashMap<Artifact, Feature>();
public void execute() throws MojoExecutionException, MojoFailureException {
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(outputFile));
readSystemPackages();
readKernelBundles();
readBundles();
discoverBundles();
writeFeatures(out);
// now lets attach it
projectHelper.attachArtifact(project, attachmentArtifactType, attachmentArtifactClassifier, outputFile);
} catch (Exception e) {
getLog().error(e);
throw new MojoExecutionException("Unable to create features.xml file: " + e, e);
} finally {
if (out != null) {
out.close();
}
}
}
/*
* Read all the system provided packages from the <code>config.properties</code> file
*/
private void readSystemPackages() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
readSystemPackages(properties, "jre-1.5");
readSystemPackages(properties, "osgi");
}
private void readSystemPackages(Properties properties, String key) {
String packages = (String) properties.get(key);
for (String pkg : packages.split(";")) {
systemExports.add(pkg.trim());
}
}
/*
* Download a Kernel distro and check the list of bundles provided by the Kernel
*/
private void readKernelBundles() throws ArtifactResolutionException, ArtifactNotFoundException, MojoExecutionException,
ZipException, IOException, DependencyTreeBuilderException {
final Collection<Artifact> kernelArtifacts;
if (kernelVersion == null) {
getLog().info("Step 1: Building list of provided bundle exports");
kernelArtifacts = new HashSet<Artifact>();
DependencyNode tree = dependencyTreeBuilder.buildDependencyTree(project, localRepo, factory, artifactMetadataSource, new ArtifactFilter() {
public boolean include(Artifact artifact) {
return true;
}
}, new DefaultArtifactCollector());
tree.accept(new DependencyNodeVisitor() {
public boolean endVisit(DependencyNode node) {
// we want the next sibling too
return true;
}
public boolean visit(DependencyNode node) {
if (node.getState() != DependencyNode.OMITTED_FOR_CONFLICT) {
Artifact artifact = node.getArtifact();
if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !artifact.getType().equals("pom")) {
kernelArtifacts.add(artifact);
}
}
// we want the children too
return true;
}
});
} else {
getLog().info("Step 1 : Building list of kernel exports");
getLog().warn("Use of 'kernelVersion' is deprecated -- use a dependency with scope 'provided' instead");
- Artifact kernel = factory.createArtifact("org.apache.servicemix.kernel", "apache-servicemix-kernel", kernelVersion, Artifact.SCOPE_PROVIDED, "pom");
+ Artifact kernel = factory.createArtifact("org.apache.felix.karaf", "apache-felix-karaf", kernelVersion, Artifact.SCOPE_PROVIDED, "pom");
resolver.resolve(kernel, remoteRepos, localRepo);
kernelArtifacts = getDependencies(kernel);
}
for (Artifact artifact : kernelArtifacts) {
registerKernelBundle(artifact);
}
getLog().info("...done!");
}
private void registerKernelBundle(Artifact artifact) throws ArtifactResolutionException, ArtifactNotFoundException, ZipException,
IOException {
Manifest manifest = getManifest(artifact);
if (manifest.getExports() != null) {
for (ManifestEntry entry : (List<ManifestEntry>)manifest.getExports()) {
kernelExports.put(entry.getName(), entry.getVersion());
getLog().debug(" adding kernel export " + entry.getName() + " (" + entry.getVersion() + ")");
}
}
registerBundle(artifact);
}
/*
* Read the list of bundles we can use to satisfy links
*/
private void readBundles() throws IOException, ArtifactResolutionException, ArtifactNotFoundException {
BufferedReader reader = null;
try {
if (bundles != null) {
getLog().info("Step 2 : Building a list of exports for bundles in " + bundles.getAbsolutePath());
reader = new BufferedReader(new FileReader(bundles));
String line = reader.readLine();
while (line != null) {
if (line.contains("/") && !line.startsWith("#")) {
String[] elements = line.split("/");
Artifact artifact = factory.createArtifact(elements[0], elements[1], elements[2], Artifact.SCOPE_PROVIDED,
elements[3]);
registerBundle(artifact);
}
line = reader.readLine();
}
} else {
getLog().info("Step 2 : No Bundle file supplied for building list of exports");
}
} finally {
if (reader != null) {
reader.close();
}
}
getLog().info("...done!");
}
/*
* Auto-discover bundles currently in the dependencies
*/
private void discoverBundles() throws ArtifactResolutionException, ArtifactNotFoundException, ZipException, IOException {
getLog().info("Step 3 : Discovering bundles in Maven dependencies");
for (Artifact dependency : (Set<Artifact>) project.getArtifacts()) {
// we will generate a feature for this afterwards
if (project.getDependencyArtifacts().contains(dependency)) {
continue;
}
// this is a provided bundle, has been handled in step 1
if (dependency.getScope().equals(Artifact.SCOPE_PROVIDED)) {
continue;
}
if (isDiscoverableBundle(dependency)) {
getLog().info(" Discovered " + dependency);
registerBundle(dependency);
}
}
getLog().info("...done!");
}
/*
* Write all project dependencies as feature
*/
private void writeFeatures(PrintStream out) throws ArtifactResolutionException, ArtifactNotFoundException,
ZipException, IOException {
getLog().info("Step 4 : Generating " + outputFile.getAbsolutePath());
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<features>");
Set<Artifact> dependencies = (Set<Artifact>)project.getDependencyArtifacts();
for (Artifact artifact : dependencies) {
if (!artifact.getScope().equals(Artifact.SCOPE_PROVIDED) && !artifact.getType().equals("pom")) {
getLog().info(" Generating feature " + artifact.getArtifactId() + " from " + artifact);
Feature feature = getFeature(artifact);
feature.write(out);
registerFeature(artifact, feature);
}
}
out.println("</features>");
getLog().info("...done!");
}
/*
* Get the feature for an artifact
*/
private Feature getFeature(Artifact artifact) throws ArtifactResolutionException, ArtifactNotFoundException, ZipException, IOException {
Feature feature = new Feature(artifact);
addRequirements(artifact, feature);
return feature;
}
/*
* Only auto-discover an OSGi bundle
* - if it is not already known as a feature itself
* - if it is not another version of an already known bundle
*/
private boolean isDiscoverableBundle(Artifact artifact) {
if (isBundle(artifact) && !isFeature(artifact) && !artifact.getScope().equals(Artifact.SCOPE_PROVIDED)) {
for (String known : knownBundles) {
String[] elements = known.split("/");
if (artifact.getGroupId().equals(elements[0]) &&
artifact.getArtifactId().equals(elements[1])) {
getLog().debug(String.format(" Avoid auto-discovery for %s because of existing bundle %s",
toString(artifact), known));
return false;
}
}
return true;
}
return false;
}
/*
* Check if the given artifact is a bundle
*/
private boolean isBundle(Artifact artifact) {
if (knownBundles.contains(toString(artifact)) || artifact.getArtifactHandler().getPackaging().equals("bundle")) {
return true;
} else {
try {
Manifest manifest = getManifest(artifact);
if (manifest.getBsn() != null) {
getLog().debug(String.format("MANIFEST.MF for '%s' contains Bundle-Name '%s'",
artifact, manifest.getBsn().getName()));
return true;
}
} catch (ZipException e) {
getLog().debug("Unable to determine if " + artifact + " is a bundle; defaulting to false", e);
} catch (IOException e) {
getLog().debug("Unable to determine if " + artifact + " is a bundle; defaulting to false", e);
} catch (Exception e) {
getLog().debug("Unable to determine if " + artifact + " is a bundle; defaulting to false", e);
}
}
return false;
}
/*
* Add requirements for an artifact to a feature
*/
private void addRequirements(Artifact artifact, Feature feature) throws ArtifactResolutionException, ArtifactNotFoundException, ZipException, IOException {
Manifest manifest = getManifest(artifact);
Collection<ManifestEntry> remaining = getRemainingImports(manifest);
Artifact previous = null;
for (ManifestEntry entry : remaining) {
Artifact add = null;
Map<VersionRange, Artifact> versions = bundleExports.get(entry.getName());
if (versions != null) {
for (VersionRange range : versions.keySet()) {
add = versions.get(range);
if (range.compareTo(entry.getVersion()) == 0) {
add = versions.get(range);
}
}
}
if (add == null) {
if (isOptional(entry)) {
// debug logging for optional dependency...
getLog().debug(String.format(" Unable to find suitable bundle for optional dependency %s (%s)",
entry.getName(), entry.getVersion()));
} else {
// ...but a warning for a mandatory dependency
getLog().warn(
String.format(" Unable to find suitable bundle for dependency %s (%s) (required by %s)",
entry.getName(), entry.getVersion(), artifact.getArtifactId()));
}
} else {
if (!add.equals(previous) && feature.push(add) && !isFeature(add)) {
//and get requirements for the bundle we just added
getLog().debug(" Getting requirements for " + add);
addRequirements(add, feature);
}
}
previous = add;
}
}
/*
* Check if a given bundle is itself being generated as a feature
*/
private boolean isFeature(Artifact artifact) {
return features.containsKey(artifact);
}
/*
* Check a manifest entry and check if the resolution for the import has been marked as optional
*/
private boolean isOptional(ManifestEntry entry) {
return entry.getAttributes() != null && entry.getAttributes().get("resolution:") != null
&& entry.getAttributes().get("resolution:").equals("optional");
}
/*
* Register a bundle, enlisting all packages it provides
*/
private void registerBundle(Artifact artifact) throws ArtifactResolutionException, ArtifactNotFoundException, ZipException,
IOException {
getLog().debug("Registering bundle " + artifact);
knownBundles.add(toString(artifact));
Manifest manifest = getManifest(artifact);
for (ManifestEntry entry : getManifestEntries(manifest.getExports())) {
Map<VersionRange, Artifact> versions = bundleExports.get(entry.getName());
if (versions == null) {
versions = new HashMap<VersionRange, Artifact>();
}
versions.put(entry.getVersion(), artifact);
getLog().debug(String.format(" %s exported by bundle %s", entry.getName(), artifact));
bundleExports.put(entry.getName(), versions);
}
}
/*
* Register a feature and also register the bundle for the feature
*/
private void registerFeature(Artifact artifact, Feature feature) throws ArtifactResolutionException, ArtifactNotFoundException, ZipException,
IOException {
features.put(artifact, feature);
registerBundle(artifact);
}
/*
* Determine the list of imports to be resolved
*/
private Collection<ManifestEntry> getRemainingImports(Manifest manifest) {
// take all imports
Collection<ManifestEntry> input = getManifestEntries(manifest.getImports());
Collection<ManifestEntry> output = new LinkedList<ManifestEntry>(input);
// remove imports satisfied by exports in the same bundle
for (ManifestEntry entry : input) {
for (ManifestEntry export : getManifestEntries(manifest.getExports())) {
if (entry.getName().equals(export.getName())) {
output.remove(entry);
}
}
}
// remove imports for packages exported by the kernel
for (ManifestEntry entry : input) {
for (String export : kernelExports.keySet()) {
if (entry.getName().equals(export)) {
output.remove(entry);
}
}
}
// remove imports for packages exported by the system bundle
for (ManifestEntry entry : input) {
if (systemExports.contains(entry.getName())) {
output.remove(entry);
}
}
return output;
}
private Collection<ManifestEntry> getManifestEntries(List imports) {
if (imports == null) {
return new LinkedList<ManifestEntry>();
} else {
return (Collection<ManifestEntry>)imports;
}
}
private Manifest getManifest(Artifact artifact) throws ArtifactResolutionException, ArtifactNotFoundException, ZipException,
IOException {
File localFile = new File(localRepo.pathOf(artifact));
ZipFile file;
if (localFile.exists()) {
//avoid going over to the repository if the file is already on the disk
file = new ZipFile(localFile);
} else {
resolver.resolve(artifact, remoteRepos, localRepo);
file = new ZipFile(artifact.getFile());
}
return new Manifest(file.getInputStream(file.getEntry("META-INF/MANIFEST.MF")));
}
private List<Artifact> getDependencies(Artifact artifact) {
List<Artifact> list = new ArrayList<Artifact>();
try {
ResolutionGroup pom = artifactMetadataSource.retrieve(artifact, localRepo, remoteRepos);
if (pom != null) {
list.addAll(pom.getArtifacts());
}
} catch (ArtifactMetadataRetrievalException e) {
getLog().warn("Unable to retrieve metadata for " + artifact + ", not including dependencies for it");
} catch (InvalidArtifactRTException e) {
getLog().warn("Unable to retrieve metadata for " + artifact + ", not including dependencies for it");
}
return list;
}
public static String toString(Artifact artifact) {
return String.format("%s/%s/%s", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
}
private class Feature {
private Stack<Artifact> artifacts = new Stack<Artifact>();
private final Artifact artifact;
private Feature(Artifact artifact) {
super();
this.artifact = artifact;
artifacts.push(artifact);
}
public boolean push(Artifact item) {
if (artifacts.contains(item)) {
artifacts.remove(item);
artifacts.push(item);
return false;
}
if (!artifacts.contains(item)) {
artifacts.push(item);
return true;
}
return false;
}
public void write(PrintStream out) {
out.println(" <feature name='" + artifact.getArtifactId() + "' version='"
+ artifact.getBaseVersion() + "'>");
Stack<Artifact> resulting = new Stack<Artifact>();
resulting.addAll(artifacts);
// remove dependencies for included features
for (Artifact next : artifacts) {
if (isFeature(next)) {
resulting.removeAll(features.get(next).getDependencies());
}
}
while (!resulting.isEmpty()) {
Artifact next = resulting.pop();
if (isFeature(next)) {
out.println(" <feature version='"
+ next.getBaseVersion() + "'>" + String.format("%s</feature>", next.getArtifactId()));
} else {
out.println(String.format(" <bundle>mvn:%s/%s/%s</bundle>",
next.getGroupId(), next.getArtifactId(), next.getBaseVersion()));
}
}
out.println(" </feature>");
}
public List<Artifact> getDependencies() {
List<Artifact> dependencies = new LinkedList<Artifact>(artifacts);
dependencies.remove(artifact);
return dependencies;
}
}
}
| true | true | private void readKernelBundles() throws ArtifactResolutionException, ArtifactNotFoundException, MojoExecutionException,
ZipException, IOException, DependencyTreeBuilderException {
final Collection<Artifact> kernelArtifacts;
if (kernelVersion == null) {
getLog().info("Step 1: Building list of provided bundle exports");
kernelArtifacts = new HashSet<Artifact>();
DependencyNode tree = dependencyTreeBuilder.buildDependencyTree(project, localRepo, factory, artifactMetadataSource, new ArtifactFilter() {
public boolean include(Artifact artifact) {
return true;
}
}, new DefaultArtifactCollector());
tree.accept(new DependencyNodeVisitor() {
public boolean endVisit(DependencyNode node) {
// we want the next sibling too
return true;
}
public boolean visit(DependencyNode node) {
if (node.getState() != DependencyNode.OMITTED_FOR_CONFLICT) {
Artifact artifact = node.getArtifact();
if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !artifact.getType().equals("pom")) {
kernelArtifacts.add(artifact);
}
}
// we want the children too
return true;
}
});
} else {
getLog().info("Step 1 : Building list of kernel exports");
getLog().warn("Use of 'kernelVersion' is deprecated -- use a dependency with scope 'provided' instead");
Artifact kernel = factory.createArtifact("org.apache.servicemix.kernel", "apache-servicemix-kernel", kernelVersion, Artifact.SCOPE_PROVIDED, "pom");
resolver.resolve(kernel, remoteRepos, localRepo);
kernelArtifacts = getDependencies(kernel);
}
for (Artifact artifact : kernelArtifacts) {
registerKernelBundle(artifact);
}
getLog().info("...done!");
}
| private void readKernelBundles() throws ArtifactResolutionException, ArtifactNotFoundException, MojoExecutionException,
ZipException, IOException, DependencyTreeBuilderException {
final Collection<Artifact> kernelArtifacts;
if (kernelVersion == null) {
getLog().info("Step 1: Building list of provided bundle exports");
kernelArtifacts = new HashSet<Artifact>();
DependencyNode tree = dependencyTreeBuilder.buildDependencyTree(project, localRepo, factory, artifactMetadataSource, new ArtifactFilter() {
public boolean include(Artifact artifact) {
return true;
}
}, new DefaultArtifactCollector());
tree.accept(new DependencyNodeVisitor() {
public boolean endVisit(DependencyNode node) {
// we want the next sibling too
return true;
}
public boolean visit(DependencyNode node) {
if (node.getState() != DependencyNode.OMITTED_FOR_CONFLICT) {
Artifact artifact = node.getArtifact();
if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !artifact.getType().equals("pom")) {
kernelArtifacts.add(artifact);
}
}
// we want the children too
return true;
}
});
} else {
getLog().info("Step 1 : Building list of kernel exports");
getLog().warn("Use of 'kernelVersion' is deprecated -- use a dependency with scope 'provided' instead");
Artifact kernel = factory.createArtifact("org.apache.felix.karaf", "apache-felix-karaf", kernelVersion, Artifact.SCOPE_PROVIDED, "pom");
resolver.resolve(kernel, remoteRepos, localRepo);
kernelArtifacts = getDependencies(kernel);
}
for (Artifact artifact : kernelArtifacts) {
registerKernelBundle(artifact);
}
getLog().info("...done!");
}
|
diff --git a/src/main/java/com/cloudbees/servlet/PostgresqlServlet.java b/src/main/java/com/cloudbees/servlet/PostgresqlServlet.java
index 317a2c9..43451f1 100644
--- a/src/main/java/com/cloudbees/servlet/PostgresqlServlet.java
+++ b/src/main/java/com/cloudbees/servlet/PostgresqlServlet.java
@@ -1,140 +1,140 @@
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
package com.cloudbees.servlet;
import com.cloudbees.entity.Countries;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collection;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
/**
*
* @author harpreet
*/
public class PostgresqlServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
prefixHTML(out);
/*
* TODO output your page here out.println("<html>");
* out.println("<head>"); out.println("<title>Servlet
* HelloJPACloudBees</title>"); out.println("</head>");
* out.println("<body>"); out.println("<h1>Servlet HelloJPACloudBees
* at " + request.getContextPath () + "</h1>");
* out.println("</body>"); out.println("</html>");
*
*
*/
/* Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/postgresql");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select * from countries");
while (rst.next()) {
int id = rst.getInt(1);
String foo = rst.getString(2);
String bar = rst.getString (3);
out.println (id + foo + bar);
}
conn.close();
*/
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PostgresqlPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Query queryAll = em.createNamedQuery("Countries.findAll");
out.println("Getting results");
Collection c = queryAll.getResultList();
out.println("DB Size :" + c.size() + "<br/>");
Iterator iterator = c.iterator();
- postfixHTML(out);
while (iterator.hasNext()) {
Countries country = (Countries) iterator.next();
out.println("<b>" + country.getCaptial() + "</b> is the capital of " + country.getCountry() + "<br/>");
}
} catch (Exception e) {
out.println(e.toString());
} finally {
+ postfixHTML(out);
out.close();
}
}
void prefixHTML(PrintWriter out) {
out.println("<html><head><title>Hello JPA CloudBees</title></head><body>");
}
void postfixHTML(PrintWriter out) {
out.println("</body></html>");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
prefixHTML(out);
/*
* TODO output your page here out.println("<html>");
* out.println("<head>"); out.println("<title>Servlet
* HelloJPACloudBees</title>"); out.println("</head>");
* out.println("<body>"); out.println("<h1>Servlet HelloJPACloudBees
* at " + request.getContextPath () + "</h1>");
* out.println("</body>"); out.println("</html>");
*
*
*/
/* Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/postgresql");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select * from countries");
while (rst.next()) {
int id = rst.getInt(1);
String foo = rst.getString(2);
String bar = rst.getString (3);
out.println (id + foo + bar);
}
conn.close();
*/
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PostgresqlPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Query queryAll = em.createNamedQuery("Countries.findAll");
out.println("Getting results");
Collection c = queryAll.getResultList();
out.println("DB Size :" + c.size() + "<br/>");
Iterator iterator = c.iterator();
postfixHTML(out);
while (iterator.hasNext()) {
Countries country = (Countries) iterator.next();
out.println("<b>" + country.getCaptial() + "</b> is the capital of " + country.getCountry() + "<br/>");
}
} catch (Exception e) {
out.println(e.toString());
} finally {
out.close();
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
prefixHTML(out);
/*
* TODO output your page here out.println("<html>");
* out.println("<head>"); out.println("<title>Servlet
* HelloJPACloudBees</title>"); out.println("</head>");
* out.println("<body>"); out.println("<h1>Servlet HelloJPACloudBees
* at " + request.getContextPath () + "</h1>");
* out.println("</body>"); out.println("</html>");
*
*
*/
/* Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/postgresql");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select * from countries");
while (rst.next()) {
int id = rst.getInt(1);
String foo = rst.getString(2);
String bar = rst.getString (3);
out.println (id + foo + bar);
}
conn.close();
*/
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PostgresqlPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Query queryAll = em.createNamedQuery("Countries.findAll");
out.println("Getting results");
Collection c = queryAll.getResultList();
out.println("DB Size :" + c.size() + "<br/>");
Iterator iterator = c.iterator();
while (iterator.hasNext()) {
Countries country = (Countries) iterator.next();
out.println("<b>" + country.getCaptial() + "</b> is the capital of " + country.getCountry() + "<br/>");
}
} catch (Exception e) {
out.println(e.toString());
} finally {
postfixHTML(out);
out.close();
}
}
|
diff --git a/WarpSuite/src/com/mrz/dyndns/server/warpsuite/commands/GoPlayersOwnWarp.java b/WarpSuite/src/com/mrz/dyndns/server/warpsuite/commands/GoPlayersOwnWarp.java
index 3bdc89c..871cf3d 100644
--- a/WarpSuite/src/com/mrz/dyndns/server/warpsuite/commands/GoPlayersOwnWarp.java
+++ b/WarpSuite/src/com/mrz/dyndns/server/warpsuite/commands/GoPlayersOwnWarp.java
@@ -1,91 +1,91 @@
package com.mrz.dyndns.server.warpsuite.commands;
import static com.mrz.dyndns.server.warpsuite.util.Coloring.*;
import java.util.List;
import com.mrz.dyndns.server.warpsuite.WarpSuite;
import com.mrz.dyndns.server.warpsuite.WarpSuitePlayer;
import com.mrz.dyndns.server.warpsuite.permissions.Permissions;
import com.mrz.dyndns.server.warpsuite.util.Config;
import com.mrz.dyndns.server.warpsuite.util.SimpleLocation;
import com.mrz.dyndns.server.warpsuite.util.Util;
public class GoPlayersOwnWarp extends WarpSuiteCommand
{
public GoPlayersOwnWarp(WarpSuite plugin)
{
super(plugin);
}
@Override
public boolean warpPlayerExecute(final WarpSuitePlayer player, List<String> args, List<String> variables)
{
- if(!Permissions.WARP.check(player) || !Permissions.HELP.check(player))
+ if(!Permissions.WARP.check(player) && !Permissions.HELP.check(player))
{
return Util.invalidPermissions(player);
}
if(args.size() == 0)
{
player.sendMessage(NEGATIVE_PRIMARY + "Invalid usage!" + POSITIVE_PRIMARY + " Correct usage: " + USAGE + "/warp " + USAGE_ARGUMENT + " [warpName]");
if(Permissions.HELP.check(player))
{
player.sendMessage(POSITIVE_PRIMARY + "Or, if you want to view all of the warp help, issue " + USAGE + "/warp help");
}
return true;
}
String warpName = args.get(0);
if(player.getWarpManager().warpIsSet(warpName))
{
final SimpleLocation sLoc = player.getWarpManager().loadWarp(warpName);
boolean canGoToWorld = sLoc.tryLoad(plugin);
if(canGoToWorld)
{
//it is time to teleport!
if(Permissions.DELAY_BYPASS.check(player) || !Util.areTherePlayersInRadius(player))
{
player.teleport(plugin, sLoc);
return true;
}
else
{
Util.sendYouWillBeWarpedMessage(player);
plugin.getPendingWarpManager().addPlayer(player.getName());
plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run()
{
if(plugin.getPendingWarpManager().isWaitingToTeleport(player.getName()))
{
plugin.getPendingWarpManager().removePlayer(player.getName());
player.teleport(plugin, sLoc);
}
}
}, Config.timer * 20L);
return true;
}
}
else
{
player.sendMessage(NEGATIVE_PRIMARY + "The world warp \'" + NEGATIVE_SECONDARY + "\' is located in either no longer exists, or isn't loaded");
return true;
}
}
else
{
player.sendMessage(NEGATIVE_PRIMARY + "Warp \'" + NEGATIVE_SECONDARY + warpName + NEGATIVE_PRIMARY + "\' is not set!");
return true;
}
}
@Override
public String getUsage()
{
//I'll do this myself above (see line (around) 25)
return null;
}
}
| true | true | public boolean warpPlayerExecute(final WarpSuitePlayer player, List<String> args, List<String> variables)
{
if(!Permissions.WARP.check(player) || !Permissions.HELP.check(player))
{
return Util.invalidPermissions(player);
}
if(args.size() == 0)
{
player.sendMessage(NEGATIVE_PRIMARY + "Invalid usage!" + POSITIVE_PRIMARY + " Correct usage: " + USAGE + "/warp " + USAGE_ARGUMENT + " [warpName]");
if(Permissions.HELP.check(player))
{
player.sendMessage(POSITIVE_PRIMARY + "Or, if you want to view all of the warp help, issue " + USAGE + "/warp help");
}
return true;
}
String warpName = args.get(0);
if(player.getWarpManager().warpIsSet(warpName))
{
final SimpleLocation sLoc = player.getWarpManager().loadWarp(warpName);
boolean canGoToWorld = sLoc.tryLoad(plugin);
if(canGoToWorld)
{
//it is time to teleport!
if(Permissions.DELAY_BYPASS.check(player) || !Util.areTherePlayersInRadius(player))
{
player.teleport(plugin, sLoc);
return true;
}
else
{
Util.sendYouWillBeWarpedMessage(player);
plugin.getPendingWarpManager().addPlayer(player.getName());
plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run()
{
if(plugin.getPendingWarpManager().isWaitingToTeleport(player.getName()))
{
plugin.getPendingWarpManager().removePlayer(player.getName());
player.teleport(plugin, sLoc);
}
}
}, Config.timer * 20L);
return true;
}
}
else
{
player.sendMessage(NEGATIVE_PRIMARY + "The world warp \'" + NEGATIVE_SECONDARY + "\' is located in either no longer exists, or isn't loaded");
return true;
}
}
else
{
player.sendMessage(NEGATIVE_PRIMARY + "Warp \'" + NEGATIVE_SECONDARY + warpName + NEGATIVE_PRIMARY + "\' is not set!");
return true;
}
}
| public boolean warpPlayerExecute(final WarpSuitePlayer player, List<String> args, List<String> variables)
{
if(!Permissions.WARP.check(player) && !Permissions.HELP.check(player))
{
return Util.invalidPermissions(player);
}
if(args.size() == 0)
{
player.sendMessage(NEGATIVE_PRIMARY + "Invalid usage!" + POSITIVE_PRIMARY + " Correct usage: " + USAGE + "/warp " + USAGE_ARGUMENT + " [warpName]");
if(Permissions.HELP.check(player))
{
player.sendMessage(POSITIVE_PRIMARY + "Or, if you want to view all of the warp help, issue " + USAGE + "/warp help");
}
return true;
}
String warpName = args.get(0);
if(player.getWarpManager().warpIsSet(warpName))
{
final SimpleLocation sLoc = player.getWarpManager().loadWarp(warpName);
boolean canGoToWorld = sLoc.tryLoad(plugin);
if(canGoToWorld)
{
//it is time to teleport!
if(Permissions.DELAY_BYPASS.check(player) || !Util.areTherePlayersInRadius(player))
{
player.teleport(plugin, sLoc);
return true;
}
else
{
Util.sendYouWillBeWarpedMessage(player);
plugin.getPendingWarpManager().addPlayer(player.getName());
plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run()
{
if(plugin.getPendingWarpManager().isWaitingToTeleport(player.getName()))
{
plugin.getPendingWarpManager().removePlayer(player.getName());
player.teleport(plugin, sLoc);
}
}
}, Config.timer * 20L);
return true;
}
}
else
{
player.sendMessage(NEGATIVE_PRIMARY + "The world warp \'" + NEGATIVE_SECONDARY + "\' is located in either no longer exists, or isn't loaded");
return true;
}
}
else
{
player.sendMessage(NEGATIVE_PRIMARY + "Warp \'" + NEGATIVE_SECONDARY + warpName + NEGATIVE_PRIMARY + "\' is not set!");
return true;
}
}
|
diff --git a/java-api/src/main/java/com/dubture/getcomposer/core/entities/JsonValue.java b/java-api/src/main/java/com/dubture/getcomposer/core/entities/JsonValue.java
index 0884a74..52d4453 100755
--- a/java-api/src/main/java/com/dubture/getcomposer/core/entities/JsonValue.java
+++ b/java-api/src/main/java/com/dubture/getcomposer/core/entities/JsonValue.java
@@ -1,174 +1,180 @@
package com.dubture.getcomposer.core.entities;
import java.lang.reflect.Type;
import java.util.LinkedList;
import com.dubture.getcomposer.core.collection.JsonArray;
import com.dubture.getcomposer.core.objects.JsonObject;
public class JsonValue {
private Object value;
public JsonValue(Object value) {
this.value = value;
}
public Object toJsonValue() {
if (isArray()) {
+ if (getAsArray().size() == 0) {
+ return null;
+ }
return getAsArray().prepareJson(new LinkedList<String>());
- } else if(isObject()) {
+ } else if (isObject()) {
+ if (getAsObject().size() == 0) {
+ return null;
+ }
return getAsObject().prepareJson(new LinkedList<String>());
- } else if(isNumber()) {
+ } else if (isNumber()) {
return getAsNumber();
- } else if(isBoolean()) {
+ } else if (isBoolean()) {
return getAsBoolean();
} else {
return getAsString();
}
}
/**
* Returns whether the value is instance of the given type.
*
* @param type the type
* @return <ul>
* <li><code>true</code> property is instance of type</li>
* <li><code>false</code> property is not an instance of type</li>
* </ul>
*/
public boolean is(Type type) {
return value.getClass().isAssignableFrom((Class<?>) type);
}
/**
* Returns whether the value is instance of an array.
*
* @see #getAsArray
* @return <ul>
* <li><code>true</code> property is an array</li>
* <li><code>false</code> property is not an array</li>
* </ul>
*/
public boolean isArray() {
return value instanceof JsonArray;
}
/**
* Returns whether the property is instance of an entity.
*
* @see #getAsEntity
* @return <ul>
* <li><code>true</code> property is an entity</li>
* <li><code>false</code> property is not an entity</li>
* </ul>
*/
public boolean isObject() {
return value instanceof JsonObject;
}
/**
* Returns whether the property is a boolean.
*
* @return <ul>
* <li><code>true</code> property is a boolean</li>
* <li><code>false</code> property is not a boolean</li>
* </ul>
*/
public boolean isBoolean() {
return value instanceof Boolean;
}
/**
* Returns whether the property is a number.
*
* @return <ul>
* <li><code>true</code> property is a number</li>
* <li><code>false</code> property is not a number</li>
* </ul>
*/
public boolean isNumber() {
return value instanceof Number;
}
/**
* Returns the value.
*
* @return the value
*/
public Object getAsRaw() {
return value;
}
/**
* Returns the value as array.
*
* @return the value
*/
public JsonArray getAsArray() {
return (JsonArray)value;
}
/**
* Returns the value as string.
*
* @return the value as string
*/
public String getAsString() {
return (String)value;
}
/**
* Returns the value as boolean.
*
* @return the value as boolean
*/
public Boolean getAsBoolean() {
if (value instanceof String) {
return Boolean.parseBoolean((String)value);
}
return (Boolean)value;
}
/**
* Returns the value as integer.
*
* @return the value as integer
*/
public Integer getAsInteger() {
if (value instanceof String) {
return Integer.valueOf((String)value);
} else if (value instanceof Long) {
return ((Long)value).intValue();
}
return (Integer)value;
}
/**
* Returns the value as float.
*
* @return the value as float
*/
public Float getAsFloat() {
return Float.valueOf((String)value);
}
/**
* Returns the value as number.
*
* @return the value as number
*/
public Number getAsNumber() {
return (Number)value;
}
/**
* Returns the value as entity.
*
* @return the value as entity
*/
public JsonObject getAsObject() {
return (JsonObject)value;
}
}
| false | true | public Object toJsonValue() {
if (isArray()) {
return getAsArray().prepareJson(new LinkedList<String>());
} else if(isObject()) {
return getAsObject().prepareJson(new LinkedList<String>());
} else if(isNumber()) {
return getAsNumber();
} else if(isBoolean()) {
return getAsBoolean();
} else {
return getAsString();
}
}
| public Object toJsonValue() {
if (isArray()) {
if (getAsArray().size() == 0) {
return null;
}
return getAsArray().prepareJson(new LinkedList<String>());
} else if (isObject()) {
if (getAsObject().size() == 0) {
return null;
}
return getAsObject().prepareJson(new LinkedList<String>());
} else if (isNumber()) {
return getAsNumber();
} else if (isBoolean()) {
return getAsBoolean();
} else {
return getAsString();
}
}
|
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/templates/repository/maven/Maven2ProxyRepositoryTemplate.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/templates/repository/maven/Maven2ProxyRepositoryTemplate.java
index a5697e4d3..67ab04b87 100644
--- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/templates/repository/maven/Maven2ProxyRepositoryTemplate.java
+++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/templates/repository/maven/Maven2ProxyRepositoryTemplate.java
@@ -1,62 +1,62 @@
package org.sonatype.nexus.templates.repository.maven;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.sonatype.nexus.configuration.CoreConfiguration;
import org.sonatype.nexus.configuration.model.CRemoteStorage;
import org.sonatype.nexus.configuration.model.CRepository;
import org.sonatype.nexus.configuration.model.CRepositoryCoreConfiguration;
import org.sonatype.nexus.configuration.model.DefaultCRepository;
import org.sonatype.nexus.proxy.maven.MavenProxyRepository;
import org.sonatype.nexus.proxy.maven.RepositoryPolicy;
import org.sonatype.nexus.proxy.maven.maven2.M2RepositoryConfiguration;
import org.sonatype.nexus.proxy.maven.maven2.Maven2ContentClass;
import org.sonatype.nexus.proxy.repository.Repository;
import org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage;
import org.sonatype.nexus.templates.repository.DefaultRepositoryTemplateProvider;
public class Maven2ProxyRepositoryTemplate
extends AbstractMavenRepositoryTemplate
{
public Maven2ProxyRepositoryTemplate( DefaultRepositoryTemplateProvider provider, String id, String description,
RepositoryPolicy repositoryPolicy )
{
super( provider, id, description, new Maven2ContentClass(), MavenProxyRepository.class, repositoryPolicy );
}
public M2RepositoryConfiguration getExternalConfiguration()
{
return (M2RepositoryConfiguration) getCoreConfiguration().getExternalConfiguration();
}
@Override
protected CoreConfiguration initCoreConfiguration()
{
CRepository repo = new DefaultCRepository();
repo.setId( "" );
repo.setName( "" );
repo.setProviderRole( Repository.class.getName() );
repo.setProviderHint( "maven2" );
repo.setRemoteStorage( new CRemoteStorage() );
repo.getRemoteStorage().setProvider( CommonsHttpClientRemoteStorage.PROVIDER_STRING );
repo.getRemoteStorage().setUrl( "http://some-remote-repository/repo-root" );
Xpp3Dom ex = new Xpp3Dom( DefaultCRepository.EXTERNAL_CONFIGURATION_NODE_NAME );
repo.setExternalConfiguration( ex );
M2RepositoryConfiguration exConf = new M2RepositoryConfiguration( ex );
exConf.setRepositoryPolicy( getRepositoryPolicy() );
exConf.applyChanges();
repo.externalConfigurationImple = exConf;
repo.setAllowWrite( true );
repo.setNotFoundCacheTTL( 1440 );
- exConf.setArtifactMaxAge( 1440 );
+ exConf.setArtifactMaxAge( -1 );
CRepositoryCoreConfiguration result = new CRepositoryCoreConfiguration( repo );
return result;
}
}
| true | true | protected CoreConfiguration initCoreConfiguration()
{
CRepository repo = new DefaultCRepository();
repo.setId( "" );
repo.setName( "" );
repo.setProviderRole( Repository.class.getName() );
repo.setProviderHint( "maven2" );
repo.setRemoteStorage( new CRemoteStorage() );
repo.getRemoteStorage().setProvider( CommonsHttpClientRemoteStorage.PROVIDER_STRING );
repo.getRemoteStorage().setUrl( "http://some-remote-repository/repo-root" );
Xpp3Dom ex = new Xpp3Dom( DefaultCRepository.EXTERNAL_CONFIGURATION_NODE_NAME );
repo.setExternalConfiguration( ex );
M2RepositoryConfiguration exConf = new M2RepositoryConfiguration( ex );
exConf.setRepositoryPolicy( getRepositoryPolicy() );
exConf.applyChanges();
repo.externalConfigurationImple = exConf;
repo.setAllowWrite( true );
repo.setNotFoundCacheTTL( 1440 );
exConf.setArtifactMaxAge( 1440 );
CRepositoryCoreConfiguration result = new CRepositoryCoreConfiguration( repo );
return result;
}
| protected CoreConfiguration initCoreConfiguration()
{
CRepository repo = new DefaultCRepository();
repo.setId( "" );
repo.setName( "" );
repo.setProviderRole( Repository.class.getName() );
repo.setProviderHint( "maven2" );
repo.setRemoteStorage( new CRemoteStorage() );
repo.getRemoteStorage().setProvider( CommonsHttpClientRemoteStorage.PROVIDER_STRING );
repo.getRemoteStorage().setUrl( "http://some-remote-repository/repo-root" );
Xpp3Dom ex = new Xpp3Dom( DefaultCRepository.EXTERNAL_CONFIGURATION_NODE_NAME );
repo.setExternalConfiguration( ex );
M2RepositoryConfiguration exConf = new M2RepositoryConfiguration( ex );
exConf.setRepositoryPolicy( getRepositoryPolicy() );
exConf.applyChanges();
repo.externalConfigurationImple = exConf;
repo.setAllowWrite( true );
repo.setNotFoundCacheTTL( 1440 );
exConf.setArtifactMaxAge( -1 );
CRepositoryCoreConfiguration result = new CRepositoryCoreConfiguration( repo );
return result;
}
|
diff --git a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java
index 4c68467a2..fa1b86465 100644
--- a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java
+++ b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/MigrationHandler.java
@@ -1,122 +1,122 @@
package org.apache.ode.bpel.engine.migration;
import org.apache.ode.bpel.engine.Contexts;
import org.apache.ode.bpel.engine.BpelDatabase;
import org.apache.ode.bpel.engine.BpelProcess;
import org.apache.ode.bpel.dao.BpelDAOConnection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.*;
import java.util.*;
import java.util.concurrent.Callable;
/**
* Checks database schema versions and migrates when necessary.
*/
public class MigrationHandler {
private static final Log __log = LogFactory.getLog(MigrationHandler.class);
public static final int CURRENT_SCHEMA_VERSION = 3;
private Contexts _contexts;
private List<Object[]> migrations = new ArrayList<Object[]>() {{
add(new Object[] { 2, new CorrelatorsMigration() });
add(new Object[] { 2, new CorrelationKeyMigration() });
add(new Object[] { 3, new CorrelationKeySetMigration() });
}};
public MigrationHandler(Contexts _contexts) {
this._contexts = _contexts;
}
public boolean migrate(final Set<BpelProcess> registeredProcesses) {
if (_contexts.dao.getDataSource() == null) {
__log.debug("No datasource available, stopping migration. Probably running fully in-memory.");
return false;
}
final int version;
try {
version = getDbVersion();
- } catch (Exception e) {
+ } catch (Throwable e) {
__log.info("The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data" +
"from a past version, this message can be safely ignored.");
return false;
}
if (version == -1) {
__log.info("No schema version available from the database, migrations will be skipped.");
return false;
}
try {
boolean success = _contexts.scheduler.execTransaction(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean res = true;
boolean migrated = false;
for (Object[] me : migrations) {
if (((Integer)me[0]) > version) {
__log.debug("Running migration " + me[1]);
res = ((Migration)me[1]).migrate(registeredProcesses, _contexts.dao.getConnection()) && res;
migrated = true;
}
}
if (!res) _contexts.scheduler.setRollbackOnly();
else if (migrated) setDbVersion(CURRENT_SCHEMA_VERSION);
return res;
}
});
return success;
} catch (Exception e) {
__log.error("An error occured while migrating your database to a newer version of ODE, changes have " +
"been aborted", e);
throw new RuntimeException(e);
}
}
private int getDbVersion() {
int version = -1;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = _contexts.dao.getDataSource().getConnection();
stmt = conn.prepareStatement("SELECT VERSION FROM ODE_SCHEMA_VERSION");
rs = stmt.executeQuery();
if (rs.next()) version = rs.getInt("VERSION");
} catch (Exception e) {
// Swallow, we'll just abort based on the version number
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return version;
}
private void setDbVersion(int version) {
Connection conn = null;
Statement stmt = null;
try {
conn = _contexts.dao.getDataSource().getConnection();
stmt = conn.createStatement();
int res = stmt.executeUpdate("UPDATE ODE_SCHEMA_VERSION SET VERSION = " + version);
// This should never happen but who knows?
if (res == 0) throw new RuntimeException("Couldn't update schema version.");
} catch (Exception e) {
// Swallow, we'll just abort based on the version number
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
| true | true | public boolean migrate(final Set<BpelProcess> registeredProcesses) {
if (_contexts.dao.getDataSource() == null) {
__log.debug("No datasource available, stopping migration. Probably running fully in-memory.");
return false;
}
final int version;
try {
version = getDbVersion();
} catch (Exception e) {
__log.info("The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data" +
"from a past version, this message can be safely ignored.");
return false;
}
if (version == -1) {
__log.info("No schema version available from the database, migrations will be skipped.");
return false;
}
try {
boolean success = _contexts.scheduler.execTransaction(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean res = true;
boolean migrated = false;
for (Object[] me : migrations) {
if (((Integer)me[0]) > version) {
__log.debug("Running migration " + me[1]);
res = ((Migration)me[1]).migrate(registeredProcesses, _contexts.dao.getConnection()) && res;
migrated = true;
}
}
if (!res) _contexts.scheduler.setRollbackOnly();
else if (migrated) setDbVersion(CURRENT_SCHEMA_VERSION);
return res;
}
});
return success;
} catch (Exception e) {
__log.error("An error occured while migrating your database to a newer version of ODE, changes have " +
"been aborted", e);
throw new RuntimeException(e);
}
}
| public boolean migrate(final Set<BpelProcess> registeredProcesses) {
if (_contexts.dao.getDataSource() == null) {
__log.debug("No datasource available, stopping migration. Probably running fully in-memory.");
return false;
}
final int version;
try {
version = getDbVersion();
} catch (Throwable e) {
__log.info("The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data" +
"from a past version, this message can be safely ignored.");
return false;
}
if (version == -1) {
__log.info("No schema version available from the database, migrations will be skipped.");
return false;
}
try {
boolean success = _contexts.scheduler.execTransaction(new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean res = true;
boolean migrated = false;
for (Object[] me : migrations) {
if (((Integer)me[0]) > version) {
__log.debug("Running migration " + me[1]);
res = ((Migration)me[1]).migrate(registeredProcesses, _contexts.dao.getConnection()) && res;
migrated = true;
}
}
if (!res) _contexts.scheduler.setRollbackOnly();
else if (migrated) setDbVersion(CURRENT_SCHEMA_VERSION);
return res;
}
});
return success;
} catch (Exception e) {
__log.error("An error occured while migrating your database to a newer version of ODE, changes have " +
"been aborted", e);
throw new RuntimeException(e);
}
}
|
diff --git a/src/com/era7/bioinfo/annotation/gb/ExportGenBankFiles.java b/src/com/era7/bioinfo/annotation/gb/ExportGenBankFiles.java
index 951f537..c728310 100644
--- a/src/com/era7/bioinfo/annotation/gb/ExportGenBankFiles.java
+++ b/src/com/era7/bioinfo/annotation/gb/ExportGenBankFiles.java
@@ -1,700 +1,700 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.era7.bioinfo.annotation.gb;
import com.era7.lib.bioinfo.bioinfoutil.genbank.GBCommon;
import com.era7.lib.bioinfo.bioinfoutil.Executable;
import com.era7.lib.bioinfo.bioinfoutil.model.Feature;
import com.era7.lib.bioinfoxml.Annotation;
import com.era7.lib.bioinfoxml.ContigXML;
import com.era7.lib.bioinfoxml.PredictedGene;
import com.era7.lib.bioinfoxml.PredictedGenes;
import com.era7.lib.bioinfoxml.PredictedRna;
import com.era7.lib.bioinfoxml.PredictedRnas;
import com.era7.lib.bioinfoxml.gb.GenBankXML;
import com.era7.lib.era7xmlapi.model.XMLElementException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jdom.Element;
/**
*
* @author Pablo Pareja Tobes <[email protected]>
*/
public class ExportGenBankFiles implements Executable {
public void execute(ArrayList<String> array) {
String[] args = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
args[i] = array.get(i);
}
main(args);
}
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("This program expects 4 parameters: \n"
+ "1. Gene annotation XML result filename \n"
+ "2. Contig external general info XML filename\n"
+ "3. FNA file with both header and contig sequence\n"
+ "4. Prefix string for output files\n");
} else {
String annotationFileString = args[0];
String genBankXmlFileString = args[1];
String fnaContigFileString = args[2];
String outFileString = args[3];
File annotationFile = new File(annotationFileString);
File fnaContigFile = new File(fnaContigFileString);
File genBankXmlFile = new File(genBankXmlFileString);
File mainOutFile = new File(args[3] + GBCommon.GEN_BANK_FILE_EXTENSION);
File allContigsFile = new File(args[3] + "_all" + GBCommon.GEN_BANK_FILE_EXTENSION);
try {
//---Writer for file containing all gbks together----
BufferedWriter allContigsOutBuff = new BufferedWriter(new FileWriter(allContigsFile));
//-----READING XML FILE WITH ANNOTATION DATA------------
BufferedReader reader = new BufferedReader(new FileReader(annotationFile));
String tempSt;
StringBuilder stBuilder = new StringBuilder();
while ((tempSt = reader.readLine()) != null) {
stBuilder.append(tempSt);
}
//Closing file
reader.close();
Annotation annotation = new Annotation(stBuilder.toString());
//-------------------------------------------------------------
//-----READING GENBANK XML------------
reader = new BufferedReader(new FileReader(genBankXmlFile));
stBuilder.delete(0, stBuilder.length());
while ((tempSt = reader.readLine()) != null) {
stBuilder.append(tempSt);
}
//Closing file
reader.close();
GenBankXML genBankXml = new GenBankXML(stBuilder.toString());
//-------------------------------------------------------------
//-------------PARSING CONTIGS & THEIR SEQUENCES------------------
HashMap<String, String> contigsMap = new HashMap<String, String>();
reader = new BufferedReader(new FileReader(fnaContigFile));
stBuilder.delete(0, stBuilder.length());
String currentContigId = "";
while ((tempSt = reader.readLine()) != null) {
if (tempSt.charAt(0) == '>') {
if (stBuilder.length() > 0) {
contigsMap.put(currentContigId, stBuilder.toString());
stBuilder.delete(0, stBuilder.length());
}
currentContigId = tempSt.substring(1).trim().split(" ")[0].split("\t")[0];
System.out.println("currentContigId = " + currentContigId);
} else {
stBuilder.append(tempSt);
}
}
if (stBuilder.length() > 0) {
contigsMap.put(currentContigId, stBuilder.toString());
}
reader.close();
//-------------------------------------------------------------
List<Element> contigList = annotation.asJDomElement().getChild(PredictedGenes.TAG_NAME).getChildren(ContigXML.TAG_NAME);
List<Element> contigListRna = annotation.asJDomElement().getChild(PredictedRnas.TAG_NAME).getChildren(ContigXML.TAG_NAME);
HashMap<String, ContigXML> contigsRnaMap = new HashMap<String, ContigXML>();
for (Element element : contigListRna) {
ContigXML rnaContig = new ContigXML(element);
contigsRnaMap.put(rnaContig.getId(), rnaContig);
}
//-----------WRITING GENERAL FILE------------------
BufferedWriter mainOutBuff = new BufferedWriter(new FileWriter(mainOutFile));
String linearSt = GBCommon.LINEAR_STR + getWhiteSpaces(2);
if(!genBankXml.getLinear()){
- linearSt += GBCommon.CIRCULAR_STR;
+ linearSt = GBCommon.CIRCULAR_STR;
}
//------------------------------------------------------
//------------------------locus line------------------
mainOutBuff.write(GBCommon.LOCUS_STR
+ getWhiteSpaceIndentationForString(GBCommon.LOCUS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + GBCommon.LOCUS_LINE_SEPARATOR
+ contigsMap.size() + " " + GBCommon.CONTIGS_SIZE_STR + GBCommon.LOCUS_LINE_SEPARATOR
+ GBCommon.DNA_STR + GBCommon.LOCUS_LINE_SEPARATOR
+ linearSt + GBCommon.LOCUS_LINE_SEPARATOR
+ genBankXml.getGenBankDivision() + GBCommon.LOCUS_LINE_SEPARATOR
+ genBankXml.getModificationDate()
+ "\n");
//------------------------------------------------------
//------------------------------------------------------
mainOutBuff.write(GBCommon.DEFINITION_STR
+ getWhiteSpaceIndentationForString(GBCommon.DEFINITION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getDefinition() + "\n");
mainOutBuff.write(GBCommon.ACCESSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.ACCESSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + "\n");
mainOutBuff.write(GBCommon.VERSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.VERSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + ".1" + "\n");
mainOutBuff.write(GBCommon.KEYWORDS_STR
+ getWhiteSpaceIndentationForString(GBCommon.KEYWORDS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getKeywords() + "\n");
mainOutBuff.write(
patatizaEnLineas(GBCommon.COMMENT_STR
+ getWhiteSpaceIndentationForString(GBCommon.COMMENT_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
genBankXml.getComment(),
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
mainOutBuff.write(GBCommon.FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.FEATURES_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "Location/Qualifiers" + "\n");
mainOutBuff.write(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.SOURCE_FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.SOURCE_FEATURES_STR + GBCommon.FIRST_LEVEL_INDENTATION_FEATURES,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "1.." + contigsMap.size() + "\n");
mainOutBuff.write(getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "/organism=\"" + genBankXml.getOrganism() + "\"\n");
Set<String> keySet = contigsMap.keySet();
List<String> keySetList = new ArrayList<String>(keySet);
Collections.sort(keySetList);
String contigsIdsList = "";
for (String string : keySetList) {
contigsIdsList += string + ", ";
}
//I have to get rid of the last comma
contigsIdsList = contigsIdsList.substring(0, contigsIdsList.length() - 1);
System.out.println(contigsIdsList);
mainOutBuff.write(
patatizaEnLineas(GBCommon.WGS_STR
+ getWhiteSpaceIndentationForString(GBCommon.WGS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
contigsIdsList,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
mainOutBuff.close();
//-------------------------------------------------------------
//-----------CONTIGS LOOP-----------------------
//---ordering contigs----
HashMap<String, ContigXML> contigXMLMap = new HashMap<String, ContigXML>();
for (Element elem : contigList) {
ContigXML currentContig = new ContigXML(elem);
contigXMLMap.put(currentContig.getId(), currentContig);
}
Set<String> idsSet = contigXMLMap.keySet();
SortedSet<String> idsSorted = new TreeSet<String>();
idsSorted.addAll(idsSet);
for (String key : idsSorted) {
ContigXML contig = contigXMLMap.get(key);
String mainSequence = contigsMap.get(contig.getId());
//removing the sequence from the map so that afterwards contigs
//with no annotations can be identified
contigsMap.remove(contig.getId());
exportContigToGenBank(contig, genBankXml, outFileString, mainSequence, contigsRnaMap, allContigsOutBuff);
}
System.out.println("There are " + contigsMap.size() + " contigs with no annotations...");
System.out.println("generating their gbk files...");
Set<String> keys = contigsMap.keySet();
for (String tempKey : keys) {
System.out.println("generating file for contig: " + tempKey);
ContigXML currentContig = new ContigXML();
currentContig.setId(tempKey);
String mainSequence = contigsMap.get(currentContig.getId());
exportContigToGenBank(currentContig, genBankXml, outFileString, mainSequence, contigsRnaMap, allContigsOutBuff);
}
//---closing all contigs out buff----
allContigsOutBuff.close();
System.out.println("Gbk files succesfully created! :)");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void exportContigToGenBank(ContigXML currentContig,
GenBankXML genBankXml,
String outFileString,
String mainSequence,
HashMap<String, ContigXML> contigsRnaMap,
BufferedWriter allContigsOutBuff) throws IOException, XMLElementException {
File outFile = new File(outFileString + currentContig.getId() + GBCommon.GEN_BANK_FILE_EXTENSION);
BufferedWriter outBuff = new BufferedWriter(new FileWriter(outFile));
StringBuilder outStringBuilder = new StringBuilder();
//-------------------------locus line-----------------------------------
//in this case the format is a bit more restrictive so we have to write
//words in specific positions paying also attention to their separators
String locusLineSt = "";
locusLineSt += GBCommon.LOCUS_STR + getWhiteSpaces(6);
if (genBankXml.getLocusName().length() > 16) {
locusLineSt += genBankXml.getLocusName().substring(0, 16);
} else {
locusLineSt += genBankXml.getLocusName() + getWhiteSpaces(16 - genBankXml.getLocusName().length());
}
String seqLength = String.valueOf(mainSequence.length());
locusLineSt += getWhiteSpaces(1) + getWhiteSpaces(11 - seqLength.length()) + seqLength;
locusLineSt += getWhiteSpaces(1) + GBCommon.BASE_PAIRS_STR + getWhiteSpaces(1);
if (genBankXml.getStrandedType().length() == 0) {
locusLineSt += getWhiteSpaces(3);
} else {
locusLineSt += genBankXml.getStrandedType();
}
locusLineSt += genBankXml.getDnaType() + getWhiteSpaces(1);
if (genBankXml.getLinear()) {
locusLineSt += GBCommon.LINEAR_STR + getWhiteSpaces(2);
} else {
locusLineSt += GBCommon.CIRCULAR_STR;
}
locusLineSt += getWhiteSpaces(1) + genBankXml.getGenBankDivision() + getWhiteSpaces(1);
locusLineSt += genBankXml.getModificationDate() + "\n";
outStringBuilder.append(locusLineSt);
// outBuff.write(GBCommon.LOCUS_STR
// + getWhiteSpaceIndentationForString(GBCommon.LOCUS_STR,
// GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
// + genBankXml.getLocusName() + GBCommon.LOCUS_LINE_SEPARATOR
// + genBankXml.getSequenceLength() + " "
// + GBCommon.BASE_PAIRS_STR + GBCommon.LOCUS_LINE_SEPARATOR
// + GBCommon.DNA_STR + GBCommon.LOCUS_LINE_SEPARATOR
// + GBCommon.LINEAR_STR + GBCommon.LOCUS_LINE_SEPARATOR
// + genBankXml.getGenBankDivision() + GBCommon.LOCUS_LINE_SEPARATOR
// + genBankXml.getModificationDate()
// + "\n");
outStringBuilder.append((GBCommon.DEFINITION_STR
+ getWhiteSpaceIndentationForString(GBCommon.DEFINITION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getDefinition()
+ ". " + currentContig.getId() + "\n"));
outStringBuilder.append((GBCommon.ACCESSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.ACCESSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ currentContig.getId() + "\n"));
outStringBuilder.append((GBCommon.VERSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.VERSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ currentContig.getId() + ".1" + "\n"));
outStringBuilder.append((GBCommon.KEYWORDS_STR
+ getWhiteSpaceIndentationForString(GBCommon.KEYWORDS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getKeywords() + "\n"));
outStringBuilder.append((GBCommon.SOURCE_STR
+ getWhiteSpaceIndentationForString(GBCommon.SOURCE_STR, GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getOrganism() + "\n"));
outStringBuilder.append(
patatizaEnLineas(GBCommon.FIRST_LEVEL_INDENTATION
+ GBCommon.ORGANISM_STR
+ getWhiteSpaceIndentationForString(GBCommon.FIRST_LEVEL_INDENTATION
+ GBCommon.ORGANISM_STR, GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
genBankXml.getOrganismCompleteTaxonomyLineage() + "\n",
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
outStringBuilder.append((GBCommon.FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.FEATURES_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "Location/Qualifiers" + "\n"));
outStringBuilder.append((GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.SOURCE_FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.SOURCE_FEATURES_STR + GBCommon.FIRST_LEVEL_INDENTATION_FEATURES,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "1.." + mainSequence.length() + "\n"));
outStringBuilder.append((getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "/organism=\"" + genBankXml.getOrganism() + "\"\n"));
//------Hashmap with key = gene/rna id and the value =
//---- respective String exactly as is must be written to the result file---------------------------
HashMap<String, String> genesRnasMixedUpMap = new HashMap<String, String>();
TreeSet<Feature> featuresTreeSet = new TreeSet<Feature>();
//----------------------GENES LOOP----------------------------
List<Element> genesList = currentContig.asJDomElement().getChildren(PredictedGene.TAG_NAME);
for (Element element : genesList) {
PredictedGene gene = new PredictedGene(element);
Feature tempFeature = new Feature();
tempFeature.setId(gene.getId());
if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) {
tempFeature.setBegin(gene.getStartPosition());
tempFeature.setEnd(gene.getEndPosition());
} else {
tempFeature.setBegin(gene.getEndPosition());
tempFeature.setEnd(gene.getStartPosition());
}
featuresTreeSet.add(tempFeature);
genesRnasMixedUpMap.put(gene.getId(), getGeneStringForGenBank(gene));
}
//--------------------------------------------------------------
//Now rnas are added (if there are any) so that everything can be sort afterwards
ContigXML contig = contigsRnaMap.get(currentContig.getId());
if (contig != null) {
List<Element> rnas = contig.asJDomElement().getChildren(PredictedRna.TAG_NAME);
for (Element tempElem : rnas) {
PredictedRna rna = new PredictedRna(tempElem);
Feature tempFeature = new Feature();
tempFeature.setId(rna.getId());
if (rna.getStrand().equals(PredictedGene.POSITIVE_STRAND)) {
tempFeature.setBegin(rna.getStartPosition());
tempFeature.setEnd(rna.getEndPosition());
} else {
tempFeature.setBegin(rna.getEndPosition());
tempFeature.setEnd(rna.getStartPosition());
}
featuresTreeSet.add(tempFeature);
genesRnasMixedUpMap.put(rna.getId(), getRnaStringForGenBank(rna));
}
}
//Once genes & rnas are sorted, we just have to write them
for (Feature f : featuresTreeSet) {
outStringBuilder.append(genesRnasMixedUpMap.get(f.getId()));
}
//--------------ORIGIN-----------------------------------------
outStringBuilder.append((GBCommon.ORIGIN_STR + "\n"));
int maxDigits = 9;
int positionCounter = 1;
int maxBasesPerLine = 60;
int currentBase = 0;
int seqFragmentLength = 10;
// System.out.println("currentContig.getId() = " + currentContig.getId());
// System.out.println("mainSequence.length() = " + mainSequence.length());
// System.out.println(contigsMap.get(currentContig.getId()).length());
for (currentBase = 0; (currentBase + maxBasesPerLine) < mainSequence.length(); positionCounter += maxBasesPerLine) {
String posSt = String.valueOf(positionCounter);
String tempLine = getWhiteSpaces(maxDigits - posSt.length()) + posSt;
for (int i = 1; i <= (maxBasesPerLine / seqFragmentLength); i++) {
tempLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength);
currentBase += seqFragmentLength;
}
outStringBuilder.append((tempLine + "\n"));
}
if (currentBase < mainSequence.length()) {
String posSt = String.valueOf(positionCounter);
String lastLine = getWhiteSpaces(maxDigits - posSt.length()) + posSt;
while (currentBase < mainSequence.length()) {
if ((currentBase + seqFragmentLength) < mainSequence.length()) {
lastLine += " " + mainSequence.substring(currentBase, currentBase + seqFragmentLength);
} else {
lastLine += " " + mainSequence.substring(currentBase, mainSequence.length());
}
currentBase += seqFragmentLength;
}
outStringBuilder.append((lastLine + "\n"));
}
//--------------------------------------------------------------
//--- finally I have to add the string "//" in the last line--
outStringBuilder.append("//\n");
outBuff.write(outStringBuilder.toString());
outBuff.close();
allContigsOutBuff.write(outStringBuilder.toString());
}
private static String getWhiteSpaceIndentationForString(String value,
int numberOfWhiteSpaces) {
int number = numberOfWhiteSpaces - value.length();
if (number <= 0) {
return "";
} else {
return getWhiteSpaces(number);
}
}
private static String getWhiteSpaces(int number) {
String result = "";
for (int i = 0; i < number; i++) {
result += " ";
}
return result;
}
private static String patatizaEnLineas(String header,
String value,
int numberOfWhiteSpacesForIndentation,
boolean putQuotationMarksInTheEnd) {
//value = value.toUpperCase();
String result = "";
result += header;
int lengthWithoutIndentation = GBCommon.LINE_MAX_LENGTH - numberOfWhiteSpacesForIndentation;
if (value.length() < (GBCommon.LINE_MAX_LENGTH - header.length())) {
result += value;
if (putQuotationMarksInTheEnd) {
result += "\"";
}
result += "\n";
} else if (value.length() == (GBCommon.LINE_MAX_LENGTH - header.length())) {
result += value + "\n";
if (putQuotationMarksInTheEnd) {
result += getWhiteSpaces(numberOfWhiteSpacesForIndentation) + "\"\n";
}
} else {
result += value.substring(0, (GBCommon.LINE_MAX_LENGTH - header.length())) + "\n";
value = value.substring((GBCommon.LINE_MAX_LENGTH - header.length()), value.length());
while (value.length() > lengthWithoutIndentation) {
result += getWhiteSpaces(numberOfWhiteSpacesForIndentation)
+ value.substring(0, lengthWithoutIndentation) + "\n";
value = value.substring(lengthWithoutIndentation, value.length());
}
if (value.length() == lengthWithoutIndentation) {
result += getWhiteSpaces(numberOfWhiteSpacesForIndentation)
+ value + "\n";
if (putQuotationMarksInTheEnd) {
result += getWhiteSpaces(numberOfWhiteSpacesForIndentation) + "\"\n";
}
} else {
result += getWhiteSpaces(numberOfWhiteSpacesForIndentation)
+ value;
if (putQuotationMarksInTheEnd) {
result += "\"";
}
result += "\n";
}
}
return result;
}
private static String getGeneStringForGenBank(PredictedGene gene) {
StringBuilder geneStBuilder = new StringBuilder();
boolean negativeStrand = gene.getStrand().equals(PredictedGene.NEGATIVE_STRAND);
String positionsString = "";
if (negativeStrand) {
positionsString += "complement(";
if (!gene.getEndIsCanonical()) {
positionsString += "<";
}
positionsString += gene.getEndPosition() + "..";
if (!gene.getStartIsCanonical()) {
positionsString += ">";
}
positionsString += gene.getStartPosition() + ")";
} else {
if (!gene.getStartIsCanonical()) {
positionsString += "<";
}
positionsString += gene.getStartPosition() + "..";
if (!gene.getEndIsCanonical()) {
positionsString += ">";
}
positionsString += gene.getEndPosition();
}
//gene part
String tempGeneStr = GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.GENE_STR
+ getWhiteSpaceIndentationForString(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.GENE_STR, GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ positionsString + "\n";
geneStBuilder.append(tempGeneStr);
geneStBuilder.append(patatizaEnLineas(
getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES) + "/product=\"",
gene.getProteinNames(),
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES,
true));
String tempCDSString = GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.CDS_STR
+ getWhiteSpaceIndentationForString(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.CDS_STR, GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES);
tempCDSString += positionsString + "\n";
geneStBuilder.append(tempCDSString);
geneStBuilder.append(patatizaEnLineas(
getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES) + "/product=\"",
gene.getProteinNames(),
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES,
true));
if (gene.getProteinSequence() != null) {
if (!gene.getProteinSequence().equals("")) {
geneStBuilder.append(patatizaEnLineas(
getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES) + "/translation=\"",
gene.getProteinSequence(),
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES,
true));
}
}
return geneStBuilder.toString();
}
private static String getRnaStringForGenBank(PredictedRna rna) {
StringBuilder rnaStBuilder = new StringBuilder();
boolean negativeStrand = rna.getStrand().equals(PredictedRna.NEGATIVE_STRAND);
String positionsString = "";
if (negativeStrand) {
positionsString += "complement(";
// if (!rna.getEndIsCanonical()) {
// positionsString += "<";
// }
positionsString += "<" + rna.getEndPosition() + ".." + ">" + rna.getStartPosition();
// if (!rna.getStartIsCanonical()) {
// positionsString += ">";
// }
positionsString += ")";
} else {
// if (!rna.getStartIsCanonical()) {
// positionsString += "<";
// }
positionsString += "<" + rna.getStartPosition() + ".." + ">" + rna.getEndPosition();
// if (!rna.getEndIsCanonical()) {
// positionsString += ">";
// }
}
//gene part
String tempRnaStr = GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.GENE_STR
+ getWhiteSpaceIndentationForString(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.GENE_STR, GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ positionsString + "\n";
rnaStBuilder.append(tempRnaStr);
rnaStBuilder.append(patatizaEnLineas(
getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES) + "/product=\"",
rna.getAnnotationUniprotId().split("\\|")[3],
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES,
true));
String tempRNAString = GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.RNA_STR
+ getWhiteSpaceIndentationForString(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.RNA_STR, GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES);
tempRNAString += positionsString + "\n";
rnaStBuilder.append(tempRNAString);
rnaStBuilder.append(patatizaEnLineas(
getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES) + "/product=\"",
rna.getAnnotationUniprotId().split("\\|")[3],
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES,
true));
// if (rna.getProteinSequence() != null) {
// if (!gene.getProteinSequence().equals("")) {
// geneStBuilder.append(patatizaEnLineas(
// getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES) + "/translation=\"",
// gene.getProteinSequence(),
// GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES,
// true));
// }
// }
return rnaStBuilder.toString();
}
}
| true | true | public static void main(String[] args) {
if (args.length != 4) {
System.out.println("This program expects 4 parameters: \n"
+ "1. Gene annotation XML result filename \n"
+ "2. Contig external general info XML filename\n"
+ "3. FNA file with both header and contig sequence\n"
+ "4. Prefix string for output files\n");
} else {
String annotationFileString = args[0];
String genBankXmlFileString = args[1];
String fnaContigFileString = args[2];
String outFileString = args[3];
File annotationFile = new File(annotationFileString);
File fnaContigFile = new File(fnaContigFileString);
File genBankXmlFile = new File(genBankXmlFileString);
File mainOutFile = new File(args[3] + GBCommon.GEN_BANK_FILE_EXTENSION);
File allContigsFile = new File(args[3] + "_all" + GBCommon.GEN_BANK_FILE_EXTENSION);
try {
//---Writer for file containing all gbks together----
BufferedWriter allContigsOutBuff = new BufferedWriter(new FileWriter(allContigsFile));
//-----READING XML FILE WITH ANNOTATION DATA------------
BufferedReader reader = new BufferedReader(new FileReader(annotationFile));
String tempSt;
StringBuilder stBuilder = new StringBuilder();
while ((tempSt = reader.readLine()) != null) {
stBuilder.append(tempSt);
}
//Closing file
reader.close();
Annotation annotation = new Annotation(stBuilder.toString());
//-------------------------------------------------------------
//-----READING GENBANK XML------------
reader = new BufferedReader(new FileReader(genBankXmlFile));
stBuilder.delete(0, stBuilder.length());
while ((tempSt = reader.readLine()) != null) {
stBuilder.append(tempSt);
}
//Closing file
reader.close();
GenBankXML genBankXml = new GenBankXML(stBuilder.toString());
//-------------------------------------------------------------
//-------------PARSING CONTIGS & THEIR SEQUENCES------------------
HashMap<String, String> contigsMap = new HashMap<String, String>();
reader = new BufferedReader(new FileReader(fnaContigFile));
stBuilder.delete(0, stBuilder.length());
String currentContigId = "";
while ((tempSt = reader.readLine()) != null) {
if (tempSt.charAt(0) == '>') {
if (stBuilder.length() > 0) {
contigsMap.put(currentContigId, stBuilder.toString());
stBuilder.delete(0, stBuilder.length());
}
currentContigId = tempSt.substring(1).trim().split(" ")[0].split("\t")[0];
System.out.println("currentContigId = " + currentContigId);
} else {
stBuilder.append(tempSt);
}
}
if (stBuilder.length() > 0) {
contigsMap.put(currentContigId, stBuilder.toString());
}
reader.close();
//-------------------------------------------------------------
List<Element> contigList = annotation.asJDomElement().getChild(PredictedGenes.TAG_NAME).getChildren(ContigXML.TAG_NAME);
List<Element> contigListRna = annotation.asJDomElement().getChild(PredictedRnas.TAG_NAME).getChildren(ContigXML.TAG_NAME);
HashMap<String, ContigXML> contigsRnaMap = new HashMap<String, ContigXML>();
for (Element element : contigListRna) {
ContigXML rnaContig = new ContigXML(element);
contigsRnaMap.put(rnaContig.getId(), rnaContig);
}
//-----------WRITING GENERAL FILE------------------
BufferedWriter mainOutBuff = new BufferedWriter(new FileWriter(mainOutFile));
String linearSt = GBCommon.LINEAR_STR + getWhiteSpaces(2);
if(!genBankXml.getLinear()){
linearSt += GBCommon.CIRCULAR_STR;
}
//------------------------------------------------------
//------------------------locus line------------------
mainOutBuff.write(GBCommon.LOCUS_STR
+ getWhiteSpaceIndentationForString(GBCommon.LOCUS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + GBCommon.LOCUS_LINE_SEPARATOR
+ contigsMap.size() + " " + GBCommon.CONTIGS_SIZE_STR + GBCommon.LOCUS_LINE_SEPARATOR
+ GBCommon.DNA_STR + GBCommon.LOCUS_LINE_SEPARATOR
+ linearSt + GBCommon.LOCUS_LINE_SEPARATOR
+ genBankXml.getGenBankDivision() + GBCommon.LOCUS_LINE_SEPARATOR
+ genBankXml.getModificationDate()
+ "\n");
//------------------------------------------------------
//------------------------------------------------------
mainOutBuff.write(GBCommon.DEFINITION_STR
+ getWhiteSpaceIndentationForString(GBCommon.DEFINITION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getDefinition() + "\n");
mainOutBuff.write(GBCommon.ACCESSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.ACCESSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + "\n");
mainOutBuff.write(GBCommon.VERSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.VERSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + ".1" + "\n");
mainOutBuff.write(GBCommon.KEYWORDS_STR
+ getWhiteSpaceIndentationForString(GBCommon.KEYWORDS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getKeywords() + "\n");
mainOutBuff.write(
patatizaEnLineas(GBCommon.COMMENT_STR
+ getWhiteSpaceIndentationForString(GBCommon.COMMENT_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
genBankXml.getComment(),
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
mainOutBuff.write(GBCommon.FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.FEATURES_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "Location/Qualifiers" + "\n");
mainOutBuff.write(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.SOURCE_FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.SOURCE_FEATURES_STR + GBCommon.FIRST_LEVEL_INDENTATION_FEATURES,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "1.." + contigsMap.size() + "\n");
mainOutBuff.write(getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "/organism=\"" + genBankXml.getOrganism() + "\"\n");
Set<String> keySet = contigsMap.keySet();
List<String> keySetList = new ArrayList<String>(keySet);
Collections.sort(keySetList);
String contigsIdsList = "";
for (String string : keySetList) {
contigsIdsList += string + ", ";
}
//I have to get rid of the last comma
contigsIdsList = contigsIdsList.substring(0, contigsIdsList.length() - 1);
System.out.println(contigsIdsList);
mainOutBuff.write(
patatizaEnLineas(GBCommon.WGS_STR
+ getWhiteSpaceIndentationForString(GBCommon.WGS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
contigsIdsList,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
mainOutBuff.close();
//-------------------------------------------------------------
//-----------CONTIGS LOOP-----------------------
//---ordering contigs----
HashMap<String, ContigXML> contigXMLMap = new HashMap<String, ContigXML>();
for (Element elem : contigList) {
ContigXML currentContig = new ContigXML(elem);
contigXMLMap.put(currentContig.getId(), currentContig);
}
Set<String> idsSet = contigXMLMap.keySet();
SortedSet<String> idsSorted = new TreeSet<String>();
idsSorted.addAll(idsSet);
for (String key : idsSorted) {
ContigXML contig = contigXMLMap.get(key);
String mainSequence = contigsMap.get(contig.getId());
//removing the sequence from the map so that afterwards contigs
//with no annotations can be identified
contigsMap.remove(contig.getId());
exportContigToGenBank(contig, genBankXml, outFileString, mainSequence, contigsRnaMap, allContigsOutBuff);
}
System.out.println("There are " + contigsMap.size() + " contigs with no annotations...");
System.out.println("generating their gbk files...");
Set<String> keys = contigsMap.keySet();
for (String tempKey : keys) {
System.out.println("generating file for contig: " + tempKey);
ContigXML currentContig = new ContigXML();
currentContig.setId(tempKey);
String mainSequence = contigsMap.get(currentContig.getId());
exportContigToGenBank(currentContig, genBankXml, outFileString, mainSequence, contigsRnaMap, allContigsOutBuff);
}
//---closing all contigs out buff----
allContigsOutBuff.close();
System.out.println("Gbk files succesfully created! :)");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
if (args.length != 4) {
System.out.println("This program expects 4 parameters: \n"
+ "1. Gene annotation XML result filename \n"
+ "2. Contig external general info XML filename\n"
+ "3. FNA file with both header and contig sequence\n"
+ "4. Prefix string for output files\n");
} else {
String annotationFileString = args[0];
String genBankXmlFileString = args[1];
String fnaContigFileString = args[2];
String outFileString = args[3];
File annotationFile = new File(annotationFileString);
File fnaContigFile = new File(fnaContigFileString);
File genBankXmlFile = new File(genBankXmlFileString);
File mainOutFile = new File(args[3] + GBCommon.GEN_BANK_FILE_EXTENSION);
File allContigsFile = new File(args[3] + "_all" + GBCommon.GEN_BANK_FILE_EXTENSION);
try {
//---Writer for file containing all gbks together----
BufferedWriter allContigsOutBuff = new BufferedWriter(new FileWriter(allContigsFile));
//-----READING XML FILE WITH ANNOTATION DATA------------
BufferedReader reader = new BufferedReader(new FileReader(annotationFile));
String tempSt;
StringBuilder stBuilder = new StringBuilder();
while ((tempSt = reader.readLine()) != null) {
stBuilder.append(tempSt);
}
//Closing file
reader.close();
Annotation annotation = new Annotation(stBuilder.toString());
//-------------------------------------------------------------
//-----READING GENBANK XML------------
reader = new BufferedReader(new FileReader(genBankXmlFile));
stBuilder.delete(0, stBuilder.length());
while ((tempSt = reader.readLine()) != null) {
stBuilder.append(tempSt);
}
//Closing file
reader.close();
GenBankXML genBankXml = new GenBankXML(stBuilder.toString());
//-------------------------------------------------------------
//-------------PARSING CONTIGS & THEIR SEQUENCES------------------
HashMap<String, String> contigsMap = new HashMap<String, String>();
reader = new BufferedReader(new FileReader(fnaContigFile));
stBuilder.delete(0, stBuilder.length());
String currentContigId = "";
while ((tempSt = reader.readLine()) != null) {
if (tempSt.charAt(0) == '>') {
if (stBuilder.length() > 0) {
contigsMap.put(currentContigId, stBuilder.toString());
stBuilder.delete(0, stBuilder.length());
}
currentContigId = tempSt.substring(1).trim().split(" ")[0].split("\t")[0];
System.out.println("currentContigId = " + currentContigId);
} else {
stBuilder.append(tempSt);
}
}
if (stBuilder.length() > 0) {
contigsMap.put(currentContigId, stBuilder.toString());
}
reader.close();
//-------------------------------------------------------------
List<Element> contigList = annotation.asJDomElement().getChild(PredictedGenes.TAG_NAME).getChildren(ContigXML.TAG_NAME);
List<Element> contigListRna = annotation.asJDomElement().getChild(PredictedRnas.TAG_NAME).getChildren(ContigXML.TAG_NAME);
HashMap<String, ContigXML> contigsRnaMap = new HashMap<String, ContigXML>();
for (Element element : contigListRna) {
ContigXML rnaContig = new ContigXML(element);
contigsRnaMap.put(rnaContig.getId(), rnaContig);
}
//-----------WRITING GENERAL FILE------------------
BufferedWriter mainOutBuff = new BufferedWriter(new FileWriter(mainOutFile));
String linearSt = GBCommon.LINEAR_STR + getWhiteSpaces(2);
if(!genBankXml.getLinear()){
linearSt = GBCommon.CIRCULAR_STR;
}
//------------------------------------------------------
//------------------------locus line------------------
mainOutBuff.write(GBCommon.LOCUS_STR
+ getWhiteSpaceIndentationForString(GBCommon.LOCUS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + GBCommon.LOCUS_LINE_SEPARATOR
+ contigsMap.size() + " " + GBCommon.CONTIGS_SIZE_STR + GBCommon.LOCUS_LINE_SEPARATOR
+ GBCommon.DNA_STR + GBCommon.LOCUS_LINE_SEPARATOR
+ linearSt + GBCommon.LOCUS_LINE_SEPARATOR
+ genBankXml.getGenBankDivision() + GBCommon.LOCUS_LINE_SEPARATOR
+ genBankXml.getModificationDate()
+ "\n");
//------------------------------------------------------
//------------------------------------------------------
mainOutBuff.write(GBCommon.DEFINITION_STR
+ getWhiteSpaceIndentationForString(GBCommon.DEFINITION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getDefinition() + "\n");
mainOutBuff.write(GBCommon.ACCESSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.ACCESSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + "\n");
mainOutBuff.write(GBCommon.VERSION_STR
+ getWhiteSpaceIndentationForString(GBCommon.VERSION_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getLocusName() + ".1" + "\n");
mainOutBuff.write(GBCommon.KEYWORDS_STR
+ getWhiteSpaceIndentationForString(GBCommon.KEYWORDS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION)
+ genBankXml.getKeywords() + "\n");
mainOutBuff.write(
patatizaEnLineas(GBCommon.COMMENT_STR
+ getWhiteSpaceIndentationForString(GBCommon.COMMENT_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
genBankXml.getComment(),
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
mainOutBuff.write(GBCommon.FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.FEATURES_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "Location/Qualifiers" + "\n");
mainOutBuff.write(GBCommon.FIRST_LEVEL_INDENTATION_FEATURES
+ GBCommon.SOURCE_FEATURES_STR
+ getWhiteSpaceIndentationForString(GBCommon.SOURCE_FEATURES_STR + GBCommon.FIRST_LEVEL_INDENTATION_FEATURES,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "1.." + contigsMap.size() + "\n");
mainOutBuff.write(getWhiteSpaces(GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION_FEATURES)
+ "/organism=\"" + genBankXml.getOrganism() + "\"\n");
Set<String> keySet = contigsMap.keySet();
List<String> keySetList = new ArrayList<String>(keySet);
Collections.sort(keySetList);
String contigsIdsList = "";
for (String string : keySetList) {
contigsIdsList += string + ", ";
}
//I have to get rid of the last comma
contigsIdsList = contigsIdsList.substring(0, contigsIdsList.length() - 1);
System.out.println(contigsIdsList);
mainOutBuff.write(
patatizaEnLineas(GBCommon.WGS_STR
+ getWhiteSpaceIndentationForString(GBCommon.WGS_STR,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION),
contigsIdsList,
GBCommon.NUMBER_OF_WHITE_SPACES_FOR_INDENTATION,
false));
mainOutBuff.close();
//-------------------------------------------------------------
//-----------CONTIGS LOOP-----------------------
//---ordering contigs----
HashMap<String, ContigXML> contigXMLMap = new HashMap<String, ContigXML>();
for (Element elem : contigList) {
ContigXML currentContig = new ContigXML(elem);
contigXMLMap.put(currentContig.getId(), currentContig);
}
Set<String> idsSet = contigXMLMap.keySet();
SortedSet<String> idsSorted = new TreeSet<String>();
idsSorted.addAll(idsSet);
for (String key : idsSorted) {
ContigXML contig = contigXMLMap.get(key);
String mainSequence = contigsMap.get(contig.getId());
//removing the sequence from the map so that afterwards contigs
//with no annotations can be identified
contigsMap.remove(contig.getId());
exportContigToGenBank(contig, genBankXml, outFileString, mainSequence, contigsRnaMap, allContigsOutBuff);
}
System.out.println("There are " + contigsMap.size() + " contigs with no annotations...");
System.out.println("generating their gbk files...");
Set<String> keys = contigsMap.keySet();
for (String tempKey : keys) {
System.out.println("generating file for contig: " + tempKey);
ContigXML currentContig = new ContigXML();
currentContig.setId(tempKey);
String mainSequence = contigsMap.get(currentContig.getId());
exportContigToGenBank(currentContig, genBankXml, outFileString, mainSequence, contigsRnaMap, allContigsOutBuff);
}
//---closing all contigs out buff----
allContigsOutBuff.close();
System.out.println("Gbk files succesfully created! :)");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
diff --git a/src/org/newdawn/slick/state/StateBasedGame.java b/src/org/newdawn/slick/state/StateBasedGame.java
index 75b6a28..9963630 100644
--- a/src/org/newdawn/slick/state/StateBasedGame.java
+++ b/src/org/newdawn/slick/state/StateBasedGame.java
@@ -1,444 +1,444 @@
package org.newdawn.slick.state;
import java.util.HashMap;
import java.util.Iterator;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.transition.EmptyTransition;
import org.newdawn.slick.state.transition.Transition;
import org.newdawn.slick.util.Log;
/**
* A state based game isolated different stages of the game (menu, ingame, hiscores, etc) into
* different states so they can be easily managed and maintained.
*
* @author kevin
*/
public abstract class StateBasedGame implements Game {
/** The list of states making up this game */
private HashMap states = new HashMap();
/** The current state */
private GameState currentState;
/** The next state we're moving into */
private GameState nextState;
/** The container holding this game */
private GameContainer container;
/** The title of the game */
private String title;
/** The transition being used to enter the state */
private Transition enterTransition;
/** The transition being used to leave the state */
private Transition leaveTransition;
/**
* Create a new state based game
*
* @param name The name of the game
*/
public StateBasedGame(String name) {
this.title = name;
currentState = new BasicGameState() {
public int getID() {
return -1;
}
public void init(GameContainer container, StateBasedGame game) throws SlickException {
}
public void render(StateBasedGame game, Graphics g) throws SlickException {
}
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
}
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
}
};
}
/**
* Get the ID of the state the game is currently in
*
* @return The ID of the state the game is currently in
*/
public int getCurrentStateID() {
return currentState.getID();
}
/**
* Get the state the game is currently in
*
* @return The state the game is currently in
*/
public GameState getCurrentState() {
return currentState;
}
/**
* @see org.newdawn.slick.InputListener#setInput(org.newdawn.slick.Input)
*/
public void setInput(Input input) {
}
/**
* Add a state to the game. The state will be updated and maintained
* by the game
*
* @param state The state to be added
*/
public void addState(GameState state) {
states.put(new Integer(state.getID()), state);
if (currentState.getID() == -1) {
currentState = state;
}
}
/**
* Get a state based on it's identifier
*
* @param id The ID of the state to retrieve
* @return The state requested or null if no state with the specified ID exists
*/
public GameState getState(int id) {
return (GameState) states.get(new Integer(id));
}
/**
* Enter a particular game state with no transition
*
* @param id The ID of the state to enter
*/
public void enterState(int id) {
enterState(id, new EmptyTransition(), new EmptyTransition());
}
/**
* Enter a particular game state with no transition
*
* @param id The ID of the state to enter
* @param leave The transition to use when leaving the current state
* @param enter The transition to use when entering the new state
*/
public void enterState(int id, Transition leave, Transition enter) {
if (leave == null) {
leave = new EmptyTransition();
}
if (enter == null) {
enter = new EmptyTransition();
}
leaveTransition = leave;
enterTransition = enter;
nextState = getState(id);
if (nextState == null) {
throw new RuntimeException("No game state registered with the ID: "+id);
}
if (leave == null) {
try {
currentState.leave(container, this);
} catch (SlickException e) {
Log.error(e);
}
}
}
/**
* @see org.newdawn.slick.BasicGame#init(org.newdawn.slick.GameContainer)
*/
public final void init(GameContainer container) throws SlickException {
this.container = container;
initStatesList(container);
Iterator gameStates = states.values().iterator();
while (gameStates.hasNext()) {
GameState state = (GameState) gameStates.next();
state.init(container, this);
}
if (currentState != null) {
currentState.enter(container, this);
}
}
/**
* Initialise the list of states making up this game
*
* @param container The container holding the game
* @throws SlickException Indicates a failure to initialise the state based game resources
*/
public abstract void initStatesList(GameContainer container) throws SlickException;
/**
* @see org.newdawn.slick.Game#render(org.newdawn.slick.GameContainer, org.newdawn.slick.Graphics)
*/
public final void render(GameContainer container, Graphics g) throws SlickException {
if (leaveTransition != null) {
leaveTransition.preRender(this, container, g);
} else if (enterTransition != null) {
enterTransition.preRender(this, container, g);
}
currentState.render(container, this, g);
if (leaveTransition != null) {
leaveTransition.postRender(this, container, g);
} else if (enterTransition != null) {
enterTransition.postRender(this, container, g);
}
}
/**
* @see org.newdawn.slick.BasicGame#update(org.newdawn.slick.GameContainer, int)
*/
public final void update(GameContainer container, int delta) throws SlickException {
if (leaveTransition != null) {
leaveTransition.update(this, container, delta);
if (leaveTransition.isComplete()) {
currentState.leave(container, this);
currentState = nextState;
nextState = null;
leaveTransition = null;
if (enterTransition == null) {
- nextState.enter(container, this);
+ currentState.enter(container, this);
}
} else {
return;
}
}
if (enterTransition != null) {
enterTransition.update(this, container, delta);
if (enterTransition.isComplete()) {
currentState.enter(container, this);
enterTransition = null;
} else {
return;
}
}
currentState.update(container, this, delta);
}
/**
* Check if the game is transitioning between states
*
* @return True if we're transitioning between states
*/
private boolean transitioning() {
return (leaveTransition != null) || (enterTransition != null);
}
/**
* @see org.newdawn.slick.Game#closeRequested()
*/
public boolean closeRequested() {
return true;
}
/**
* @see org.newdawn.slick.Game#getTitle()
*/
public String getTitle() {
return title;
}
/**
* Get the container holding this game
*
* @return The game container holding this game
*/
public GameContainer getContainer() {
return container;
}
/**
* @see org.newdawn.slick.InputListener#controllerButtonPressed(int, int)
*/
public void controllerButtonPressed(int controller, int button) {
if (transitioning()) {
return;
}
currentState.controllerButtonPressed(controller, button);
}
/**
* @see org.newdawn.slick.InputListener#controllerButtonReleased(int, int)
*/
public void controllerButtonReleased(int controller, int button) {
if (transitioning()) {
return;
}
currentState.controllerButtonReleased(controller, button);
}
/**
* @see org.newdawn.slick.InputListener#controllerDownPressed(int)
*/
public void controllerDownPressed(int controller) {
if (transitioning()) {
return;
}
currentState.controllerDownPressed(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerDownReleased(int)
*/
public void controllerDownReleased(int controller) {
if (transitioning()) {
return;
}
currentState.controllerDownPressed(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerLeftPressed(int)
*/
public void controllerLeftPressed(int controller) {
if (transitioning()) {
return;
}
currentState.controllerLeftPressed(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerLeftReleased(int)
*/
public void controllerLeftReleased(int controller) {
if (transitioning()) {
return;
}
currentState.controllerLeftReleased(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerRightPressed(int)
*/
public void controllerRightPressed(int controller) {
if (transitioning()) {
return;
}
currentState.controllerRightPressed(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerRightReleased(int)
*/
public void controllerRightReleased(int controller) {
if (transitioning()) {
return;
}
currentState.controllerRightReleased(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerUpPressed(int)
*/
public void controllerUpPressed(int controller) {
if (transitioning()) {
return;
}
currentState.controllerUpPressed(controller);
}
/**
* @see org.newdawn.slick.InputListener#controllerUpReleased(int)
*/
public void controllerUpReleased(int controller) {
if (transitioning()) {
return;
}
currentState.controllerUpReleased(controller);
}
/**
* @see org.newdawn.slick.InputListener#keyPressed(int, char)
*/
public void keyPressed(int key, char c) {
if (transitioning()) {
return;
}
currentState.keyPressed(key, c);
}
/**
* @see org.newdawn.slick.InputListener#keyReleased(int, char)
*/
public void keyReleased(int key, char c) {
if (transitioning()) {
return;
}
currentState.keyReleased(key, c);
}
/**
* @see org.newdawn.slick.InputListener#mouseMoved(int, int, int, int)
*/
public void mouseMoved(int oldx, int oldy, int newx, int newy) {
if (transitioning()) {
return;
}
currentState.mouseMoved(oldx, oldy, newx, newy);
}
/**
* @see org.newdawn.slick.InputListener#mousePressed(int, int, int)
*/
public void mousePressed(int button, int x, int y) {
if (transitioning()) {
return;
}
currentState.mousePressed(button, x, y);
}
/**
* @see org.newdawn.slick.InputListener#mouseReleased(int, int, int)
*/
public void mouseReleased(int button, int x, int y) {
if (transitioning()) {
return;
}
currentState.mouseReleased(button, x, y);
}
/**
* @see org.newdawn.slick.InputListener#isAcceptingInput()
*/
public boolean isAcceptingInput() {
return true;
}
/**
* @see org.newdawn.slick.InputListener#inputEnded()
*/
public void inputEnded() {
}
/**
* @see org.newdawn.slick.InputListener#mouseWheelMoved(int)
*/
public void mouseWheelMoved(int newValue) {
}
}
| true | true | public final void update(GameContainer container, int delta) throws SlickException {
if (leaveTransition != null) {
leaveTransition.update(this, container, delta);
if (leaveTransition.isComplete()) {
currentState.leave(container, this);
currentState = nextState;
nextState = null;
leaveTransition = null;
if (enterTransition == null) {
nextState.enter(container, this);
}
} else {
return;
}
}
if (enterTransition != null) {
enterTransition.update(this, container, delta);
if (enterTransition.isComplete()) {
currentState.enter(container, this);
enterTransition = null;
} else {
return;
}
}
currentState.update(container, this, delta);
}
| public final void update(GameContainer container, int delta) throws SlickException {
if (leaveTransition != null) {
leaveTransition.update(this, container, delta);
if (leaveTransition.isComplete()) {
currentState.leave(container, this);
currentState = nextState;
nextState = null;
leaveTransition = null;
if (enterTransition == null) {
currentState.enter(container, this);
}
} else {
return;
}
}
if (enterTransition != null) {
enterTransition.update(this, container, delta);
if (enterTransition.isComplete()) {
currentState.enter(container, this);
enterTransition = null;
} else {
return;
}
}
currentState.update(container, this, delta);
}
|
diff --git a/common/src/main/java/org/apache/xmlrpc/serializer/CharSetXmlWriterFactory.java b/common/src/main/java/org/apache/xmlrpc/serializer/CharSetXmlWriterFactory.java
index 0712512..d44b59e 100644
--- a/common/src/main/java/org/apache/xmlrpc/serializer/CharSetXmlWriterFactory.java
+++ b/common/src/main/java/org/apache/xmlrpc/serializer/CharSetXmlWriterFactory.java
@@ -1,30 +1,30 @@
/*
* Copyright 1999,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlrpc.serializer;
import org.apache.ws.commons.serialize.CharSetXMLWriter;
import org.apache.ws.commons.serialize.XMLWriter;
/** An implementation of {@link org.apache.xmlrpc.serializer.XmlWriterFactory},
* which creates instances of
* {@link org.apache.ws.commons.serialize.CharSetXMLWriter}.
*/
public class CharSetXmlWriterFactory extends BaseXmlWriterFactory {
- protected XMLWriter newXMLWriter() {
+ protected XMLWriter newXmlWriter() {
return new CharSetXMLWriter();
}
}
| true | true | protected XMLWriter newXMLWriter() {
return new CharSetXMLWriter();
}
| protected XMLWriter newXmlWriter() {
return new CharSetXMLWriter();
}
|
diff --git a/Andriod/MerchantActivity/src/app/merchantLocalization/Customers.java b/Andriod/MerchantActivity/src/app/merchantLocalization/Customers.java
index 528e5c4..486ba9c 100644
--- a/Andriod/MerchantActivity/src/app/merchantLocalization/Customers.java
+++ b/Andriod/MerchantActivity/src/app/merchantLocalization/Customers.java
@@ -1,241 +1,241 @@
package app.merchantLocalization;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Customerlist. Pulls subscribed or nearby customer names from the database.
* Need service-oriented architecture and needs three elements:
* external database, web-service, mobile web-service client.
* @author Chihiro
*
*
* Notes:
* For connection to work, Apache server must be handled to start PHP.
* Also, make sure NAU Wi-Fi is connected on the device.
*
* IP address changes for each Wi-Fi access!
*
*/
@SuppressLint("NewApi")
public class Customers extends Activity {
/** Called when the activity is first created. */
TextView username;
TextView result;
String dbResult;
LinearLayout customerLayout;
Customers currentThis = this;
static int TIMEOUT_MILLISEC = 3000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
customerLayout = (LinearLayout)findViewById(R.id.customerLayout);
getData();
}
/**
* Connect to webservice (database)
*/
public void getData() {
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// can't use localhost, since localhost refers to the device itself
// (in this case the android device being tested).
// Use 10.0.2.2 for emulator
// Use own IP for device: 192.168.0.9
// cd C:\Windows\System32
// ipconfig
// Look at 10.1.64.169
//HttpGet httpGet = new HttpGet("http://10.1.64.169/PHPQuery.php");
HttpGet httpGet = new HttpGet("http://dana.ucc.nau.edu/~cs854/PHPGetNearbyCustomers.php");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(final String results) {
if (results!=null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// EditText et = (EditText)findViewById(R.id.databaseText);
// et.setText("Database connection worked!: " + results);
/**
* Gets customers names from JSON and creates buttons that charge the users if
* pressed.
*/
try {
JSONArray jsonArray = new JSONArray(results);
for (int i = 0; i < jsonArray.length(); i++){
Button tempButton = new Button(currentThis);
final String customerName = jsonArray.getJSONObject(i).getString("userName");
tempButton.setText(customerName);
tempButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(currentThis);
- builder.setMessage("Are you sure youwant to charge " + customerName + "?")
+ builder.setMessage("Are you sure you want to charge " + customerName + "?")
.setTitle("Charge Customer");
builder.setPositiveButton("Charge", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
try{
JSONObject json = new JSONObject();
json.put("userName", customerName);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://dana.ucc.nau.edu/~cs854/PHPToggleCustomerNotification.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response;
response = client.execute(request);
HttpEntity entity = response.getEntity();
} catch (Throwable t) {
//Toast.makeText(this, "Request failed: " + t.toString(),
// Toast.LENGTH_LONG).show();
}
Builder builder2 = new AlertDialog.Builder(currentThis);
builder2.setMessage("You have successfully charged " + customerName + "." );
builder2.setCancelable(false);
builder2.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}});
AlertDialog dialog2 = builder2.create();
dialog2.show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// If the response does not enclose an entity, there is no need
AlertDialog dialog = builder.create();
dialog.show();
}
});
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
customerLayout.addView(tempButton,lp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*adapter = new ArrayAdapter<String>(currentThis,
android.R.layout.simple_list_item_1, listContents);
adapter.setNotifyOnChange(true);
myListView.setAdapter(adapter); */
}
});
} else {
//TODO: Error notification of some sort
//EditText et = (EditText)findViewById(R.id.databaseText);
//et.setText("Database connection failed");
}
}
}
}
| true | true | protected void onPostExecute(final String results) {
if (results!=null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// EditText et = (EditText)findViewById(R.id.databaseText);
// et.setText("Database connection worked!: " + results);
/**
* Gets customers names from JSON and creates buttons that charge the users if
* pressed.
*/
try {
JSONArray jsonArray = new JSONArray(results);
for (int i = 0; i < jsonArray.length(); i++){
Button tempButton = new Button(currentThis);
final String customerName = jsonArray.getJSONObject(i).getString("userName");
tempButton.setText(customerName);
tempButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(currentThis);
builder.setMessage("Are you sure youwant to charge " + customerName + "?")
.setTitle("Charge Customer");
builder.setPositiveButton("Charge", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
try{
JSONObject json = new JSONObject();
json.put("userName", customerName);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://dana.ucc.nau.edu/~cs854/PHPToggleCustomerNotification.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response;
response = client.execute(request);
HttpEntity entity = response.getEntity();
} catch (Throwable t) {
//Toast.makeText(this, "Request failed: " + t.toString(),
// Toast.LENGTH_LONG).show();
}
Builder builder2 = new AlertDialog.Builder(currentThis);
builder2.setMessage("You have successfully charged " + customerName + "." );
builder2.setCancelable(false);
builder2.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}});
AlertDialog dialog2 = builder2.create();
dialog2.show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// If the response does not enclose an entity, there is no need
AlertDialog dialog = builder.create();
dialog.show();
}
});
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
customerLayout.addView(tempButton,lp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*adapter = new ArrayAdapter<String>(currentThis,
android.R.layout.simple_list_item_1, listContents);
adapter.setNotifyOnChange(true);
myListView.setAdapter(adapter); */
}
});
} else {
//TODO: Error notification of some sort
//EditText et = (EditText)findViewById(R.id.databaseText);
//et.setText("Database connection failed");
}
}
| protected void onPostExecute(final String results) {
if (results!=null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// EditText et = (EditText)findViewById(R.id.databaseText);
// et.setText("Database connection worked!: " + results);
/**
* Gets customers names from JSON and creates buttons that charge the users if
* pressed.
*/
try {
JSONArray jsonArray = new JSONArray(results);
for (int i = 0; i < jsonArray.length(); i++){
Button tempButton = new Button(currentThis);
final String customerName = jsonArray.getJSONObject(i).getString("userName");
tempButton.setText(customerName);
tempButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(currentThis);
builder.setMessage("Are you sure you want to charge " + customerName + "?")
.setTitle("Charge Customer");
builder.setPositiveButton("Charge", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
try{
JSONObject json = new JSONObject();
json.put("userName", customerName);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://dana.ucc.nau.edu/~cs854/PHPToggleCustomerNotification.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response;
response = client.execute(request);
HttpEntity entity = response.getEntity();
} catch (Throwable t) {
//Toast.makeText(this, "Request failed: " + t.toString(),
// Toast.LENGTH_LONG).show();
}
Builder builder2 = new AlertDialog.Builder(currentThis);
builder2.setMessage("You have successfully charged " + customerName + "." );
builder2.setCancelable(false);
builder2.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}});
AlertDialog dialog2 = builder2.create();
dialog2.show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// If the response does not enclose an entity, there is no need
AlertDialog dialog = builder.create();
dialog.show();
}
});
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
customerLayout.addView(tempButton,lp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*adapter = new ArrayAdapter<String>(currentThis,
android.R.layout.simple_list_item_1, listContents);
adapter.setNotifyOnChange(true);
myListView.setAdapter(adapter); */
}
});
} else {
//TODO: Error notification of some sort
//EditText et = (EditText)findViewById(R.id.databaseText);
//et.setText("Database connection failed");
}
}
|
diff --git a/src/net/sf/gogui/gui/GtpShell.java b/src/net/sf/gogui/gui/GtpShell.java
index 18d6a587..ab49cf77 100644
--- a/src/net/sf/gogui/gui/GtpShell.java
+++ b/src/net/sf/gogui/gui/GtpShell.java
@@ -1,673 +1,676 @@
//----------------------------------------------------------------------------
// $Id$
//----------------------------------------------------------------------------
package net.sf.gogui.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.prefs.Preferences;
import javax.swing.Box;
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import net.sf.gogui.gtp.GtpClient;
import net.sf.gogui.gtp.GtpUtil;
import net.sf.gogui.util.Platform;
import net.sf.gogui.util.PrefUtil;
/** Dialog for displaying the GTP stream and for entering commands. */
public class GtpShell
extends JDialog
implements ActionListener, GtpClient.IOCallback
{
/** Callback for events generated by GtpShell. */
public interface Listener
{
void actionSendCommand(String command, boolean isSignificant,
boolean showError);
}
public GtpShell(Frame owner, Listener listener)
{
super(owner, "Shell");
m_listener = listener;
Preferences prefs = Preferences.userNodeForPackage(getClass());
m_historyMin = prefs.getInt("history-min", 2000);
m_historyMax = prefs.getInt("history-max", 3000);
JPanel panel = new JPanel(new BorderLayout());
getContentPane().add(panel, BorderLayout.CENTER);
m_gtpShellText = new GtpShellText(m_historyMin, m_historyMax, false);
m_scrollPane =
new JScrollPane(m_gtpShellText.get(),
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
int fontSize = m_gtpShellText.get().getFont().getSize();
m_finalSize = new Dimension(fontSize * 40, fontSize * 30);
panel.add(m_scrollPane, BorderLayout.CENTER);
panel.add(createCommandInput(), BorderLayout.SOUTH);
// not supported in java 1.4
//setMinimumSize(new Dimension(160, 112));
pack();
}
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (command.equals("comboBoxEdited"))
{
}
else if (command.equals("run"))
commandEntered();
else if (command.equals("close"))
setVisible(false);
}
public void receivedInvalidResponse(String response)
{
if (SwingUtilities.isEventDispatchThread())
{
appendInvalidResponse(response);
return;
}
Runnable r = new UpdateInvalidResponse(this, response);
invokeAndWait(r);
}
public void receivedResponse(boolean error, String response)
{
if (SwingUtilities.isEventDispatchThread())
{
appendResponse(error, response);
return;
}
Runnable r = new UpdateResponse(this, error, response);
invokeAndWait(r);
}
public void receivedStdErr(String s)
{
if (SwingUtilities.isEventDispatchThread())
{
appendLog(s);
return;
}
Runnable r = new UpdateStdErr(this, s);
invokeAndWait(r);
}
public void saveLog(JFrame parent)
{
save(parent, m_gtpShellText.getLog(),
m_gtpShellText.getLinesTruncated());
}
public void saveCommands(JFrame parent)
{
save(parent, m_commands.toString(), m_linesTruncated);
}
public void saveHistory()
{
int maxHistory = 100;
int max = m_history.size();
if (max > maxHistory)
max = maxHistory;
ArrayList list = new ArrayList(max);
for (int i = m_history.size() - max; i < m_history.size(); ++i)
list.add(m_history.get(i));
PrefUtil.putList("net/sf/gogui/gui/gtpshell/recentcommands", list);
}
public void setCommandInProgess(boolean commandInProgess)
{
m_commandInProgress = commandInProgess;
}
public void setCommandCompletion(boolean commandCompletion)
{
m_disableCompletions = ! commandCompletion;
}
public void setTimeStamp(boolean enable)
{
m_gtpShellText.setTimeStamp(enable);
}
public void sentCommand(String command)
{
if (SwingUtilities.isEventDispatchThread())
{
appendSentCommand(command);
return;
}
Runnable r = new UpdateCommand(this, command);
invokeAndWait(r);
}
public void setFinalSize(int width, int height)
{
if (m_isFinalSizeSet)
setSize(width, height);
else
m_finalSize = new Dimension(width, height);
}
public void setInitialCompletions(ArrayList completions)
{
for (int i = completions.size() - 1; i >= 0; --i)
{
String command = completions.get(i).toString();
if (! GtpUtil.isStateChangingCommand(command))
appendToHistory(command);
}
ArrayList list =
PrefUtil.getList("net/sf/gogui/gui/gtpshell/recentcommands");
for (int i = 0; i < list.size(); ++i)
appendToHistory((String)list.get(i));
addAllCompletions(m_history);
}
public void setProgramCommand(String command)
{
m_programCommand = command;
}
public void setProgramName(String name)
{
m_programName = name;
}
public void setProgramVersion(String version)
{
m_programVersion = version;
}
private static class UpdateCommand implements Runnable
{
public UpdateCommand(GtpShell gtpShell, String text)
{
m_gtpShell = gtpShell;
m_text = text;
}
public void run()
{
m_gtpShell.appendSentCommand(m_text);
}
private final String m_text;
private final GtpShell m_gtpShell;
}
private static class UpdateInvalidResponse implements Runnable
{
public UpdateInvalidResponse(GtpShell gtpShell, String text)
{
m_gtpShell = gtpShell;
m_text = text;
}
public void run()
{
m_gtpShell.appendInvalidResponse(m_text);
}
private final String m_text;
private final GtpShell m_gtpShell;
}
private static class UpdateResponse implements Runnable
{
public UpdateResponse(GtpShell gtpShell, boolean error, String text)
{
m_gtpShell = gtpShell;
m_error = error;
m_text = text;
}
public void run()
{
m_gtpShell.appendResponse(m_error, m_text);
}
private final boolean m_error;
private final String m_text;
private final GtpShell m_gtpShell;
}
private static class UpdateStdErr implements Runnable
{
public UpdateStdErr(GtpShell gtpShell, String text)
{
m_gtpShell = gtpShell;
m_text = text;
}
public void run()
{
assert(SwingUtilities.isEventDispatchThread());
m_gtpShell.appendLog(m_text);
m_gtpShell.setFinalSize();
}
private final String m_text;
private final GtpShell m_gtpShell;
}
/** Wrapper object for JComboBox items.
JComboBox can have focus and keyboard navigation problems if
duplicate String objects are added.
See JDK 1.4 doc for JComboBox.addItem.
*/
private static class WrapperObject
{
WrapperObject(String item)
{
m_item = item;
}
public String toString()
{
return m_item;
}
private final String m_item;
}
private boolean m_disableCompletions;
private boolean m_isFinalSizeSet;
private boolean m_commandInProgress;
private final int m_historyMax;
private final int m_historyMin;
private int m_linesTruncated;
private int m_numberCommands;
/** Serial version to suppress compiler warning.
Contains a marker comment for serialver.sourceforge.net
*/
private static final long serialVersionUID = 0L; // SUID
private final Listener m_listener;
private ComboBoxEditor m_editor;
private Dimension m_finalSize;
private JButton m_runButton;
private JTextField m_textField;
private JComboBox m_comboBox;
private final JScrollPane m_scrollPane;
private final GtpShellText m_gtpShellText;
private final StringBuffer m_commands = new StringBuffer(4096);
private final ArrayList m_history = new ArrayList(128);
private String m_programCommand = "unknown";
private String m_programName = "unknown";
private String m_programVersion = "unknown";
private void addAllCompletions(ArrayList completions)
{
// On Windows JDK 1.4 changing the popup automatically
// selects all text in the text field, so we remember and
// restore the state.
String oldText = m_textField.getText();
int oldCaretPosition = m_textField.getCaretPosition();
if (completions.size() > m_comboBox.getItemCount())
m_comboBox.hidePopup();
m_comboBox.removeAllItems();
for (int i = completions.size() - 1; i >= 0; --i)
{
Object object = new WrapperObject((String)completions.get(i));
m_comboBox.addItem(object);
}
m_comboBox.setSelectedIndex(-1);
m_textField.setText(oldText);
m_textField.setCaretPosition(oldCaretPosition);
}
private void appendInvalidResponse(String response)
{
assert(SwingUtilities.isEventDispatchThread());
m_gtpShellText.appendInvalidResponse(response);
}
private void appendLog(String line)
{
assert(SwingUtilities.isEventDispatchThread());
m_gtpShellText.appendLog(line);
}
private void appendResponse(boolean error, String response)
{
assert(SwingUtilities.isEventDispatchThread());
if (error)
m_gtpShellText.appendError(response);
else
m_gtpShellText.appendInput(response);
setFinalSize();
}
private void appendSentCommand(String command)
{
assert(SwingUtilities.isEventDispatchThread());
m_commands.append(command);
m_commands.append('\n');
++m_numberCommands;
if (m_numberCommands > m_historyMax)
{
int truncateLines = m_numberCommands - m_historyMin;
String s = m_commands.toString();
int index = GtpShellText.findTruncateIndex(s, truncateLines);
assert(index != -1);
m_commands.delete(0, index);
m_linesTruncated += truncateLines;
m_numberCommands = 0;
}
m_gtpShellText.appendOutput(command + "\n");
setFinalSize();
}
private void appendToHistory(String command)
{
command = command.trim();
int i = m_history.indexOf(command);
if (i >= 0)
m_history.remove(i);
m_history.add(command);
}
private void commandEntered()
{
assert(SwingUtilities.isEventDispatchThread());
String command = m_textField.getText().trim();
if (command.trim().equals(""))
return;
if (command.startsWith("#"))
{
m_gtpShellText.appendComment(command + "\n");
}
else
{
if (GtpUtil.isStateChangingCommand(command))
{
showError("Cannot send board changing command from GTP shell",
false);
return;
}
if (m_commandInProgress)
{
showError("Cannot execute while computer is thinking", false);
return;
}
m_listener.actionSendCommand(command, false, false);
}
appendToHistory(command);
m_gtpShellText.setPositionToEnd();
m_comboBox.hidePopup();
addAllCompletions(m_history);
m_editor.setItem(null);
}
private JComponent createCommandInput()
{
Box box = Box.createVerticalBox();
//JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
JPanel panel = new JPanel(new BorderLayout());
box.add(GuiUtil.createSmallFiller());
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
m_comboBox = new JComboBox();
+ if (Platform.isMac())
+ // Workaround for bug in Quaqua Look and Feel 3.6.11
+ m_comboBox.setMaximumRowCount(7);
m_editor = m_comboBox.getEditor();
m_textField = (JTextField)m_editor.getEditorComponent();
m_textField.setFocusTraversalKeysEnabled(false);
KeyAdapter keyAdapter = new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
int c = e.getKeyCode();
int mod = e.getModifiers();
if (c == KeyEvent.VK_ESCAPE)
return;
else if (c == KeyEvent.VK_TAB)
{
findBestCompletion();
popupCompletions();
}
else if (c == KeyEvent.VK_PAGE_UP
&& mod == ActionEvent.SHIFT_MASK)
scrollPage(true);
else if (c == KeyEvent.VK_PAGE_DOWN
&& mod == ActionEvent.SHIFT_MASK)
scrollPage(false);
else if (c == KeyEvent.VK_ENTER
&& ! m_comboBox.isPopupVisible())
commandEntered();
else if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
popupCompletions();
}
};
m_textField.addKeyListener(keyAdapter);
m_comboBox.setEditable(true);
m_comboBox.setFont(m_gtpShellText.get().getFont());
m_comboBox.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
m_comboBox.requestFocusInWindow();
m_textField.requestFocusInWindow();
}
});
panel.add(m_comboBox, BorderLayout.CENTER);
m_runButton = new JButton();
m_runButton.setIcon(GuiUtil.getIcon("gogui-key_enter", "Run"));
m_runButton.setActionCommand("run");
m_runButton.setFocusable(false);
m_runButton.setToolTipText("Send command line");
m_runButton.addActionListener(this);
JPanel buttonPanel =
new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(buttonPanel, BorderLayout.EAST);
buttonPanel.add(GuiUtil.createSmallFiller());
buttonPanel.add(m_runButton);
// Workaround for Java 1.4.1 on Mac OS X add some empty space
// so that combobox does not overlap the window resize widget
if (Platform.isMac())
{
Dimension dimension = new Dimension(20, 1);
Box.Filler filler =
new Box.Filler(dimension, dimension, dimension);
buttonPanel.add(filler);
}
return box;
}
private void findBestCompletion()
{
String text = m_textField.getText().trim();
if (text.equals(""))
return;
String bestCompletion = null;
for (int i = 0; i < m_history.size(); ++i)
{
String completion = (String)m_history.get(i);
if (completion.startsWith(text))
{
if (bestCompletion == null)
{
bestCompletion = completion;
continue;
}
int j = text.length();
while (true)
{
if (j >= bestCompletion.length())
{
break;
}
if (j >= completion.length())
break;
if (bestCompletion.charAt(j) != completion.charAt(j))
break;
++j;
}
bestCompletion = completion.substring(0, j);
}
}
if (bestCompletion != null)
m_textField.setText(bestCompletion);
}
private void invokeAndWait(Runnable runnable)
{
try
{
SwingUtilities.invokeAndWait(runnable);
}
catch (InterruptedException e)
{
System.err.println("Thread interrupted");
}
catch (java.lang.reflect.InvocationTargetException e)
{
System.err.println("InvocationTargetException");
}
}
private void popupCompletions()
{
String text = m_textField.getText();
text = text.replaceAll("^ *", "");
ArrayList completions = new ArrayList(128);
for (int i = 0; i < m_history.size(); ++i)
{
String c = (String)m_history.get(i);
if (c.startsWith(text))
completions.add(c);
}
addAllCompletions(completions);
if (m_disableCompletions)
return;
int size = completions.size();
if (text.length() > 0
&& (size > 1 || (size == 1 && ! text.equals(completions.get(0)))))
m_comboBox.showPopup();
else
m_comboBox.hidePopup();
}
private void save(JFrame parent, String s, int linesTruncated)
{
File file = SimpleDialogs.showSave(parent, null);
if (file == null)
return;
try
{
PrintStream out = new PrintStream(new FileOutputStream(file));
out.println("# Name: " + m_programName);
out.println("# Version: " + m_programVersion);
out.println("# Command: " + m_programCommand);
out.println("# Lines truncated: " + linesTruncated);
out.print(s);
out.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(parent, "Could not save to file.",
"GoGui: Error",
JOptionPane.ERROR_MESSAGE);
}
}
private void showError(String message, boolean isSignificant)
{
SimpleDialogs.showError(this, message, isSignificant);
}
private void scrollPage(boolean up)
{
JViewport viewport = m_scrollPane.getViewport();
Point position = viewport.getViewPosition();
int delta = m_scrollPane.getSize().height
- m_gtpShellText.get().getFont().getSize();
if (up)
{
position.y -= delta;
if (position.y < 0)
position.y = 0;
}
else
{
position.y += delta;
int max = viewport.getViewSize().height
- m_scrollPane.getSize().height;
if (position.y > max)
position.y = max;
}
viewport.setViewPosition(position);
}
/** Modify dialog size after first write.
This is a workaround for problems with a JTextPane in a JScrollable
in Sun JDK 1.4 and Mac JDK 1.4.
Sometimes garbage text is left after inserting text
if the JTextPane was created empty and the size was set by
JScrollpane.setPreferredSize or letting the scrollable track the
viewport width.
The garbage text disappears after resizing the dialog,
so we use JDialog.setSize after the first text was inserted.
This workaround should be removed when no longer needed (e.g. after
requiring newer Java versions that don't need this workaround).
*/
private void setFinalSize()
{
if (m_isFinalSizeSet)
return;
setSize(m_finalSize);
m_isFinalSizeSet = true;
}
}
| true | true | private JComponent createCommandInput()
{
Box box = Box.createVerticalBox();
//JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
JPanel panel = new JPanel(new BorderLayout());
box.add(GuiUtil.createSmallFiller());
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
m_comboBox = new JComboBox();
m_editor = m_comboBox.getEditor();
m_textField = (JTextField)m_editor.getEditorComponent();
m_textField.setFocusTraversalKeysEnabled(false);
KeyAdapter keyAdapter = new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
int c = e.getKeyCode();
int mod = e.getModifiers();
if (c == KeyEvent.VK_ESCAPE)
return;
else if (c == KeyEvent.VK_TAB)
{
findBestCompletion();
popupCompletions();
}
else if (c == KeyEvent.VK_PAGE_UP
&& mod == ActionEvent.SHIFT_MASK)
scrollPage(true);
else if (c == KeyEvent.VK_PAGE_DOWN
&& mod == ActionEvent.SHIFT_MASK)
scrollPage(false);
else if (c == KeyEvent.VK_ENTER
&& ! m_comboBox.isPopupVisible())
commandEntered();
else if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
popupCompletions();
}
};
m_textField.addKeyListener(keyAdapter);
m_comboBox.setEditable(true);
m_comboBox.setFont(m_gtpShellText.get().getFont());
m_comboBox.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
m_comboBox.requestFocusInWindow();
m_textField.requestFocusInWindow();
}
});
panel.add(m_comboBox, BorderLayout.CENTER);
m_runButton = new JButton();
m_runButton.setIcon(GuiUtil.getIcon("gogui-key_enter", "Run"));
m_runButton.setActionCommand("run");
m_runButton.setFocusable(false);
m_runButton.setToolTipText("Send command line");
m_runButton.addActionListener(this);
JPanel buttonPanel =
new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(buttonPanel, BorderLayout.EAST);
buttonPanel.add(GuiUtil.createSmallFiller());
buttonPanel.add(m_runButton);
// Workaround for Java 1.4.1 on Mac OS X add some empty space
// so that combobox does not overlap the window resize widget
if (Platform.isMac())
{
Dimension dimension = new Dimension(20, 1);
Box.Filler filler =
new Box.Filler(dimension, dimension, dimension);
buttonPanel.add(filler);
}
return box;
}
| private JComponent createCommandInput()
{
Box box = Box.createVerticalBox();
//JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
JPanel panel = new JPanel(new BorderLayout());
box.add(GuiUtil.createSmallFiller());
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
m_comboBox = new JComboBox();
if (Platform.isMac())
// Workaround for bug in Quaqua Look and Feel 3.6.11
m_comboBox.setMaximumRowCount(7);
m_editor = m_comboBox.getEditor();
m_textField = (JTextField)m_editor.getEditorComponent();
m_textField.setFocusTraversalKeysEnabled(false);
KeyAdapter keyAdapter = new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
int c = e.getKeyCode();
int mod = e.getModifiers();
if (c == KeyEvent.VK_ESCAPE)
return;
else if (c == KeyEvent.VK_TAB)
{
findBestCompletion();
popupCompletions();
}
else if (c == KeyEvent.VK_PAGE_UP
&& mod == ActionEvent.SHIFT_MASK)
scrollPage(true);
else if (c == KeyEvent.VK_PAGE_DOWN
&& mod == ActionEvent.SHIFT_MASK)
scrollPage(false);
else if (c == KeyEvent.VK_ENTER
&& ! m_comboBox.isPopupVisible())
commandEntered();
else if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
popupCompletions();
}
};
m_textField.addKeyListener(keyAdapter);
m_comboBox.setEditable(true);
m_comboBox.setFont(m_gtpShellText.get().getFont());
m_comboBox.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
m_comboBox.requestFocusInWindow();
m_textField.requestFocusInWindow();
}
});
panel.add(m_comboBox, BorderLayout.CENTER);
m_runButton = new JButton();
m_runButton.setIcon(GuiUtil.getIcon("gogui-key_enter", "Run"));
m_runButton.setActionCommand("run");
m_runButton.setFocusable(false);
m_runButton.setToolTipText("Send command line");
m_runButton.addActionListener(this);
JPanel buttonPanel =
new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(buttonPanel, BorderLayout.EAST);
buttonPanel.add(GuiUtil.createSmallFiller());
buttonPanel.add(m_runButton);
// Workaround for Java 1.4.1 on Mac OS X add some empty space
// so that combobox does not overlap the window resize widget
if (Platform.isMac())
{
Dimension dimension = new Dimension(20, 1);
Box.Filler filler =
new Box.Filler(dimension, dimension, dimension);
buttonPanel.add(filler);
}
return box;
}
|
diff --git a/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java b/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java
index 603a29085..24b8b7b8a 100644
--- a/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java
+++ b/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java
@@ -1,1026 +1,1026 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.ejb;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.x509.PrivateKeyUsagePeriod;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.ejbca.util.CertTools;
import org.signserver.common.ArchiveDataVO;
import org.signserver.common.AuthorizationRequiredException;
import org.signserver.common.AuthorizedClient;
import org.signserver.common.CryptoTokenAuthenticationFailureException;
import org.signserver.common.CryptoTokenOfflineException;
import org.signserver.common.GlobalConfiguration;
import org.signserver.common.IArchivableProcessResponse;
import org.signserver.common.ICertReqData;
import org.signserver.common.ISignResponse;
import org.signserver.common.ISignerCertReqInfo;
import org.signserver.common.IllegalRequestException;
import org.signserver.common.InvalidWorkerIdException;
import org.signserver.common.ProcessRequest;
import org.signserver.common.ProcessResponse;
import org.signserver.common.ProcessableConfig;
import org.signserver.common.RequestContext;
import org.signserver.common.SignServerConstants;
import org.signserver.common.SignServerException;
import org.signserver.common.WorkerConfig;
import org.signserver.common.WorkerStatus;
import org.signserver.ejb.interfaces.IGlobalConfigurationSession;
import org.signserver.ejb.interfaces.IServiceTimerSession;
import org.signserver.ejb.interfaces.IWorkerSession;
import org.signserver.server.AccounterException;
import org.signserver.server.BaseProcessable;
import org.signserver.server.IClientCredential;
import org.signserver.server.IProcessable;
import org.signserver.server.ISystemLogger;
import org.signserver.server.IWorker;
import org.signserver.server.IWorkerLogger;
import org.signserver.server.NotGrantedException;
import org.signserver.server.SignServerContext;
import org.signserver.server.SystemLoggerException;
import org.signserver.server.SystemLoggerFactory;
import org.signserver.server.WorkerFactory;
import org.signserver.server.WorkerLoggerException;
import org.signserver.server.KeyUsageCounter;
import org.signserver.server.statistics.Event;
import org.signserver.server.statistics.StatisticsManager;
/**
* The main worker session bean.
*
* @version $Id$
*/
@Stateless
public class WorkerSessionBean implements IWorkerSession.ILocal,
IWorkerSession.IRemote {
private static final long serialVersionUID = 1L;
/** Log4j instance for this class. */
private static final Logger LOG = Logger.getLogger(WorkerSessionBean.class);
/** Audit logger. */
private static final ISystemLogger AUDITLOG = SystemLoggerFactory
.getInstance().getLogger(WorkerSessionBean.class);
/** The local home interface of Worker Config entity bean. */
private transient WorkerConfigDataService workerConfigService;
/** The local home interface of archive entity bean. */
private transient ArchiveDataService archiveDataService;
@EJB
private IGlobalConfigurationSession.ILocal globalConfigurationSession;
@EJB
private IServiceTimerSession.ILocal serviceTimerSession;
@PersistenceContext(unitName = "SignServerJPA")
EntityManager em;
@PostConstruct
public void create() {
workerConfigService = new WorkerConfigDataService(em);
archiveDataService = new ArchiveDataService(em);
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#process(int,
* org.signserver.common.ISignRequest, java.security.cert.X509Certificate,
* java.lang.String)
*/
public ProcessResponse process(final int workerId,
final ProcessRequest request, final RequestContext requestContext)
throws IllegalRequestException, CryptoTokenOfflineException,
SignServerException {
if (LOG.isDebugEnabled()) {
LOG.debug(">process: " + workerId);
}
// Start time
final long startTime = System.currentTimeMillis();
// Map of log entries
final Map<String, String> logMap = getLogMap(requestContext);
// Get transaction ID or create new if not created yet
final String transactionID;
if (requestContext.get(RequestContext.TRANSACTION_ID) == null) {
transactionID = generateTransactionID();
} else {
transactionID = (String) requestContext.get(
RequestContext.TRANSACTION_ID);
}
// Store values for request context and logging
requestContext.put(RequestContext.TRANSACTION_ID, transactionID);
logMap.put(IWorkerLogger.LOG_TIME, String.valueOf(startTime));
logMap.put(IWorkerLogger.LOG_ID, transactionID);
logMap.put(IWorkerLogger.LOG_WORKER_ID, String.valueOf(workerId));
logMap.put(IWorkerLogger.LOG_CLIENT_IP,
(String) requestContext.get(RequestContext.REMOTE_IP));
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker == null) {
final IllegalRequestException ex =
new IllegalRequestException("Non-existing workerId: "
+ workerId);
LOG.error(ex.getMessage(), ex); //TODO: Not really error more like 404 Not Found
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
try {
AUDITLOG.log(logMap);
} catch (SystemLoggerException ex2) {
LOG.error("Audit log failure", ex2);
}
throw ex;
}
// Get worker log instance
final IWorkerLogger workerLogger = WorkerFactory.getInstance().
getWorkerLogger(workerId,
worker.getStatus().getActiveSignerConfig(), em);
if (LOG.isDebugEnabled()) {
LOG.info("Worker[" + workerId + "]: " + "WorkerLogger: "
+ workerLogger);
}
try {
// Get processable
if (!(worker instanceof IProcessable)) {
final IllegalRequestException ex = new IllegalRequestException(
"Worker exists but isn't a processable: " + workerId);
// auditLog(startTime, workerId, false, requestContext, ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw ex;
}
final IProcessable processable = (IProcessable) worker;
// Check authorization
logMap.put(IWorkerLogger.LOG_WORKER_AUTHTYPE,
processable.getAuthenticationType());
try {
WorkerFactory.getInstance()
.getAuthenticator(workerId,
processable.getAuthenticationType(),
worker.getStatus().getActiveSignerConfig(),
em).isAuthorized(request, requestContext);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(true));
} catch (AuthorizationRequiredException ex) {
throw ex;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (SignServerException ex) {
final SignServerException exception =
new SignServerException("Authorization failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_CLIENT_AUTHORIZED,
String.valueOf(false));
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Log client certificate (if any)
final Certificate clientCertificate = (Certificate)
requestContext.get(RequestContext.CLIENT_CERTIFICATE);
if (clientCertificate instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) clientCertificate;
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_CLIENT_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
}
// Check activation
final WorkerConfig awc =
processable.getStatus().getActiveSignerConfig();
if (awc.getProperties().getProperty(SignServerConstants.DISABLED,
"FALSE").equalsIgnoreCase("TRUE")) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException("Error Signer : "
+ workerId
+ " is disabled and cannot perform any signature operations");
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Check signer certificate
try {
// Check if the signer has a signer certificate and if that
// certificate have ok validity and private key usage periods.
checkCertificateValidity(workerId, awc, logMap);
// Check key usage limit
incrementAndCheckSignerKeyUsageCounter(processable, workerId,
awc, em);
} catch (CryptoTokenOfflineException ex) {
final CryptoTokenOfflineException exception =
new CryptoTokenOfflineException(ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Statistics: start event
final Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
// Process the request
final ProcessResponse res;
try {
res = processable.processData(request, requestContext);
} catch (AuthorizationRequiredException ex) {
throw ex; // This can happen in dispatching workers
} catch (SignServerException e) {
final SignServerException exception = new SignServerException(
"SignServerException calling signer with id " + workerId
+ " : " + e.getMessage(), e);
LOG.error(exception.getMessage(), exception);
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
} catch (IllegalRequestException ex) {
final IllegalRequestException exception =
new IllegalRequestException(
"SignServerException calling signer with id " + workerId
+ " : " + ex.getMessage(), ex);
LOG.error(exception.getMessage(), exception);
logMap.put(IWorkerLogger.LOG_EXCEPTION, exception.getMessage());
workerLogger.log(logMap);
throw exception;
}
// Charge the client if the request was successfull
if (Boolean.TRUE.equals(requestContext.get(
RequestContext.WORKER_FULFILLED_REQUEST))) {
// Billing time
boolean purchased = false;
try {
IClientCredential credential =
(IClientCredential) requestContext.get(
RequestContext.CLIENT_CREDENTIAL);
purchased = WorkerFactory.getInstance().getAccounter(workerId,
worker.getStatus().getActiveSignerConfig(),
em).purchase(credential, request, res,
requestContext);
logMap.put(IWorkerLogger.LOG_PURCHASED, "true");
} catch (AccounterException ex) {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
final SignServerException exception =
new SignServerException("Accounter failed: "
+ ex.getMessage(), ex);
logMap.put(IWorkerLogger.LOG_EXCEPTION, ex.getMessage());
workerLogger.log(logMap);
throw exception;
}
if (!purchased) {
final String error = "Purchase not granted";
logMap.put(IWorkerLogger.LOG_EXCEPTION, error);
workerLogger.log(logMap);
throw new NotGrantedException(error);
}
} else {
logMap.put(IWorkerLogger.LOG_PURCHASED, "false");
}
// Archiving
if (res instanceof IArchivableProcessResponse) {
final IArchivableProcessResponse arres =
(IArchivableProcessResponse) res;
if (awc.getProperties().getProperty(SignServerConstants.ARCHIVE,
"FALSE").equalsIgnoreCase("TRUE")) {
if (arres.getArchiveData() != null) {
final String requestIP = (String)
requestContext.get(RequestContext.REMOTE_IP);
final X509Certificate clientCert = (X509Certificate)
requestContext.get(
RequestContext.CLIENT_CERTIFICATE);
archiveDataService.create(
ArchiveDataVO.TYPE_RESPONSE,
workerId, arres.getArchiveId(), clientCert,
requestIP, arres.getArchiveData());
} else {
LOG.error("Error archiving response generated of signer "
+ workerId
+ ", archiving is not supported by signer.");
}
}
}
// Statistics: end event
StatisticsManager.endEvent(workerId, awc, em, event);
// Output successfully
if (res instanceof ISignResponse) {
LOG.info("Worker " + workerId + " Processed request "
+ ((ISignResponse) res).getRequestID()
+ " successfully");
} else {
LOG.info("Worker " + workerId
+ " Processed request successfully");
}
// Log
logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(true));
workerLogger.log(logMap);
LOG.debug("<process");
return res;
} catch (WorkerLoggerException ex) {
final SignServerException exception =
new SignServerException("Logging failed", ex);
LOG.error(exception.getMessage(), exception);
throw exception;
}
}
/** Verify the certificate validity times and also that the PrivateKeyUsagePeriod is ok
*
* @param workerId
* @param awc
* @throws CryptoTokenOfflineException
*/
private void checkCertificateValidity(final int workerId,
final WorkerConfig awc, final Map<String, String> logMap)
throws CryptoTokenOfflineException {
boolean checkcertvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTVALIDITY, "TRUE").equalsIgnoreCase(
"TRUE");
boolean checkprivatekeyvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTPRIVATEKEYVALIDITY, "TRUE").
equalsIgnoreCase("TRUE");
int minremainingcertvalidity = Integer.valueOf(awc.getProperties().
getProperty(SignServerConstants.MINREMAININGCERTVALIDITY, "0"));
if (LOG.isDebugEnabled()) {
LOG.debug("checkcertvalidity: " + checkcertvalidity);
LOG.debug("checkprivatekeyvalidity: " + checkprivatekeyvalidity);
LOG.debug("minremainingcertvalidity: " + minremainingcertvalidity);
}
if (checkcertvalidity || checkprivatekeyvalidity || (minremainingcertvalidity
> 0)) {
// If the signer have a certificate, check that it is usable
- X509Certificate cert = (new ProcessableConfig(awc)).
- getSignerCertificate();
- if (cert != null) {
+ final Certificate signerCert = getSignerCertificate(workerId);
+ if (signerCert instanceof X509Certificate) {
+ final X509Certificate cert = (X509Certificate) signerCert;
// Log client certificate
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
// Check regular certificate validity
Date notBefore = cert.getNotBefore();
Date notAfter = cert.getNotAfter();
if (LOG.isDebugEnabled()) {
LOG.debug("The signer certificate is valid from '"
+ notBefore + "' until '" + notAfter + "'");
}
Date now = new Date();
// Certificate validity period. Cert must not be expired.
if (checkcertvalidity) {
if (now.before(notBefore)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that is not valid until "
+ notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that expired at "
+ notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
// Private key usage period. Private key must not be expired
if (checkprivatekeyvalidity) {
// Check privateKeyUsagePeriod of it exists
byte[] extvalue = cert.getExtensionValue(X509Extensions.PrivateKeyUsagePeriod.
getId());
if ((extvalue != null) && (extvalue.length > 0)) {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Found a PrivateKeyUsagePeriod in the signer certificate.");
}
try {
DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(
extvalue)).readObject());
PrivateKeyUsagePeriod p = PrivateKeyUsagePeriod.
getInstance((ASN1Sequence) new ASN1InputStream(
new ByteArrayInputStream(oct.getOctets())).
readObject());
if (p != null) {
notBefore = p.getNotBefore().getDate();
notAfter = p.getNotAfter().getDate();
if (LOG.isDebugEnabled()) {
LOG.debug("The signer certificate has a private key usage period from '"
+ notBefore + "' until '" + notAfter
+ "'");
}
now = new Date();
if (now.before(notBefore)) {
String msg = "Error Signer " + workerId
+ " have a private key that is not valid until "
+ notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a private key that expired at "
+ notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
} catch (IOException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
} catch (ParseException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
}
}
} // if (checkprivatekeyvalidity)
// Check remaining validity of certificate. Must not be too short.
if (minremainingcertvalidity > 0) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, minremainingcertvalidity);
Date check = cal.getTime();
if (LOG.isDebugEnabled()) {
LOG.debug("Checking if signer certificate expires before: "
+ check);
}
if (check.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that expires within "
+ minremainingcertvalidity + " days.";
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
} else { // if (cert != null)
if (LOG.isDebugEnabled()) {
LOG.debug("Worker does not have a signing certificate. Worker: "
+ workerId);
}
}
} // if (checkcertvalidity || checkprivatekeyvalidity) {
} // checkCertificateValidity
/**
* Checks that if this worker has a certificate (ie the worker is a Signer)
* the counter of the usages of the key has not reached the configured
* limit.
* @param workerId
* @param awc
* @param em
* @throws CryptoTokenOfflineException
*/
private void incrementAndCheckSignerKeyUsageCounter(final IProcessable worker,
final int workerId, final WorkerConfig awc, EntityManager em)
throws CryptoTokenOfflineException {
// If the signer have a certificate, check that the usage of the key
// has not reached the limit
Certificate cert = null;
if (worker instanceof BaseProcessable) {
cert = ((BaseProcessable) worker).getSigningCertificate();
} else {
// The following will not work for keystores where the SIGNSERCERT
// property is not set
cert = (new ProcessableConfig(awc)).getSignerCertificate();
}
if (cert != null) {
final long keyUsageLimit
= Long.valueOf(awc.getProperty(SignServerConstants.KEYUSAGELIMIT, "-1"));
final String keyHash
= KeyUsageCounter.createKeyHash(cert.getPublicKey());
if(LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId +"]: "
+ "Key usage limit: " + keyUsageLimit);
LOG.debug("Worker[" + workerId +"]: "
+ "Key hash: " + keyHash);
}
final Query updateQuery;
if (keyUsageLimit < 0) {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash");
} else {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash AND w.counter < :limit");
updateQuery.setParameter("limit", keyUsageLimit);
}
updateQuery.setParameter("keyhash", keyHash);
if (updateQuery.executeUpdate() < 1) {
final String message
= "Key usage limit exceeded or not initialized for worker "
+ workerId;
LOG.debug(message);
throw new CryptoTokenOfflineException(message);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "No certificate so not checking signing key usage counter");
}
}
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getStatus(int)
*/
public WorkerStatus getStatus(int workerId) throws InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + workerId
+ " doesn't exist");
}
return worker.getStatus();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getWorkerId(java.lang.String)
*/
public int getWorkerId(String signerName) {
return WorkerFactory.getInstance().getWorkerIdFromName(signerName.
toUpperCase(), workerConfigService, globalConfigurationSession, new SignServerContext(
em));
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#reloadConfiguration(int)
*/
public void reloadConfiguration(int workerId) {
if (workerId == 0) {
globalConfigurationSession.reload();
} else {
WorkerFactory.getInstance().reloadWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
// Try to insert a key usage counter entry for this worker's public
// key
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
try {
final Certificate cert = ((BaseProcessable)worker)
.getSigningCertificate();
if (cert != null) {
final String keyHash = KeyUsageCounter
.createKeyHash(cert.getPublicKey());
KeyUsageCounter counter
= em.find(KeyUsageCounter.class, keyHash);
if (counter == null) {
counter = new KeyUsageCounter(keyHash);
em.persist(counter);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "key usage counter: " + counter.getCounter());
}
}
} catch (CryptoTokenOfflineException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[ " + workerId + "]: "
+ "Crypto token offline trying to create key usage counter");
}
}
}
}
if (workerId == 0 || globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_SERVICES).contains(new Integer(
workerId))) {
serviceTimerSession.unload(workerId);
serviceTimerSession.load(workerId);
}
StatisticsManager.flush(workerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#activateSigner(int, java.lang.String)
*/
public void activateSigner(int signerId, String authenticationCode)
throws CryptoTokenAuthenticationFailureException,
CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
signer.activateSigner(authenticationCode);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#deactivateSigner(int)
*/
public boolean deactivateSigner(int signerId)
throws CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.deactivateSigner();
}
/* (non-Javadoc)
* @see org.signserver.ejb.IWorkerSession#getCurrentSignerConfig(int)
*/
public WorkerConfig getCurrentWorkerConfig(int signerId) {
return getWorkerConfig(signerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#setWorkerProperty(int, java.lang.String, java.lang.String)
*/
public void setWorkerProperty(int workerId, String key, String value) {
WorkerConfig config = getWorkerConfig(workerId);
config.setProperty(key.toUpperCase(), value);
workerConfigService.setWorkerConfig(workerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeWorkerProperty(int, java.lang.String)
*/
public boolean removeWorkerProperty(int workerId, String key) {
boolean result = false;
WorkerConfig config = getWorkerConfig(workerId);
result = config.removeProperty(key.toUpperCase());
if (config.getProperties().size() == 0) {
workerConfigService.removeWorkerConfig(workerId);
LOG.debug("WorkerConfig is empty and therefore removed.");
} else {
workerConfigService.setWorkerConfig(workerId, config);
}
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getAuthorizedClients(int)
*/
public Collection<AuthorizedClient> getAuthorizedClients(int signerId) {
return new ProcessableConfig(getWorkerConfig(signerId)).
getAuthorizedClients();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#addAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public void addAuthorizedClient(int signerId, AuthorizedClient authClient) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).addAuthorizedClient(authClient);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public boolean removeAuthorizedClient(int signerId,
AuthorizedClient authClient) {
boolean result = false;
WorkerConfig config = getWorkerConfig(signerId);
result = (new ProcessableConfig(config)).removeAuthorizedClient(
authClient);
workerConfigService.setWorkerConfig(signerId, config);
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getCertificateRequest(int, org.signserver.common.ISignerCertReqInfo)
*/
public ICertReqData getCertificateRequest(int signerId,
ISignerCertReqInfo certReqInfo) throws
CryptoTokenOfflineException, InvalidWorkerIdException {
if (LOG.isTraceEnabled()) {
LOG.trace(">getCertificateRequest: signerId=" + signerId);
}
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable processable = (IProcessable) worker;
if (LOG.isDebugEnabled()) {
LOG.debug("Found processable worker of type: " + processable.
getClass().getName());
}
ICertReqData ret = processable.genCertificateRequest(certReqInfo);
if (LOG.isTraceEnabled()) {
LOG.trace("<getCertificateRequest: signerId=" + signerId);
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificate(int)
*/
public Certificate getSignerCertificate(final int signerId) throws CryptoTokenOfflineException {
Certificate ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
ret = ((BaseProcessable) worker).getSigningCertificate();
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificateChain(int)
*/
public List<Certificate> getSignerCertificateChain(final int signerId) throws CryptoTokenOfflineException {
List<Certificate> ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
Collection<Certificate> certs = ((BaseProcessable) worker)
.getSigningCertificateChain();
if (certs instanceof List) {
ret = (List) certs;
} else {
ret = new LinkedList<Certificate>(certs);
}
}
return ret;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#destroyKey(int, int)
*/
public boolean destroyKey(int signerId, int purpose) throws
InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.destroyKey(purpose);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificate(int, java.security.cert.X509Certificate, java.lang.String)
*/
public void uploadSignerCertificate(int signerId, X509Certificate signerCert,
String scope) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).setSignerCertificate(signerCert, scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificateChain(int, java.util.Collection, java.lang.String)
*/
public void uploadSignerCertificateChain(int signerId,
Collection<Certificate> signerCerts, String scope) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).setSignerCertificateChain(signerCerts,
scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#genFreeWorkerId()
*/
public int genFreeWorkerId() {
Collection<Integer> ids = globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_ALL);
int max = 0;
Iterator<Integer> iter = ids.iterator();
while (iter.hasNext()) {
Integer id = iter.next();
if (id.intValue() > max) {
max = id.intValue();
}
}
return max + 1;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDataFromArchiveId(int, java.lang.String)
*/
public ArchiveDataVO findArchiveDataFromArchiveId(int signerId,
String archiveId) {
ArchiveDataVO retval = null;
ArchiveDataBean adb = archiveDataService.findByArchiveId(
ArchiveDataVO.TYPE_RESPONSE, signerId, archiveId);
if (adb != null) {
retval = adb.getArchiveDataVO();
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestIP(int, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestIP(int signerId,
String requestIP) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.findByRequestIP(
ArchiveDataVO.TYPE_RESPONSE, signerId, requestIP);
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestCertificate(int, java.math.BigInteger, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestCertificate(
int signerId, BigInteger requestCertSerialnumber,
String requestCertIssuerDN) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.
findByRequestCertificate(ArchiveDataVO.TYPE_RESPONSE, signerId, CertTools.
stringToBCDNString(requestCertIssuerDN), requestCertSerialnumber.
toString(16));
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
private WorkerConfig getWorkerConfig(int workerId) {
WorkerConfig workerConfig =
workerConfigService.getWorkerConfig(workerId);
if (workerConfig == null) {
workerConfigService.create(workerId, WorkerConfig.class.getName());
workerConfig = workerConfigService.getWorkerConfig(workerId);
}
return workerConfig;
}
private String generateTransactionID() {
return UUID.randomUUID().toString();
}
private Map<String, String> getLogMap(final RequestContext requestContext) {
Map<String, String> logMap = (Map)
requestContext.get(RequestContext.LOGMAP);
if (logMap == null) {
logMap = new HashMap<String, String>();
requestContext.put(RequestContext.LOGMAP, logMap);
}
return logMap;
}
}
| true | true | private void checkCertificateValidity(final int workerId,
final WorkerConfig awc, final Map<String, String> logMap)
throws CryptoTokenOfflineException {
boolean checkcertvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTVALIDITY, "TRUE").equalsIgnoreCase(
"TRUE");
boolean checkprivatekeyvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTPRIVATEKEYVALIDITY, "TRUE").
equalsIgnoreCase("TRUE");
int minremainingcertvalidity = Integer.valueOf(awc.getProperties().
getProperty(SignServerConstants.MINREMAININGCERTVALIDITY, "0"));
if (LOG.isDebugEnabled()) {
LOG.debug("checkcertvalidity: " + checkcertvalidity);
LOG.debug("checkprivatekeyvalidity: " + checkprivatekeyvalidity);
LOG.debug("minremainingcertvalidity: " + minremainingcertvalidity);
}
if (checkcertvalidity || checkprivatekeyvalidity || (minremainingcertvalidity
> 0)) {
// If the signer have a certificate, check that it is usable
X509Certificate cert = (new ProcessableConfig(awc)).
getSignerCertificate();
if (cert != null) {
// Log client certificate
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
// Check regular certificate validity
Date notBefore = cert.getNotBefore();
Date notAfter = cert.getNotAfter();
if (LOG.isDebugEnabled()) {
LOG.debug("The signer certificate is valid from '"
+ notBefore + "' until '" + notAfter + "'");
}
Date now = new Date();
// Certificate validity period. Cert must not be expired.
if (checkcertvalidity) {
if (now.before(notBefore)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that is not valid until "
+ notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that expired at "
+ notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
// Private key usage period. Private key must not be expired
if (checkprivatekeyvalidity) {
// Check privateKeyUsagePeriod of it exists
byte[] extvalue = cert.getExtensionValue(X509Extensions.PrivateKeyUsagePeriod.
getId());
if ((extvalue != null) && (extvalue.length > 0)) {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Found a PrivateKeyUsagePeriod in the signer certificate.");
}
try {
DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(
extvalue)).readObject());
PrivateKeyUsagePeriod p = PrivateKeyUsagePeriod.
getInstance((ASN1Sequence) new ASN1InputStream(
new ByteArrayInputStream(oct.getOctets())).
readObject());
if (p != null) {
notBefore = p.getNotBefore().getDate();
notAfter = p.getNotAfter().getDate();
if (LOG.isDebugEnabled()) {
LOG.debug("The signer certificate has a private key usage period from '"
+ notBefore + "' until '" + notAfter
+ "'");
}
now = new Date();
if (now.before(notBefore)) {
String msg = "Error Signer " + workerId
+ " have a private key that is not valid until "
+ notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a private key that expired at "
+ notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
} catch (IOException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
} catch (ParseException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
}
}
} // if (checkprivatekeyvalidity)
// Check remaining validity of certificate. Must not be too short.
if (minremainingcertvalidity > 0) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, minremainingcertvalidity);
Date check = cal.getTime();
if (LOG.isDebugEnabled()) {
LOG.debug("Checking if signer certificate expires before: "
+ check);
}
if (check.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that expires within "
+ minremainingcertvalidity + " days.";
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
} else { // if (cert != null)
if (LOG.isDebugEnabled()) {
LOG.debug("Worker does not have a signing certificate. Worker: "
+ workerId);
}
}
} // if (checkcertvalidity || checkprivatekeyvalidity) {
} // checkCertificateValidity
/**
* Checks that if this worker has a certificate (ie the worker is a Signer)
* the counter of the usages of the key has not reached the configured
* limit.
* @param workerId
* @param awc
* @param em
* @throws CryptoTokenOfflineException
*/
private void incrementAndCheckSignerKeyUsageCounter(final IProcessable worker,
final int workerId, final WorkerConfig awc, EntityManager em)
throws CryptoTokenOfflineException {
// If the signer have a certificate, check that the usage of the key
// has not reached the limit
Certificate cert = null;
if (worker instanceof BaseProcessable) {
cert = ((BaseProcessable) worker).getSigningCertificate();
} else {
// The following will not work for keystores where the SIGNSERCERT
// property is not set
cert = (new ProcessableConfig(awc)).getSignerCertificate();
}
if (cert != null) {
final long keyUsageLimit
= Long.valueOf(awc.getProperty(SignServerConstants.KEYUSAGELIMIT, "-1"));
final String keyHash
= KeyUsageCounter.createKeyHash(cert.getPublicKey());
if(LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId +"]: "
+ "Key usage limit: " + keyUsageLimit);
LOG.debug("Worker[" + workerId +"]: "
+ "Key hash: " + keyHash);
}
final Query updateQuery;
if (keyUsageLimit < 0) {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash");
} else {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash AND w.counter < :limit");
updateQuery.setParameter("limit", keyUsageLimit);
}
updateQuery.setParameter("keyhash", keyHash);
if (updateQuery.executeUpdate() < 1) {
final String message
= "Key usage limit exceeded or not initialized for worker "
+ workerId;
LOG.debug(message);
throw new CryptoTokenOfflineException(message);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "No certificate so not checking signing key usage counter");
}
}
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getStatus(int)
*/
public WorkerStatus getStatus(int workerId) throws InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + workerId
+ " doesn't exist");
}
return worker.getStatus();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getWorkerId(java.lang.String)
*/
public int getWorkerId(String signerName) {
return WorkerFactory.getInstance().getWorkerIdFromName(signerName.
toUpperCase(), workerConfigService, globalConfigurationSession, new SignServerContext(
em));
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#reloadConfiguration(int)
*/
public void reloadConfiguration(int workerId) {
if (workerId == 0) {
globalConfigurationSession.reload();
} else {
WorkerFactory.getInstance().reloadWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
// Try to insert a key usage counter entry for this worker's public
// key
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
try {
final Certificate cert = ((BaseProcessable)worker)
.getSigningCertificate();
if (cert != null) {
final String keyHash = KeyUsageCounter
.createKeyHash(cert.getPublicKey());
KeyUsageCounter counter
= em.find(KeyUsageCounter.class, keyHash);
if (counter == null) {
counter = new KeyUsageCounter(keyHash);
em.persist(counter);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "key usage counter: " + counter.getCounter());
}
}
} catch (CryptoTokenOfflineException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[ " + workerId + "]: "
+ "Crypto token offline trying to create key usage counter");
}
}
}
}
if (workerId == 0 || globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_SERVICES).contains(new Integer(
workerId))) {
serviceTimerSession.unload(workerId);
serviceTimerSession.load(workerId);
}
StatisticsManager.flush(workerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#activateSigner(int, java.lang.String)
*/
public void activateSigner(int signerId, String authenticationCode)
throws CryptoTokenAuthenticationFailureException,
CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
signer.activateSigner(authenticationCode);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#deactivateSigner(int)
*/
public boolean deactivateSigner(int signerId)
throws CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.deactivateSigner();
}
/* (non-Javadoc)
* @see org.signserver.ejb.IWorkerSession#getCurrentSignerConfig(int)
*/
public WorkerConfig getCurrentWorkerConfig(int signerId) {
return getWorkerConfig(signerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#setWorkerProperty(int, java.lang.String, java.lang.String)
*/
public void setWorkerProperty(int workerId, String key, String value) {
WorkerConfig config = getWorkerConfig(workerId);
config.setProperty(key.toUpperCase(), value);
workerConfigService.setWorkerConfig(workerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeWorkerProperty(int, java.lang.String)
*/
public boolean removeWorkerProperty(int workerId, String key) {
boolean result = false;
WorkerConfig config = getWorkerConfig(workerId);
result = config.removeProperty(key.toUpperCase());
if (config.getProperties().size() == 0) {
workerConfigService.removeWorkerConfig(workerId);
LOG.debug("WorkerConfig is empty and therefore removed.");
} else {
workerConfigService.setWorkerConfig(workerId, config);
}
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getAuthorizedClients(int)
*/
public Collection<AuthorizedClient> getAuthorizedClients(int signerId) {
return new ProcessableConfig(getWorkerConfig(signerId)).
getAuthorizedClients();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#addAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public void addAuthorizedClient(int signerId, AuthorizedClient authClient) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).addAuthorizedClient(authClient);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public boolean removeAuthorizedClient(int signerId,
AuthorizedClient authClient) {
boolean result = false;
WorkerConfig config = getWorkerConfig(signerId);
result = (new ProcessableConfig(config)).removeAuthorizedClient(
authClient);
workerConfigService.setWorkerConfig(signerId, config);
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getCertificateRequest(int, org.signserver.common.ISignerCertReqInfo)
*/
public ICertReqData getCertificateRequest(int signerId,
ISignerCertReqInfo certReqInfo) throws
CryptoTokenOfflineException, InvalidWorkerIdException {
if (LOG.isTraceEnabled()) {
LOG.trace(">getCertificateRequest: signerId=" + signerId);
}
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable processable = (IProcessable) worker;
if (LOG.isDebugEnabled()) {
LOG.debug("Found processable worker of type: " + processable.
getClass().getName());
}
ICertReqData ret = processable.genCertificateRequest(certReqInfo);
if (LOG.isTraceEnabled()) {
LOG.trace("<getCertificateRequest: signerId=" + signerId);
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificate(int)
*/
public Certificate getSignerCertificate(final int signerId) throws CryptoTokenOfflineException {
Certificate ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
ret = ((BaseProcessable) worker).getSigningCertificate();
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificateChain(int)
*/
public List<Certificate> getSignerCertificateChain(final int signerId) throws CryptoTokenOfflineException {
List<Certificate> ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
Collection<Certificate> certs = ((BaseProcessable) worker)
.getSigningCertificateChain();
if (certs instanceof List) {
ret = (List) certs;
} else {
ret = new LinkedList<Certificate>(certs);
}
}
return ret;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#destroyKey(int, int)
*/
public boolean destroyKey(int signerId, int purpose) throws
InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.destroyKey(purpose);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificate(int, java.security.cert.X509Certificate, java.lang.String)
*/
public void uploadSignerCertificate(int signerId, X509Certificate signerCert,
String scope) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).setSignerCertificate(signerCert, scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificateChain(int, java.util.Collection, java.lang.String)
*/
public void uploadSignerCertificateChain(int signerId,
Collection<Certificate> signerCerts, String scope) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).setSignerCertificateChain(signerCerts,
scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#genFreeWorkerId()
*/
public int genFreeWorkerId() {
Collection<Integer> ids = globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_ALL);
int max = 0;
Iterator<Integer> iter = ids.iterator();
while (iter.hasNext()) {
Integer id = iter.next();
if (id.intValue() > max) {
max = id.intValue();
}
}
return max + 1;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDataFromArchiveId(int, java.lang.String)
*/
public ArchiveDataVO findArchiveDataFromArchiveId(int signerId,
String archiveId) {
ArchiveDataVO retval = null;
ArchiveDataBean adb = archiveDataService.findByArchiveId(
ArchiveDataVO.TYPE_RESPONSE, signerId, archiveId);
if (adb != null) {
retval = adb.getArchiveDataVO();
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestIP(int, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestIP(int signerId,
String requestIP) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.findByRequestIP(
ArchiveDataVO.TYPE_RESPONSE, signerId, requestIP);
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestCertificate(int, java.math.BigInteger, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestCertificate(
int signerId, BigInteger requestCertSerialnumber,
String requestCertIssuerDN) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.
findByRequestCertificate(ArchiveDataVO.TYPE_RESPONSE, signerId, CertTools.
stringToBCDNString(requestCertIssuerDN), requestCertSerialnumber.
toString(16));
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
private WorkerConfig getWorkerConfig(int workerId) {
WorkerConfig workerConfig =
workerConfigService.getWorkerConfig(workerId);
if (workerConfig == null) {
workerConfigService.create(workerId, WorkerConfig.class.getName());
workerConfig = workerConfigService.getWorkerConfig(workerId);
}
return workerConfig;
}
private String generateTransactionID() {
return UUID.randomUUID().toString();
}
private Map<String, String> getLogMap(final RequestContext requestContext) {
Map<String, String> logMap = (Map)
requestContext.get(RequestContext.LOGMAP);
if (logMap == null) {
logMap = new HashMap<String, String>();
requestContext.put(RequestContext.LOGMAP, logMap);
}
return logMap;
}
}
| private void checkCertificateValidity(final int workerId,
final WorkerConfig awc, final Map<String, String> logMap)
throws CryptoTokenOfflineException {
boolean checkcertvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTVALIDITY, "TRUE").equalsIgnoreCase(
"TRUE");
boolean checkprivatekeyvalidity = awc.getProperties().getProperty(
SignServerConstants.CHECKCERTPRIVATEKEYVALIDITY, "TRUE").
equalsIgnoreCase("TRUE");
int minremainingcertvalidity = Integer.valueOf(awc.getProperties().
getProperty(SignServerConstants.MINREMAININGCERTVALIDITY, "0"));
if (LOG.isDebugEnabled()) {
LOG.debug("checkcertvalidity: " + checkcertvalidity);
LOG.debug("checkprivatekeyvalidity: " + checkprivatekeyvalidity);
LOG.debug("minremainingcertvalidity: " + minremainingcertvalidity);
}
if (checkcertvalidity || checkprivatekeyvalidity || (minremainingcertvalidity
> 0)) {
// If the signer have a certificate, check that it is usable
final Certificate signerCert = getSignerCertificate(workerId);
if (signerCert instanceof X509Certificate) {
final X509Certificate cert = (X509Certificate) signerCert;
// Log client certificate
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SUBJECTDN,
cert.getSubjectDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_ISSUERDN,
cert.getIssuerDN().getName());
logMap.put(IWorkerLogger.LOG_SIGNER_CERT_SERIALNUMBER,
cert.getSerialNumber().toString(16));
// Check regular certificate validity
Date notBefore = cert.getNotBefore();
Date notAfter = cert.getNotAfter();
if (LOG.isDebugEnabled()) {
LOG.debug("The signer certificate is valid from '"
+ notBefore + "' until '" + notAfter + "'");
}
Date now = new Date();
// Certificate validity period. Cert must not be expired.
if (checkcertvalidity) {
if (now.before(notBefore)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that is not valid until "
+ notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that expired at "
+ notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
// Private key usage period. Private key must not be expired
if (checkprivatekeyvalidity) {
// Check privateKeyUsagePeriod of it exists
byte[] extvalue = cert.getExtensionValue(X509Extensions.PrivateKeyUsagePeriod.
getId());
if ((extvalue != null) && (extvalue.length > 0)) {
if (LOG.isDebugEnabled()) {
LOG.debug(
"Found a PrivateKeyUsagePeriod in the signer certificate.");
}
try {
DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(
extvalue)).readObject());
PrivateKeyUsagePeriod p = PrivateKeyUsagePeriod.
getInstance((ASN1Sequence) new ASN1InputStream(
new ByteArrayInputStream(oct.getOctets())).
readObject());
if (p != null) {
notBefore = p.getNotBefore().getDate();
notAfter = p.getNotAfter().getDate();
if (LOG.isDebugEnabled()) {
LOG.debug("The signer certificate has a private key usage period from '"
+ notBefore + "' until '" + notAfter
+ "'");
}
now = new Date();
if (now.before(notBefore)) {
String msg = "Error Signer " + workerId
+ " have a private key that is not valid until "
+ notBefore;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
if (now.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a private key that expired at "
+ notAfter;
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
} catch (IOException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
} catch (ParseException e) {
LOG.error(e);
CryptoTokenOfflineException newe =
new CryptoTokenOfflineException(
"Error Signer " + workerId
+ " have a problem with PrivateKeyUsagePeriod, check server log.");
newe.initCause(e);
throw newe;
}
}
} // if (checkprivatekeyvalidity)
// Check remaining validity of certificate. Must not be too short.
if (minremainingcertvalidity > 0) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, minremainingcertvalidity);
Date check = cal.getTime();
if (LOG.isDebugEnabled()) {
LOG.debug("Checking if signer certificate expires before: "
+ check);
}
if (check.after(notAfter)) {
String msg = "Error Signer " + workerId
+ " have a signing certificate that expires within "
+ minremainingcertvalidity + " days.";
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new CryptoTokenOfflineException(msg);
}
}
} else { // if (cert != null)
if (LOG.isDebugEnabled()) {
LOG.debug("Worker does not have a signing certificate. Worker: "
+ workerId);
}
}
} // if (checkcertvalidity || checkprivatekeyvalidity) {
} // checkCertificateValidity
/**
* Checks that if this worker has a certificate (ie the worker is a Signer)
* the counter of the usages of the key has not reached the configured
* limit.
* @param workerId
* @param awc
* @param em
* @throws CryptoTokenOfflineException
*/
private void incrementAndCheckSignerKeyUsageCounter(final IProcessable worker,
final int workerId, final WorkerConfig awc, EntityManager em)
throws CryptoTokenOfflineException {
// If the signer have a certificate, check that the usage of the key
// has not reached the limit
Certificate cert = null;
if (worker instanceof BaseProcessable) {
cert = ((BaseProcessable) worker).getSigningCertificate();
} else {
// The following will not work for keystores where the SIGNSERCERT
// property is not set
cert = (new ProcessableConfig(awc)).getSignerCertificate();
}
if (cert != null) {
final long keyUsageLimit
= Long.valueOf(awc.getProperty(SignServerConstants.KEYUSAGELIMIT, "-1"));
final String keyHash
= KeyUsageCounter.createKeyHash(cert.getPublicKey());
if(LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId +"]: "
+ "Key usage limit: " + keyUsageLimit);
LOG.debug("Worker[" + workerId +"]: "
+ "Key hash: " + keyHash);
}
final Query updateQuery;
if (keyUsageLimit < 0) {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash");
} else {
updateQuery = em.createQuery("UPDATE KeyUsageCounter w SET w.counter = w.counter + 1 WHERE w.keyHash = :keyhash AND w.counter < :limit");
updateQuery.setParameter("limit", keyUsageLimit);
}
updateQuery.setParameter("keyhash", keyHash);
if (updateQuery.executeUpdate() < 1) {
final String message
= "Key usage limit exceeded or not initialized for worker "
+ workerId;
LOG.debug(message);
throw new CryptoTokenOfflineException(message);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "No certificate so not checking signing key usage counter");
}
}
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getStatus(int)
*/
public WorkerStatus getStatus(int workerId) throws InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + workerId
+ " doesn't exist");
}
return worker.getStatus();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getWorkerId(java.lang.String)
*/
public int getWorkerId(String signerName) {
return WorkerFactory.getInstance().getWorkerIdFromName(signerName.
toUpperCase(), workerConfigService, globalConfigurationSession, new SignServerContext(
em));
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#reloadConfiguration(int)
*/
public void reloadConfiguration(int workerId) {
if (workerId == 0) {
globalConfigurationSession.reload();
} else {
WorkerFactory.getInstance().reloadWorker(workerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
// Try to insert a key usage counter entry for this worker's public
// key
// Get worker instance
final IWorker worker = WorkerFactory.getInstance().getWorker(workerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
try {
final Certificate cert = ((BaseProcessable)worker)
.getSigningCertificate();
if (cert != null) {
final String keyHash = KeyUsageCounter
.createKeyHash(cert.getPublicKey());
KeyUsageCounter counter
= em.find(KeyUsageCounter.class, keyHash);
if (counter == null) {
counter = new KeyUsageCounter(keyHash);
em.persist(counter);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[" + workerId + "]: "
+ "key usage counter: " + counter.getCounter());
}
}
} catch (CryptoTokenOfflineException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Worker[ " + workerId + "]: "
+ "Crypto token offline trying to create key usage counter");
}
}
}
}
if (workerId == 0 || globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_SERVICES).contains(new Integer(
workerId))) {
serviceTimerSession.unload(workerId);
serviceTimerSession.load(workerId);
}
StatisticsManager.flush(workerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#activateSigner(int, java.lang.String)
*/
public void activateSigner(int signerId, String authenticationCode)
throws CryptoTokenAuthenticationFailureException,
CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
signer.activateSigner(authenticationCode);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#deactivateSigner(int)
*/
public boolean deactivateSigner(int signerId)
throws CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.deactivateSigner();
}
/* (non-Javadoc)
* @see org.signserver.ejb.IWorkerSession#getCurrentSignerConfig(int)
*/
public WorkerConfig getCurrentWorkerConfig(int signerId) {
return getWorkerConfig(signerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#setWorkerProperty(int, java.lang.String, java.lang.String)
*/
public void setWorkerProperty(int workerId, String key, String value) {
WorkerConfig config = getWorkerConfig(workerId);
config.setProperty(key.toUpperCase(), value);
workerConfigService.setWorkerConfig(workerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeWorkerProperty(int, java.lang.String)
*/
public boolean removeWorkerProperty(int workerId, String key) {
boolean result = false;
WorkerConfig config = getWorkerConfig(workerId);
result = config.removeProperty(key.toUpperCase());
if (config.getProperties().size() == 0) {
workerConfigService.removeWorkerConfig(workerId);
LOG.debug("WorkerConfig is empty and therefore removed.");
} else {
workerConfigService.setWorkerConfig(workerId, config);
}
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getAuthorizedClients(int)
*/
public Collection<AuthorizedClient> getAuthorizedClients(int signerId) {
return new ProcessableConfig(getWorkerConfig(signerId)).
getAuthorizedClients();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#addAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public void addAuthorizedClient(int signerId, AuthorizedClient authClient) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).addAuthorizedClient(authClient);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public boolean removeAuthorizedClient(int signerId,
AuthorizedClient authClient) {
boolean result = false;
WorkerConfig config = getWorkerConfig(signerId);
result = (new ProcessableConfig(config)).removeAuthorizedClient(
authClient);
workerConfigService.setWorkerConfig(signerId, config);
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getCertificateRequest(int, org.signserver.common.ISignerCertReqInfo)
*/
public ICertReqData getCertificateRequest(int signerId,
ISignerCertReqInfo certReqInfo) throws
CryptoTokenOfflineException, InvalidWorkerIdException {
if (LOG.isTraceEnabled()) {
LOG.trace(">getCertificateRequest: signerId=" + signerId);
}
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable processable = (IProcessable) worker;
if (LOG.isDebugEnabled()) {
LOG.debug("Found processable worker of type: " + processable.
getClass().getName());
}
ICertReqData ret = processable.genCertificateRequest(certReqInfo);
if (LOG.isTraceEnabled()) {
LOG.trace("<getCertificateRequest: signerId=" + signerId);
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificate(int)
*/
public Certificate getSignerCertificate(final int signerId) throws CryptoTokenOfflineException {
Certificate ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
ret = ((BaseProcessable) worker).getSigningCertificate();
}
return ret;
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#getSigningCertificateChain(int)
*/
public List<Certificate> getSignerCertificateChain(final int signerId) throws CryptoTokenOfflineException {
List<Certificate> ret = null;
final IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession,
new SignServerContext(em));
if (worker instanceof BaseProcessable) {
Collection<Certificate> certs = ((BaseProcessable) worker)
.getSigningCertificateChain();
if (certs instanceof List) {
ret = (List) certs;
} else {
ret = new LinkedList<Certificate>(certs);
}
}
return ret;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#destroyKey(int, int)
*/
public boolean destroyKey(int signerId, int purpose) throws
InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId,
workerConfigService, globalConfigurationSession, new SignServerContext(
em));
if (worker == null) {
throw new InvalidWorkerIdException("Given SignerId " + signerId
+ " doesn't exist");
}
if (!(worker instanceof IProcessable)) {
throw new InvalidWorkerIdException(
"Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.destroyKey(purpose);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificate(int, java.security.cert.X509Certificate, java.lang.String)
*/
public void uploadSignerCertificate(int signerId, X509Certificate signerCert,
String scope) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).setSignerCertificate(signerCert, scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificateChain(int, java.util.Collection, java.lang.String)
*/
public void uploadSignerCertificateChain(int signerId,
Collection<Certificate> signerCerts, String scope) {
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).setSignerCertificateChain(signerCerts,
scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#genFreeWorkerId()
*/
public int genFreeWorkerId() {
Collection<Integer> ids = globalConfigurationSession.getWorkers(
GlobalConfiguration.WORKERTYPE_ALL);
int max = 0;
Iterator<Integer> iter = ids.iterator();
while (iter.hasNext()) {
Integer id = iter.next();
if (id.intValue() > max) {
max = id.intValue();
}
}
return max + 1;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDataFromArchiveId(int, java.lang.String)
*/
public ArchiveDataVO findArchiveDataFromArchiveId(int signerId,
String archiveId) {
ArchiveDataVO retval = null;
ArchiveDataBean adb = archiveDataService.findByArchiveId(
ArchiveDataVO.TYPE_RESPONSE, signerId, archiveId);
if (adb != null) {
retval = adb.getArchiveDataVO();
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestIP(int, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestIP(int signerId,
String requestIP) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.findByRequestIP(
ArchiveDataVO.TYPE_RESPONSE, signerId, requestIP);
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestCertificate(int, java.math.BigInteger, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestCertificate(
int signerId, BigInteger requestCertSerialnumber,
String requestCertIssuerDN) {
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.
findByRequestCertificate(ArchiveDataVO.TYPE_RESPONSE, signerId, CertTools.
stringToBCDNString(requestCertIssuerDN), requestCertSerialnumber.
toString(16));
Iterator<ArchiveDataBean> iter = result.iterator();
while (iter.hasNext()) {
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
private WorkerConfig getWorkerConfig(int workerId) {
WorkerConfig workerConfig =
workerConfigService.getWorkerConfig(workerId);
if (workerConfig == null) {
workerConfigService.create(workerId, WorkerConfig.class.getName());
workerConfig = workerConfigService.getWorkerConfig(workerId);
}
return workerConfig;
}
private String generateTransactionID() {
return UUID.randomUUID().toString();
}
private Map<String, String> getLogMap(final RequestContext requestContext) {
Map<String, String> logMap = (Map)
requestContext.get(RequestContext.LOGMAP);
if (logMap == null) {
logMap = new HashMap<String, String>();
requestContext.put(RequestContext.LOGMAP, logMap);
}
return logMap;
}
}
|
diff --git a/RocksInterpreter.java b/RocksInterpreter.java
index c646dbe..2774a69 100644
--- a/RocksInterpreter.java
+++ b/RocksInterpreter.java
@@ -1,2021 +1,2023 @@
/*
javascript4P5 is a port of javascript4me for Processing, by Davide Della Casa
javascript4me is made by Wang Lei ( [email protected] ) and is released under GNU Lesser GPL
You can find javascript4me at http://code.google.com/p/javascript4me/
*/
import java.util.*;
public class RocksInterpreter {
public boolean DEBUG = true;
/** whether to evaluate in-string expressions in language level */
public boolean evalString = true;
public String src;
// array of tokens. a token = (type, { [pos, len], value} )
public Pack tt;
public int pos = 0;
public int endpos = 0;
public boolean dontPrintOutput;
public StringBuffer out = new StringBuffer();
public RocksInterpreter(String src, boolean dontPrintOutput, Pack tokens, int pos, int len) {
this.dontPrintOutput = dontPrintOutput;
reset(src, tokens, pos, len);
}
public RocksInterpreter reset(String src, Pack tokens, int pos, int len) {
this.src = src;
if (tokens == null) {
tt = tokenize(src, pos, len);
this.pos = 0;
this.endpos = tt.iSize;
} else {
tt = tokens;
this.pos = pos;
this.endpos = pos + len;
}
return this;
}
////////////////////////////// Lexer Method ///////////////////////////
/**
* TODO support of native regular expression "/<pattern>/<args>"
* TODO smarter tokenizing for ignoring semicolon
* @param src
* @param pos
* @param len
* @return
*/
public final Pack tokenize(String src, int pos, int len) {
char[] cc = src.toCharArray();
Pack tt = new Pack(50, 50);
// lexer states:
// * 0: normal,
// * '/': single-line comments, '*': multi-line comments
// * '\'': single-quote string, '"': double-quote string
// * '3': triple quote string
int state = 0; //
StringBuffer buf = new StringBuffer();
int startPos = 0, endpos = pos + len;
boolean continueline = false;
while (pos < endpos) {
mainswitch:
switch (state) {
case 0:
char c = cc[pos];
// skip white spaces { ' ', '\t', '\r' }
for (; c == ' ' || c == '\t' || c == '\r';) {
++pos;
if (pos < endpos) {
c = cc[pos];
} else {
break mainswitch;
}
}
if (continueline && c == RC.TOK_EOL) {
++pos;
continueline = false;
} else if (c >= '0' && c <= '9') { // number
int next, p = pos;
float ival;
if (c == '0' && pos + 1 < endpos && ((next = cc[pos + 1]) == 'x' || next == 'X')) {
int d;
for (d = 8, pos += 2, c = cc[pos]; --d >= 0
&& (c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F');
c = cc[++pos])
;
ival = (int) Long.parseLong(new String(cc, p + 2, pos - p - 2), 16);
} else {
boolean noPoint = true;
while (c >= '0' && c <= '9' || noPoint && c == '.') {
if (c == '.') noPoint = false;
++pos;
c = pos < endpos ? cc[pos] : 0;
}
ival = Float.parseFloat(new String(cc, p, pos - p));
}
addToken(tt, RC.TOK_NUMBER, p, pos - p, new Float(ival));
} else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
|| c == '_' || c == '$') { // symbol or keyword
int p = pos;
while (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
|| c >= '0' && c <= '9'
|| c == '_' || c == '$') {
++pos;
c = pos < endpos ? cc[pos] : 0;
}
String symb = new String(cc, p, pos - p);
int iKey = keywordIndex(symb);
addToken(tt, iKey < 0 ? RC.TOK_SYMBOL : iKey, p, pos - p, symb);
} else {
switch (c) {
case RC.TOK_SEM: // ;
case RC.TOK_EOL: // \n
case RC.TOK_DOT: // .
case RC.TOK_LBK: // [
case RC.TOK_RBK: // ]
case RC.TOK_LBR: // {
case RC.TOK_RBR: // }
case RC.TOK_LPR: // (
case RC.TOK_RPR: // )
case RC.TOK_COM: // ,
case RC.TOK_COL: // :
case RC.TOK_QMK: // ?
case RC.TOK_BNO: // ~
addToken(tt, c, pos++, 1, null);
break;
case RC.BACKSLASH: // \
++pos;
continueline = true;
break;
case RC.DQUOT: // ", """
case RC.SQUOT: // '
if (c == '"' && pos + 2 < endpos && cc[pos + 1] == '"' && cc[pos + 2] == '"') {
state = 3;
pos += 3;
startPos = pos;
} else {
state = c; // '\'' or '"'
startPos = ++pos;
}
break;
case RC.TOK_MOD: // %, %=
case RC.TOK_BXO: // ^, ^=
case RC.TOK_ADD: // +, +=, ++
case RC.TOK_MIN: // -, -=, --
case RC.TOK_MUL: // *, *=, **
case RC.TOK_BOR: // |, |=, ||
case RC.TOK_BAN: // &, &=, &&
case RC.TOK_ASS: // =, ==, ===
case RC.TOK_NOT: // !, !=, !==
case RC.TOK_DIV: // /, /=, //, /*
case RC.TOK_GRT: // >, >=, >>, >>=, >>>, >>>=
case RC.TOK_LES: // <, <=, <<, <<=
int nextp, nextc = (nextp = pos + 1) < endpos ? cc[nextp] : 0;
int tokinc = 0, posinc = 1;
if (c == '/' && (nextc == '/' || nextc == '*')) {
state = nextc; // '/' or '*'
pos += 2;
startPos = pos;
break;
} else if (nextc == '=') {
if ((c == '=' || c == '!') && pos + 2 < endpos && cc[pos + 2] == '=') {
tokinc = RC.TRI_START;
posinc = 3;
} else {
tokinc = RC.ASS_START;
++posinc;
}
} else if (nextc == c) {
int nnext = pos + 2 < endpos ? cc[pos + 2] : 0;
if (c == '>' || c == '<') {
if (nnext == '=') { // <<=, >>=
tokinc = RC.TRI_START;
posinc = 3;
} else if (c == '>' && nnext == '>') { // >>>, >>>=
if (pos + 3 < endpos && cc[pos + 3] == '=') { // >>>=
addToken(tt, RC.TOK_RZA, pos, 4, null);
pos += 4;
} else { // >>>
addToken(tt, RC.TOK_RSZ, pos, 3, null);
pos += 3;
}
break;
} else { // <<, >>
tokinc = RC.DBL_START;
++posinc;
}
} else if (c != '%' && c != '^') {
tokinc = RC.DBL_START;
++posinc;
}
}
addToken(tt, c + tokinc, pos, posinc, null);
pos += posinc;
break;
default:
throw ex(c, pos, null);
}
}
break;
case '\'':
case '"':
case 3: // """: triple quote string
c = cc[pos];
if (state == 3 && c == '"' && pos + 2 < endpos && cc[pos + 1] == '"' && cc[pos + 2] == '"') {
addToken(tt, RC.TOK_STRING, startPos, pos - startPos, buf.toString());
buf.setLength(0);
pos += 3;
state = 0;
} else if (state != 3 && c == state) {
addToken(tt, RC.TOK_STRING, startPos, pos - startPos, buf.toString());
buf.setLength(0);
++pos;
state = 0;
} else if (state != 3 && c == RC.TOK_EOL) {
throw ex(c, pos, String.valueOf((char) state));
} else if (c == '\\' && pos + 1 < endpos){
char nc = cc[pos + 1];
int inc = 2;
switch (nc) {
case 'n':
buf.append('\n');
break;
case 'r':
buf.append('\r');
break;
case 't':
buf.append('\t');
break;
case 'u':
if (pos + 5 < endpos) {
char uc = (char) Integer.parseInt(new String(cc, pos + 2, 4), 16);
buf.append(uc);
inc = 6;
}
break;
case '\\':
case '\'':
case '"':
buf.append(nc);
break;
default:
inc = 1;
buf.append(c);
break;
}
pos += inc;
} else {
buf.append(c);
++pos;
}
break;
case '/': // single-line comment
c = cc[pos++];
if (c == RC.TOK_EOL) {
state = 0;
}
break;
case '*': // multi-line comment
c = cc[pos++];
if (c == '*' && pos < endpos && cc[pos] == '/') {
++pos;
state = 0;
}
break;
}
}
addToken(tt, RC.TOK_EOL, pos, 0, null);
// debug output only
// buf.setLength(0);
// for (int i = 0, n = tt.oSize; i < n; i++) {
// int token = tt.getInt(i);
// Object tinfo = tt.getObject(i);
// buf.append(i).append(":\t").append(RC.tokenName(token, tinfo))
// .append(" (").append(token).append(")\r\n");
// }
// System.out.println(buf);
return tt;
}
////////////////////////////// Parser Methods ///////////////////////////
final void statements(Rv callObj, Node node, int loop) {
int[] tti = tt.iArray;
int endpos = this.endpos;
while (pos < endpos && loop-- != 0) {
int t;
if ((t = tti[pos]) == RC.TOK_EOL) {
t = eat(RC.TOK_EOL);
}
if (pos >= endpos) break;
int posmk = pos++;
switch (t) {
// case RC.TOK_SEM: // blank statement
// break;
case RC.TOK_IF:
Node n = astNode(node, t, posmk, 0);
eat(RC.TOK_LPR);
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_RPR, 0)); // * = exp
eat(RC.TOK_RPR);
statements(callObj, n, 1);
if (pos < endpos && tti[pos] == RC.TOK_ELSE) {
++pos;
n.tagType = RC.TOK_ELSE;
statements(callObj, n, 1);
}
break;
case RC.TOK_WHILE:
case RC.TOK_WITH:
n = astNode(node, t, posmk, 0);
eat(RC.TOK_LPR);
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_RPR, 0)); // * = exp
eat(RC.TOK_RPR);
statements(callObj, n, 1);
break;
case RC.TOK_DO:
n = astNode(node, t, posmk, 0);
statements(callObj, n, 1);
eat(RC.TOK_WHILE);
eat(RC.TOK_LPR);
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_RPR, 0)); // * = exp
eat(RC.TOK_RPR);
break;
case RC.TOK_FOR:
n = astNode(node, t, posmk, 0);
eat(RC.TOK_LPR);
int p = pos;
eatUntil(RC.TOK_SEM, RC.TOK_RPR);
if ((t = tti[pos]) == RC.TOK_RPR) { // ';' not found, this is a "for ... in"
pos = p; // go back
n.tagType = RC.TOK_IN;
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_IN, 0));
eat(RC.TOK_IN);
} else { // found ';'
astNode(n, RC.TOK_MUL, p, pos - p);
eat(t); // skip ';'
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_SEM, 0)); // * = exp
eat(RC.TOK_SEM);
}
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_RPR, 0));
eat(RC.TOK_RPR);
statements(callObj, n, 1);
break;
case RC.TOK_SWITCH:
n = astNode(node, t, posmk, 0);
eat(RC.TOK_LPR);
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_RPR, 0));
eat(RC.TOK_RPR);
eat(RC.TOK_LBR);
astNode(n, RC.TOK_LBR, pos, eatUntil(RC.TOK_RBR, 0));
eat(RC.TOK_RBR);
break;
case RC.TOK_CASE:
n = astNode(node, t, posmk, 0);
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_COL, 0));
eat(RC.TOK_COL);
break;
case RC.TOK_DEFAULT:
n = astNode(node, t, posmk, 1);
eat(RC.TOK_COL);
break;
case RC.TOK_FUNCTION:
n = astNode(null, t, posmk, 0);
int pp = pos;
eatUntil(RC.TOK_LPR, 0);
boolean findname = false;
Rv func = null;
for (int ii = pos; --ii >= pp;) {
if (tti[ii] == RC.TOK_SYMBOL) {
String funcId;
funcId = n.id = (String) ((Object[]) tt.oArray[ii])[1];
func = new Rv(false, n, 0);
func.co.prev = callObj;
callObj.putl(funcId, func);
findname = true;
break;
}
}
if (!findname) throw ex(tti[pos], new Object[] { new int[] { pos, 0 } }, "function name");
funcBody(n);
func.num = n.children.oSize - 1;
break;
case RC.TOK_TRY:
n = astNode(node, t, posmk, 0);
eat(RC.TOK_LBR);
Node fn = astNode(n, RC.TOK_FUNCTION, pos, 0);
astNode(fn, RC.TOK_LBR, pos, eatUntil(RC.TOK_RBR, 0));
eat(RC.TOK_RBR);
boolean hascatch = false, hasfinally = false;
if (tti[pos] == RC.TOK_CATCH) {
eat(RC.TOK_CATCH);
eat(RC.TOK_LPR);
fn = astNode(n, RC.TOK_FUNCTION, pos, 0);
astNode(fn, RC.TOK_MUL, pos, eatUntil(RC.TOK_RPR, 0));
eat(RC.TOK_RPR);
eat(RC.TOK_LBR);
astNode(fn, RC.TOK_LBR, pos, eatUntil(RC.TOK_RBR, 0));
eat(RC.TOK_RBR);
hascatch = true;
}
if (pos < endpos && tti[pos] == RC.TOK_FINALLY) {
if (!hascatch) {
fn = astNode(n, RC.TOK_FUNCTION, pos, 0);
}
eat(RC.TOK_FINALLY);
eat(RC.TOK_LBR);
fn = astNode(n, RC.TOK_FUNCTION, pos, 0);
astNode(fn, RC.TOK_LBR, pos, eatUntil(RC.TOK_RBR, 0));
eat(RC.TOK_RBR);
hasfinally = true;
}
if (!hasfinally && !hascatch) { // try only
throw ex(tti[pos], new Object[] { new int[] { pos, 0 } }, "catch/finally");
}
if (!hasfinally) {
fn = astNode(n, RC.TOK_FUNCTION, pos, 0);
}
break;
case RC.TOK_RETURN:
case RC.TOK_THROW:
n = astNode(node, t, posmk, 0);
astNode(n, RC.TOK_MUL, pos, eatUntil(RC.TOK_EOL, RC.TOK_SEM));
if (pos < endpos) eat(tti[pos]); // skip eol or ';'
break;
case RC.TOK_BREAK:
case RC.TOK_CONTINUE:
astNode(node, t, posmk, 1);
break;
case RC.TOK_LBR:
n = astNode(node, t, pos, eatUntil(RC.TOK_RBR, 0)); // '{' = block
eat(RC.TOK_RBR);
break;
default: // expression
pos = posmk; // pos was increased by default
astNode(node, RC.TOK_MUL, posmk, eatUntil(RC.TOK_EOL, RC.TOK_SEM));
if (pos < endpos) eat(tti[pos]); // skip eol or ';'
break;
}
}
}
final void expression(Node node, Rv callObj) {
int[] tti = tt.iArray;
Object[] tto = tt.oArray;
int endpos = this.endpos, prev, cocnt, len;
int state; // 1: normal, 2: invoke, 3: json array, 4: json object
prev = cocnt = state = 0;
Pack rpn = new Pack(len = endpos - pos, len); // for generated reverse polish notation
Pack op = new Pack(20, 20); // for operator
Pack st = new Pack(10, -1); // stack for [ state, comma_count ]
Rhash opidx = htOptrIndex;
int[][] ptab = prioTable;
boolean isNew = false;
mainloop:
while (pos <= endpos) {
boolean noeof;
int t = (noeof = pos < endpos) ? tti[pos] : RC.TOK_EOF;
Object[] to = noeof ? (Object[]) tto[pos] : null;
switch (t) {
case RC.TOK_NEW: // fall throuth
// TODO handle new Array;
isNew = true;
case RC.TOK_EOL:
++pos;
continue mainloop;
case RC.TOK_COM:
if (state > 1) {
t = RC.TOK_SEP;
if (state == 3 && (prev == RC.TOK_SEP || prev == RC.TOK_JSONARR)) { // handle arr = [1,,,2]
rpn.add(RC.TOK_NUMBER).add(Rv._undefined);
}
}
++cocnt;
break;
case RC.TOK_COL:
if (state == 4) t = RC.TOK_JSONCOL;
break;
case RC.TOK_LPR:
case RC.TOK_LBK:
case RC.TOK_INC:
case RC.TOK_DEC:
case RC.TOK_MIN:
case RC.TOK_ADD:
boolean prevSym = prev > 0 && prev <= RC.TOK_SYMBOL // NUMBER, STRING or SYMBOL
|| prev == RC.TOK_RPR || prev == RC.TOK_RBK || prev == RC.TOK_RBR;
boolean isBkOrMin = t == RC.TOK_LBK || t == RC.TOK_MIN || t == RC.TOK_ADD;
if (prevSym && !isBkOrMin // foo(), a++
|| !prevSym && isBkOrMin) { // a = [1, 2], 12 + -5
t += RC.RPN_START;
if (t == RC.TOK_INVOKE && isNew) {
t = RC.TOK_INIT;
isNew = false;
}
}
break;
case RC.TOK_FUNCTION:
Node n = astNode(null, t, pos, 0);
eat(RC.TOK_FUNCTION); // skip "function"
String id = null;
if (tti[pos] == RC.TOK_SYMBOL) { // named function
id = (String) ((Object[]) tto[pos++])[1];
} else {
id = "$direct_func$" + pos;
}
n.id = id;
funcBody(n);
Rv func = new Rv(false, n, 0);
Rv go;
for (go = callObj; go.prev != null; go = go.prev);
func.co.prev = go;
go.putl(id, func);
func.num = n.children.oSize - 1;
rpn.add(RC.TOK_SYMBOL).add(Rv.symbol("Function"))
.add(RC.TOK_SYMBOL).add(Rv.symbol(id))
.add(RC.TOK_NUMBER).add(Rv._true) // numArgs = 1
.add(RC.TOK_INIT).add(new Rv());
prev = RC.TOK_INIT;
continue mainloop;
}
while (t != 0) {
int top = op.iSize > 0 ? op.iArray[op.iSize - 1] : RC.TOK_EMPTY;
int offset = top >>> 16;
top &= 0xffff;
int row = opidx.get(t, -1), col = opidx.get(top, -1);
if (row == -1 || col == -1) {
throw ex(t, to, "stack top: " + RC.tokenName(top, null));
}
int act = ptab[row][col];
int newstt = (act >> 1) & 0x7, newact = (act >> 4) & 0x7, consume = act & 0x1;
switch (newact) {
case 2: // p
op.removeInt(-1);
op.removeObject(-1);
break;
case 3: // q
op.removeInt(-1); // pop '?'
op.removeObject(-1);
op.add(t).add(to);
break;
case 4: // n
Object o = to[1];
Rv val = t == RC.TOK_NUMBER ? new Rv(((Float) o).intValue())
: t == RC.TOK_STRING ? new Rv((String) o)
: Rv.symbol((String) o);
rpn.add(t).add(val); // this must be an operand
break;
case 5: // <
if (top == RC.TOK_INVOKE || top == RC.TOK_INIT
|| top == RC.TOK_JSONARR || top == RC.TOK_LBR) {
int inc = prev == RC.TOK_SEP || prev == top ? 0 : 1;
rpn.add(RC.TOK_NUMBER).add(new Rv(cocnt + inc));
}
if (top == RC.TOK_AND || top == RC.TOK_OR) {
rpn.iArray[offset] += rpn.iSize << 16;
}
--op.iSize;
rpn.add(top).add(new Rv(0)); // this must be an operator
break;
case 6: // >
int newt = t;
if (t == RC.TOK_AND || t == RC.TOK_OR) {
newt = t + (rpn.iSize << 16);
rpn.add(t).add(new Rv(0)); // this is an operator
}
op.add(newt).add(to);
break;
case 7: // x
throw ex(t, to, "stack top: " + RC.tokenName(top, null));
}
if (consume > 0) {
prev = t;
t = 0;
if (newstt == 7) {
cocnt = st.removeInt(-1);
state = st.removeInt(-1);
} else if (newstt > 0) {
st.add(state).add(cocnt);
state = newstt;
cocnt = 0;
}
}
}
++pos;
}
--pos; // let pos = endpos
node.children = rpn;
}
////////////////////////////// Interpreter Methods ///////////////////////////
/**
* Evaluate an expression node
* @param callObj
* @param node
* @return
*/
public final Rv eval(Rv callObj, Object node) {
Node nd;
if ((nd = (Node) node).state >= 0) { // not resolved
this.reset(src, nd.properties, nd.display, nd.state);
expression(nd, callObj);
nd.state |= 0x80000000;
}
if (DEBUG) {
System.out.println("EVAL_EXP: " + node);
System.out.println("CALL_OBJ: " + callObj);
}
// node must be a expression node
Pack rpn = nd.children;
if (rpn.iSize == 0) return Rv._undefined;
int[] tt = rpn.iArray;
Object[] to = rpn.oArray;
Pack opnd = new Pack(-1, 10);
boolean isLocal = false;
for (int i = 0, n = rpn.iSize; i < n; i++) {
int t = tt[i];
int offset = t >> 16;
t &= 0xffff;
switch (htOptrType.get(t, -1)) {
case 1: // unary op
Rv o = (Rv) opnd.oArray[opnd.oSize - 1];
opnd.oArray[opnd.oSize - 1] = ((Rv) to[i]).unary(callObj, t, o);
break;
case 2: // binary op
Rv o2 = ((Rv) opnd.oArray[--opnd.oSize]).evalVal(callObj);
Rv o1 = ((Rv) opnd.oArray[opnd.oSize - 1]).evalVal(callObj);
opnd.oArray[opnd.oSize - 1] = ((Rv) to[i]).binary(t, o1, o2);
break;
case 3: // assign
int next = i + 1 < n ? tt[i + 1] : RC.TOK_EOF;
if (!isLocal && next == RC.TOK_VAR) {
isLocal = true;
next = RC.TOK_COM;
}
o2 = ((Rv) opnd.oArray[--opnd.oSize]).evalVal(callObj);
o1 = ((Rv) opnd.oArray[opnd.oSize - 1]).evalRef(callObj);
String symname = o1.str;
if (isLocal && next == RC.TOK_COM) {
callObj.putl(symname, Rv._undefined);
}
opnd.oArray[opnd.oSize - 1] = ((Rv) to[i]).assign(callObj, t, o1, o2);
break;
default: // misc op
int num = 0;
switch (t) {
case RC.TOK_AND:
case RC.TOK_OR:
if (offset > 0) {
o = ((Rv) opnd.oArray[opnd.oSize - 1]).evalVal(callObj);
boolean b, or = t == RC.TOK_OR;
if ((b = o.asBool()) && or || !b && !or) {
i = offset; // skip next condition check
} else {
--opnd.oSize;
}
} // else keep first condition on opnd stack
break;
case RC.TOK_NUMBER:
opnd.add(opnd.oSize, to[i]);
break;
case RC.TOK_SYMBOL:
next = i + 1 < n ? tt[i + 1] : RC.TOK_EOF;
if (!isLocal && next == RC.TOK_VAR) {
isLocal = true;
next = RC.TOK_COM;
}
if (isLocal && next == RC.TOK_COM) {
callObj.putl(((Rv) to[i]).str, Rv._undefined);
}
opnd.add(opnd.oSize, to[i]);
break;
case RC.TOK_STRING:
Rv s = (Rv) to[i], rv = null;
if (evalString && (rv = evalString(s.str, callObj)).type == Rv.ERROR) return rv;
opnd.add(opnd.oSize, evalString ? rv : s);
break;
case RC.TOK_VAR:
// skip
break;
case RC.TOK_COM:
o2 = ((Rv) opnd.oArray[--opnd.oSize]).evalVal(callObj);
o1 = ((Rv) opnd.oArray[opnd.oSize - 1]).evalVal(callObj);
opnd.oArray[opnd.oSize - 1] = o2;
break;
case RC.TOK_DOT:
case RC.TOK_LBK:
o2 = (Rv) opnd.oArray[--opnd.oSize];
if (t == RC.TOK_DOT && o2.type != Rv.SYMBOL) {
return Rv.error("syntax error");
}
String pname = t == RC.TOK_LBK ? o2.evalVal(callObj).toStr().str : o2.str;
o1 = ((Rv) opnd.oArray[opnd.oSize - 1]).evalVal(callObj);
Rv ref;
opnd.oArray[opnd.oSize - 1] = (ref = (Rv) to[i]);
ref.type = Rv.LVALUE;
ref.co = o1;
ref.str = pname;
break;
case RC.TOK_INIT:
case RC.TOK_INVOKE:
num = ((Rv) opnd.oArray[opnd.oSize - 1]).num;
int idx = opnd.oSize - num - 2;
Rv fun = (Rv) opnd.oArray[idx];
Rv funRef, funObj;
if (fun.type == Rv.FUNCTION) {
funRef = new Rv("inline", callObj);
funObj = fun;
} else {
funRef = fun.evalRef(callObj);
funObj = funRef.get();
}
int type;
boolean isInit;
if ((type = funObj.type) < Rv.FUNCTION) {
return Rv.error("undefined function: " + funRef.str);
}
if ((isInit = (t == RC.TOK_INIT)) && (type & Rv.CTOR_MASK) == 0) { // call as a constructor for the first time
funObj.type |= Rv.CTOR_MASK;
funObj.ctorOrProt = new Rv(Rv.OBJECT, Rv._Object);
}
for (int ii = idx + 1, nn = ii + num; ii < nn; ii++) {
opnd.oArray[ii] = ((Rv) opnd.oArray[ii]).evalVal(callObj).pv();
}
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = funObj == Rv._Function ? callObj : funObj.co.prev;
Rv thiz = isInit ? new Rv(Rv.OBJECT, funObj) : funRef.co;
Rv cobak = funObj.co;
Rv ret = call(false, isInit, funObj, funObj.co = funCo, thiz, opnd, idx + 1, num);
funObj.co = cobak;
opnd.oSize = idx + 1;
opnd.oArray[opnd.oSize - 1] = isInit && ret == Rv._undefined ? thiz : ret;
break;
case RC.TOK_COL:
num = 3; // fall through
case RC.TOK_JSONARR:
if (num == 0) num = ((Rv) opnd.oArray[opnd.oSize - 1]).num + 1; // fall through
case RC.TOK_LBR: // json object
if (num == 0) num = ((Rv) opnd.oArray[opnd.oSize - 1]).num * 2 + 1;
rv = Rv.polynary(callObj, t, opnd, num);
opnd.oSize = opnd.oSize - num + 1;
opnd.oArray[opnd.oSize - 1] = rv;
break;
}
break;
}
}
if (opnd.oSize > 1) {
return Rv.error("invalid expression");
}
if (DEBUG) {
System.out.println("EVAL_RETURN: " + opnd.oArray[0]);
}
return (Rv) opnd.oArray[0];
}
/**
* function
* - type: FUNCTION
* - node:
* - Arg1
* - Arg2
* - ...
* - block
* - co: callObj
* - this
* - arguments
* - arg1
* - arg2
* - ...
* - function1
* - function2
* - ...
* @return
*/
public final Rv call(boolean isAnEvalCall, boolean isInit, Rv function, Rv funCo, Rv thiz, Pack argSrc, int start, int num) {
if (function.type < Rv.FUNCTION) {
return Rv.error("invalid function");
}
boolean isNative = (function.type & ~Rv.CTOR_MASK) == Rv.NATIVE;
Pack children = isNative ? null : ((Node) function.obj).children;
if (thiz != null) {
Rv args = new Rv(Rv.ARGUMENTS, Rv._Arguments);
args.num = num;
args.putl("callee", function);
int numFormalArgs = isNative ? 0 : children.oSize - 1; // minus Block node
for (int i = 0; i < num; i++) {
Rv realArg;
args.putl(i, realArg = ((Rv) argSrc.getObject(i + start)));
if (i >= numFormalArgs) continue;
Node argnode = (Node) children.getObject(i);
Object argName = ((Object[]) argnode.properties.getObject(argnode.display))[1];
funCo.putl((String) argName, realArg);
}
funCo.putl("this", thiz);
funCo.putl("arguments", args);
}
if (isNative) {
return callNative(isInit, function, funCo);
}
Node node = (Node) children.getObject(-1); // the block ('{') node
Pack stack = new Pack(20, 20);
int idx = 0;
Rv evr = null;
for (;;) {
Object next = null;
int t;
if ((t = node.tagType) == RC.TOK_LBR && node.state >= 0) { // not resolved
this.reset(src, node.properties, node.display, node.state);
statements(funCo, node, -1);
node.state |= 0x80000000;
}
boolean isbrk;
if ((isbrk = t == RC.TOK_BREAK) || t == RC.TOK_CONTINUE) {
for (;;) {
if (stack.iSize == 0) {
throw new RuntimeException("syntax error: " + (isbrk ? "break" : "continue"));
}
idx = stack.removeInt(-1) + 1;
node = (Node) stack.removeObject(-1);
int ty = node.tagType;
if (ty == RC.TOK_WHILE || ty == RC.TOK_FOR || ty == RC.TOK_IN || ty == RC.TOK_DO
|| isbrk && ty == RC.TOK_SWITCH) {
break;
}
}
if (isbrk) { // one more pop
idx = stack.removeInt(-1) + 1;
node = (Node) stack.removeObject(-1);
}
continue;
}
if ((children = node.children) == null) children = EMPTY_BLOCK;
Object[] cc = children.oArray;
int startIdx = 0;
switch (t) {
case RC.TOK_LBR: // block
if (idx < children.oSize) {
next = cc[idx];
} // else pop
break;
case RC.TOK_IF:
case RC.TOK_ELSE:
if (idx == 0) {
if ((evr = eval(funCo, cc[0])).type == Rv.ERROR) return evr;
if (evr.evalVal(funCo).asBool()) {
next = cc[1];
} else if (t == RC.TOK_ELSE) { // has else
next = cc[2];
}
}
break;
case RC.TOK_WHILE:
if ((evr = eval(funCo, cc[0])).type == Rv.ERROR) return evr;
if (evr.evalVal(funCo).asBool()) {
next = cc[1];
}
break;
case RC.TOK_DO:
if (idx > 0 && (evr = eval(funCo, cc[1])).type == Rv.ERROR) return evr;
if (idx == 0 || evr.evalVal(funCo).asBool()) next = cc[0];
break;
case RC.TOK_FOR:
if (idx == 0 && (evr = eval(funCo, cc[idx++])).type == Rv.ERROR) return evr;
if (((idx - 1) & 0x1) == 0) {
if ((evr = eval(funCo, cc[1])).type == Rv.ERROR) return evr;
Rv cond = evr.evalVal(funCo);
if (((Node) cc[1]).children.iSize == 0 // empty condition
|| cond.asBool()) {
next = cc[3];
} // else pop
} else {
next = cc[2];
}
break;
case RC.TOK_THROW:
evr = eval(funCo, cc[0]).evalVal(funCo);
if (evr.type >= Rv.OBJECT) {
evr.type = Rv.ERROR;
} else {
evr = Rv.error(evr.toStr().str);
}
return evr;
case RC.TOK_RETURN:
return eval(funCo, cc[0]).evalVal(funCo);
case RC.TOK_TRY:
Rv tmpfun = new Rv(false, cc[0], 0); // try node
Rv tmpret = call(false, false, tmpfun, funCo, null, null, 0, 0);
if (tmpret.type == Rv.ERROR) {
Node catnode = (Node) cc[1];
if (catnode.children != null) { // valid catch
Node argnode = (Node) catnode.children.oArray[0];
Object argName = ((Object[]) argnode.properties.getObject(argnode.display))[1];
funCo.putl((String) argName, tmpret);
tmpfun = new Rv(false, catnode, 0);
tmpret = call(false, false, tmpfun, funCo, null, null, 0, 0);
}
}
Node finode = (Node) cc[2];
Rv tmpret2 = Rv._undefined;
if (finode.children != null) { // valid finally
tmpfun = new Rv(false, finode, 0);
tmpret2 = call(false, false, tmpfun, funCo, null, null, 0, 0);
}
boolean ret2;
if ((ret2 = tmpret2 != Rv._undefined) || tmpret != Rv._undefined ) {
return ret2 ? tmpret2 : tmpret;
}
break;
case RC.TOK_IN:
if ((evr = eval(funCo, cc[1])).type == Rv.ERROR) return evr;
Pack arr = evr.evalVal(funCo).keyArray();
if (idx < arr.oSize) {
Rv ref;
if ((ref = eval(funCo, cc[0])).type == Rv.ERROR) return ref;
ref.evalRef(funCo).put(new Rv((String) arr.oArray[idx]));
next = cc[2];
} // else pop
break;
case RC.TOK_WITH:
if (idx == 0) {
if ((evr = eval(funCo, cc[0])).type == Rv.ERROR) return evr;
Rv tmpCo = evr.evalVal(funCo);
tmpCo.prev = funCo;
funCo = tmpCo;
next = cc[1];
} else {
Rv tmpCo = funCo;
funCo = funCo.prev;
tmpCo.prev = null;
// and pop
}
break;
case RC.TOK_SWITCH:
Node block;
if ((block = (Node) cc[1]).children == null) {
this.reset(src, block.properties, block.display, block.state);
statements(funCo, block, -1);
block.state |= 0x80000000;
}
Object[] blkoo = (block = (Node) cc[1]).children.oArray;
if (idx == 0) {
if ((evr = eval(funCo, cc[0])).type == Rv.ERROR) return evr;
Rv rv = evr.evalVal(funCo);
if (node.className == null) { // first call
Pack brch = node.className = new Pack(8, 8);
int defIdx = -1;
for (int i = 0, n = block.children.oSize; i < n; i++) {
Node stmt;
int stty = (stmt = (Node) blkoo[i]).tagType;
if (stty == RC.TOK_CASE) {
brch.add(i).add(stmt.children.oArray[0]); // index => exp
} else if (stty == RC.TOK_DEFAULT) {
defIdx = i;
} else if (i == 0) {
throw new RuntimeException("syntax error: switch");
}
}
if (defIdx >= 0) brch.add(defIdx).add(null); // default branch
}
Pack brch = node.className;
for (int i = 0, n = brch.iSize; i < n; i++) {
Object caseexp;
if ((caseexp = brch.getObject(i)) != null) {
if ((evr = eval(funCo, caseexp)).type == Rv.ERROR) return evr;
if (!rv.equals(evr.evalVal(funCo))) continue;
}
startIdx = brch.getInt(i) + 1;
next = block;
break;
}
// no matching branch, pop
} // else pop
break;
}
int nextty;
if (next == null) {
if (stack.iSize == 0) break;
idx = stack.iArray[--stack.iSize] + 1;
node = (Node) stack.oArray[--stack.oSize];
} else if ((nextty = ((Node) next).tagType) == '*') {
if ((evr = eval(funCo, next)).type == Rv.ERROR) return evr;
++idx;
} else if (nextty == RC.TOK_CASE || nextty == RC.TOK_DEFAULT) { // go to next node
++idx;
} else {
stack.add(node).add(idx);
node = (Node) next;
idx = startIdx;
}
}
if (isAnEvalCall) {
return evr != null ? evr : Rv._undefined;
}
else {
return Rv._undefined;
}
}
/**
* call a native function
* @param isNew
* @param thiz
* @param args
* @return
*/
protected Rv callNative(boolean isNew, Rv function, Rv callObj) {
Rv idEnt;
if ((idEnt = htNativeIndex.getEntry(0, function.str)) == null) return Rv._undefined;
Rv args = callObj.get("arguments");
Rv thiz = callObj.get("this");
Rhash prop = thiz.prop;
int argLen = args.num;
Rv arg0, arg1, ret;
arg0 = argLen > 0 ? (Rv) args.get("0") : null;
arg1 = argLen > 1 ? (Rv) args.get("1") : null;
ret = Rv._undefined;
int funcId;
switch (funcId = idEnt.num) {
case 101: // Object(1)
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Object);
if (arg0 != null) {
int type;
if ((type = arg0.type) == Rv.NUMBER || type == Rv.NUMBER_OBJECT) {
ret.type = Rv.NUMBER_OBJECT;
ret.num = arg0.num;
} else if (type == Rv.STRING || type == Rv.STRING_OBJECT) {
ret.type = Rv.STRING_OBJECT;
ret.str = arg0.str;
} else { // object
ret = arg0;
}
}
break;
case 102: // Function(1)
if (argLen > 0) {
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Object);
ret.type = Rv.FUNCTION;
Node n;
if (argLen == 1 && arg0.type == Rv.FUNCTION) {
n = (Node) arg0.obj;
} else {
n = astNode(null, RC.TOK_FUNCTION, 0, 0);
int numArgs = argLen - 1;
for (int i = 0; i < numArgs; i++) {
String arg;
this.reset(arg = args.get(Integer.toString(i)).toStr().str, null, 0, arg.length());
astNode(n, RC.TOK_MUL, 0, this.endpos);
}
String src;
this.reset(src = args.get(Integer.toString(numArgs)).toStr().str, null, 0, src.length());
astNode(n, RC.TOK_LBR, 0, this.endpos); // '{' = block
}
ret.obj = n;
ret.ctorOrProt = Rv._Function;
ret.co = new Rv(Rv.OBJECT, Rv._Object);
ret.co.prev = callObj.prev;
}
break;
case 103: // Number(1)
if (isNew) {
ret = thiz;
ret.type = Rv.NUMBER_OBJECT;
ret.ctorOrProt = Rv._Number;
} else {
ret = new Rv(0);
}
ret.num = arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
break;
case 104: // String(1)
if (isNew) {
ret = thiz;
ret.type = Rv.STRING_OBJECT;
ret.ctorOrProt = Rv._String;
} else {
ret = new Rv("");
}
ret.str = arg0 != null? arg0.toStr().str : "";
break;
case 105: // Array(1)
ret = isNew ? thiz : new Rv(Rv.ARRAY, Rv._Array);
ret.type = Rv.ARRAY;
ret.ctorOrProt = Rv._Array;
Rv len;
if (argLen == 1 && (len = arg0.toNum()) != Rv._NaN) {
ret.num = len.num;
} else { // 0 or more
ret.num = argLen;
for (int i = 0; i < argLen; i++) {
ret.putl(i, args.get(Integer.toString(i)));
}
}
break;
case 106: // Date(1)
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Date);
ret.type = Rv.NUMBER_OBJECT;
ret.ctorOrProt = Rv._Date;
thiz.num = arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num
: (int) (System.currentTimeMillis() - bootTime);
break;
case 107: // Error(1)
ret = isNew ? thiz : new Rv(Rv.ERROR, Rv._Error);
ret.type = Rv.ERROR;
ret.ctorOrProt = Rv._Error;
if (arg0 != null) ret.putl("message", arg0.toStr());
break;
case 111: // Object.toString(0)
ret = thiz.toStr();
break;
case 112: // Object.hasOwnProperty(1)
ret = arg0 != null && thiz.has(arg0.toStr().str) ? Rv._true : Rv._false;
break;
case 121: // Function.call(1)
case 122: // Function.apply(2)
boolean isCall;
if (arg0 != null && arg0.type >= Rv.OBJECT
&& ((isCall = (funcId == 121)) || arg1 != null && arg1.type == Rv.ARRAY)) {
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = thiz.co.prev;
int argNum, argStart;
Rv argsArr;
if (isCall) {
argNum = argLen - 1;
argStart = 1;
argsArr = args;
} else {
argNum = arg1.num;
argStart = 0;
argsArr = arg1;
}
Pack argSrc = new Pack(-1, argNum);
for (int ii = argStart, nn = argStart + argNum; ii < nn; argSrc.add(argsArr.get(Integer.toString(ii++))));
Rv cobak = thiz.co;
ret = call(false, false, thiz, thiz.co = funCo, arg0, argSrc, 0, argNum);
thiz.co = cobak;
}
break;
case 131: // Number.valueOf(0)
ret = thiz.type == Rv.NUMBER_OBJECT ? thiz : Rv._undefined;
break;
case 141: // String.valueOf(0)
ret = thiz.type == Rv.STRING_OBJECT ? thiz : Rv._undefined;
break;
case 142: // String.charAt(1)
int pos = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : -1;
ret = pos < 0 || pos >= thiz.str.length() ? Rv._empty
: new Rv(String.valueOf(thiz.str.charAt(pos)));
break;
case 143: // String.indexOf(1)
ret = new Rv(-1);
if (arg0 != null) {
String s = arg0.toStr().str;
int idx = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : 0;
ret = new Rv(thiz.str.indexOf(s, idx));
}
break;
case 144: // String.lastIndexOf(1)
ret = new Rv(-1);
if (arg0 != null) {
String s = arg0.toStr().str;
String src = thiz.toStr().str;
int l = s.length(), srcl = src.length();
int idx = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : srcl;
if (idx >= 0) {
if (idx >= srcl - l) idx = srcl - l;
for (int i = idx + 1; --i >= 0;) {
if (src.regionMatches(false, i, s, 0, l)) {
ret = new Rv(i);
break;
}
}
}
}
break;
case 145: // String.substring(2)
if (arg0 != null) {
thiz = thiz.toStr();
int i1 = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
int i2 = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : Integer.MAX_VALUE;
int strlen;
if (i2 > (strlen = thiz.str.length())) i2 = strlen;
ret = new Rv(thiz.str.substring(i1, i2));
}
break;
case 146: // String.split(2)
if (arg0 != null) {
thiz = thiz.toStr();
int limit = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : -1;
String delim;
Pack p = split(thiz.str, delim = arg0.toStr().str);
if (limit >= 1) {
StringBuffer buf = new StringBuffer();
for (int i = limit - 1, n = p.oSize; i < n; i++) {
if (i > limit - 1) buf.append(delim);
buf.append(p.oArray[i]);
}
p.setSize(-1, limit).set(-1, buf.toString());
}
ret = new Rv(Rv.ARRAY, Rv._Array);
for (int i = 0, n = p.oSize; i < n; i++) {
ret.putl(i, new Rv((String) p.oArray[i]));
}
}
break;
case 147: // String.charCodeAt(1)
pos = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : -1;
ret = pos < 0 || pos >= thiz.str.length() ? Rv._NaN
: new Rv(thiz.str.charAt(pos));
break;
case 148: // String.fromCharCode(1)
StringBuffer buf = new StringBuffer();
for (int i = 0; i < argLen; i++) {
Rv charcode = args.get(Integer.toString(i)).toNum();
if (charcode != Rv._NaN) buf.append((char) charcode.num);
}
ret = new Rv(buf.toString());
break;
case 151: // Array.concat(1)
ret = new Rv(Rv.ARRAY, Rv._Array);
ret.num = thiz.num;
Rhash dest = ret.prop;
String key;
Pack keys = prop.keys();
for (int i = 0, n = keys.oSize; i < n; i++) {
dest.put(key = (String) keys.oArray[i], prop.get(key));
}
for (int i = 0; i < argLen; i++) {
Rv obj = args.get(Integer.toString(i));
if (obj.type == Rv.ARRAY) {
for (int j = 0, n = obj.num, b = ret.num; j < n; j++) {
ret.putl(b + j, obj.get(Integer.toString(j)));
}
} else {
ret.putl(ret.num, obj);
}
}
break;
case 152: // Array.join(1)
String sep = arg0 != null ? arg0.toStr().str : ",";
buf = new StringBuffer();
for (int i = 0, n = thiz.num; i < n; i++) {
if (i > 0) buf.append(sep);
buf.append(prop.get(Integer.toString(i)).toStr().str);
}
ret = new Rv(buf.toString());
break;
case 153: // Array.push(1)
for (int i = 0, b = thiz.num; i < argLen; i++) {
thiz.putl(b + i, args.get(Integer.toString(i)));
}
ret = new Rv(thiz.num);
break;
case 154: // Array.pop(0)
ret = thiz.shift(thiz.num - 1);
break;
case 155: // Array.shift(0)
ret = thiz.shift(0);
break;
case 156: // Array.unshift(1)
Rhash ht = new Rhash(11);
for (int i = 0; i < argLen; i++) {
String idx = Integer.toString(i);
Rv val = args.prop.get(idx);
if (val != null) ht.put(idx, val);
}
for (int i = 0, n = thiz.num; i < n; i++) {
Rv val = prop.get(Integer.toString(i));
if (val != null) ht.put(Integer.toString(i + argLen), val);
}
thiz.num += argLen;
thiz.prop = ht;
break;
case 157: // Array.slice(2)
if (arg0 != null) {
int i1 = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
int i2 = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : thiz.num;
ret = new Rv(Rv.ARRAY, Rv._Array);
ht = ret.prop;
int i = 0, n = ret.num = i2 - i1;
for (; i < n; i++) {
Rv val = prop.get(Integer.toString(i + i1));
if (val != null) ht.put(Integer.toString(i), val);
}
}
break;
case 158: // Array.sort(1)
Rv comp = arg0 != null && arg0.type >= Rv.FUNCTION ? arg0 : null;
int num;
Pack tmp = new Pack(-1, num = thiz.num);
for (int i = 0; i < num; tmp.add(prop.get(Integer.toString(i++))));
Object[] arr = tmp.oArray;
for (int i = 0, n = num - 1; i < n; i++) {
Rv r1 = (Rv) arr[i];
for (int j = i + 1; j < num; j++) {
Rv r2 = (Rv) arr[j];
boolean grtr = false;
if (r1 == null || r2 == null || r1 == Rv._undefined || r2 == Rv._undefined) {
grtr = r1 == null && r2 != null
|| r1 == Rv._undefined && r2 != null && r2 != Rv._undefined;
} else {
if (comp == null) {
grtr = r1.toStr().str.compareTo(r2.toStr().str) > 0;
} else {
Pack argSrc = new Pack(-1, 2).add(r1).add(r2);
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = comp.co.prev;
Rv cobak = comp.co;
grtr = call(false, false, comp, comp.co = funCo, thiz, argSrc, 0, 2).toNum().num > 0;
comp.co = cobak;
}
}
if (grtr) {
arr[j] = r1;
arr[i] = r1 = r2;
}
}
}
ht = new Rhash(11);
for (int i = num; --i >= 0;) {
Rv val;
if ((val = (Rv) arr[i]) != null) ht.put(Integer.toString(i), val);
}
thiz.prop = ht;
break;
case 159: // Array.reverse(0)
ht = new Rhash(11);
for (int i = 0, j = thiz.num; --j >= 0; i++) {
Rv val = prop.get(Integer.toString(j));
if (val != null) ht.put(Integer.toString(i), val);
}
thiz.prop = ht;
break;
case 160: // Date.getTime(0)
ret = new Rv(thiz.num);
break;
case 161: // Date.setTime(1)
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN) {
thiz.num = arg0.num;
}
break;
case 170: // Error.toString(0)
ret = thiz.get("message");
break;
case 203: // Math.random(1)
if (arg0 != null && arg0.toNum() != Rv._NaN) {
int low = arg0.num;
int high = arg1 != null && arg1.toNum() != Rv._NaN ? arg1.num : low - 1;
if (high <= low) {
high = low;
low = 0;
}
int rand = (random.nextInt() & 0x7FFFFFFF) % (high - low);
ret = new Rv(low + rand);
}
break;
case 210: // Math.min(2)
case 211: // Math.max(2)
if (argLen > 0) {
boolean isMax;
int iret = (isMax = funcId == 211) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
for (int i = 0; i < argLen; i++) {
Rv val = args.get(Integer.toString(i)).toNum();
if (val == Rv._NaN) {
ret = val;
break;
}
if (isMax && iret < val.num || !isMax && iret > val.num) iret = val.num;
}
ret = new Rv(iret);
}
break;
case 212: // Math.abs(1)
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN) {
- thiz.num = Math.abs(arg0.num);
+ ret = new Rv(Math.abs(arg0.num));
}
break;
case 213: // Math.pow(2)
if (argLen > 0) {
+ System.out.println("Math.pow with args: " + arg0.num + " " + arg1.num);
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN && arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN) {
- thiz.num = (int)Math.pow(arg0.num, arg1.num);
+ ret = new Rv((int)Math.pow(arg0.num, arg1.num));
+ System.out.println("Calculated: " + thiz.num);
}
}
break;
case 204: // isNaN(1)
ret = arg0 != null && arg0 == Rv._NaN ? Rv._true : Rv._false;
break;
case 205: // parseInt(1)
int radix = arg1 != null && arg1.toNum() != Rv._NaN ? arg1.num : 10;
String sNum = arg0 != null ? arg0.toStr().str : null;
try {
ret = new Rv(Integer.parseInt(sNum, radix));
} catch (Exception ex) { } // do nothing, ret = undefined
break;
case 206: // eval(1)
if (arg0 != null) {
String s;
this.reset(s = arg0.toStr().str, null, 0, s.length());
Node node = astNode(null, RC.TOK_FUNCTION, 0, 0);
astNode(node, RC.TOK_LBR, 0, this.endpos); // '{' = block
Rv func = new Rv(false, node, 0);
System.out.println("\nNode printout for eval(1):\n"+ node);
ret = call(true, false, func, thiz, null, null, 0, 0);
}
break;
case 207: // es(1)
if (arg0 != null) {
ret = evalString(arg0.toStr().str, thiz);
}
break;
case 208: // print(1);
case 209: // println(1);
String msg = argLen > 0 ? arg0.toStr().str : "";
if (!dontPrintOutput) System.out.print(msg);
out.append(msg);
if (funcId == 209) {
if (!dontPrintOutput) System.out.println();
out.append("\n");
}
break;
}
// StringBuffer buf = new StringBuffer();
// buf.append("this=" + thiz.toStr());
// for (int i = 0; i < argLen; i++) {
// buf.append(", ").append(args.get(Integer.toString(i)));
// }
// System.out.println(">> " + (isNew ? " NEW" : "CALL") + ": " + function.str + "(" + buf + "), Result=" + ret);
return ret;
}
public Rv initGlobalObject() {
Rv go = new Rv();
go.type = Rv.OBJECT;
go.prop = new Rhash(41);
if (Rv._Object.type == Rv.UNDEFINED) { // Rv not initialized
Rv._Object.nativeCtor("Object", go)
.ctorOrProt
.putl("toString", nat("Object.toString"))
.putl("hasOwnProperty", nat("Object.hasOwnProperty"))
.ctorOrProt = null;
;
Rv._Function.nativeCtor("Function", go)
.ctorOrProt
.putl("call", nat("Function.call")) // call(thisObj, [arg1, [arg2...]])
.putl("apply", nat("Function.apply")) // apply(thisObj, arrayArgs)
;
Rv._Number.nativeCtor("Number", go)
.putl("MAX_VALUE", new Rv(Integer.MAX_VALUE))
.putl("MIN_VALUE", new Rv(Integer.MIN_VALUE))
.putl("NaN", Rv._NaN)
.ctorOrProt
.putl("valueOf", nat("Number.valueOf"))
;
Rv._String.nativeCtor("String", go)
.putl("fromCharCode", nat("String.fromCharCode"))
.ctorOrProt
.putl("valueOf", nat("String.valueOf"))
.putl("charAt", nat("String.charAt"))
.putl("charCodeAt", nat("String.charCodeAt"))
.putl("indexOf", nat("String.indexOf"))
.putl("lastIndexOf", nat("String.lastIndexOf"))
.putl("substring", nat("String.substring"))
.putl("split", nat("String.split"))
;
Rv._Array.nativeCtor("Array", go)
.ctorOrProt
.putl("concat", nat("Array.concat")) // concat(arg0[, arg1...])
.putl("join", nat("Array.join")) // join(separator)
.putl("push", nat("Array.push")) // push(arg0[, arg1...])
.putl("pop", nat("Array.pop")) // pop()
.putl("shift", nat("Array.shift")) // shift()
.putl("unshift", nat("Array.unshift")) // unshift(arg0[, arg1...])
.putl("slice", nat("Array.slice")) // slice(start, end)
.putl("sort", nat("Array.sort")) // sort(comparefn)
.putl("reverse", nat("Array.reverse")) // reverse()
;
Rv._Date.nativeCtor("Date", go)
.ctorOrProt
.putl("getTime", nat("Date.getTime")) // getTime()
.putl("setTime", nat("Date.setTime")) // setTime(arg0)
;
Rv._Error.nativeCtor("Error", go)
.putl("name", new Rv("Error"))
.putl("message", new Rv("Error"))
.ctorOrProt
.putl("toString", nat("Error.toString")) // toString()
;
Rv._Arguments.nativeCtor("Arguments", go)
.ctorOrProt
.ctorOrProt = Rv._Array
;
}
Rv _Math = new Rv(Rv.OBJECT, Rv._Object)
.putl("random", nat("Math.random"))
.putl("min", nat("Math.min"))
.putl("max", nat("Math.max"))
.putl("abs", nat("Math.abs"))
.putl("pow", nat("Math.pow"))
;
// fill global Object
Rv println;
go.putl("true", Rv._true)
.putl("false", Rv._false)
.putl("null", Rv._null)
.putl("undefined", Rv._undefined)
.putl("NaN", Rv._NaN)
.putl("Object", Rv._Object)
.putl("Function", Rv._Function)
.putl("Number", Rv._Number)
.putl("String", Rv._String)
.putl("Array", Rv._Array)
.putl("Date", Rv._Date)
.putl("Error", Rv._Error)
.putl("Math", _Math)
.putl("isNaN", nat("isNaN"))
.putl("parseInt", nat("parseInt"))
.putl("eval", nat("eval"))
.putl("es", nat("es"))
.putl("print", nat("print"))
.putl("println", (println = nat("println")))
.putl("alert", println)
;
go.putl("this", go);
return go;
}
////////////////////////////// Auxiliary Routines ///////////////////////////
final int eat(int tokenType) {
int[] tti = tt.iArray;
int tpos = pos, endpos = this.endpos;
int token = 0;
boolean found = false;
for (;;) {
if (tpos >= endpos) {
if (found) break;
throw ex(RC.TOK_EOF, new Object[] { new int[] { src.length(), 0 } }, RC.tokenName(tokenType, null));
}
token = tti[tpos];
if (!found && token == tokenType) {
found = true;
++tpos;
} else if (token == RC.TOK_EOL) {
++tpos;
} else if (found) {
break;
} else {
throw ex(token, tt.getObject(tpos), RC.tokenName(tokenType, null));
}
}
pos = tpos;
return token;
}
/**
* TODO in expression, consider operators (+, *, &&, !, ?, :, function() etc.)
* @param ttype
* @param ttype2
* @return run length
*/
final int eatUntil(int ttype, int ttype2) {
int[] tti = tt.iArray;
int tpos = pos, endpos = this.endpos;
Pack stack = new Pack(20, -1);
for (;;) {
if (tpos >= endpos) {
if (ttype != RC.TOK_EOL) {
String expected = RC.tokenName(ttype, null);
if (ttype2 > 0) expected += "," + RC.tokenName(ttype2, null);
throw ex(RC.TOK_EOF, new Object[] { new int[] { src.length(), 0 } }, expected);
}
break;
}
int token = tti[tpos];
if ((token == ttype || token == ttype2) && stack.iSize == 0) {
break;
}
int pr = 0;
switch (token) {
case RC.TOK_QMK:
pr = RC.TOK_COL;
case RC.TOK_FUNCTION:
if (pr == 0) pr = RC.TOK_LBR;
case RC.TOK_LBK:
if (pr == 0) pr = RC.TOK_RBK;
case RC.TOK_LPR:
if (pr == 0) pr = RC.TOK_RPR;
stack.add(pr);
break;
case RC.TOK_LBR:
if (stack.iSize > 0 && token == stack.getInt(-1)) {
stack.iSize--;
}
stack.add(RC.TOK_RBR);
break;
case RC.TOK_COL:
if (stack.iSize > 0 && token == stack.getInt(-1)) {
stack.iSize--;
}
break;
case RC.TOK_RPR:
case RC.TOK_RBR:
case RC.TOK_RBK:
int top = stack.getInt(-1);
if (top == token) {
stack.iSize--;
} else {
String expected = RC.tokenName(top, null);
throw ex(token, tt.getObject(tpos), expected);
}
break;
}
++tpos;
}
int ret = tpos - pos;
pos = tpos;
return ret;
}
/**
* @param function
*/
final private void funcBody(Node function) {
int[] tti = tt.iArray;
eat(RC.TOK_LPR);
for (;;) {
int pp = pos;
for (int ii = pp + eatUntil(RC.TOK_COM, RC.TOK_RPR); --ii >= pp;) {
if (tti[ii] != RC.TOK_EOL) {
astNode(function, RC.TOK_MUL, pp, pos - pp);
break;
}
}
int delim = tti[pos];
eat(delim);
if (delim == RC.TOK_RPR) break;
}
eat(RC.TOK_LBR);
astNode(function, RC.TOK_LBR, pos, eatUntil(RC.TOK_RBR, 0)); // '{' = block
eat(RC.TOK_RBR);
}
//
public final Node astNode(Node parent, int type, int pos, int len) {
Node n = new Node(this, type);
if (parent != null) {
parent.appendChild(n);
}
n.properties = tt;
n.display = pos;
n.state = len;
return n;
}
final Rv evalString(String str, Rv callObj) {
char[] cc = str.toCharArray();
StringBuffer buf = new StringBuffer();
for (int ii = 0, nn = cc.length; ii < nn; ++ii) {
char c;
switch (c = cc[ii]) {
case '\\':
if (ii + 1 < nn && cc[ii + 1] == '$') {
buf.append('$');
++ii;
}
break;
case '$':
int iistart = ii;
try {
String exp = null;
if ((c = cc[++ii]) == '{') {
int ccnt = 1;
while ((c = cc[++ii]) != '}' || --ccnt > 0) {
if (c == '{') ++ccnt;
}
exp = str.substring(iistart + 2, ii);
} else if (c >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| c == '_' || c == '$') { // identifier start
int ccnt = 0;
while (++ii < nn
&& ((c = cc[ii]) >= 'A' && c <= 'Z'
|| c >= 'a' && c <= 'z'
|| c >= '0' && c <= '9'
|| c == '_' || c == '$'
|| c == '.' || c == '['
|| (c == ']' && ccnt >= 1))) {
if (c == '[' || c == ']') ccnt += '\\' - c; // [: 0x5B, \: 0x5C, ]: 0x5D
}
exp = str.substring(iistart + 1, ii--);
} else {
buf.append('$').append(c);
}
if (exp != null) {
this.reset(exp, null, 0, exp.length());
Node expnode = astNode(null, RC.TOK_MUL, 0, this.endpos);
Rv ret;
if ((ret = eval(callObj, expnode)).type == Rv.ERROR) return ret;
buf.append(ret.evalVal(callObj).toStr().str);
}
} catch (Exception ex) {
buf.append('$');
ii = iistart; // recover
}
break;
default:
buf.append(c);
break;
}
}
return new Rv(buf.toString());
}
final RuntimeException ex(char encountered, int pos, String expected) {
return ex("LEXER", pos, "'" + encountered + "'", expected);
}
final RuntimeException ex(int ttype, Object tinfo, String expected) {
Object[] oo = (Object[]) tinfo;
int pos = ((int[]) oo[0])[0];
return ex("PARSER", pos, RC.tokenName(ttype, null), expected);
}
final RuntimeException ex(String type, int pos, String encountered, String expected) {
StringBuffer buf = new StringBuffer(type).append(" ERROR: at position ");
Pack l = loc(pos);
buf.append("line " + l.iSize + " column " + l.oSize);
buf.append(", encountered ").append(encountered);
if (expected != null) {
buf.append(", expects ").append(expected);
}
buf.append('.');
return new RuntimeException(buf.toString());
}
final Pack loc(int pos) {
int i1, i2, row, col;
i1 = i2 = row = col = 0;
for (;;) {
i2 = src.indexOf('\n', i1);
if (pos >= i1 && pos <= i2 || i2 < 0) {
col = pos - i1;
break;
}
i1 = i2 + 1;
++row;
}
Pack ret = new Pack(-1, -1);
ret.iSize = row + 1;
ret.oSize = col + 1;
return ret;
}
/**
* Special symbols are members of global/call object
* "this", "null", "undefined", "NaN", "true", "false", "arguments"
*/
static final String KEYWORDS =
"if," +
"else," +
"for," +
"while," +
"do," +
"break," +
"continue," +
"var," +
"function," +
"return," +
"with," +
"new," +
"in," +
"switch," +
"case," +
"default," +
"typeof," +
"delete," +
"instanceof," +
"throw," +
"try," +
"catch," +
"finally," +
"";
static final Rhash htKeywords;
static final String OPTRINDEX =
",46," + // .
",442," + // **
",42,47,37," + // *, /, %
",43,45," + // +, -
",460,462,641," + // <<, >>, >>>
",60,62,260,262,142,148," + // <, >, <=, >=, in, instanceof
",261,233,661,633," + // ==, !=, ===, !==
",38," + // &
",94," + // ^
",124," + // |
",438," + // &&
",524," + // ||
",61,243,245,242,247,237,238,324,294,660,662,693," + // =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
",44," + // ,
",1443,1445," + // POSTINC, POSTDEC
",443,445,147," + // INC, DEC, delete
",1043,1045,146,33,126," + // POS, NEG, typeof, !, ~
",63," + // ?
",58," + // COLON
",1058," + // jsoncol
",137," + // var
",40," + // (
",1040,1141," + // invoke, init
",91," + // [
",1091," + // jsonarr
",123," + // { (jsonobj)
",41," + // )
",93," + // ]
",125," + // }
",1044," + // SEPTOR
",1," + // NUMBER
",2," + // STRING
",3," + // SYMBOL
",999," + // EOF
"";
static final Rhash htOptrIndex;
static final Rhash htOptrType;
static final String PRECEDENCE =
"Paaaaaaaaaaaaapaaaaapaaaapa" + // DOT
"PPaaaaaaaaaaaaPPPaaapaaaapa" + // POW
"PPPaaaaaaaaaaaPPPaaapaaaapa" + // MUL
"PPPPaaaaaaaaaaPPPaaapaaaapa" + // ADD
"PPPPPaaaaaaaaaPPPaaapaaaapa" + // LSH
"PPPPPPaaaaaaaaPPPaaapaaaapa" + // LES
"PPPPPPPaaaaaaaPPPaaapaaaapa" + // EQ
"PPPPPPPPaaaaaaPPPaaapaaaapa" + // BAN
"PPPPPPPPPaaaaaPPPaaapaaaapa" + // BXO
"PPPPPPPPPPaaaaPPPaaapaaaapa" + // BOR
"PPPPPPPPPPPaaaPPPaaapaaaapa" + // AND
"PPPPPPPPPPPPaaPPPaaapaaaapa" + // OR
"PPPPPPPPPPPPaaPPPpppaaaaapa" + // ASS
"PPPPPPPPPPPPPPPPPpPpPapappa" + // COMMA
"paaaaaaaaaaaaapppaaapaaaapa" + // POSTINC
"paaaaaaaaaaaaapppaaapaaaapa" + // INC
"paaaaaaaaaaaaapppaaapaaaapa" + // POS
"RRRRRRRRRRRRccRRRcccpccccpc" + // QMK
"PPPPPPPPPPPPppPPP?Ppppppppp" + // COLON
"pppppppppppppppppppppppppap" + // jsoncol
"ppppppppppppppppppppppppppa" + // var
"ccccccccccccccpcccccccccccc" + // (
"Teeeeeeeeeeeeepeeeeeeeeeepe" + // invoke
"Rcccccccccccccpccccccccccpc" + // [
"pgggggggggggggpggggggggggpg" + // jsonarr
"piiiiiiiiiiiiipiiiiiiiiiipi" + // {
"PPPPPPPPPPPPPPPPPpPpp/_pppp" + // )
"PPPPPPPPPPPPPPPPPpPpppp__pp" + // ]
"PPPPPPPPPPPPPPPPPpPPppppp_p" + // }
"PPPPPPPPPPPPPpPPPpPQpp\u0001p\u0001\u0001p" + // SEPTOR
"AAAAAAAAAAAAAAppAAAApAAAAAA" + // NUMBER
"AAAAAAAAAAAAAAppAAAApAAAAAA" + // STRING
"AAAAAAAAAAAAAApAAAAAAAAAAAA" + // SYMBOL
"PPPPPPPPPPPPPPPPPpPpPppppp\u0001" + // EOF
"";
static final int PT_COL = 27;
static final int PT_ROW = 34;
static final int[][] prioTable;
private static final String NATIVE_FUNC =
// id, name, numArguments
"101,Object,1," +
"102,Function,1," +
"103,Number,1," +
"104,String,1," +
"105,Array,1," +
"106,Date,1," +
"107,Error,1," +
"111,Object.toString,0," +
"112,Object.hasOwnProperty,1," +
"121,Function.call,1," +
"122,Function.apply,2," +
"131,Number.valueOf,0," +
"141,String.valueOf,0," +
"142,String.charAt,1," +
"143,String.indexOf,1," +
"144,String.lastIndexOf,1," +
"145,String.substring,2," +
"146,String.split,2," +
"147,String.charCodeAt,1," +
"148,String.fromCharCode,1," +
"151,Array.concat,1," +
"152,Array.join,1," +
"153,Array.push,1," +
"154,Array.pop,0," +
"155,Array.shift,0," +
"156,Array.unshift,1," +
"157,Array.slice,2," +
"158,Array.sort,1," +
"159,Array.reverse,0," +
"160,Date.getTime,0," +
"161,Date.setTime,1," +
"170,Error.toString,0," +
"203,Math.random,1," +
"204,isNaN,1," +
"205,parseInt,1," +
"206,eval,1," +
"207,es,1," + // eval string
"208,print,1," +
"209,println,1," +
"210,Math.min,2," +
"211,Math.max,2," +
"212,Math.abs,1," +
"213,Math.pow,2," +
"";
static final Rhash htNativeIndex;
static final Rhash htNativeLength;
static final long bootTime = System.currentTimeMillis();
static final Random random = new Random(bootTime);
static final Pack EMPTY_BLOCK = new Pack(-1, 0);
static {
Rhash ht = htKeywords = new Rhash(41);
Pack pk = split(KEYWORDS, ",");
Object[] pkar = pk.oArray;
for (int i = pk.oSize; --i >= 0; ht.put((String) pkar[i], 130 + i));
Rhash ih = htOptrIndex = new Rhash(53);
Rhash ot = htOptrType = new Rhash(53);
pk = split(OPTRINDEX, ",");
pkar = pk.oArray;
for (int i = 0, idx = -1, n = pk.oSize; i < n; i++) {
String s = (String) pkar[i];
if (s.length() == 0) {
++idx;
} else {
int optr;
ih.put(optr = Integer.parseInt(s), idx);
int type = idx >= 14 && idx <= 16 ? 1 // unary op
: idx >= 1 && idx <= 9 ? 2 // binary op
: idx == 12 ? 3 // assign op
: 0; // misc op
ot.put(optr, type);
}
}
int[][] pt = prioTable = new int[PT_ROW][PT_COL];
char[] cc = PRECEDENCE.toCharArray();
for (int i = 0, ii = 0; i < PT_ROW; i++) {
for (int j = 0; j < PT_COL; j++) {
pt[i][j] = cc[ii++];
}
}
ht = htNativeIndex = new Rhash(61);
Rhash ht2 = htNativeLength = new Rhash(61);
// OK so here we are going to parse something like:
// "203,Math.random,1,"
pk = split(NATIVE_FUNC, ",");
pkar = pk.oArray;
for (int i = 0, n = pk.oSize; i < n; i += 3) {
String name = (String) pkar[i + 1];
int id = Integer.parseInt((String) pkar[i]);
int len = Integer.parseInt((String) pkar[i + 2]);
ht.put(name, id);
ht2.put(name, len);
}
}
static final int keywordIndex(String s) {
Rv entry;
return (entry = htKeywords.getEntry(0, s)) == null ? -1 : entry.num;
}
static final Pack split(String src, String delim) {
Pack ret = new Pack(-1, 20);
if (delim.length() == 0) {
char[] cc = src.toCharArray();
for (int i = 0, n = cc.length; i < n; ret.add("" + cc[i++]));
return ret;
}
int i1, i2;
i1 = i2 = 0;
for (;;) {
i2 = src.indexOf(delim, i1);
if (i2 < 0) break; // reaches end
ret.add(src.substring(i1, i2));
i1 = i2 + 1;
}
if (i1 < src.length()) {
ret.add(src.substring(i1));
}
return ret;
}
final static void addToken(Pack tokens, int type, int pos, int len, Object val) {
Object[] oo = new Object[val != null ? 2 : 1];
oo[0] = new int[] { pos, len };
if (val != null) oo[1] = val;
tokens.add(type).add(oo);
}
final static Rv nat(String name) {
return new Rv(true, name, htNativeLength.getEntry(0, name).num);
}
}
| false | true | protected Rv callNative(boolean isNew, Rv function, Rv callObj) {
Rv idEnt;
if ((idEnt = htNativeIndex.getEntry(0, function.str)) == null) return Rv._undefined;
Rv args = callObj.get("arguments");
Rv thiz = callObj.get("this");
Rhash prop = thiz.prop;
int argLen = args.num;
Rv arg0, arg1, ret;
arg0 = argLen > 0 ? (Rv) args.get("0") : null;
arg1 = argLen > 1 ? (Rv) args.get("1") : null;
ret = Rv._undefined;
int funcId;
switch (funcId = idEnt.num) {
case 101: // Object(1)
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Object);
if (arg0 != null) {
int type;
if ((type = arg0.type) == Rv.NUMBER || type == Rv.NUMBER_OBJECT) {
ret.type = Rv.NUMBER_OBJECT;
ret.num = arg0.num;
} else if (type == Rv.STRING || type == Rv.STRING_OBJECT) {
ret.type = Rv.STRING_OBJECT;
ret.str = arg0.str;
} else { // object
ret = arg0;
}
}
break;
case 102: // Function(1)
if (argLen > 0) {
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Object);
ret.type = Rv.FUNCTION;
Node n;
if (argLen == 1 && arg0.type == Rv.FUNCTION) {
n = (Node) arg0.obj;
} else {
n = astNode(null, RC.TOK_FUNCTION, 0, 0);
int numArgs = argLen - 1;
for (int i = 0; i < numArgs; i++) {
String arg;
this.reset(arg = args.get(Integer.toString(i)).toStr().str, null, 0, arg.length());
astNode(n, RC.TOK_MUL, 0, this.endpos);
}
String src;
this.reset(src = args.get(Integer.toString(numArgs)).toStr().str, null, 0, src.length());
astNode(n, RC.TOK_LBR, 0, this.endpos); // '{' = block
}
ret.obj = n;
ret.ctorOrProt = Rv._Function;
ret.co = new Rv(Rv.OBJECT, Rv._Object);
ret.co.prev = callObj.prev;
}
break;
case 103: // Number(1)
if (isNew) {
ret = thiz;
ret.type = Rv.NUMBER_OBJECT;
ret.ctorOrProt = Rv._Number;
} else {
ret = new Rv(0);
}
ret.num = arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
break;
case 104: // String(1)
if (isNew) {
ret = thiz;
ret.type = Rv.STRING_OBJECT;
ret.ctorOrProt = Rv._String;
} else {
ret = new Rv("");
}
ret.str = arg0 != null? arg0.toStr().str : "";
break;
case 105: // Array(1)
ret = isNew ? thiz : new Rv(Rv.ARRAY, Rv._Array);
ret.type = Rv.ARRAY;
ret.ctorOrProt = Rv._Array;
Rv len;
if (argLen == 1 && (len = arg0.toNum()) != Rv._NaN) {
ret.num = len.num;
} else { // 0 or more
ret.num = argLen;
for (int i = 0; i < argLen; i++) {
ret.putl(i, args.get(Integer.toString(i)));
}
}
break;
case 106: // Date(1)
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Date);
ret.type = Rv.NUMBER_OBJECT;
ret.ctorOrProt = Rv._Date;
thiz.num = arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num
: (int) (System.currentTimeMillis() - bootTime);
break;
case 107: // Error(1)
ret = isNew ? thiz : new Rv(Rv.ERROR, Rv._Error);
ret.type = Rv.ERROR;
ret.ctorOrProt = Rv._Error;
if (arg0 != null) ret.putl("message", arg0.toStr());
break;
case 111: // Object.toString(0)
ret = thiz.toStr();
break;
case 112: // Object.hasOwnProperty(1)
ret = arg0 != null && thiz.has(arg0.toStr().str) ? Rv._true : Rv._false;
break;
case 121: // Function.call(1)
case 122: // Function.apply(2)
boolean isCall;
if (arg0 != null && arg0.type >= Rv.OBJECT
&& ((isCall = (funcId == 121)) || arg1 != null && arg1.type == Rv.ARRAY)) {
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = thiz.co.prev;
int argNum, argStart;
Rv argsArr;
if (isCall) {
argNum = argLen - 1;
argStart = 1;
argsArr = args;
} else {
argNum = arg1.num;
argStart = 0;
argsArr = arg1;
}
Pack argSrc = new Pack(-1, argNum);
for (int ii = argStart, nn = argStart + argNum; ii < nn; argSrc.add(argsArr.get(Integer.toString(ii++))));
Rv cobak = thiz.co;
ret = call(false, false, thiz, thiz.co = funCo, arg0, argSrc, 0, argNum);
thiz.co = cobak;
}
break;
case 131: // Number.valueOf(0)
ret = thiz.type == Rv.NUMBER_OBJECT ? thiz : Rv._undefined;
break;
case 141: // String.valueOf(0)
ret = thiz.type == Rv.STRING_OBJECT ? thiz : Rv._undefined;
break;
case 142: // String.charAt(1)
int pos = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : -1;
ret = pos < 0 || pos >= thiz.str.length() ? Rv._empty
: new Rv(String.valueOf(thiz.str.charAt(pos)));
break;
case 143: // String.indexOf(1)
ret = new Rv(-1);
if (arg0 != null) {
String s = arg0.toStr().str;
int idx = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : 0;
ret = new Rv(thiz.str.indexOf(s, idx));
}
break;
case 144: // String.lastIndexOf(1)
ret = new Rv(-1);
if (arg0 != null) {
String s = arg0.toStr().str;
String src = thiz.toStr().str;
int l = s.length(), srcl = src.length();
int idx = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : srcl;
if (idx >= 0) {
if (idx >= srcl - l) idx = srcl - l;
for (int i = idx + 1; --i >= 0;) {
if (src.regionMatches(false, i, s, 0, l)) {
ret = new Rv(i);
break;
}
}
}
}
break;
case 145: // String.substring(2)
if (arg0 != null) {
thiz = thiz.toStr();
int i1 = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
int i2 = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : Integer.MAX_VALUE;
int strlen;
if (i2 > (strlen = thiz.str.length())) i2 = strlen;
ret = new Rv(thiz.str.substring(i1, i2));
}
break;
case 146: // String.split(2)
if (arg0 != null) {
thiz = thiz.toStr();
int limit = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : -1;
String delim;
Pack p = split(thiz.str, delim = arg0.toStr().str);
if (limit >= 1) {
StringBuffer buf = new StringBuffer();
for (int i = limit - 1, n = p.oSize; i < n; i++) {
if (i > limit - 1) buf.append(delim);
buf.append(p.oArray[i]);
}
p.setSize(-1, limit).set(-1, buf.toString());
}
ret = new Rv(Rv.ARRAY, Rv._Array);
for (int i = 0, n = p.oSize; i < n; i++) {
ret.putl(i, new Rv((String) p.oArray[i]));
}
}
break;
case 147: // String.charCodeAt(1)
pos = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : -1;
ret = pos < 0 || pos >= thiz.str.length() ? Rv._NaN
: new Rv(thiz.str.charAt(pos));
break;
case 148: // String.fromCharCode(1)
StringBuffer buf = new StringBuffer();
for (int i = 0; i < argLen; i++) {
Rv charcode = args.get(Integer.toString(i)).toNum();
if (charcode != Rv._NaN) buf.append((char) charcode.num);
}
ret = new Rv(buf.toString());
break;
case 151: // Array.concat(1)
ret = new Rv(Rv.ARRAY, Rv._Array);
ret.num = thiz.num;
Rhash dest = ret.prop;
String key;
Pack keys = prop.keys();
for (int i = 0, n = keys.oSize; i < n; i++) {
dest.put(key = (String) keys.oArray[i], prop.get(key));
}
for (int i = 0; i < argLen; i++) {
Rv obj = args.get(Integer.toString(i));
if (obj.type == Rv.ARRAY) {
for (int j = 0, n = obj.num, b = ret.num; j < n; j++) {
ret.putl(b + j, obj.get(Integer.toString(j)));
}
} else {
ret.putl(ret.num, obj);
}
}
break;
case 152: // Array.join(1)
String sep = arg0 != null ? arg0.toStr().str : ",";
buf = new StringBuffer();
for (int i = 0, n = thiz.num; i < n; i++) {
if (i > 0) buf.append(sep);
buf.append(prop.get(Integer.toString(i)).toStr().str);
}
ret = new Rv(buf.toString());
break;
case 153: // Array.push(1)
for (int i = 0, b = thiz.num; i < argLen; i++) {
thiz.putl(b + i, args.get(Integer.toString(i)));
}
ret = new Rv(thiz.num);
break;
case 154: // Array.pop(0)
ret = thiz.shift(thiz.num - 1);
break;
case 155: // Array.shift(0)
ret = thiz.shift(0);
break;
case 156: // Array.unshift(1)
Rhash ht = new Rhash(11);
for (int i = 0; i < argLen; i++) {
String idx = Integer.toString(i);
Rv val = args.prop.get(idx);
if (val != null) ht.put(idx, val);
}
for (int i = 0, n = thiz.num; i < n; i++) {
Rv val = prop.get(Integer.toString(i));
if (val != null) ht.put(Integer.toString(i + argLen), val);
}
thiz.num += argLen;
thiz.prop = ht;
break;
case 157: // Array.slice(2)
if (arg0 != null) {
int i1 = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
int i2 = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : thiz.num;
ret = new Rv(Rv.ARRAY, Rv._Array);
ht = ret.prop;
int i = 0, n = ret.num = i2 - i1;
for (; i < n; i++) {
Rv val = prop.get(Integer.toString(i + i1));
if (val != null) ht.put(Integer.toString(i), val);
}
}
break;
case 158: // Array.sort(1)
Rv comp = arg0 != null && arg0.type >= Rv.FUNCTION ? arg0 : null;
int num;
Pack tmp = new Pack(-1, num = thiz.num);
for (int i = 0; i < num; tmp.add(prop.get(Integer.toString(i++))));
Object[] arr = tmp.oArray;
for (int i = 0, n = num - 1; i < n; i++) {
Rv r1 = (Rv) arr[i];
for (int j = i + 1; j < num; j++) {
Rv r2 = (Rv) arr[j];
boolean grtr = false;
if (r1 == null || r2 == null || r1 == Rv._undefined || r2 == Rv._undefined) {
grtr = r1 == null && r2 != null
|| r1 == Rv._undefined && r2 != null && r2 != Rv._undefined;
} else {
if (comp == null) {
grtr = r1.toStr().str.compareTo(r2.toStr().str) > 0;
} else {
Pack argSrc = new Pack(-1, 2).add(r1).add(r2);
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = comp.co.prev;
Rv cobak = comp.co;
grtr = call(false, false, comp, comp.co = funCo, thiz, argSrc, 0, 2).toNum().num > 0;
comp.co = cobak;
}
}
if (grtr) {
arr[j] = r1;
arr[i] = r1 = r2;
}
}
}
ht = new Rhash(11);
for (int i = num; --i >= 0;) {
Rv val;
if ((val = (Rv) arr[i]) != null) ht.put(Integer.toString(i), val);
}
thiz.prop = ht;
break;
case 159: // Array.reverse(0)
ht = new Rhash(11);
for (int i = 0, j = thiz.num; --j >= 0; i++) {
Rv val = prop.get(Integer.toString(j));
if (val != null) ht.put(Integer.toString(i), val);
}
thiz.prop = ht;
break;
case 160: // Date.getTime(0)
ret = new Rv(thiz.num);
break;
case 161: // Date.setTime(1)
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN) {
thiz.num = arg0.num;
}
break;
case 170: // Error.toString(0)
ret = thiz.get("message");
break;
case 203: // Math.random(1)
if (arg0 != null && arg0.toNum() != Rv._NaN) {
int low = arg0.num;
int high = arg1 != null && arg1.toNum() != Rv._NaN ? arg1.num : low - 1;
if (high <= low) {
high = low;
low = 0;
}
int rand = (random.nextInt() & 0x7FFFFFFF) % (high - low);
ret = new Rv(low + rand);
}
break;
case 210: // Math.min(2)
case 211: // Math.max(2)
if (argLen > 0) {
boolean isMax;
int iret = (isMax = funcId == 211) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
for (int i = 0; i < argLen; i++) {
Rv val = args.get(Integer.toString(i)).toNum();
if (val == Rv._NaN) {
ret = val;
break;
}
if (isMax && iret < val.num || !isMax && iret > val.num) iret = val.num;
}
ret = new Rv(iret);
}
break;
case 212: // Math.abs(1)
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN) {
thiz.num = Math.abs(arg0.num);
}
break;
case 213: // Math.pow(2)
if (argLen > 0) {
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN && arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN) {
thiz.num = (int)Math.pow(arg0.num, arg1.num);
}
}
break;
case 204: // isNaN(1)
ret = arg0 != null && arg0 == Rv._NaN ? Rv._true : Rv._false;
break;
case 205: // parseInt(1)
int radix = arg1 != null && arg1.toNum() != Rv._NaN ? arg1.num : 10;
String sNum = arg0 != null ? arg0.toStr().str : null;
try {
ret = new Rv(Integer.parseInt(sNum, radix));
} catch (Exception ex) { } // do nothing, ret = undefined
break;
case 206: // eval(1)
if (arg0 != null) {
String s;
this.reset(s = arg0.toStr().str, null, 0, s.length());
Node node = astNode(null, RC.TOK_FUNCTION, 0, 0);
astNode(node, RC.TOK_LBR, 0, this.endpos); // '{' = block
Rv func = new Rv(false, node, 0);
System.out.println("\nNode printout for eval(1):\n"+ node);
ret = call(true, false, func, thiz, null, null, 0, 0);
}
break;
case 207: // es(1)
if (arg0 != null) {
ret = evalString(arg0.toStr().str, thiz);
}
break;
case 208: // print(1);
case 209: // println(1);
String msg = argLen > 0 ? arg0.toStr().str : "";
if (!dontPrintOutput) System.out.print(msg);
out.append(msg);
if (funcId == 209) {
if (!dontPrintOutput) System.out.println();
out.append("\n");
}
break;
}
// StringBuffer buf = new StringBuffer();
// buf.append("this=" + thiz.toStr());
// for (int i = 0; i < argLen; i++) {
// buf.append(", ").append(args.get(Integer.toString(i)));
// }
// System.out.println(">> " + (isNew ? " NEW" : "CALL") + ": " + function.str + "(" + buf + "), Result=" + ret);
return ret;
}
| protected Rv callNative(boolean isNew, Rv function, Rv callObj) {
Rv idEnt;
if ((idEnt = htNativeIndex.getEntry(0, function.str)) == null) return Rv._undefined;
Rv args = callObj.get("arguments");
Rv thiz = callObj.get("this");
Rhash prop = thiz.prop;
int argLen = args.num;
Rv arg0, arg1, ret;
arg0 = argLen > 0 ? (Rv) args.get("0") : null;
arg1 = argLen > 1 ? (Rv) args.get("1") : null;
ret = Rv._undefined;
int funcId;
switch (funcId = idEnt.num) {
case 101: // Object(1)
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Object);
if (arg0 != null) {
int type;
if ((type = arg0.type) == Rv.NUMBER || type == Rv.NUMBER_OBJECT) {
ret.type = Rv.NUMBER_OBJECT;
ret.num = arg0.num;
} else if (type == Rv.STRING || type == Rv.STRING_OBJECT) {
ret.type = Rv.STRING_OBJECT;
ret.str = arg0.str;
} else { // object
ret = arg0;
}
}
break;
case 102: // Function(1)
if (argLen > 0) {
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Object);
ret.type = Rv.FUNCTION;
Node n;
if (argLen == 1 && arg0.type == Rv.FUNCTION) {
n = (Node) arg0.obj;
} else {
n = astNode(null, RC.TOK_FUNCTION, 0, 0);
int numArgs = argLen - 1;
for (int i = 0; i < numArgs; i++) {
String arg;
this.reset(arg = args.get(Integer.toString(i)).toStr().str, null, 0, arg.length());
astNode(n, RC.TOK_MUL, 0, this.endpos);
}
String src;
this.reset(src = args.get(Integer.toString(numArgs)).toStr().str, null, 0, src.length());
astNode(n, RC.TOK_LBR, 0, this.endpos); // '{' = block
}
ret.obj = n;
ret.ctorOrProt = Rv._Function;
ret.co = new Rv(Rv.OBJECT, Rv._Object);
ret.co.prev = callObj.prev;
}
break;
case 103: // Number(1)
if (isNew) {
ret = thiz;
ret.type = Rv.NUMBER_OBJECT;
ret.ctorOrProt = Rv._Number;
} else {
ret = new Rv(0);
}
ret.num = arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
break;
case 104: // String(1)
if (isNew) {
ret = thiz;
ret.type = Rv.STRING_OBJECT;
ret.ctorOrProt = Rv._String;
} else {
ret = new Rv("");
}
ret.str = arg0 != null? arg0.toStr().str : "";
break;
case 105: // Array(1)
ret = isNew ? thiz : new Rv(Rv.ARRAY, Rv._Array);
ret.type = Rv.ARRAY;
ret.ctorOrProt = Rv._Array;
Rv len;
if (argLen == 1 && (len = arg0.toNum()) != Rv._NaN) {
ret.num = len.num;
} else { // 0 or more
ret.num = argLen;
for (int i = 0; i < argLen; i++) {
ret.putl(i, args.get(Integer.toString(i)));
}
}
break;
case 106: // Date(1)
ret = isNew ? thiz : new Rv(Rv.OBJECT, Rv._Date);
ret.type = Rv.NUMBER_OBJECT;
ret.ctorOrProt = Rv._Date;
thiz.num = arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num
: (int) (System.currentTimeMillis() - bootTime);
break;
case 107: // Error(1)
ret = isNew ? thiz : new Rv(Rv.ERROR, Rv._Error);
ret.type = Rv.ERROR;
ret.ctorOrProt = Rv._Error;
if (arg0 != null) ret.putl("message", arg0.toStr());
break;
case 111: // Object.toString(0)
ret = thiz.toStr();
break;
case 112: // Object.hasOwnProperty(1)
ret = arg0 != null && thiz.has(arg0.toStr().str) ? Rv._true : Rv._false;
break;
case 121: // Function.call(1)
case 122: // Function.apply(2)
boolean isCall;
if (arg0 != null && arg0.type >= Rv.OBJECT
&& ((isCall = (funcId == 121)) || arg1 != null && arg1.type == Rv.ARRAY)) {
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = thiz.co.prev;
int argNum, argStart;
Rv argsArr;
if (isCall) {
argNum = argLen - 1;
argStart = 1;
argsArr = args;
} else {
argNum = arg1.num;
argStart = 0;
argsArr = arg1;
}
Pack argSrc = new Pack(-1, argNum);
for (int ii = argStart, nn = argStart + argNum; ii < nn; argSrc.add(argsArr.get(Integer.toString(ii++))));
Rv cobak = thiz.co;
ret = call(false, false, thiz, thiz.co = funCo, arg0, argSrc, 0, argNum);
thiz.co = cobak;
}
break;
case 131: // Number.valueOf(0)
ret = thiz.type == Rv.NUMBER_OBJECT ? thiz : Rv._undefined;
break;
case 141: // String.valueOf(0)
ret = thiz.type == Rv.STRING_OBJECT ? thiz : Rv._undefined;
break;
case 142: // String.charAt(1)
int pos = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : -1;
ret = pos < 0 || pos >= thiz.str.length() ? Rv._empty
: new Rv(String.valueOf(thiz.str.charAt(pos)));
break;
case 143: // String.indexOf(1)
ret = new Rv(-1);
if (arg0 != null) {
String s = arg0.toStr().str;
int idx = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : 0;
ret = new Rv(thiz.str.indexOf(s, idx));
}
break;
case 144: // String.lastIndexOf(1)
ret = new Rv(-1);
if (arg0 != null) {
String s = arg0.toStr().str;
String src = thiz.toStr().str;
int l = s.length(), srcl = src.length();
int idx = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : srcl;
if (idx >= 0) {
if (idx >= srcl - l) idx = srcl - l;
for (int i = idx + 1; --i >= 0;) {
if (src.regionMatches(false, i, s, 0, l)) {
ret = new Rv(i);
break;
}
}
}
}
break;
case 145: // String.substring(2)
if (arg0 != null) {
thiz = thiz.toStr();
int i1 = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
int i2 = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : Integer.MAX_VALUE;
int strlen;
if (i2 > (strlen = thiz.str.length())) i2 = strlen;
ret = new Rv(thiz.str.substring(i1, i2));
}
break;
case 146: // String.split(2)
if (arg0 != null) {
thiz = thiz.toStr();
int limit = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : -1;
String delim;
Pack p = split(thiz.str, delim = arg0.toStr().str);
if (limit >= 1) {
StringBuffer buf = new StringBuffer();
for (int i = limit - 1, n = p.oSize; i < n; i++) {
if (i > limit - 1) buf.append(delim);
buf.append(p.oArray[i]);
}
p.setSize(-1, limit).set(-1, buf.toString());
}
ret = new Rv(Rv.ARRAY, Rv._Array);
for (int i = 0, n = p.oSize; i < n; i++) {
ret.putl(i, new Rv((String) p.oArray[i]));
}
}
break;
case 147: // String.charCodeAt(1)
pos = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : -1;
ret = pos < 0 || pos >= thiz.str.length() ? Rv._NaN
: new Rv(thiz.str.charAt(pos));
break;
case 148: // String.fromCharCode(1)
StringBuffer buf = new StringBuffer();
for (int i = 0; i < argLen; i++) {
Rv charcode = args.get(Integer.toString(i)).toNum();
if (charcode != Rv._NaN) buf.append((char) charcode.num);
}
ret = new Rv(buf.toString());
break;
case 151: // Array.concat(1)
ret = new Rv(Rv.ARRAY, Rv._Array);
ret.num = thiz.num;
Rhash dest = ret.prop;
String key;
Pack keys = prop.keys();
for (int i = 0, n = keys.oSize; i < n; i++) {
dest.put(key = (String) keys.oArray[i], prop.get(key));
}
for (int i = 0; i < argLen; i++) {
Rv obj = args.get(Integer.toString(i));
if (obj.type == Rv.ARRAY) {
for (int j = 0, n = obj.num, b = ret.num; j < n; j++) {
ret.putl(b + j, obj.get(Integer.toString(j)));
}
} else {
ret.putl(ret.num, obj);
}
}
break;
case 152: // Array.join(1)
String sep = arg0 != null ? arg0.toStr().str : ",";
buf = new StringBuffer();
for (int i = 0, n = thiz.num; i < n; i++) {
if (i > 0) buf.append(sep);
buf.append(prop.get(Integer.toString(i)).toStr().str);
}
ret = new Rv(buf.toString());
break;
case 153: // Array.push(1)
for (int i = 0, b = thiz.num; i < argLen; i++) {
thiz.putl(b + i, args.get(Integer.toString(i)));
}
ret = new Rv(thiz.num);
break;
case 154: // Array.pop(0)
ret = thiz.shift(thiz.num - 1);
break;
case 155: // Array.shift(0)
ret = thiz.shift(0);
break;
case 156: // Array.unshift(1)
Rhash ht = new Rhash(11);
for (int i = 0; i < argLen; i++) {
String idx = Integer.toString(i);
Rv val = args.prop.get(idx);
if (val != null) ht.put(idx, val);
}
for (int i = 0, n = thiz.num; i < n; i++) {
Rv val = prop.get(Integer.toString(i));
if (val != null) ht.put(Integer.toString(i + argLen), val);
}
thiz.num += argLen;
thiz.prop = ht;
break;
case 157: // Array.slice(2)
if (arg0 != null) {
int i1 = (arg0 = arg0.toNum()) != Rv._NaN ? arg0.num : 0;
int i2 = arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN ? arg1.num : thiz.num;
ret = new Rv(Rv.ARRAY, Rv._Array);
ht = ret.prop;
int i = 0, n = ret.num = i2 - i1;
for (; i < n; i++) {
Rv val = prop.get(Integer.toString(i + i1));
if (val != null) ht.put(Integer.toString(i), val);
}
}
break;
case 158: // Array.sort(1)
Rv comp = arg0 != null && arg0.type >= Rv.FUNCTION ? arg0 : null;
int num;
Pack tmp = new Pack(-1, num = thiz.num);
for (int i = 0; i < num; tmp.add(prop.get(Integer.toString(i++))));
Object[] arr = tmp.oArray;
for (int i = 0, n = num - 1; i < n; i++) {
Rv r1 = (Rv) arr[i];
for (int j = i + 1; j < num; j++) {
Rv r2 = (Rv) arr[j];
boolean grtr = false;
if (r1 == null || r2 == null || r1 == Rv._undefined || r2 == Rv._undefined) {
grtr = r1 == null && r2 != null
|| r1 == Rv._undefined && r2 != null && r2 != Rv._undefined;
} else {
if (comp == null) {
grtr = r1.toStr().str.compareTo(r2.toStr().str) > 0;
} else {
Pack argSrc = new Pack(-1, 2).add(r1).add(r2);
Rv funCo = new Rv(Rv.OBJECT, Rv._Object);
funCo.prev = comp.co.prev;
Rv cobak = comp.co;
grtr = call(false, false, comp, comp.co = funCo, thiz, argSrc, 0, 2).toNum().num > 0;
comp.co = cobak;
}
}
if (grtr) {
arr[j] = r1;
arr[i] = r1 = r2;
}
}
}
ht = new Rhash(11);
for (int i = num; --i >= 0;) {
Rv val;
if ((val = (Rv) arr[i]) != null) ht.put(Integer.toString(i), val);
}
thiz.prop = ht;
break;
case 159: // Array.reverse(0)
ht = new Rhash(11);
for (int i = 0, j = thiz.num; --j >= 0; i++) {
Rv val = prop.get(Integer.toString(j));
if (val != null) ht.put(Integer.toString(i), val);
}
thiz.prop = ht;
break;
case 160: // Date.getTime(0)
ret = new Rv(thiz.num);
break;
case 161: // Date.setTime(1)
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN) {
thiz.num = arg0.num;
}
break;
case 170: // Error.toString(0)
ret = thiz.get("message");
break;
case 203: // Math.random(1)
if (arg0 != null && arg0.toNum() != Rv._NaN) {
int low = arg0.num;
int high = arg1 != null && arg1.toNum() != Rv._NaN ? arg1.num : low - 1;
if (high <= low) {
high = low;
low = 0;
}
int rand = (random.nextInt() & 0x7FFFFFFF) % (high - low);
ret = new Rv(low + rand);
}
break;
case 210: // Math.min(2)
case 211: // Math.max(2)
if (argLen > 0) {
boolean isMax;
int iret = (isMax = funcId == 211) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
for (int i = 0; i < argLen; i++) {
Rv val = args.get(Integer.toString(i)).toNum();
if (val == Rv._NaN) {
ret = val;
break;
}
if (isMax && iret < val.num || !isMax && iret > val.num) iret = val.num;
}
ret = new Rv(iret);
}
break;
case 212: // Math.abs(1)
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN) {
ret = new Rv(Math.abs(arg0.num));
}
break;
case 213: // Math.pow(2)
if (argLen > 0) {
System.out.println("Math.pow with args: " + arg0.num + " " + arg1.num);
if (arg0 != null && (arg0 = arg0.toNum()) != Rv._NaN && arg1 != null && (arg1 = arg1.toNum()) != Rv._NaN) {
ret = new Rv((int)Math.pow(arg0.num, arg1.num));
System.out.println("Calculated: " + thiz.num);
}
}
break;
case 204: // isNaN(1)
ret = arg0 != null && arg0 == Rv._NaN ? Rv._true : Rv._false;
break;
case 205: // parseInt(1)
int radix = arg1 != null && arg1.toNum() != Rv._NaN ? arg1.num : 10;
String sNum = arg0 != null ? arg0.toStr().str : null;
try {
ret = new Rv(Integer.parseInt(sNum, radix));
} catch (Exception ex) { } // do nothing, ret = undefined
break;
case 206: // eval(1)
if (arg0 != null) {
String s;
this.reset(s = arg0.toStr().str, null, 0, s.length());
Node node = astNode(null, RC.TOK_FUNCTION, 0, 0);
astNode(node, RC.TOK_LBR, 0, this.endpos); // '{' = block
Rv func = new Rv(false, node, 0);
System.out.println("\nNode printout for eval(1):\n"+ node);
ret = call(true, false, func, thiz, null, null, 0, 0);
}
break;
case 207: // es(1)
if (arg0 != null) {
ret = evalString(arg0.toStr().str, thiz);
}
break;
case 208: // print(1);
case 209: // println(1);
String msg = argLen > 0 ? arg0.toStr().str : "";
if (!dontPrintOutput) System.out.print(msg);
out.append(msg);
if (funcId == 209) {
if (!dontPrintOutput) System.out.println();
out.append("\n");
}
break;
}
// StringBuffer buf = new StringBuffer();
// buf.append("this=" + thiz.toStr());
// for (int i = 0; i < argLen; i++) {
// buf.append(", ").append(args.get(Integer.toString(i)));
// }
// System.out.println(">> " + (isNew ? " NEW" : "CALL") + ": " + function.str + "(" + buf + "), Result=" + ret);
return ret;
}
|
diff --git a/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java b/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java
index c42939050f..88f8fcce73 100644
--- a/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java
+++ b/server-integ/src/test/java/org/apache/directory/server/replication/ClientServerReplicationIT.java
@@ -1,387 +1,387 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.replication;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.CoreSession;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreateIndex;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.factory.DSAnnotationProcessor;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.server.factory.ServerAnnotationProcessor;
import org.apache.directory.server.ldap.LdapServer;
import org.apache.directory.server.ldap.replication.ReplicationConsumer;
import org.apache.directory.server.ldap.replication.SyncReplConsumer;
import org.apache.directory.server.ldap.replication.SyncReplRequestHandler;
import org.apache.directory.server.ldap.replication.SyncreplConfiguration;
import org.apache.directory.shared.ldap.model.entry.DefaultEntry;
import org.apache.directory.shared.ldap.model.entry.Entry;
import org.apache.directory.shared.ldap.model.message.ModifyRequest;
import org.apache.directory.shared.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.shared.ldap.model.name.Dn;
import org.apache.directory.shared.ldap.model.name.Rdn;
import org.apache.directory.shared.ldap.model.schema.SchemaManager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/**
* Tests for replication subsystem in client-server mode.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class ClientServerReplicationIT
{
private static LdapServer providerServer;
private static LdapServer consumerServer;
private static SchemaManager schemaManager;
private static CoreSession providerSession;
private static CoreSession consumerSession;
private static AtomicInteger entryCount = new AtomicInteger();
@BeforeClass
public static void setUp() throws Exception
{
Class justLoadToSetControlProperties = Class.forName( FrameworkRunner.class.getName() );
startProvider();
startConsumer();
}
@AfterClass
public static void tearDown()
{
consumerServer.stop();
providerServer.stop();
}
@Test
public void testInjectContextEntry() throws Exception
{
String dn = "dc=example,dc=com";
DefaultEntry entry = new DefaultEntry( schemaManager, dn );
entry.add( "objectClass", "domain" );
entry.add( "dc", "example" );
assertFalse( consumerSession.exists( dn ) );
providerSession.add( entry );
waitAndCompareEntries( entry.getDn() );
}
@Test
public void testModify() throws Exception
{
Entry provUser = createEntry();
assertFalse( consumerSession.exists( provUser.getDn() ) );
providerSession.add( provUser );
ModifyRequest modReq = new ModifyRequestImpl();
modReq.setName( provUser.getDn() );
modReq.add( "userPassword", "secret" );
providerSession.modify( modReq );
waitAndCompareEntries( provUser.getDn() );
}
@Test
public void testModDn() throws Exception
{
Entry provUser = createEntry();
assertFalse( consumerSession.exists( provUser.getDn() ) );
providerSession.add( provUser );
Dn usersContainer = new Dn( schemaManager, "ou=users,dc=example,dc=com" );
DefaultEntry entry = new DefaultEntry( schemaManager, usersContainer );
entry.add( "objectClass", "organizationalUnit" );
entry.add( "ou", "users" );
providerSession.add( entry );
waitAndCompareEntries( entry.getDn() );
// move
Dn userDn = provUser.getDn();
providerSession.move( userDn, usersContainer );
userDn = usersContainer.add( userDn.getRdn() );
waitAndCompareEntries( userDn );
// now try renaming
Rdn newName = new Rdn( schemaManager, userDn.getRdn().getName() + "renamed");
providerSession.rename( userDn, newName, true );
userDn = usersContainer.add( newName );
waitAndCompareEntries( userDn );
// now move and rename
Dn newParent = usersContainer.getParent();
newName = new Rdn( schemaManager, userDn.getRdn().getName() + "MovedAndRenamed");
providerSession.moveAndRename( userDn, newParent, newName, false );
userDn = newParent.add( newName );
waitAndCompareEntries( userDn );
}
@Test
public void testDelete() throws Exception
{
Entry provUser = createEntry();
providerSession.add( provUser );
waitAndCompareEntries( provUser.getDn() );
providerSession.delete( provUser.getDn() );
Thread.sleep( 2000 );
assertFalse( consumerSession.exists( provUser.getDn() ) );
}
@Test
@Ignore("this test often fails due to a timing issue")
public void testRebootConsumer() throws Exception
{
Entry provUser = createEntry();
providerSession.add( provUser );
waitAndCompareEntries( provUser.getDn() );
consumerServer.stop();
Dn deletedUserDn = provUser.getDn();
providerSession.delete( deletedUserDn );
provUser = createEntry();
Dn addedUserDn = provUser.getDn();
providerSession.add( provUser );
startConsumer();
Thread.sleep( 5000 );
assertFalse( consumerSession.exists( deletedUserDn ) );
waitAndCompareEntries( addedUserDn );
}
private void waitAndCompareEntries( Dn dn ) throws Exception
{
// sleep for 2 sec (twice the refresh interval), just to let the first refresh request succeed
Thread.sleep( 2000 );
Entry providerEntry = providerSession.lookup( dn, "*", "+" );
Entry consumerEntry = consumerSession.lookup( dn, "*", "+" );
assertEquals( providerEntry, consumerEntry );
}
private Entry createEntry() throws Exception
{
String user = "user"+ entryCount.incrementAndGet();
String dn = "cn=" + user + ",dc=example,dc=com";
DefaultEntry entry = new DefaultEntry( schemaManager, dn );
entry.add( "objectClass", "person" );
entry.add( "cn", user );
entry.add( "sn", user );
return entry;
}
@CreateDS(allowAnonAccess = true, name = "provider-replication", partitions =
{
@CreatePartition(
name = "example",
suffix = "dc=example,dc=com",
indexes =
{
@CreateIndex(attribute = "objectClass"),
@CreateIndex(attribute = "dc"),
@CreateIndex(attribute = "ou")
})
})
@CreateLdapServer(transports =
{ @CreateTransport( port=16000, protocol = "LDAP") })
private static void startProvider() throws Exception
{
Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startProvider" );
CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class );
DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation );
CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class );
providerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 );
providerServer.setReplicationReqHandler( new SyncReplRequestHandler() );
Runnable r = new Runnable()
{
public void run()
{
try
{
providerServer.start();
schemaManager = providerServer.getDirectoryService().getSchemaManager();
providerSession = providerServer.getDirectoryService().getAdminSession();
}
catch( Exception e )
{
e.printStackTrace();
}
}
};
Thread t = new Thread( r );
t.setDaemon( true );
t.start();
t.join();
}
@CreateDS(allowAnonAccess = true, name = "consumer-replication", partitions =
{
@CreatePartition(
name = "example",
suffix = "dc=example,dc=com",
indexes =
{
@CreateIndex(attribute = "objectClass"),
@CreateIndex(attribute = "dc"),
@CreateIndex(attribute = "ou")
})
})
@CreateLdapServer(transports =
{ @CreateTransport( port=17000, protocol = "LDAP") })
private static void startConsumer() throws Exception
{
Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startConsumer" );
CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class );
DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation );
CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class );
consumerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 );
SyncReplConsumer syncreplClient = new SyncReplConsumer();
final SyncreplConfiguration config = new SyncreplConfiguration();
config.setProviderHost( "localhost" );
config.setPort( 16000 );
config.setReplUserDn( "uid=admin,ou=system" );
config.setReplUserPassword( "secret".getBytes() );
config.setUseTls( false );
config.setBaseDn( "dc=example,dc=com" );
config.setRefreshInterval( 1000 );
syncreplClient.setConfig( config );
List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>();
replConsumers.add( syncreplClient );
consumerServer.setReplConsumers( replConsumers );
Runnable r = new Runnable()
{
public void run()
{
try
{
consumerServer.start();
DirectoryService ds = consumerServer.getDirectoryService();
Dn configDn = new Dn( ds.getSchemaManager(), "ads-replProviderId=localhost,ou=system" );
config.setConfigEntryDn( configDn );
Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn );
provConfigEntry.add( "objectClass", "ads-replConsumer" );
- provConfigEntry.add( "ads-replConsumerId", "localhost" );
+ provConfigEntry.add( "ads-replProviderId", "localhost" );
provConfigEntry.add( "ads-searchBaseDN", config.getBaseDn() );
provConfigEntry.add( "ads-replProvHostName", config.getProviderHost() );
provConfigEntry.add( "ads-replProvPort", String.valueOf( config.getPort() ) );
provConfigEntry.add( "ads-replAliasDerefMode", config.getAliasDerefMode().getJndiValue() );
provConfigEntry.add( "ads-replAttributes", config.getAttributes() );
provConfigEntry.add( "ads-replRefreshInterval", String.valueOf( config.getRefreshInterval() ) );
provConfigEntry.add( "ads-replRefreshNPersist", String.valueOf( config.isRefreshNPersist() ) );
provConfigEntry.add( "ads-replSearchScope", config.getSearchScope().getLdapUrlValue() );
provConfigEntry.add( "ads-replSearchFilter", config.getFilter() );
provConfigEntry.add( "ads-replSearchSizeLimit", String.valueOf( config.getSearchSizeLimit() ) );
provConfigEntry.add( "ads-replSearchTimeOut", String.valueOf( config.getSearchTimeout() ) );
provConfigEntry.add( "ads-replUserDn", config.getReplUserDn() );
provConfigEntry.add( "ads-replUserPassword", config.getReplUserPassword() );
consumerSession = consumerServer.getDirectoryService().getAdminSession();
consumerSession.add( provConfigEntry );
}
catch( Exception e )
{
e.printStackTrace();
}
}
};
Thread t = new Thread( r );
t.setDaemon( true );
t.start();
t.join();
}
}
| true | true | private static void startConsumer() throws Exception
{
Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startConsumer" );
CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class );
DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation );
CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class );
consumerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 );
SyncReplConsumer syncreplClient = new SyncReplConsumer();
final SyncreplConfiguration config = new SyncreplConfiguration();
config.setProviderHost( "localhost" );
config.setPort( 16000 );
config.setReplUserDn( "uid=admin,ou=system" );
config.setReplUserPassword( "secret".getBytes() );
config.setUseTls( false );
config.setBaseDn( "dc=example,dc=com" );
config.setRefreshInterval( 1000 );
syncreplClient.setConfig( config );
List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>();
replConsumers.add( syncreplClient );
consumerServer.setReplConsumers( replConsumers );
Runnable r = new Runnable()
{
public void run()
{
try
{
consumerServer.start();
DirectoryService ds = consumerServer.getDirectoryService();
Dn configDn = new Dn( ds.getSchemaManager(), "ads-replProviderId=localhost,ou=system" );
config.setConfigEntryDn( configDn );
Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn );
provConfigEntry.add( "objectClass", "ads-replConsumer" );
provConfigEntry.add( "ads-replConsumerId", "localhost" );
provConfigEntry.add( "ads-searchBaseDN", config.getBaseDn() );
provConfigEntry.add( "ads-replProvHostName", config.getProviderHost() );
provConfigEntry.add( "ads-replProvPort", String.valueOf( config.getPort() ) );
provConfigEntry.add( "ads-replAliasDerefMode", config.getAliasDerefMode().getJndiValue() );
provConfigEntry.add( "ads-replAttributes", config.getAttributes() );
provConfigEntry.add( "ads-replRefreshInterval", String.valueOf( config.getRefreshInterval() ) );
provConfigEntry.add( "ads-replRefreshNPersist", String.valueOf( config.isRefreshNPersist() ) );
provConfigEntry.add( "ads-replSearchScope", config.getSearchScope().getLdapUrlValue() );
provConfigEntry.add( "ads-replSearchFilter", config.getFilter() );
provConfigEntry.add( "ads-replSearchSizeLimit", String.valueOf( config.getSearchSizeLimit() ) );
provConfigEntry.add( "ads-replSearchTimeOut", String.valueOf( config.getSearchTimeout() ) );
provConfigEntry.add( "ads-replUserDn", config.getReplUserDn() );
provConfigEntry.add( "ads-replUserPassword", config.getReplUserPassword() );
consumerSession = consumerServer.getDirectoryService().getAdminSession();
consumerSession.add( provConfigEntry );
}
catch( Exception e )
{
e.printStackTrace();
}
}
};
Thread t = new Thread( r );
t.setDaemon( true );
t.start();
t.join();
}
| private static void startConsumer() throws Exception
{
Method createProviderMethod = ClientServerReplicationIT.class.getDeclaredMethod( "startConsumer" );
CreateDS dsAnnotation = createProviderMethod.getAnnotation( CreateDS.class );
DirectoryService provDirService = DSAnnotationProcessor.createDS( dsAnnotation );
CreateLdapServer serverAnnotation = createProviderMethod.getAnnotation( CreateLdapServer.class );
consumerServer = ServerAnnotationProcessor.instantiateLdapServer( serverAnnotation, provDirService, 0 );
SyncReplConsumer syncreplClient = new SyncReplConsumer();
final SyncreplConfiguration config = new SyncreplConfiguration();
config.setProviderHost( "localhost" );
config.setPort( 16000 );
config.setReplUserDn( "uid=admin,ou=system" );
config.setReplUserPassword( "secret".getBytes() );
config.setUseTls( false );
config.setBaseDn( "dc=example,dc=com" );
config.setRefreshInterval( 1000 );
syncreplClient.setConfig( config );
List<ReplicationConsumer> replConsumers = new ArrayList<ReplicationConsumer>();
replConsumers.add( syncreplClient );
consumerServer.setReplConsumers( replConsumers );
Runnable r = new Runnable()
{
public void run()
{
try
{
consumerServer.start();
DirectoryService ds = consumerServer.getDirectoryService();
Dn configDn = new Dn( ds.getSchemaManager(), "ads-replProviderId=localhost,ou=system" );
config.setConfigEntryDn( configDn );
Entry provConfigEntry = new DefaultEntry( ds.getSchemaManager(), configDn );
provConfigEntry.add( "objectClass", "ads-replConsumer" );
provConfigEntry.add( "ads-replProviderId", "localhost" );
provConfigEntry.add( "ads-searchBaseDN", config.getBaseDn() );
provConfigEntry.add( "ads-replProvHostName", config.getProviderHost() );
provConfigEntry.add( "ads-replProvPort", String.valueOf( config.getPort() ) );
provConfigEntry.add( "ads-replAliasDerefMode", config.getAliasDerefMode().getJndiValue() );
provConfigEntry.add( "ads-replAttributes", config.getAttributes() );
provConfigEntry.add( "ads-replRefreshInterval", String.valueOf( config.getRefreshInterval() ) );
provConfigEntry.add( "ads-replRefreshNPersist", String.valueOf( config.isRefreshNPersist() ) );
provConfigEntry.add( "ads-replSearchScope", config.getSearchScope().getLdapUrlValue() );
provConfigEntry.add( "ads-replSearchFilter", config.getFilter() );
provConfigEntry.add( "ads-replSearchSizeLimit", String.valueOf( config.getSearchSizeLimit() ) );
provConfigEntry.add( "ads-replSearchTimeOut", String.valueOf( config.getSearchTimeout() ) );
provConfigEntry.add( "ads-replUserDn", config.getReplUserDn() );
provConfigEntry.add( "ads-replUserPassword", config.getReplUserPassword() );
consumerSession = consumerServer.getDirectoryService().getAdminSession();
consumerSession.add( provConfigEntry );
}
catch( Exception e )
{
e.printStackTrace();
}
}
};
Thread t = new Thread( r );
t.setDaemon( true );
t.start();
t.join();
}
|
diff --git a/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/model/JSF2ComponentModelManager.java b/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/model/JSF2ComponentModelManager.java
index 249a738c4..184f53d60 100644
--- a/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/model/JSF2ComponentModelManager.java
+++ b/jsf/plugins/org.jboss.tools.jsf/src/org/jboss/tools/jsf/jsf2/model/JSF2ComponentModelManager.java
@@ -1,434 +1,435 @@
/*******************************************************************************
* Copyright (c) 2007-2010 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jsf.jsf2.model;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.internal.core.JarEntryFile;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.DocumentProviderRegistry;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.wst.html.core.internal.encoding.HTMLModelLoader;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.text.JobSafeStructuredDocument;
import org.eclipse.wst.xml.core.internal.document.ElementImpl;
import org.eclipse.wst.xml.core.internal.parser.XMLSourceParser;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.eclipse.wst.xml.core.internal.provisional.format.DocumentNodeFormatter;
import org.jboss.tools.jsf.JSFModelPlugin;
import org.jboss.tools.jsf.jsf2.util.JSF2ResourceUtil;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author yzhishko
*
*/
@SuppressWarnings("restriction")
public class JSF2ComponentModelManager {
public final static String INTERFACE = "interface";
public final static String ATTRIBUTE = "attribute";
public final static String NAME = "name";
public final static String XMLNS = "xmlns";
public final static String COLON = ":";
public final static String DEFAULT_COMPOSITE_PREFIX = "composite";
public final static String XHTML_URI = "http://www.w3.org/1999/xhtml";
public final static String HTML = "html";
public final static String HTML_URI = "http://java.sun.com/jsf/html";
public final static String HTML_PREFIX = "h";
private static JSF2ComponentModelManager instance = new JSF2ComponentModelManager();
private JSF2ComponentModelManager() {
}
public static JSF2ComponentModelManager getManager() {
return instance;
}
public IFile updateJSF2CompositeComponentFile(
final IFile componentFileContatiner, final String[] attrNames) {
IFile file = updateFileContent(new EditableDOMFile() {
@Override
public IFile getFile() {
return componentFileContatiner;
}
@Override
protected void edit(IDOMModel model) throws CoreException,
IOException {
FileEditorInput input = new FileEditorInput(getFile());
IDocumentProvider provider = DocumentProviderRegistry.getDefault().getDocumentProvider(input);
provider.connect(input);
IDocument document = provider.getDocument(input);
updateJSF2CompositeComponent(model.getDocument(), attrNames);
provider.aboutToChange(input);
provider.saveDocument(new NullProgressMonitor(), input, document, true);
+ provider.changed(input);
provider.disconnect(input);
}
});
return file;
}
private void updateJSF2CompositeComponent(IDOMDocument componentDoc,
String[] attrNames) {
Element interfaceElement = findInterfaceComponent(componentDoc);
if(interfaceElement == null)
interfaceElement = createCompositeInterface(componentDoc);
createCompositeCompInterface(interfaceElement, attrNames);
}
private Element findInterfaceComponent(Node node) {
if (node instanceof IDOMDocument) {
IDOMDocument document = (IDOMDocument) node;
Element element = findInterfaceComponent(document.getDocumentElement());
if(element != null)
return element;
}
if (node instanceof ElementImpl) {
ElementImpl impl = (ElementImpl) node;
String nameSpace = impl.getNamespaceURI();
if (JSF2ResourceUtil.JSF2_URI_PREFIX.equals(nameSpace)) {
String nodeName = impl.getLocalName();
if (INTERFACE.equals(nodeName)) { //$NON-NLS-1$
return impl;
}
} else {
NodeList nodeList = node.getChildNodes();
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = findInterfaceComponent(nodeList.item(i));
if(element != null)
return element;
}
}
}
}
return null;
}
private void createCompositeCompInterface(Element element,
String[] attrNames) {
Document document = (Document) element.getOwnerDocument();
String prefix = element.getPrefix();
Set<String> existInerfaceAttrs = getInterfaceAttrs(element);
if (prefix != null && !"".equals(prefix)) { //$NON-NLS-1$
for (int i = 0; i < attrNames.length; i++) {
if (!existInerfaceAttrs.contains(attrNames[i])) {
Element attrEl = document.createElementNS(
JSF2ResourceUtil.JSF2_URI_PREFIX, prefix
+ COLON+ATTRIBUTE); //$NON-NLS-1$
attrEl.setAttribute(NAME, attrNames[i]); //$NON-NLS-1$
element.appendChild(attrEl);
}
}
} else {
for (int i = 0; i < attrNames.length; i++) {
if (!existInerfaceAttrs.contains(attrNames[i])) {
Element attrEl = document.createElementNS(
JSF2ResourceUtil.JSF2_URI_PREFIX, ATTRIBUTE); //$NON-NLS-1$
attrEl.setAttribute(NAME, attrNames[i]); //$NON-NLS-1$
element.appendChild(attrEl);
}
}
}
DocumentNodeFormatter formatter = new DocumentNodeFormatter();
formatter.format(document);
}
public IFile revalidateCompositeComponentFile(IFile file) {
IDOMDocument document = getReadableDOMDocument(file);
if (document == null) {
return null;
}
//Element interfaceElement = checkCompositeInterface(document);
//if (interfaceElement == null)
//return null;
return file;
}
public Element checkCompositeInterface(IDOMDocument document) {
if (document == null) {
return null;
}
Element element = document.getDocumentElement();
if (element == null) {
return null;
}
if(!hasNamespace(element, JSF2ResourceUtil.JSF2_URI_PREFIX))
return null;
return findInterfaceComponent(element);
}
private boolean hasNamespace(Node node, String URI){
NamedNodeMap attributes = node.getAttributes();
for(int i = 0; i < attributes.getLength(); i++){
Node attr = attributes.item(i);
if(attr.getNodeName().startsWith(XMLNS+COLON) && URI.equals(attr.getNodeValue()))
return true;
}
return false;
}
private String getPrefix(Node node, String URI){
NamedNodeMap attributes = node.getAttributes();
for(int i = 0; i < attributes.getLength(); i++){
Node attr = attributes.item(i);
if(attr.getNodeName().startsWith(XMLNS+COLON) && URI.equals(attr.getNodeValue()))
return attr.getLocalName();
}
return null;
}
private Element findNodeToCreateCompositeInterface(Element rootNode){
if(hasNamespace(rootNode, JSF2ResourceUtil.JSF2_URI_PREFIX))
return rootNode;
NodeList children = rootNode.getChildNodes();
for(int i = 0; i < children.getLength(); i++){
Node child = children.item(i);
if(child instanceof Element){
Node result = findNodeToCreateCompositeInterface((Element)child);
if(result != null && result instanceof Element)
return (Element)result;
}
}
return null;
}
private Element createCompositeInterface(Document document){
Element rootElement = document.getDocumentElement();
if (rootElement == null) {
rootElement = createDocumentElementForCompositeInterface(document);
}
Element node = findNodeToCreateCompositeInterface(rootElement);
if(node == null){
addURI(document, rootElement);
node = rootElement;
}
String prefix = getPrefix(node, JSF2ResourceUtil.JSF2_URI_PREFIX);
Element interfaceElement = document.createElement(prefix+COLON+INTERFACE);
node.appendChild(interfaceElement);
DocumentNodeFormatter formatter = new DocumentNodeFormatter();
formatter.format(document);
return interfaceElement;
}
private Element createDocumentElementForCompositeInterface(Document document){
Element rootElement = document.createElement(HTML);
Attr attr = document.createAttribute(XMLNS);
attr.setValue(XHTML_URI);
rootElement.setAttributeNode(attr);
attr = document.createAttribute(XMLNS+COLON+HTML_PREFIX);
attr.setValue(HTML_URI);
rootElement.setAttributeNode(attr);
attr = document.createAttribute(XMLNS+COLON+DEFAULT_COMPOSITE_PREFIX);
attr.setValue(JSF2ResourceUtil.JSF2_URI_PREFIX);
rootElement.setAttributeNode(attr);
document.appendChild(rootElement);
return rootElement;
}
private void addURI(Document document, Element rootElement){
Attr attr = document.createAttribute(XMLNS+COLON+DEFAULT_COMPOSITE_PREFIX);
attr.setValue(JSF2ResourceUtil.JSF2_URI_PREFIX);
rootElement.setAttributeNode(attr);
}
public static IDOMDocument getReadableDOMDocument(IFile file) {
IDOMDocument document = null;
IModelManager manager = StructuredModelManager.getModelManager();
if (manager == null) {
return document;
}
IStructuredModel model = null;
try {
model = manager.getModelForRead(file);
if (model instanceof IDOMModel) {
IDOMModel domModel = (IDOMModel) model;
document = domModel.getDocument();
}
} catch (CoreException e) {
JSFModelPlugin.getPluginLog().logError(e);
} catch (IOException e) {
JSFModelPlugin.getPluginLog().logError(e);
} finally {
if (model != null) {
model.releaseFromRead();
}
}
return document;
}
public static IDOMDocument getReadableDOMDocument(JarEntryFile file) {
IDOMDocument document = null;
IStructuredModel model = null;
InputStream inputStream;
try {
inputStream = file.getContents();
if (inputStream != null) {
StringBuffer buffer = new StringBuffer(""); //$NON-NLS-1$
Scanner in = new Scanner(inputStream);
while (in.hasNextLine()) {
buffer.append(in.nextLine());
}
model = new HTMLModelLoader().newModel();
model.setStructuredDocument(new JobSafeStructuredDocument(
new XMLSourceParser()));
model.getStructuredDocument().set(buffer.toString());
if (model instanceof IDOMModel) {
document = ((IDOMModel) model).getDocument();
}
}
} catch (CoreException e) {
JSFModelPlugin.getPluginLog().logError(e);
} finally {
model = null;
}
return document;
}
public static IDOMDocument getReadableDOMDocument(IDocument textDocument) {
IDOMDocument document = null;
if (!(textDocument instanceof IStructuredDocument)) {
return document;
}
IModelManager manager = StructuredModelManager.getModelManager();
if (manager == null) {
return document;
}
IStructuredModel model = null;
try {
model = manager.getModelForRead((IStructuredDocument) textDocument);
if (model instanceof IDOMModel) {
IDOMModel domModel = (IDOMModel) model;
document = domModel.getDocument();
}
} finally {
if (model != null) {
model.releaseFromRead();
}
}
return document;
}
public Set<String> getInterfaceAttrs(Element interfaceElement) {
Set<String> interfaceAttrs = new HashSet<String>(0);
if (interfaceElement != null) {
String prefix = interfaceElement.getPrefix();
String nodeName = ATTRIBUTE;
if (prefix != null && !"".equals(prefix)) { //$NON-NLS-1$
nodeName = prefix + COLON + nodeName; //$NON-NLS-1$
}
NodeList attrsElements = interfaceElement
.getElementsByTagName(nodeName);
if (attrsElements != null) {
for (int i = 0; i < attrsElements.getLength(); i++) {
Node el = attrsElements.item(i);
if (el instanceof IDOMElement) {
IDOMElement element = (IDOMElement) el;
String attrvalue = element.getAttribute(NAME); //$NON-NLS-1$
if (attrvalue != null && !"".equals(attrvalue)) { //$NON-NLS-1$
interfaceAttrs.add(attrvalue);
}
}
}
}
}
return interfaceAttrs;
}
private abstract class EditableDOMFile {
public EditableDOMFile() {
}
public IFile editFile() {
IFile file = getFile();
if (file == null) {
return file;
}
IModelManager manager = StructuredModelManager.getModelManager();
if (manager == null) {
return file;
}
IStructuredModel model = null;
try {
model = manager.getModelForEdit(file);
if (model instanceof IDOMModel) {
IDOMModel domModel = (IDOMModel) model;
edit(domModel);
}
} catch (CoreException e) {
JSFModelPlugin.getPluginLog().logError(e);
} catch (IOException e) {
JSFModelPlugin.getPluginLog().logError(e);
} finally {
if (model != null) {
model.releaseFromEdit();
}
}
return file;
};
protected abstract void edit(IDOMModel model) throws CoreException,
IOException;
public abstract IFile getFile();
}
private IFile updateFileContent(EditableDOMFile domFile) {
return domFile.editFile();
}
}
| true | true | public IFile updateJSF2CompositeComponentFile(
final IFile componentFileContatiner, final String[] attrNames) {
IFile file = updateFileContent(new EditableDOMFile() {
@Override
public IFile getFile() {
return componentFileContatiner;
}
@Override
protected void edit(IDOMModel model) throws CoreException,
IOException {
FileEditorInput input = new FileEditorInput(getFile());
IDocumentProvider provider = DocumentProviderRegistry.getDefault().getDocumentProvider(input);
provider.connect(input);
IDocument document = provider.getDocument(input);
updateJSF2CompositeComponent(model.getDocument(), attrNames);
provider.aboutToChange(input);
provider.saveDocument(new NullProgressMonitor(), input, document, true);
provider.disconnect(input);
}
});
return file;
}
| public IFile updateJSF2CompositeComponentFile(
final IFile componentFileContatiner, final String[] attrNames) {
IFile file = updateFileContent(new EditableDOMFile() {
@Override
public IFile getFile() {
return componentFileContatiner;
}
@Override
protected void edit(IDOMModel model) throws CoreException,
IOException {
FileEditorInput input = new FileEditorInput(getFile());
IDocumentProvider provider = DocumentProviderRegistry.getDefault().getDocumentProvider(input);
provider.connect(input);
IDocument document = provider.getDocument(input);
updateJSF2CompositeComponent(model.getDocument(), attrNames);
provider.aboutToChange(input);
provider.saveDocument(new NullProgressMonitor(), input, document, true);
provider.changed(input);
provider.disconnect(input);
}
});
return file;
}
|
diff --git a/test/org/jivesoftware/smack/PacketReaderTest.java b/test/org/jivesoftware/smack/PacketReaderTest.java
index cd3642cb..77fb14f1 100644
--- a/test/org/jivesoftware/smack/PacketReaderTest.java
+++ b/test/org/jivesoftware/smack/PacketReaderTest.java
@@ -1,102 +1,102 @@
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2002-2003 Jive Software. All rights reserved.
* ====================================================================
* The Jive Software License (based on Apache Software License, Version 1.1)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by
* Jive Software (http://www.jivesoftware.com)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Smack" and "Jive Software" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please
* contact [email protected].
*
* 5. Products derived from this software may not be called "Smack",
* nor may "Smack" appear in their name, without prior written
* permission of Jive Software.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*/
package org.jivesoftware.smack;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.test.SmackTestCase;
public class PacketReaderTest extends SmackTestCase {
/**
* Constructor for PacketReaderTest.
* @param arg0
*/
public PacketReaderTest(String arg0) {
super(arg0);
}
/**
* Verify that when Smack receives a "not implemented IQ" answers with an IQ packet
* with error code 501.
*/
public void testIQNotImplemented() {
// Create a new type of IQ to send. The new IQ will include a
// non-existant namespace to cause the "feature-not-implemented" answer
IQ iqPacket = new IQ() {
public String getChildElementXML() {
return "<query xmlns=\"my:ns:test\"/>";
}
};
iqPacket.setTo(getFullJID(1));
iqPacket.setType(IQ.Type.GET);
// Send the IQ and wait for the answer
PacketCollector collector = getConnection(0).createPacketCollector(
new PacketIDFilter(iqPacket.getPacketID()));
getConnection(0).sendPacket(iqPacket);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
if (response == null) {
fail("No response from the other user.");
}
- assertEquals("The received IQ is not of type ERROR", response.getType(),IQ.Type.ERROR);
- assertEquals("The error code is not 501", response.getError().getCode(),501);
+ assertEquals("The received IQ is not of type ERROR", IQ.Type.ERROR, response.getType());
+ assertEquals("The error code is not 501", 501, response.getError().getCode());
collector.cancel();
}
protected int getMaxConnections() {
return 2;
}
}
| true | true | public void testIQNotImplemented() {
// Create a new type of IQ to send. The new IQ will include a
// non-existant namespace to cause the "feature-not-implemented" answer
IQ iqPacket = new IQ() {
public String getChildElementXML() {
return "<query xmlns=\"my:ns:test\"/>";
}
};
iqPacket.setTo(getFullJID(1));
iqPacket.setType(IQ.Type.GET);
// Send the IQ and wait for the answer
PacketCollector collector = getConnection(0).createPacketCollector(
new PacketIDFilter(iqPacket.getPacketID()));
getConnection(0).sendPacket(iqPacket);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
if (response == null) {
fail("No response from the other user.");
}
assertEquals("The received IQ is not of type ERROR", response.getType(),IQ.Type.ERROR);
assertEquals("The error code is not 501", response.getError().getCode(),501);
collector.cancel();
}
| public void testIQNotImplemented() {
// Create a new type of IQ to send. The new IQ will include a
// non-existant namespace to cause the "feature-not-implemented" answer
IQ iqPacket = new IQ() {
public String getChildElementXML() {
return "<query xmlns=\"my:ns:test\"/>";
}
};
iqPacket.setTo(getFullJID(1));
iqPacket.setType(IQ.Type.GET);
// Send the IQ and wait for the answer
PacketCollector collector = getConnection(0).createPacketCollector(
new PacketIDFilter(iqPacket.getPacketID()));
getConnection(0).sendPacket(iqPacket);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
if (response == null) {
fail("No response from the other user.");
}
assertEquals("The received IQ is not of type ERROR", IQ.Type.ERROR, response.getType());
assertEquals("The error code is not 501", 501, response.getError().getCode());
collector.cancel();
}
|
diff --git a/org.dsanderson.xctrailreport.core/src/org/dsanderson/xctrailreport/core/DateComparator.java b/org.dsanderson.xctrailreport.core/src/org/dsanderson/xctrailreport/core/DateComparator.java
index b44e50b..922680c 100644
--- a/org.dsanderson.xctrailreport.core/src/org/dsanderson/xctrailreport/core/DateComparator.java
+++ b/org.dsanderson.xctrailreport.core/src/org/dsanderson/xctrailreport/core/DateComparator.java
@@ -1,39 +1,40 @@
/**
* @author David S Anderson
*
*
* Copyright (C) 2012 David S Anderson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dsanderson.xctrailreport.core;
import java.util.Comparator;
/**
*
*/
public class DateComparator implements Comparator<TrailReport> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(TrailReport o1, TrailReport o2) {
- return o1.getDate().compareTo(o2.getDate());
+ // reverse sorting no that newer reports appear first
+ return 0 - o1.getDate().compareTo(o2.getDate());
}
}
| true | true | public int compare(TrailReport o1, TrailReport o2) {
return o1.getDate().compareTo(o2.getDate());
}
| public int compare(TrailReport o1, TrailReport o2) {
// reverse sorting no that newer reports appear first
return 0 - o1.getDate().compareTo(o2.getDate());
}
|
diff --git a/GAE_shuttleatwork/test/AllTests.java b/GAE_shuttleatwork/test/AllTests.java
index 386f895..2dd382d 100644
--- a/GAE_shuttleatwork/test/AllTests.java
+++ b/GAE_shuttleatwork/test/AllTests.java
@@ -1,24 +1,26 @@
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests extends TestSuite {
// @SuppressWarnings("unchecked")
public static Test suite() throws Exception {
TestSuite suite = new TestSuite(AllTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(shuttleatwork.actions.ActionsTest.class);
suite.addTestSuite(shuttleatwork.system.JSonTest.class);
suite.addTestSuite(shuttleatwork.server.ScriptServiceTest.class);
suite.addTestSuite(shuttleatwork.model.FacadeTest.class);
suite.addTestSuite(gtfs.graph.GraphTest.class);
+ suite.addTestSuite(gtfs.graph.ArcTest.class);
+ suite.addTestSuite(gtfs.graph.TimeTest.class);
suite.addTestSuite(gtfs.reader.FeedReaderTest.class);
suite.addTestSuite(utils.csv.ReaderTest.class);
suite.addTestSuite(utils.geo.PositionTest.class);
suite.addTestSuite(utils.geo.AreaTest.class);
suite.addTestSuite(utils.geo.GeosetTest.class);
//$JUnit-END$
return suite;
}
}
| true | true | public static Test suite() throws Exception {
TestSuite suite = new TestSuite(AllTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(shuttleatwork.actions.ActionsTest.class);
suite.addTestSuite(shuttleatwork.system.JSonTest.class);
suite.addTestSuite(shuttleatwork.server.ScriptServiceTest.class);
suite.addTestSuite(shuttleatwork.model.FacadeTest.class);
suite.addTestSuite(gtfs.graph.GraphTest.class);
suite.addTestSuite(gtfs.reader.FeedReaderTest.class);
suite.addTestSuite(utils.csv.ReaderTest.class);
suite.addTestSuite(utils.geo.PositionTest.class);
suite.addTestSuite(utils.geo.AreaTest.class);
suite.addTestSuite(utils.geo.GeosetTest.class);
//$JUnit-END$
return suite;
}
| public static Test suite() throws Exception {
TestSuite suite = new TestSuite(AllTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(shuttleatwork.actions.ActionsTest.class);
suite.addTestSuite(shuttleatwork.system.JSonTest.class);
suite.addTestSuite(shuttleatwork.server.ScriptServiceTest.class);
suite.addTestSuite(shuttleatwork.model.FacadeTest.class);
suite.addTestSuite(gtfs.graph.GraphTest.class);
suite.addTestSuite(gtfs.graph.ArcTest.class);
suite.addTestSuite(gtfs.graph.TimeTest.class);
suite.addTestSuite(gtfs.reader.FeedReaderTest.class);
suite.addTestSuite(utils.csv.ReaderTest.class);
suite.addTestSuite(utils.geo.PositionTest.class);
suite.addTestSuite(utils.geo.AreaTest.class);
suite.addTestSuite(utils.geo.GeosetTest.class);
//$JUnit-END$
return suite;
}
|
diff --git a/Servidor/src/servidor/Main.java b/Servidor/src/servidor/Main.java
index ed06f07..e06ec6f 100644
--- a/Servidor/src/servidor/Main.java
+++ b/Servidor/src/servidor/Main.java
@@ -1,103 +1,103 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servidor;
import java.net.*;
import java.io.*;
import java.lang.*;
/**
*
* @author albertogg
*/
public class Main {
/**
* @param args the command line arguments
*/
private int port = 5432;
private ServerSocket server;
private boolean boleana = true;
// Constructor.
public Main() {
try {
server = new ServerSocket(port);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// Metodo encargado de escuchar aceptando las conexiones entrantes,
// provenientes de los agentes.
public void conectorServidor() {
System.out.println("Encendido y escuchando... ");
while (boleana) {
try {
Socket s1 = server.accept();
new ManejadorDeConexion(s1);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
Main nuevaConn = new Main();
nuevaConn.conectorServidor();
}
}
// Implementa de la clase Runnable para utilizar hilos
// Maneja las conexiones entrantes en base a hilos.
class ManejadorDeConexion implements Runnable {
private Socket socket;
// Constructor, Inicializamos el hilo dentro de el.
public ManejadorDeConexion(Socket socket) {
this.socket = socket;
Thread hilo = new Thread(this);
hilo.start();
}
@Override
public void run() {
try {
// Aqui ira el codigo con un switch/case para ejecutar una accion.
// accion de guardar, leer, escribir, dependiendo del mensaje
- // que se reciva.
+ // que se reciba.
// Recibimos un mensaje enviado por la red.
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
String mensaje = (String) ois.readObject();
System.out.println("Mensaje Recibido: " + mensaje);
// Leemos un mensaje enviado desde el agente.
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject("Te conectaste al Servidor.");
// Cerramos sockets.
ois.close();
oos.close();
socket.close();
System.out.println("Escuchando.. ");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| true | true | public void run() {
try {
// Aqui ira el codigo con un switch/case para ejecutar una accion.
// accion de guardar, leer, escribir, dependiendo del mensaje
// que se reciva.
// Recibimos un mensaje enviado por la red.
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
String mensaje = (String) ois.readObject();
System.out.println("Mensaje Recibido: " + mensaje);
// Leemos un mensaje enviado desde el agente.
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject("Te conectaste al Servidor.");
// Cerramos sockets.
ois.close();
oos.close();
socket.close();
System.out.println("Escuchando.. ");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
| public void run() {
try {
// Aqui ira el codigo con un switch/case para ejecutar una accion.
// accion de guardar, leer, escribir, dependiendo del mensaje
// que se reciba.
// Recibimos un mensaje enviado por la red.
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
String mensaje = (String) ois.readObject();
System.out.println("Mensaje Recibido: " + mensaje);
// Leemos un mensaje enviado desde el agente.
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject("Te conectaste al Servidor.");
// Cerramos sockets.
ois.close();
oos.close();
socket.close();
System.out.println("Escuchando.. ");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
|
diff --git a/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/VerifyMojo.java b/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/VerifyMojo.java
index 1412202ce..cc95d9149 100644
--- a/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/VerifyMojo.java
+++ b/xwiki-commons-tools/xwiki-commons-tool-xar/xwiki-commons-tool-xar-plugin/src/main/java/org/xwiki/tool/xar/VerifyMojo.java
@@ -1,133 +1,133 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.tool.xar;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* Perform various verifications of the XAR files in this project. Namely:
* <ul>
* <li>ensure that pages all have a parent (except for Main.WebHome)</li>
* <li>ensure that the author/contentAuthor/creator is {@code xwiki:XWiki.Admin}</li>
* <li>ensure that the version is {@code 1.1}</li>
* </ul>
*
* @version $Id$
* @goal verify
* @phase verify
* @requiresProject
* @requiresDependencyResolution compile
* @threadSafe
*/
public class VerifyMojo extends AbstractVerifyMojo
{
/**
* Disables the plugin execution.
*
* @parameter expression="${xar.verify.skip}" default-value="false"
* @since 4.3M1
*/
private boolean skip;
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
if (this.skip) {
return;
}
// Only format XAR modules or when forced
if (!getProject().getPackaging().equals("xar") && !this.force) {
getLog().info("Not a XAR module, skipping validity check...");
return;
}
getLog().info("Checking validity of XAR XML files...");
boolean hasErrors = false;
for (File file : getXARXMLFiles()) {
String parentName = file.getParentFile().getName();
XWikiDocument xdoc = getDocFromXML(file);
List<String> errors = new ArrayList<String>();
// Verification 1: Verify Encoding is UTF8
if (!xdoc.getEncoding().equals("UTF-8")) {
errors.add(String.format("Encoding must be [UTF-8] but was [%s]", xdoc.getEncoding()));
}
// Verification 2: Verify authors
verifyAuthor(errors, xdoc.getAuthor(), String.format("Author must be [%s] but was [%s]",
AUTHOR, xdoc.getAuthor()));
verifyAuthor(errors, xdoc.getContentAuthor(),
String.format("Content Author must be [%s] but was [%s]",
AUTHOR, xdoc.getContentAuthor()));
verifyAuthor(errors, xdoc.getCreator(), String.format("Creator must be [%s] but was [%s]",
AUTHOR, xdoc.getCreator()));
// Verification 3: Check for orphans, except for Main.WebHome since it's the topmost document
if (StringUtils.isEmpty(xdoc.getParent())
&& !(xdoc.getSpace().equals("Main") && xdoc.getName().equals("WebHome")))
{
errors.add("Parent must not be empty");
}
// Verification 4: Check for version
if (!xdoc.getVersion().equals(VERSION)) {
errors.add(String.format("Version must be [%s] but was [%s]", VERSION, xdoc.getVersion()));
}
// Verification 5: Check for empty comment
- if (xdoc.getComment() != null && xdoc.getComment().length() != 0) {
+ if (!StringUtils.isEmpty(xdoc.getComment())) {
errors.add(String.format("Comment must be empty but was [%s]", xdoc.getComment()));
}
// Verification 6: Check for minor edit is always "false"
if (!xdoc.getMinorEdit().equals("false")) {
errors.add(String.format("Minor edit must always be [false] but was [%s]", xdoc.getMinorEdit()));
}
// Verification 7: Check that default language is empty
- if (xdoc.getDefaultLanguage().length() != 0) {
+ if (!StringUtils.isEmpty(xdoc.getDefaultLanguage())) {
errors.add(String.format("Default Language must be empty but was [%s]", xdoc.getDefaultLanguage()));
}
if (errors.isEmpty()) {
getLog().info(String.format(" Verifying [%s/%s]... ok", parentName, file.getName()));
} else {
getLog().info(String.format(" Verifying [%s/%s]... errors", parentName, file.getName()));
for (String error : errors) {
getLog().info(String.format(" - %s", error));
}
hasErrors = true;
}
}
if (hasErrors) {
throw new MojoFailureException("There are errors in the XAR XML files!");
}
}
private void verifyAuthor(List<String> errors, String author, String message)
{
if (!author.equals(AUTHOR)) {
errors.add(message);
}
}
}
| false | true | public void execute() throws MojoExecutionException, MojoFailureException
{
if (this.skip) {
return;
}
// Only format XAR modules or when forced
if (!getProject().getPackaging().equals("xar") && !this.force) {
getLog().info("Not a XAR module, skipping validity check...");
return;
}
getLog().info("Checking validity of XAR XML files...");
boolean hasErrors = false;
for (File file : getXARXMLFiles()) {
String parentName = file.getParentFile().getName();
XWikiDocument xdoc = getDocFromXML(file);
List<String> errors = new ArrayList<String>();
// Verification 1: Verify Encoding is UTF8
if (!xdoc.getEncoding().equals("UTF-8")) {
errors.add(String.format("Encoding must be [UTF-8] but was [%s]", xdoc.getEncoding()));
}
// Verification 2: Verify authors
verifyAuthor(errors, xdoc.getAuthor(), String.format("Author must be [%s] but was [%s]",
AUTHOR, xdoc.getAuthor()));
verifyAuthor(errors, xdoc.getContentAuthor(),
String.format("Content Author must be [%s] but was [%s]",
AUTHOR, xdoc.getContentAuthor()));
verifyAuthor(errors, xdoc.getCreator(), String.format("Creator must be [%s] but was [%s]",
AUTHOR, xdoc.getCreator()));
// Verification 3: Check for orphans, except for Main.WebHome since it's the topmost document
if (StringUtils.isEmpty(xdoc.getParent())
&& !(xdoc.getSpace().equals("Main") && xdoc.getName().equals("WebHome")))
{
errors.add("Parent must not be empty");
}
// Verification 4: Check for version
if (!xdoc.getVersion().equals(VERSION)) {
errors.add(String.format("Version must be [%s] but was [%s]", VERSION, xdoc.getVersion()));
}
// Verification 5: Check for empty comment
if (xdoc.getComment() != null && xdoc.getComment().length() != 0) {
errors.add(String.format("Comment must be empty but was [%s]", xdoc.getComment()));
}
// Verification 6: Check for minor edit is always "false"
if (!xdoc.getMinorEdit().equals("false")) {
errors.add(String.format("Minor edit must always be [false] but was [%s]", xdoc.getMinorEdit()));
}
// Verification 7: Check that default language is empty
if (xdoc.getDefaultLanguage().length() != 0) {
errors.add(String.format("Default Language must be empty but was [%s]", xdoc.getDefaultLanguage()));
}
if (errors.isEmpty()) {
getLog().info(String.format(" Verifying [%s/%s]... ok", parentName, file.getName()));
} else {
getLog().info(String.format(" Verifying [%s/%s]... errors", parentName, file.getName()));
for (String error : errors) {
getLog().info(String.format(" - %s", error));
}
hasErrors = true;
}
}
if (hasErrors) {
throw new MojoFailureException("There are errors in the XAR XML files!");
}
}
| public void execute() throws MojoExecutionException, MojoFailureException
{
if (this.skip) {
return;
}
// Only format XAR modules or when forced
if (!getProject().getPackaging().equals("xar") && !this.force) {
getLog().info("Not a XAR module, skipping validity check...");
return;
}
getLog().info("Checking validity of XAR XML files...");
boolean hasErrors = false;
for (File file : getXARXMLFiles()) {
String parentName = file.getParentFile().getName();
XWikiDocument xdoc = getDocFromXML(file);
List<String> errors = new ArrayList<String>();
// Verification 1: Verify Encoding is UTF8
if (!xdoc.getEncoding().equals("UTF-8")) {
errors.add(String.format("Encoding must be [UTF-8] but was [%s]", xdoc.getEncoding()));
}
// Verification 2: Verify authors
verifyAuthor(errors, xdoc.getAuthor(), String.format("Author must be [%s] but was [%s]",
AUTHOR, xdoc.getAuthor()));
verifyAuthor(errors, xdoc.getContentAuthor(),
String.format("Content Author must be [%s] but was [%s]",
AUTHOR, xdoc.getContentAuthor()));
verifyAuthor(errors, xdoc.getCreator(), String.format("Creator must be [%s] but was [%s]",
AUTHOR, xdoc.getCreator()));
// Verification 3: Check for orphans, except for Main.WebHome since it's the topmost document
if (StringUtils.isEmpty(xdoc.getParent())
&& !(xdoc.getSpace().equals("Main") && xdoc.getName().equals("WebHome")))
{
errors.add("Parent must not be empty");
}
// Verification 4: Check for version
if (!xdoc.getVersion().equals(VERSION)) {
errors.add(String.format("Version must be [%s] but was [%s]", VERSION, xdoc.getVersion()));
}
// Verification 5: Check for empty comment
if (!StringUtils.isEmpty(xdoc.getComment())) {
errors.add(String.format("Comment must be empty but was [%s]", xdoc.getComment()));
}
// Verification 6: Check for minor edit is always "false"
if (!xdoc.getMinorEdit().equals("false")) {
errors.add(String.format("Minor edit must always be [false] but was [%s]", xdoc.getMinorEdit()));
}
// Verification 7: Check that default language is empty
if (!StringUtils.isEmpty(xdoc.getDefaultLanguage())) {
errors.add(String.format("Default Language must be empty but was [%s]", xdoc.getDefaultLanguage()));
}
if (errors.isEmpty()) {
getLog().info(String.format(" Verifying [%s/%s]... ok", parentName, file.getName()));
} else {
getLog().info(String.format(" Verifying [%s/%s]... errors", parentName, file.getName()));
for (String error : errors) {
getLog().info(String.format(" - %s", error));
}
hasErrors = true;
}
}
if (hasErrors) {
throw new MojoFailureException("There are errors in the XAR XML files!");
}
}
|
diff --git a/src/amrcci/SpawnTeleport.java b/src/amrcci/SpawnTeleport.java
index fd04328..a29d285 100644
--- a/src/amrcci/SpawnTeleport.java
+++ b/src/amrcci/SpawnTeleport.java
@@ -1,58 +1,58 @@
package amrcci;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.events.AuthMeTeleportEvent;
public class SpawnTeleport implements Listener {
private Main main;
private File configfile;
public SpawnTeleport(Main main)
{
this.main = main;
this.configfile = new File(main.getDataFolder(),"spawntpconfig.yml");
}
public void loadConfig()
{
FileConfiguration config = YamlConfiguration.loadConfiguration(configfile);
worlds = config.getStringList("worlds");
config.set("worlds", worlds);
try {config.save(configfile);} catch (IOException e) {}
}
private List<String> worlds = new ArrayList<String>();
@EventHandler
public void onPlayerLoginAfterTeleport(AuthMeTeleportEvent e)
{
final Player player = e.getPlayer();
- if (worlds.contains(player.getWorld().getName()) && !player.hasPermission("amrcci.ignoretp"))
+ if (worlds.contains(e.getTo().getWorld().getName()) && !player.hasPermission("amrcci.ignoretp"))
{
final Location spawn = AuthMe.getInstance().essentialsSpawn;
if (spawn != null)
{
Bukkit.getScheduler().scheduleSyncDelayedTask(main, new Runnable()
{
public void run()
{
player.teleport(spawn);
}
});
}
}
}
}
| true | true | public void onPlayerLoginAfterTeleport(AuthMeTeleportEvent e)
{
final Player player = e.getPlayer();
if (worlds.contains(player.getWorld().getName()) && !player.hasPermission("amrcci.ignoretp"))
{
final Location spawn = AuthMe.getInstance().essentialsSpawn;
if (spawn != null)
{
Bukkit.getScheduler().scheduleSyncDelayedTask(main, new Runnable()
{
public void run()
{
player.teleport(spawn);
}
});
}
}
}
| public void onPlayerLoginAfterTeleport(AuthMeTeleportEvent e)
{
final Player player = e.getPlayer();
if (worlds.contains(e.getTo().getWorld().getName()) && !player.hasPermission("amrcci.ignoretp"))
{
final Location spawn = AuthMe.getInstance().essentialsSpawn;
if (spawn != null)
{
Bukkit.getScheduler().scheduleSyncDelayedTask(main, new Runnable()
{
public void run()
{
player.teleport(spawn);
}
});
}
}
}
|
diff --git a/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java b/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java
index 77957b00..2e2431fe 100644
--- a/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java
+++ b/motech-server-omod/src/test/java/org/motechproject/server/omod/tasks/MessageProgramUpdateTaskTest.java
@@ -1,246 +1,248 @@
package org.motechproject.server.omod.tasks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.motechproject.server.model.Message;
import org.motechproject.server.model.MessageDefinition;
import org.motechproject.server.model.MessageProgramEnrollment;
import org.motechproject.server.model.MessageStatus;
import org.motechproject.server.model.MessageType;
import org.motechproject.server.model.ScheduledMessage;
import org.motechproject.server.omod.MotechModuleActivator;
import org.motechproject.server.omod.MotechService;
import org.motechproject.server.svc.RegistrarBean;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.ws.ContactNumberType;
import org.motechproject.ws.DayOfWeek;
import org.motechproject.ws.Gender;
import org.motechproject.ws.HowLearned;
import org.motechproject.ws.InterestReason;
import org.motechproject.ws.MediaType;
import org.motechproject.ws.RegistrantType;
import org.motechproject.ws.RegistrationMode;
import org.openmrs.Concept;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.scheduler.TaskDefinition;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.openmrs.test.SkipBaseSetup;
/**
* BaseModuleContextSensitiveTest loads both the OpenMRS core and module spring
* contexts and hibernate mappings, providing the OpenMRS Context for both
* OpenMRS core and module services.
*/
public class MessageProgramUpdateTaskTest extends
BaseModuleContextSensitiveTest {
static MotechModuleActivator activator;
Log log = LogFactory.getLog(MessageProgramUpdateTaskTest.class);
@BeforeClass
public static void setUpClass() throws Exception {
activator = new MotechModuleActivator(false);
}
@AfterClass
public static void tearDownClass() throws Exception {
activator = null;
}
@Before
public void setup() throws Exception {
// Perform same steps as BaseSetup (initializeInMemoryDatabase,
// executeDataSet, authenticate), except load custom XML dataset
initializeInMemoryDatabase();
// Created from org.openmrs.test.CreateInitialDataSet
// without line for "concept_synonym" table (not exist)
// using 1.4.4-createdb-from-scratch-with-demo-data.sql
// Removed all empty short_name="" from concepts
// Added missing description to relationship_type
// Removed all patients and related patient/person info (id 2-500)
executeDataSet("initial-openmrs-dataset.xml");
authenticate();
activator.startup();
}
@After
public void tearDown() throws Exception {
activator.shutdown();
}
@Test
@SkipBaseSetup
public void testMessageProgramUpdate() throws InterruptedException {
MessageProgramUpdateTask task = new MessageProgramUpdateTask();
TaskDefinition definition = new TaskDefinition();
definition.setProperty(MotechConstants.TASK_PROPERTY_BATCH_SIZE, "10");
task.initialize(definition);
Integer patientId = null;
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean regService = Context.getService(MotechService.class)
.getRegistrarBean();
Date date = new Date();
Integer motechId = 1234665;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -30);
Date birthdate = calendar.getTime();
regService.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motechId, RegistrantType.OTHER, "firstName", "middleName",
"lastName", "prefName", birthdate, false, Gender.MALE,
true, "nhis", null, null, null, "Address", "1111111111",
null, null, true, true, ContactNumberType.PERSONAL,
MediaType.VOICE, "language", DayOfWeek.MONDAY, date,
InterestReason.KNOW_MORE_PREGNANCY_CHILDBIRTH,
HowLearned.FRIEND, 5);
List<Patient> matchingPatients = regService.getPatients(
"firstName", "lastName", "prefName", birthdate, null,
"1111111111", "nhis", motechId.toString());
assertEquals(1, matchingPatients.size());
Patient patient = matchingPatients.get(0);
patientId = patient.getPatientId();
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patientId, null, null, null, null, null);
assertEquals(1, enrollments.size());
assertEquals("Weekly Info Pregnancy Message Program", enrollments
.get(0).getProgram());
assertNotNull("Obs is not set on enrollment", enrollments.get(0)
.getObsId());
// Add needed message definitions for pregnancy program
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.5", 18L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.6", 19L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.7", 20L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.8", 21L,
MessageType.INFORMATIONAL));
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
Context.authenticate("admin", "test");
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(1, scheduledMessages.size());
// Make sure message is scheduled with proper message
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
assertEquals("pregnancy.week.5", scheduledMessage.getMessage()
.getMessageKey());
Concept refDate = Context.getConceptService().getConcept(
MotechConstants.CONCEPT_ENROLLMENT_REFERENCE_DATE);
Patient patient = Context.getPatientService().getPatient(patientId);
assertNotNull("Patient does not exist with id", patient);
List<Obs> matchingObs = Context.getObsService()
.getObservationsByPersonAndConcept(patient, refDate);
assertEquals(1, matchingObs.size());
// Change reference date to 2 weeks previous
Obs refDateObs = matchingObs.get(0);
Integer originalObsId = refDateObs.getObsId();
Date date = refDateObs.getValueDatetime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int slush = 4;
calendar.add(Calendar.DATE, -(2 * 7 + slush));
refDateObs.setValueDatetime(calendar.getTime());
refDateObs = Context.getObsService().saveObs(refDateObs,
"New date in future");
assertTrue("New reference date obs id is same as previous",
!originalObsId.equals(refDateObs.getObsId()));
// Change obs referenced by enrollment to new obs
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patient.getPatientId(), null, null, null, null, null);
assertEquals(1, enrollments.size());
MessageProgramEnrollment infoEnrollment = enrollments.get(0);
infoEnrollment.setObsId(refDateObs.getObsId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(infoEnrollment);
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(2, scheduledMessages.size());
// Make sure new message is scheduled and previous message is
// cancelled
for (ScheduledMessage scheduledMessage : scheduledMessages) {
assertEquals(1, scheduledMessage.getMessageAttempts().size());
Message message = scheduledMessage.getMessageAttempts().get(0);
if (scheduledMessage.getMessage().getMessageKey().equals(
"pregnancy.week.5")) {
assertEquals(MessageStatus.CANCELLED, message
.getAttemptStatus());
} else if (scheduledMessage.getMessage().getMessageKey()
- .equals("pregnancy.week.8")) {
+ .equals("pregnancy.week.7")
+ || scheduledMessage.getMessage().getMessageKey()
+ .equals("pregnancy.week.8")) {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
} else {
fail("Scheduled message has wrong message key");
}
}
} finally {
Context.closeSession();
}
}
}
| true | true | public void testMessageProgramUpdate() throws InterruptedException {
MessageProgramUpdateTask task = new MessageProgramUpdateTask();
TaskDefinition definition = new TaskDefinition();
definition.setProperty(MotechConstants.TASK_PROPERTY_BATCH_SIZE, "10");
task.initialize(definition);
Integer patientId = null;
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean regService = Context.getService(MotechService.class)
.getRegistrarBean();
Date date = new Date();
Integer motechId = 1234665;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -30);
Date birthdate = calendar.getTime();
regService.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motechId, RegistrantType.OTHER, "firstName", "middleName",
"lastName", "prefName", birthdate, false, Gender.MALE,
true, "nhis", null, null, null, "Address", "1111111111",
null, null, true, true, ContactNumberType.PERSONAL,
MediaType.VOICE, "language", DayOfWeek.MONDAY, date,
InterestReason.KNOW_MORE_PREGNANCY_CHILDBIRTH,
HowLearned.FRIEND, 5);
List<Patient> matchingPatients = regService.getPatients(
"firstName", "lastName", "prefName", birthdate, null,
"1111111111", "nhis", motechId.toString());
assertEquals(1, matchingPatients.size());
Patient patient = matchingPatients.get(0);
patientId = patient.getPatientId();
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patientId, null, null, null, null, null);
assertEquals(1, enrollments.size());
assertEquals("Weekly Info Pregnancy Message Program", enrollments
.get(0).getProgram());
assertNotNull("Obs is not set on enrollment", enrollments.get(0)
.getObsId());
// Add needed message definitions for pregnancy program
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.5", 18L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.6", 19L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.7", 20L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.8", 21L,
MessageType.INFORMATIONAL));
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
Context.authenticate("admin", "test");
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(1, scheduledMessages.size());
// Make sure message is scheduled with proper message
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
assertEquals("pregnancy.week.5", scheduledMessage.getMessage()
.getMessageKey());
Concept refDate = Context.getConceptService().getConcept(
MotechConstants.CONCEPT_ENROLLMENT_REFERENCE_DATE);
Patient patient = Context.getPatientService().getPatient(patientId);
assertNotNull("Patient does not exist with id", patient);
List<Obs> matchingObs = Context.getObsService()
.getObservationsByPersonAndConcept(patient, refDate);
assertEquals(1, matchingObs.size());
// Change reference date to 2 weeks previous
Obs refDateObs = matchingObs.get(0);
Integer originalObsId = refDateObs.getObsId();
Date date = refDateObs.getValueDatetime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int slush = 4;
calendar.add(Calendar.DATE, -(2 * 7 + slush));
refDateObs.setValueDatetime(calendar.getTime());
refDateObs = Context.getObsService().saveObs(refDateObs,
"New date in future");
assertTrue("New reference date obs id is same as previous",
!originalObsId.equals(refDateObs.getObsId()));
// Change obs referenced by enrollment to new obs
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patient.getPatientId(), null, null, null, null, null);
assertEquals(1, enrollments.size());
MessageProgramEnrollment infoEnrollment = enrollments.get(0);
infoEnrollment.setObsId(refDateObs.getObsId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(infoEnrollment);
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(2, scheduledMessages.size());
// Make sure new message is scheduled and previous message is
// cancelled
for (ScheduledMessage scheduledMessage : scheduledMessages) {
assertEquals(1, scheduledMessage.getMessageAttempts().size());
Message message = scheduledMessage.getMessageAttempts().get(0);
if (scheduledMessage.getMessage().getMessageKey().equals(
"pregnancy.week.5")) {
assertEquals(MessageStatus.CANCELLED, message
.getAttemptStatus());
} else if (scheduledMessage.getMessage().getMessageKey()
.equals("pregnancy.week.8")) {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
} else {
fail("Scheduled message has wrong message key");
}
}
} finally {
Context.closeSession();
}
}
| public void testMessageProgramUpdate() throws InterruptedException {
MessageProgramUpdateTask task = new MessageProgramUpdateTask();
TaskDefinition definition = new TaskDefinition();
definition.setProperty(MotechConstants.TASK_PROPERTY_BATCH_SIZE, "10");
task.initialize(definition);
Integer patientId = null;
try {
Context.openSession();
Context.authenticate("admin", "test");
RegistrarBean regService = Context.getService(MotechService.class)
.getRegistrarBean();
Date date = new Date();
Integer motechId = 1234665;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -30);
Date birthdate = calendar.getTime();
regService.registerPatient(RegistrationMode.USE_PREPRINTED_ID,
motechId, RegistrantType.OTHER, "firstName", "middleName",
"lastName", "prefName", birthdate, false, Gender.MALE,
true, "nhis", null, null, null, "Address", "1111111111",
null, null, true, true, ContactNumberType.PERSONAL,
MediaType.VOICE, "language", DayOfWeek.MONDAY, date,
InterestReason.KNOW_MORE_PREGNANCY_CHILDBIRTH,
HowLearned.FRIEND, 5);
List<Patient> matchingPatients = regService.getPatients(
"firstName", "lastName", "prefName", birthdate, null,
"1111111111", "nhis", motechId.toString());
assertEquals(1, matchingPatients.size());
Patient patient = matchingPatients.get(0);
patientId = patient.getPatientId();
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patientId, null, null, null, null, null);
assertEquals(1, enrollments.size());
assertEquals("Weekly Info Pregnancy Message Program", enrollments
.get(0).getProgram());
assertNotNull("Obs is not set on enrollment", enrollments.get(0)
.getObsId());
// Add needed message definitions for pregnancy program
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.5", 18L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.6", 19L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.7", 20L,
MessageType.INFORMATIONAL));
Context.getService(MotechService.class).saveMessageDefinition(
new MessageDefinition("pregnancy.week.8", 21L,
MessageType.INFORMATIONAL));
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
Context.authenticate("admin", "test");
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(1, scheduledMessages.size());
// Make sure message is scheduled with proper message
ScheduledMessage scheduledMessage = scheduledMessages.get(0);
assertEquals("pregnancy.week.5", scheduledMessage.getMessage()
.getMessageKey());
Concept refDate = Context.getConceptService().getConcept(
MotechConstants.CONCEPT_ENROLLMENT_REFERENCE_DATE);
Patient patient = Context.getPatientService().getPatient(patientId);
assertNotNull("Patient does not exist with id", patient);
List<Obs> matchingObs = Context.getObsService()
.getObservationsByPersonAndConcept(patient, refDate);
assertEquals(1, matchingObs.size());
// Change reference date to 2 weeks previous
Obs refDateObs = matchingObs.get(0);
Integer originalObsId = refDateObs.getObsId();
Date date = refDateObs.getValueDatetime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int slush = 4;
calendar.add(Calendar.DATE, -(2 * 7 + slush));
refDateObs.setValueDatetime(calendar.getTime());
refDateObs = Context.getObsService().saveObs(refDateObs,
"New date in future");
assertTrue("New reference date obs id is same as previous",
!originalObsId.equals(refDateObs.getObsId()));
// Change obs referenced by enrollment to new obs
List<MessageProgramEnrollment> enrollments = Context.getService(
MotechService.class).getActiveMessageProgramEnrollments(
patient.getPatientId(), null, null, null, null, null);
assertEquals(1, enrollments.size());
MessageProgramEnrollment infoEnrollment = enrollments.get(0);
infoEnrollment.setObsId(refDateObs.getObsId());
Context.getService(MotechService.class)
.saveMessageProgramEnrollment(infoEnrollment);
} finally {
Context.closeSession();
}
task.execute();
try {
Context.openSession();
List<ScheduledMessage> scheduledMessages = Context.getService(
MotechService.class).getAllScheduledMessages();
assertEquals(2, scheduledMessages.size());
// Make sure new message is scheduled and previous message is
// cancelled
for (ScheduledMessage scheduledMessage : scheduledMessages) {
assertEquals(1, scheduledMessage.getMessageAttempts().size());
Message message = scheduledMessage.getMessageAttempts().get(0);
if (scheduledMessage.getMessage().getMessageKey().equals(
"pregnancy.week.5")) {
assertEquals(MessageStatus.CANCELLED, message
.getAttemptStatus());
} else if (scheduledMessage.getMessage().getMessageKey()
.equals("pregnancy.week.7")
|| scheduledMessage.getMessage().getMessageKey()
.equals("pregnancy.week.8")) {
assertEquals(MessageStatus.SHOULD_ATTEMPT, message
.getAttemptStatus());
} else {
fail("Scheduled message has wrong message key");
}
}
} finally {
Context.closeSession();
}
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/composites/StringComposite.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/composites/StringComposite.java
index a3e1836bc..2785841a9 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/codegen/composites/StringComposite.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/composites/StringComposite.java
@@ -1,267 +1,267 @@
package org.emftext.sdk.codegen.composites;
import java.util.ArrayList;
import java.util.List;
/**
* A StringComposite can be used to compose text fragments. In contrast to
* a StringBuilder or StringBuffer, this class can enable and disable text
* fragments. This is useful when text is composed, but later unnecessary
* parts need to be removed.
*
* This class is used by the code generators to insert variable declarations
* only if they are referenced.
*/
public class StringComposite {
/**
* A Node is the atomic part of a tree.
*/
public interface Node {
public Tree getParent();
}
/**
* A CompositeNode is part of a tree and contains exactly
* one StringComponent.
*/
public class ComponentNode implements Node {
private StringComponent component;
private Tree parent;
public ComponentNode(Tree parent, StringComponent component) {
this.parent = parent;
this.component = component;
}
public StringComponent getComponent() {
return component;
}
public Tree getParent() {
return parent;
}
}
/**
* A Tree is a container for Nodes. Since trees are
* nodes as well, they can contain further trees.
*/
public class Tree implements Node {
private List<Node> children = new ArrayList<Node>();
private Tree parent;
public Tree(Tree parent) {
this.parent = parent;
if (parent != null) {
parent.addChildNode(this);
}
}
public List<Node> getChildNodes() {
return children;
}
public void addChildNode(Node node) {
children.add(node);
}
public Tree getParent() {
return parent;
}
}
public static final String LINE_BREAK = "\n";
private List<StringComponent> components = new ArrayList<StringComponent>();
private List<String> lineBreakers = new ArrayList<String>();
private List<String> indentationStarters = new ArrayList<String>();
private List<String> indentationStoppers = new ArrayList<String>();
private boolean enabled;
public StringComposite() {
this(true);
}
public StringComposite(boolean enabled) {
super();
this.enabled = enabled;
}
public void addIndentationStarter(String starter) {
indentationStarters.add(starter);
}
public void addIndentationStopper(String stopper) {
indentationStoppers.add(stopper);
}
public void addLineBreaker(String lineBreaker) {
lineBreakers.add(lineBreaker);
}
public StringComposite addLineBreak() {
add(LINE_BREAK);
return this;
}
public StringComposite add(String text) {
StringComponent component = new StringComponent(text, null);
add(component);
return this;
}
public StringComposite add(StringComponent component) {
components.add(component);
return this;
}
public void add(StringComposite other) {
components.addAll(other.components);
}
@Override
public String toString() {
return toString(0, true);
}
public String toString(int tabs, boolean doLineBreaks) {
StringBuilder builder = new StringBuilder();
enableComponents();
// then add enabled components to the builder
for (Component component : components) {
if (isIndendationStopper(component)) {
tabs--;
}
if (component.isEnabled()) {
String text = component.toString(tabs);
builder.append(text);
if (doLineBreaks && isLineBreaker(component)) {
builder.append(LINE_BREAK);
}
}
if (isIndendationStarter(component)) {
tabs++;
}
}
return builder.toString();
}
private void enableComponents() {
List<ComponentNode> disabledComponents = new ArrayList<ComponentNode>();
- // TODO mseifert: this tree should be created when the components are added and replace
+ // TODO MINOR, PERFORMANCE: this tree should be created when the components are added and replace
// the field 'components'.
// find the scoping depth for the disabled components
Tree subTree = new Tree(null);
for (int i = 0; i < components.size(); i++) {
StringComponent component = components.get(i);
final ComponentNode node = new ComponentNode(subTree, component);
final boolean isStarter = isIndendationStarter(component);
final boolean isStopper = isIndendationStopper(component);
final Tree parent = subTree.getParent();
if (isStarter) {
if (isStopper) {
if (parent != null) {
subTree = parent;
}
subTree.addChildNode(node);
subTree = new Tree(subTree);
} else {
subTree.addChildNode(node);
subTree = new Tree(subTree);
}
} else {
if (isStopper) {
if (parent != null) {
subTree = parent;
}
subTree.addChildNode(node);
} else {
subTree.addChildNode(node);
}
}
if (!component.isEnabled()) {
disabledComponents.add(node);
}
}
for (ComponentNode disabledComponent : disabledComponents) {
// deep search right siblings
List<Node> siblings = disabledComponent.getParent().getChildNodes();
boolean right = false;
for (Node sibling : siblings) {
if (sibling == disabledComponent) {
right = true;
continue;
}
if (!right) {
continue;
}
enable(disabledComponent.getComponent(), sibling);
}
}
}
private void enable(StringComponent component, Node node) {
if (node instanceof Tree) {
List<Node> children = ((Tree) node).getChildNodes();
for (Node child : children) {
enable(component, child);
}
} else {
StringComponent nodeComponent = ((ComponentNode) node).getComponent();
if (nodeComponent.isEnabled()) {
String text = nodeComponent.getText();
component.enable(text);
}
}
}
protected boolean isLineBreaker(Component component) {
for (String starter : lineBreakers) {
if (component.toString().endsWith(starter)) {
return true;
}
}
return false;
}
protected boolean isIndendationStarter(Component component) {
for (String starter : indentationStarters) {
if (component.toString().endsWith(starter)) {
return true;
}
}
return false;
}
protected boolean isIndendationStopper(Component component) {
for (String stopper : indentationStoppers) {
if (component.toString().startsWith(stopper)) {
return true;
}
}
return false;
}
public static String getTabText(int tabs) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tabs; i++) {
builder.append('\t');
}
return builder.toString();
}
public boolean isEnabled() {
return enabled;
}
}
| true | true | private void enableComponents() {
List<ComponentNode> disabledComponents = new ArrayList<ComponentNode>();
// TODO mseifert: this tree should be created when the components are added and replace
// the field 'components'.
// find the scoping depth for the disabled components
Tree subTree = new Tree(null);
for (int i = 0; i < components.size(); i++) {
StringComponent component = components.get(i);
final ComponentNode node = new ComponentNode(subTree, component);
final boolean isStarter = isIndendationStarter(component);
final boolean isStopper = isIndendationStopper(component);
final Tree parent = subTree.getParent();
if (isStarter) {
if (isStopper) {
if (parent != null) {
subTree = parent;
}
subTree.addChildNode(node);
subTree = new Tree(subTree);
} else {
subTree.addChildNode(node);
subTree = new Tree(subTree);
}
} else {
if (isStopper) {
if (parent != null) {
subTree = parent;
}
subTree.addChildNode(node);
} else {
subTree.addChildNode(node);
}
}
if (!component.isEnabled()) {
disabledComponents.add(node);
}
}
for (ComponentNode disabledComponent : disabledComponents) {
// deep search right siblings
List<Node> siblings = disabledComponent.getParent().getChildNodes();
boolean right = false;
for (Node sibling : siblings) {
if (sibling == disabledComponent) {
right = true;
continue;
}
if (!right) {
continue;
}
enable(disabledComponent.getComponent(), sibling);
}
}
}
| private void enableComponents() {
List<ComponentNode> disabledComponents = new ArrayList<ComponentNode>();
// TODO MINOR, PERFORMANCE: this tree should be created when the components are added and replace
// the field 'components'.
// find the scoping depth for the disabled components
Tree subTree = new Tree(null);
for (int i = 0; i < components.size(); i++) {
StringComponent component = components.get(i);
final ComponentNode node = new ComponentNode(subTree, component);
final boolean isStarter = isIndendationStarter(component);
final boolean isStopper = isIndendationStopper(component);
final Tree parent = subTree.getParent();
if (isStarter) {
if (isStopper) {
if (parent != null) {
subTree = parent;
}
subTree.addChildNode(node);
subTree = new Tree(subTree);
} else {
subTree.addChildNode(node);
subTree = new Tree(subTree);
}
} else {
if (isStopper) {
if (parent != null) {
subTree = parent;
}
subTree.addChildNode(node);
} else {
subTree.addChildNode(node);
}
}
if (!component.isEnabled()) {
disabledComponents.add(node);
}
}
for (ComponentNode disabledComponent : disabledComponents) {
// deep search right siblings
List<Node> siblings = disabledComponent.getParent().getChildNodes();
boolean right = false;
for (Node sibling : siblings) {
if (sibling == disabledComponent) {
right = true;
continue;
}
if (!right) {
continue;
}
enable(disabledComponent.getComponent(), sibling);
}
}
}
|
diff --git a/src/org/geworkbench/engine/ccm/DependencyManager.java b/src/org/geworkbench/engine/ccm/DependencyManager.java
index 36bf0887..5cff5e73 100644
--- a/src/org/geworkbench/engine/ccm/DependencyManager.java
+++ b/src/org/geworkbench/engine/ccm/DependencyManager.java
@@ -1,232 +1,233 @@
/**
*
*/
package org.geworkbench.engine.ccm;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.engine.ccm.CCMTableModel;
/**
*
* The utility to ask for user's confirmation for load/unload dependent
* components.
*
* @author zji
*
*/
public class DependencyManager {
private Log log = LogFactory.getLog(DependencyManager.class);
private CCMTableModel ccmTableModel = null;
// only one of these are used
private List<String> required = null;
private List<Integer> dependentPlugins = null;
private int selectedRow = -1;
static JTextPane textPane = new JTextPane();
static JScrollPane scrollPane = new JScrollPane();
static {
textPane.setEditable(false);
textPane.setFocusable(false);
}
static private enum ChangeFlag {
LOAD, UNLOAD
};
ChangeFlag changeFlag = null;
/**
* The constructor for checking dependent plugins for unloading case.
*
* @param ccmTableModel
* @param dependentPlugins
* @param selectedRow
*/
DependencyManager(final CCMTableModel ccmTableModel,
final List<Integer> dependentPlugins, final int selectedRow) {
changeFlag = ChangeFlag.UNLOAD;
this.ccmTableModel = ccmTableModel;
this.selectedRow = selectedRow;
this.dependentPlugins = dependentPlugins;
String unselectedPluginName = "Plugin is missing a Name descriptor";
if (selectedRow >= 0) {
unselectedPluginName = ccmTableModel.getPluginName(selectedRow);
}
String message = "The following is a list of plugins known to be\n";
message += "dependent on the plugin you have chosen to unload\n";
message += "(" + unselectedPluginName + "):\n\n";
for (int i = 0; i < dependentPlugins.size(); i++) {
Integer dependentRow = dependentPlugins.get(i);
int row = dependentRow.intValue();
String dependentName = ccmTableModel.getPluginName(row);
message += "* " + dependentName + "\n";
}
message += "\nIf you choose the \"Continue\" button below, \n";
message += "the listed plugins will be automatically be unselected\n";
message += "in your Component Configuration Manager window\n";
message += "and will be unloaded in the application along\n";
message += "with the plugin you unselected.\n";
textPane.setText(message);
scrollPane.setViewportView(textPane);
}
/**
* The constructor for checking required plugins for loading case.
*
* @param ccmTableModel
* @param required
* @param selectedRow
* @param related
*/
DependencyManager(final CCMTableModel ccmTableModel,
final List<String> required, final int selectedRow,
final List<String> related) {
changeFlag = ChangeFlag.LOAD;
this.ccmTableModel = ccmTableModel;
this.required = required;
this.selectedRow = selectedRow;
String pluginName = "Plugin is missing a Name";
if (selectedRow >= 0) {
pluginName = (String) ccmTableModel.getPluginName(selectedRow);
}
ArrayList<String> requireAndRelated = new ArrayList<String>();
/* Format Required Plugins */
for (int i = 0; i < required.size(); i++) {
String requiredClazz = required.get(i);
int requiredRow = ccmTableModel.getModelRowByClazz(requiredClazz);
String requiredName = "missing Class description";
if (requiredRow >= 0) {
requiredName = (String) ccmTableModel.getPluginName(
requiredRow);
}
String req = "";
req += requiredName;
req += " (required)";
requireAndRelated.add(req);
}
/* Format Related Plugins */
for (int i = 0; i < related.size(); i++) {
String relatedClazz = related.get(i);
int relatedRow = ccmTableModel.getModelRowByClazz(relatedClazz);
String relatedName = "missing Class description";
if (relatedRow >= 0) {
relatedName = (String) ccmTableModel.getPluginName(
relatedRow);
}
requireAndRelated.add(relatedName);
}
String message = "The following is a list of plugins known to be\n";
message += "compatible with the plugin you have chosen to load\n";
message += "(" + pluginName + "):\n\n";
for (int i = 0; i < requireAndRelated.size(); i++) {
message += "* " + requireAndRelated.get(i) + "\n";
}
message += "\nIf you choose the \"Continue\" button below, those\n";
message += "plugins marked as \"required\" will be automatically\n";
message += "selected in your Component Configuration Manager\n";
message += "window and will be uploaded in the application along\n";
- message += "with the plugin you selected.\n";
+ message += "with the plugin you selected. If \"Cancel\" is pushed,\n" +
+ "the plugin you chose will not be selected.";
textPane.setText(message);
scrollPane.setViewportView(textPane);
}
static private JOptionPane optionPane = new JOptionPane(scrollPane,
JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null,
new String[] { "Continue", "Cancel" });
private void updateDependent() {
// if is unload
for (int i = 0; i < dependentPlugins.size(); i++) {
Integer dependentRow = dependentPlugins.get(i);
int row = dependentRow.intValue();
ccmTableModel.unselectWithoutValiation(row);
}
}
private void updateRequired() {
for (int i = 0; i < this.required.size(); i++) {
String requiredClazz = this.required.get(i);
int requiredRow = ccmTableModel.getModelRowByClazz(requiredClazz);
if (requiredRow < 0) {
log.error("Missing Class in Plugin");
}
boolean successful = ccmTableModel.selectWithoutValiation(requiredRow);
/*
* If a license is not agreed to for a dependent component, then
* roll back all the selections for all components
*/
if (!successful) {
rollBack();
}
}
}
void checkDependency() {
// in case other component does not like this
Object oldSetting = UIManager.get("Button.defaultButtonFollowsFocus");
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
JDialog dialog = optionPane.createDialog(null,
"Dependency Checking Dialog");
dialog.setVisible(true);
Object obj = optionPane.getValue();
UIManager.put("Button.defaultButtonFollowsFocus", oldSetting); // restore
if (obj == null) {
rollBack();
return;
}
String selectedValue = (String) optionPane.getValue();
if (selectedValue.equals("Continue")) {
switch (changeFlag) {
case LOAD:
updateRequired();
break;
case UNLOAD:
updateDependent();
break;
default:
log.error("invalid flag independency manager");
}
return;
} else { // if not "Continue"
rollBack();
}
}
private void rollBack() {
if (selectedRow >= 0) {
ccmTableModel.switchSelected(selectedRow);
} else {
log.error("Missing Class in Plugin");
}
}
}
| true | true | DependencyManager(final CCMTableModel ccmTableModel,
final List<String> required, final int selectedRow,
final List<String> related) {
changeFlag = ChangeFlag.LOAD;
this.ccmTableModel = ccmTableModel;
this.required = required;
this.selectedRow = selectedRow;
String pluginName = "Plugin is missing a Name";
if (selectedRow >= 0) {
pluginName = (String) ccmTableModel.getPluginName(selectedRow);
}
ArrayList<String> requireAndRelated = new ArrayList<String>();
/* Format Required Plugins */
for (int i = 0; i < required.size(); i++) {
String requiredClazz = required.get(i);
int requiredRow = ccmTableModel.getModelRowByClazz(requiredClazz);
String requiredName = "missing Class description";
if (requiredRow >= 0) {
requiredName = (String) ccmTableModel.getPluginName(
requiredRow);
}
String req = "";
req += requiredName;
req += " (required)";
requireAndRelated.add(req);
}
/* Format Related Plugins */
for (int i = 0; i < related.size(); i++) {
String relatedClazz = related.get(i);
int relatedRow = ccmTableModel.getModelRowByClazz(relatedClazz);
String relatedName = "missing Class description";
if (relatedRow >= 0) {
relatedName = (String) ccmTableModel.getPluginName(
relatedRow);
}
requireAndRelated.add(relatedName);
}
String message = "The following is a list of plugins known to be\n";
message += "compatible with the plugin you have chosen to load\n";
message += "(" + pluginName + "):\n\n";
for (int i = 0; i < requireAndRelated.size(); i++) {
message += "* " + requireAndRelated.get(i) + "\n";
}
message += "\nIf you choose the \"Continue\" button below, those\n";
message += "plugins marked as \"required\" will be automatically\n";
message += "selected in your Component Configuration Manager\n";
message += "window and will be uploaded in the application along\n";
message += "with the plugin you selected.\n";
textPane.setText(message);
scrollPane.setViewportView(textPane);
}
| DependencyManager(final CCMTableModel ccmTableModel,
final List<String> required, final int selectedRow,
final List<String> related) {
changeFlag = ChangeFlag.LOAD;
this.ccmTableModel = ccmTableModel;
this.required = required;
this.selectedRow = selectedRow;
String pluginName = "Plugin is missing a Name";
if (selectedRow >= 0) {
pluginName = (String) ccmTableModel.getPluginName(selectedRow);
}
ArrayList<String> requireAndRelated = new ArrayList<String>();
/* Format Required Plugins */
for (int i = 0; i < required.size(); i++) {
String requiredClazz = required.get(i);
int requiredRow = ccmTableModel.getModelRowByClazz(requiredClazz);
String requiredName = "missing Class description";
if (requiredRow >= 0) {
requiredName = (String) ccmTableModel.getPluginName(
requiredRow);
}
String req = "";
req += requiredName;
req += " (required)";
requireAndRelated.add(req);
}
/* Format Related Plugins */
for (int i = 0; i < related.size(); i++) {
String relatedClazz = related.get(i);
int relatedRow = ccmTableModel.getModelRowByClazz(relatedClazz);
String relatedName = "missing Class description";
if (relatedRow >= 0) {
relatedName = (String) ccmTableModel.getPluginName(
relatedRow);
}
requireAndRelated.add(relatedName);
}
String message = "The following is a list of plugins known to be\n";
message += "compatible with the plugin you have chosen to load\n";
message += "(" + pluginName + "):\n\n";
for (int i = 0; i < requireAndRelated.size(); i++) {
message += "* " + requireAndRelated.get(i) + "\n";
}
message += "\nIf you choose the \"Continue\" button below, those\n";
message += "plugins marked as \"required\" will be automatically\n";
message += "selected in your Component Configuration Manager\n";
message += "window and will be uploaded in the application along\n";
message += "with the plugin you selected. If \"Cancel\" is pushed,\n" +
"the plugin you chose will not be selected.";
textPane.setText(message);
scrollPane.setViewportView(textPane);
}
|
diff --git a/org.dadacoalition.yedit/src/org/dadacoalition/yedit/editor/DocumentStartAndEndRule.java b/org.dadacoalition.yedit/src/org/dadacoalition/yedit/editor/DocumentStartAndEndRule.java
index afa933c..f049d8b 100644
--- a/org.dadacoalition.yedit/src/org/dadacoalition/yedit/editor/DocumentStartAndEndRule.java
+++ b/org.dadacoalition.yedit/src/org/dadacoalition/yedit/editor/DocumentStartAndEndRule.java
@@ -1,51 +1,51 @@
package org.dadacoalition.yedit.editor;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;
/**
* Scanner rule to match the start and end of the document.
*/
public class DocumentStartAndEndRule implements IRule {
private IToken token;
private String matchString;
/**
* @param matchString The string to match. Should either be '---' or '...'
* @param token The token that should be returned for a match.
*/
public DocumentStartAndEndRule(String matchString, IToken token){
this.token = token;
this.matchString = matchString;
}
@Override
public IToken evaluate(ICharacterScanner scanner) {
char c = (char) scanner.read();
int count = 1;
- String chars = "";
+ String chars = "" + c;
while( c != ICharacterScanner.EOF && count < 3 ){
- chars += c;
c = (char) scanner.read();
+ chars += c;
count++;
}
if( matchString.equals(chars)){
return token;
} else {
//no match so need to rewind scanner.
for( int i = 0; i < count; i++ ){
scanner.unread();
}
return Token.UNDEFINED;
}
}
}
| false | true | public IToken evaluate(ICharacterScanner scanner) {
char c = (char) scanner.read();
int count = 1;
String chars = "";
while( c != ICharacterScanner.EOF && count < 3 ){
chars += c;
c = (char) scanner.read();
count++;
}
if( matchString.equals(chars)){
return token;
} else {
//no match so need to rewind scanner.
for( int i = 0; i < count; i++ ){
scanner.unread();
}
return Token.UNDEFINED;
}
}
| public IToken evaluate(ICharacterScanner scanner) {
char c = (char) scanner.read();
int count = 1;
String chars = "" + c;
while( c != ICharacterScanner.EOF && count < 3 ){
c = (char) scanner.read();
chars += c;
count++;
}
if( matchString.equals(chars)){
return token;
} else {
//no match so need to rewind scanner.
for( int i = 0; i < count; i++ ){
scanner.unread();
}
return Token.UNDEFINED;
}
}
|
diff --git a/model/org/eclipse/cdt/internal/core/model/CContainerInfo.java b/model/org/eclipse/cdt/internal/core/model/CContainerInfo.java
index c2dba7599..6f28c8d22 100644
--- a/model/org/eclipse/cdt/internal/core/model/CContainerInfo.java
+++ b/model/org/eclipse/cdt/internal/core/model/CContainerInfo.java
@@ -1,141 +1,139 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.model;
import java.util.ArrayList;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.model.ISourceRoot;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.core.settings.model.ICSourceEntry;
import org.eclipse.cdt.internal.core.settings.model.CProjectDescriptionManager;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
/**
*/
public class CContainerInfo extends OpenableInfo {
Object[] nonCResources = null;
/**
* Constructs a new C Model Info
*/
protected CContainerInfo(CElement element) {
super(element);
}
/**
* @param container
* @return
*/
public Object[] getNonCResources(IResource res) {
if (nonCResources != null)
return nonCResources;
ArrayList notChildren = new ArrayList();
ICElement celement = getElement();
ICProject cproject = celement.getCProject();
// move back to the sourceroot.
while (! (celement instanceof ISourceRoot) && celement != null) {
celement = celement.getParent();
}
ISourceRoot root = null;
if (celement instanceof ISourceRoot) {
root = (ISourceRoot)celement;
- } else {
- return new Object[0]; // should not be. assert
}
try {
IResource[] resources = null;
if (res instanceof IContainer) {
IContainer container = (IContainer)res;
resources = container.members(false);
}
ICSourceEntry[] entries = null;
ICProjectDescription des = CProjectDescriptionManager.getInstance().getProjectDescription(cproject.getProject(), false);
if(des != null){
ICConfigurationDescription cfg = des.getDefaultSettingConfiguration();
if(cfg != null){
entries = cfg.getResolvedSourceEntries();
}
}
if (resources != null) {
for (int i = 0; i < resources.length; i++) {
IResource member = resources[i];
switch(member.getType()) {
case IResource.FOLDER: {
// Check if the folder is not itself a sourceEntry.
IPath resourcePath = member.getFullPath();
if (cproject.isOnSourceRoot(member) || isSourceEntry(resourcePath, entries)
|| cproject.isOnOutputEntry(member)) {
continue;
}
break;
}
case IResource.FILE: {
String filename = member.getName();
- if (CoreModel.isValidTranslationUnitName(cproject.getProject(), filename)
+ if (root != null && CoreModel.isValidTranslationUnitName(cproject.getProject(), filename)
&& root.isOnSourceEntry(member)) {
continue;
}
if (cproject.isOnOutputEntry(member)
&& CModelManager.getDefault().createBinaryFile((IFile) member) != null) {
continue;
}
break;
}
}
notChildren.add(member);
}
}
} catch (CoreException e) {
//System.out.println (e);
//CPlugin.log (e);
//e.printStackTrace();
}
setNonCResources(notChildren.toArray());
return nonCResources;
}
/**
* @param container
* @return
*/
public void setNonCResources(Object[] resources) {
nonCResources = resources;
}
private static boolean isSourceEntry(IPath resourcePath, ICSourceEntry[] entries) {
if(entries == null)
return false;
for (int k = 0; k < entries.length; k++) {
ICSourceEntry entry = entries[k];
// if (entry.getEntryKind() == IPathEntry.CDT_SOURCE) {
IPath sourcePath = entry.getFullPath();
if (resourcePath.equals(sourcePath)) {
return true;
}
// }
}
return false;
}
}
| false | true | public Object[] getNonCResources(IResource res) {
if (nonCResources != null)
return nonCResources;
ArrayList notChildren = new ArrayList();
ICElement celement = getElement();
ICProject cproject = celement.getCProject();
// move back to the sourceroot.
while (! (celement instanceof ISourceRoot) && celement != null) {
celement = celement.getParent();
}
ISourceRoot root = null;
if (celement instanceof ISourceRoot) {
root = (ISourceRoot)celement;
} else {
return new Object[0]; // should not be. assert
}
try {
IResource[] resources = null;
if (res instanceof IContainer) {
IContainer container = (IContainer)res;
resources = container.members(false);
}
ICSourceEntry[] entries = null;
ICProjectDescription des = CProjectDescriptionManager.getInstance().getProjectDescription(cproject.getProject(), false);
if(des != null){
ICConfigurationDescription cfg = des.getDefaultSettingConfiguration();
if(cfg != null){
entries = cfg.getResolvedSourceEntries();
}
}
if (resources != null) {
for (int i = 0; i < resources.length; i++) {
IResource member = resources[i];
switch(member.getType()) {
case IResource.FOLDER: {
// Check if the folder is not itself a sourceEntry.
IPath resourcePath = member.getFullPath();
if (cproject.isOnSourceRoot(member) || isSourceEntry(resourcePath, entries)
|| cproject.isOnOutputEntry(member)) {
continue;
}
break;
}
case IResource.FILE: {
String filename = member.getName();
if (CoreModel.isValidTranslationUnitName(cproject.getProject(), filename)
&& root.isOnSourceEntry(member)) {
continue;
}
if (cproject.isOnOutputEntry(member)
&& CModelManager.getDefault().createBinaryFile((IFile) member) != null) {
continue;
}
break;
}
}
notChildren.add(member);
}
}
} catch (CoreException e) {
//System.out.println (e);
//CPlugin.log (e);
//e.printStackTrace();
}
setNonCResources(notChildren.toArray());
return nonCResources;
}
| public Object[] getNonCResources(IResource res) {
if (nonCResources != null)
return nonCResources;
ArrayList notChildren = new ArrayList();
ICElement celement = getElement();
ICProject cproject = celement.getCProject();
// move back to the sourceroot.
while (! (celement instanceof ISourceRoot) && celement != null) {
celement = celement.getParent();
}
ISourceRoot root = null;
if (celement instanceof ISourceRoot) {
root = (ISourceRoot)celement;
}
try {
IResource[] resources = null;
if (res instanceof IContainer) {
IContainer container = (IContainer)res;
resources = container.members(false);
}
ICSourceEntry[] entries = null;
ICProjectDescription des = CProjectDescriptionManager.getInstance().getProjectDescription(cproject.getProject(), false);
if(des != null){
ICConfigurationDescription cfg = des.getDefaultSettingConfiguration();
if(cfg != null){
entries = cfg.getResolvedSourceEntries();
}
}
if (resources != null) {
for (int i = 0; i < resources.length; i++) {
IResource member = resources[i];
switch(member.getType()) {
case IResource.FOLDER: {
// Check if the folder is not itself a sourceEntry.
IPath resourcePath = member.getFullPath();
if (cproject.isOnSourceRoot(member) || isSourceEntry(resourcePath, entries)
|| cproject.isOnOutputEntry(member)) {
continue;
}
break;
}
case IResource.FILE: {
String filename = member.getName();
if (root != null && CoreModel.isValidTranslationUnitName(cproject.getProject(), filename)
&& root.isOnSourceEntry(member)) {
continue;
}
if (cproject.isOnOutputEntry(member)
&& CModelManager.getDefault().createBinaryFile((IFile) member) != null) {
continue;
}
break;
}
}
notChildren.add(member);
}
}
} catch (CoreException e) {
//System.out.println (e);
//CPlugin.log (e);
//e.printStackTrace();
}
setNonCResources(notChildren.toArray());
return nonCResources;
}
|
diff --git a/DW_Coord_0_0.java b/DW_Coord_0_0.java
index 0b1bbf2..d33f8f3 100644
--- a/DW_Coord_0_0.java
+++ b/DW_Coord_0_0.java
@@ -1,393 +1,388 @@
/*
* Copyright Author
* (USE & RESTRICTIONS - Please read COPYRIGHT file)
* Version : XX.XX
* Date : 4/20/11 1:09 PM
*/
// Default Package
package DWLProject;
import java.awt.Color;
import java.util.List;
import model.modeling.message;
import view.modeling.ViewableAtomic;
import GenCol.Pair;
import GenCol.Queue;
import GenCol.entity;
public class DW_Coord_0_0 extends ViewableAtomic{
private static final message NULL_MESSAGE = new message();
//in port
private static final String EXT_CAT_IN = "ExtCatIn";
private static final String LOAD = "load";
private static final String STOP = "stop";
private static final String WRITER_DONE = "WriterDone";
//out port
private static final String EXT_CAT_OUT = "ExtCatOut";
private static final String CAT_OUT = "CatOut";
private static final String HALT = "halt";
//phases
private static final String PASSIVE = "passive";
private static final String HALTING = "halting";
private static final String QUEUEING = "QueueingCat";
private static final String RECEIVING_EXT_CAT = "ReceivingExtCat";
private static final String SEND_EXT_CAT = "SendingExtCat";
private static final String SEND_CAT = "SendingCat";
private static final String WRITERS_DONE = "WritersDone";
private static final String START = "start";
/**
* Takes 1 unit of time to queue an incoming Cat File
*/
private double QUEUEING_TIME = 1;
private message haltMessage;
private boolean startReceived;
private message outputMessage;
private CatFile currentCatFile;
private Queue writersQueue;
private Queue catFileQueue;
private Queue workingCatFileQueue;
private Queue completedCatFileQueue;
private ExtCatFile currentExtCatFile;
private Queue pendingExtCatFileQueue;
private Queue workingExtCatFileQueue;
// Add Default Constructor
public DW_Coord_0_0(){
this("Coordinator");
}
// Add Parameterized Constructors
public DW_Coord_0_0(String name){
super(name);
// Structure information start
// Add input port names
addInport(EXT_CAT_IN);
addInport(LOAD);
addInport(STOP);
addInport(WRITER_DONE);
// Add output port names
addOutport(EXT_CAT_OUT);
addOutport(CAT_OUT);
addOutport(HALT);
//add test input ports:
addTestInput(EXT_CAT_IN, new ExtCatFile("ExtCat1", 100, "L1", 2011, 10, 1D));
addTestInput(EXT_CAT_IN, new ExtCatFile("ExtCat2", 100, "L1", 2011, 10, 1D));
addTestInput(EXT_CAT_IN, new ExtCatFile("ExtCat3", 100, "L1", 2011, 10, 1D));
addTestInput(EXT_CAT_IN, new ExtCatFile("ExtCat4", 80, "L2", 2011, 8, 1D));
addTestInput(EXT_CAT_IN, new ExtCatFile("ExtCat5", 20, "L3", 2011, 2, 1D));
addTestInput(LOAD, new entity("start"));
// Structure information end
writersQueue = new Queue();
initialize();
}
// Add initialize function
public void initialize(){
super.initialize();
phase = PASSIVE;
sigma = INFINITY;
startReceived = false;
outputMessage = null;
currentCatFile = null;
catFileQueue = new Queue();
workingCatFileQueue = new Queue();
// processedCatFileQueue = new Queue();
completedCatFileQueue = new Queue();
workingExtCatFileQueue = new Queue();
pendingExtCatFileQueue = new Queue();
currentExtCatFile = null;
}
// Add external transition function
@SuppressWarnings("unchecked")
@Override
public void deltext(double e, message x){
Continue(e);
for (int i = 0 ; i < x.getLength(); i++) {
checkForStop(x, i);
}
if (phaseIs(RECEIVING_EXT_CAT)) {
queueExtCatFiles(x, e);
}
if (phaseIs(PASSIVE)) {
checkForExtCat(x);
}
for (int i = 0 ; i < x.getLength(); i++) {
checkForStartOnLoadPort(x, i);
}
for (int i = 0; i < x.size(); i++) {
if (messageOnPort(x, WRITER_DONE, i)) {
entity value = x.getValOnPort(WRITER_DONE, i);
Pair pair = (Pair) value;
writersQueue.add(pair.getKey());
ExtCatFile aCatFile = (ExtCatFile) pair.getValue();
CatFile parentCatFile = aCatFile.getParentCatFile();
if (parentCatFile.isCompleted()) {
if (!completedCatFileQueue.contains(parentCatFile)) {
completedCatFileQueue.add(parentCatFile);
currentCatFile = null;
holdIn(SEND_CAT, 1);
outputMessage = new message();
Pair aPair = new Pair(parentCatFile.getName(), parentCatFile);
outputMessage.add(makeContent(CAT_OUT, aPair));
}
}
holdIn(SEND_EXT_CAT, 0);
this.setBackgroundColor(Color.MAGENTA);
sendExtCatToWriters();
}
}
if ((phaseIs(PASSIVE) || phaseIs(RECEIVING_EXT_CAT))
&& pendingExtCatFileQueue.isEmpty()
&& startReceived) {
holdIn(SEND_EXT_CAT, 0);
sendExtCatToWriters();
this.setBackgroundColor(Color.MAGENTA);
}
}
@SuppressWarnings("unchecked")
private void sendExtCatToWriters() {
outputMessage = new message();
if (currentCatFile == null && !workingCatFileQueue.isEmpty()) {
currentCatFile = (CatFile) workingCatFileQueue.remove();
if (currentCatFile.getProcessedExtCatList().isEmpty()) {
workingExtCatFileQueue.addAll(currentCatFile.getExtCatList());
}
}
while (!writersQueue.isEmpty() && !workingExtCatFileQueue.isEmpty()) {
Writer_0_0 aWriter = (Writer_0_0)writersQueue.remove();
ExtCatFile aCatFile = (ExtCatFile) workingExtCatFileQueue.remove();
Pair aPair = new Pair(aWriter.getName(), aCatFile);
outputMessage.add(makeContent(EXT_CAT_OUT, aPair));
}
}
/**
* Checks if the loading of ExtCat should start
*
* @param x
* @param i
*/
private void checkForStartOnLoadPort(message x, int i) {
if (messageOnPort(x, LOAD, i)) {
entity value = x.getValOnPort(LOAD, i);
if (value.getName().equals(START)) {
startReceived = true;
}
}
}
/**
* Queues any <code>ExtCatFile</code> that comes
* in while the <tt>DW</tt> is <code>BUSY</code>
* @param x
* @param e
*/
@SuppressWarnings("unchecked")
private void queueExtCatFiles(message x, double e) {
for (int i = 0; i < x.getLength(); i++) {
if (messageOnPort(x, EXT_CAT_IN, i)) {
entity value = x.getValOnPort(EXT_CAT_IN, i);
if (value instanceof ExtCatFile) {
ExtCatFile aCatFile = (ExtCatFile) value;
currentExtCatFile.updateTimeToRegister(e);
holdIn(QUEUEING, QUEUEING_TIME);
this.setBackgroundColor(Color.MAGENTA);
pendingExtCatFileQueue.add(aCatFile);
} else {
System.out.println("Not an Ext Cat File: " + value.getName());
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GRAY);
}
}
}
}
/**
* Picks up all <code>ExtCatFile</code> that are on
* input port <code>LOAD</code>
*
* @param x
*/
@SuppressWarnings("unchecked")
private void checkForExtCat(message x) {
for (int i = 0; i < x.getLength(); i++) {
if (messageOnPort(x, EXT_CAT_IN, i)) {
entity value = x.getValOnPort(EXT_CAT_IN, i);
if (value instanceof ExtCatFile) {
ExtCatFile aCatFile = (ExtCatFile) value;
holdIn(RECEIVING_EXT_CAT, aCatFile.getTimeToRegister());
this.setBackgroundColor(Color.MAGENTA);
CatFile parent = aCatFile.getParentCatFile();
if (!catFileQueue.contains(parent)) {
catFileQueue.add(parent);
workingCatFileQueue.add(parent);
}
currentExtCatFile = aCatFile;
}
else {
System.out.println("Not an Ext Cat File: " + value.getName());
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GRAY);
}
}
}
}
/**
* Checks if there is a halt command from the Experimental Frame
* @param x
* @param i
*/
private void checkForStop(message x, int i) {
if (messageOnPort(x, STOP, i)) {
entity value = x.getValOnPort(STOP, i);
if (value.getName().equals(STOP)) {
holdIn(HALTING, 1);
this.setBackgroundColor(Color.MAGENTA);
haltMessage = new message();
haltMessage.add(makeContent(HALT, new entity(HALT)));
}
}
}
// Add internal transition function
@SuppressWarnings("unchecked")
@Override
public void deltint(){
if (phaseIs(HALTING)) {
passivateIn(PASSIVE);
this.setBackgroundColor(Color.GRAY);
} else if (phaseIs(QUEUEING)) {
double timeLeftForRegistration = currentExtCatFile.getTimeToRegister();
if (timeLeftForRegistration > 0D) {
holdIn(RECEIVING_EXT_CAT, timeLeftForRegistration);
this.setBackgroundColor(Color.MAGENTA);
} else {
currentExtCatFile = null;
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GRAY);
}
} else if (phaseIs(RECEIVING_EXT_CAT)) {
if (pendingExtCatFileQueue.size() > 0) {
currentExtCatFile = (ExtCatFile) pendingExtCatFileQueue.remove();
holdIn(RECEIVING_EXT_CAT,
currentExtCatFile.getTimeToRegister());
CatFile parent = currentExtCatFile.getParentCatFile();
if (!catFileQueue.contains(parent)) {
catFileQueue.add(parent);
workingCatFileQueue.add(parent);
}
this.setBackgroundColor(Color.MAGENTA);
} else if (workingCatFileQueue.isEmpty()){
passivateIn(PASSIVE);
currentExtCatFile = null;
this.setBackgroundColor(Color.GRAY);
} else if (startReceived) {
- holdIn(SEND_EXT_CAT, 1);
+ holdIn(SEND_EXT_CAT, 0);
this.setBackgroundColor(Color.MAGENTA);
sendExtCatToWriters();
}
} else if (phaseIs(WRITERS_DONE)) {
passivateIn(PASSIVE);
this.setBackgroundColor(Color.GRAY);
} else if (phaseIs(SEND_EXT_CAT)) {
if (catFileQueue.size() == completedCatFileQueue.size()) {
holdIn(WRITERS_DONE, 0);
this.setBackgroundColor(Color.MAGENTA);
} else {
holdIn(PASSIVE, INFINITY);
- this.setBackgroundColor(Color.GREEN);
+ this.setBackgroundColor(Color.GRAY);
}
} else if (phaseIs(SEND_CAT)) {
- if (!workingCatFileQueue.isEmpty()) {
- holdIn(SEND_EXT_CAT, 0);
- sendExtCatToWriters();
- } else {
- if (catFileQueue.size() == completedCatFileQueue.size()) {
- holdIn(WRITERS_DONE, 0);
- this.setBackgroundColor(Color.MAGENTA);
- }
+ if (catFileQueue.size() == completedCatFileQueue.size()) {
+ holdIn(WRITERS_DONE, 0);
+ this.setBackgroundColor(Color.MAGENTA);
}
}
}
// Add confluent function
@Override
public void deltcon(double e, message x){
deltint();
deltext(0, x);
}
// Add output function
@Override
public message out(){
if (phaseIs(HALTING)) {
return haltMessage;
}
if (phaseIs(SEND_EXT_CAT) || phaseIs(SEND_CAT)) {
return outputMessage;
}
return NULL_MESSAGE;
}
@Override
public void showState() {
super.showState();
System.out.println("The CatFile Queue has " + catFileQueue.size() + " elements");
System.out.println("The Queue contains: " + catFileQueue);
System.out.println("The Completed Cat Queue has " + completedCatFileQueue.size() + " elements");
System.out.println("The Queue contains: " + completedCatFileQueue);
System.out.println("The Writers Queue has " + writersQueue.size() + " elements");
System.out.println("The Queue contains: " + writersQueue);
}
@Override
public String getTooltipText() {
StringBuilder myBuilder = new StringBuilder();
myBuilder.append("\n");
myBuilder.append("Writers Queue: ");
myBuilder.append(writersQueue);
myBuilder.append("\n");
myBuilder.append("Cat File Queue: ");
myBuilder.append(catFileQueue);
myBuilder.append("\n");
myBuilder.append("Completed Cat File Queue: ");
myBuilder.append(completedCatFileQueue);
myBuilder.append("\n");
myBuilder.append("Ext Cat File Queue: ");
myBuilder.append(workingExtCatFileQueue);
return super.getTooltipText() + myBuilder.toString();
}
/**
* @return <code>CAT_OUT</code> port
*/
public static String getExtCatOut() {
return EXT_CAT_OUT;
}
public static String getWriterDone() {
return WRITER_DONE;
}
/**
* Set the writers into the queue
* @param writerList
*/
@SuppressWarnings("unchecked")
public void setWriters(List<Writer_0_0> writerList) {
writersQueue.addAll(writerList);
}
}
| false | true | public void deltint(){
if (phaseIs(HALTING)) {
passivateIn(PASSIVE);
this.setBackgroundColor(Color.GRAY);
} else if (phaseIs(QUEUEING)) {
double timeLeftForRegistration = currentExtCatFile.getTimeToRegister();
if (timeLeftForRegistration > 0D) {
holdIn(RECEIVING_EXT_CAT, timeLeftForRegistration);
this.setBackgroundColor(Color.MAGENTA);
} else {
currentExtCatFile = null;
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GRAY);
}
} else if (phaseIs(RECEIVING_EXT_CAT)) {
if (pendingExtCatFileQueue.size() > 0) {
currentExtCatFile = (ExtCatFile) pendingExtCatFileQueue.remove();
holdIn(RECEIVING_EXT_CAT,
currentExtCatFile.getTimeToRegister());
CatFile parent = currentExtCatFile.getParentCatFile();
if (!catFileQueue.contains(parent)) {
catFileQueue.add(parent);
workingCatFileQueue.add(parent);
}
this.setBackgroundColor(Color.MAGENTA);
} else if (workingCatFileQueue.isEmpty()){
passivateIn(PASSIVE);
currentExtCatFile = null;
this.setBackgroundColor(Color.GRAY);
} else if (startReceived) {
holdIn(SEND_EXT_CAT, 1);
this.setBackgroundColor(Color.MAGENTA);
sendExtCatToWriters();
}
} else if (phaseIs(WRITERS_DONE)) {
passivateIn(PASSIVE);
this.setBackgroundColor(Color.GRAY);
} else if (phaseIs(SEND_EXT_CAT)) {
if (catFileQueue.size() == completedCatFileQueue.size()) {
holdIn(WRITERS_DONE, 0);
this.setBackgroundColor(Color.MAGENTA);
} else {
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GREEN);
}
} else if (phaseIs(SEND_CAT)) {
if (!workingCatFileQueue.isEmpty()) {
holdIn(SEND_EXT_CAT, 0);
sendExtCatToWriters();
} else {
if (catFileQueue.size() == completedCatFileQueue.size()) {
holdIn(WRITERS_DONE, 0);
this.setBackgroundColor(Color.MAGENTA);
}
}
}
}
| public void deltint(){
if (phaseIs(HALTING)) {
passivateIn(PASSIVE);
this.setBackgroundColor(Color.GRAY);
} else if (phaseIs(QUEUEING)) {
double timeLeftForRegistration = currentExtCatFile.getTimeToRegister();
if (timeLeftForRegistration > 0D) {
holdIn(RECEIVING_EXT_CAT, timeLeftForRegistration);
this.setBackgroundColor(Color.MAGENTA);
} else {
currentExtCatFile = null;
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GRAY);
}
} else if (phaseIs(RECEIVING_EXT_CAT)) {
if (pendingExtCatFileQueue.size() > 0) {
currentExtCatFile = (ExtCatFile) pendingExtCatFileQueue.remove();
holdIn(RECEIVING_EXT_CAT,
currentExtCatFile.getTimeToRegister());
CatFile parent = currentExtCatFile.getParentCatFile();
if (!catFileQueue.contains(parent)) {
catFileQueue.add(parent);
workingCatFileQueue.add(parent);
}
this.setBackgroundColor(Color.MAGENTA);
} else if (workingCatFileQueue.isEmpty()){
passivateIn(PASSIVE);
currentExtCatFile = null;
this.setBackgroundColor(Color.GRAY);
} else if (startReceived) {
holdIn(SEND_EXT_CAT, 0);
this.setBackgroundColor(Color.MAGENTA);
sendExtCatToWriters();
}
} else if (phaseIs(WRITERS_DONE)) {
passivateIn(PASSIVE);
this.setBackgroundColor(Color.GRAY);
} else if (phaseIs(SEND_EXT_CAT)) {
if (catFileQueue.size() == completedCatFileQueue.size()) {
holdIn(WRITERS_DONE, 0);
this.setBackgroundColor(Color.MAGENTA);
} else {
holdIn(PASSIVE, INFINITY);
this.setBackgroundColor(Color.GRAY);
}
} else if (phaseIs(SEND_CAT)) {
if (catFileQueue.size() == completedCatFileQueue.size()) {
holdIn(WRITERS_DONE, 0);
this.setBackgroundColor(Color.MAGENTA);
}
}
}
|
diff --git a/src/ArgCheck.java b/src/ArgCheck.java
index c05a8b4..aad46d8 100644
--- a/src/ArgCheck.java
+++ b/src/ArgCheck.java
@@ -1,40 +1,40 @@
import java.util.ArrayList;
public class ArgCheck {
public static void check(String[] argss){
ArrayList<String> args = new ArrayList<String>();
for(String s : argss) args.add(s);
if(args.contains("randommu")){
Constants._murand = true;
if(args.indexOf("randommu") < args.size() - 2){
Constants.randMuStart = Double.parseDouble(args.get(1));
Constants.randMuEnd = Double.parseDouble(args.get(2));
}
}
if(args.contains("mu")){
Constants.muCheck = true;
if(args.indexOf("mu") < args.size() - 1){
- Constants.muIncUp = Double.parseDouble(args.get(args.indexOf("mu") + 1 ));
+ Constants.muIncUp = Double.parseDouble(args.get(args.indexOf("mu")+1));
}
}
if(args.contains("constantep")){
Constants.ConstantEp = true;
if(args.indexOf("constantep") < args.size() - 1){
Main.monitor.constants._epsilon = Double.parseDouble(args.get(args.indexOf("constantep") + 1 ));
}
}
if(args.contains("repulse")){
Constants.Repulsive = true;
if(args.indexOf("repulse") < args.size() - 1){
- Constants.repuslivePer = Integer.parseInt(args.get(args.indexOf("repulsive") + 1 ));
+ Constants.repuslivePer = Integer.parseInt(args.get(args.indexOf("repulse") + 1 ));
}
}
if(args.contains("nodes")){
Constants.resetVals(Integer.parseInt(args.get(args.indexOf("nodes") + 1)),
Integer.parseInt(args.get(args.indexOf("nodes") + 2)));
}
}
}
| false | true | public static void check(String[] argss){
ArrayList<String> args = new ArrayList<String>();
for(String s : argss) args.add(s);
if(args.contains("randommu")){
Constants._murand = true;
if(args.indexOf("randommu") < args.size() - 2){
Constants.randMuStart = Double.parseDouble(args.get(1));
Constants.randMuEnd = Double.parseDouble(args.get(2));
}
}
if(args.contains("mu")){
Constants.muCheck = true;
if(args.indexOf("mu") < args.size() - 1){
Constants.muIncUp = Double.parseDouble(args.get(args.indexOf("mu") + 1 ));
}
}
if(args.contains("constantep")){
Constants.ConstantEp = true;
if(args.indexOf("constantep") < args.size() - 1){
Main.monitor.constants._epsilon = Double.parseDouble(args.get(args.indexOf("constantep") + 1 ));
}
}
if(args.contains("repulse")){
Constants.Repulsive = true;
if(args.indexOf("repulse") < args.size() - 1){
Constants.repuslivePer = Integer.parseInt(args.get(args.indexOf("repulsive") + 1 ));
}
}
if(args.contains("nodes")){
Constants.resetVals(Integer.parseInt(args.get(args.indexOf("nodes") + 1)),
Integer.parseInt(args.get(args.indexOf("nodes") + 2)));
}
}
| public static void check(String[] argss){
ArrayList<String> args = new ArrayList<String>();
for(String s : argss) args.add(s);
if(args.contains("randommu")){
Constants._murand = true;
if(args.indexOf("randommu") < args.size() - 2){
Constants.randMuStart = Double.parseDouble(args.get(1));
Constants.randMuEnd = Double.parseDouble(args.get(2));
}
}
if(args.contains("mu")){
Constants.muCheck = true;
if(args.indexOf("mu") < args.size() - 1){
Constants.muIncUp = Double.parseDouble(args.get(args.indexOf("mu")+1));
}
}
if(args.contains("constantep")){
Constants.ConstantEp = true;
if(args.indexOf("constantep") < args.size() - 1){
Main.monitor.constants._epsilon = Double.parseDouble(args.get(args.indexOf("constantep") + 1 ));
}
}
if(args.contains("repulse")){
Constants.Repulsive = true;
if(args.indexOf("repulse") < args.size() - 1){
Constants.repuslivePer = Integer.parseInt(args.get(args.indexOf("repulse") + 1 ));
}
}
if(args.contains("nodes")){
Constants.resetVals(Integer.parseInt(args.get(args.indexOf("nodes") + 1)),
Integer.parseInt(args.get(args.indexOf("nodes") + 2)));
}
}
|
diff --git a/src/DocumentChecker.java b/src/DocumentChecker.java
index eebd179..629582b 100644
--- a/src/DocumentChecker.java
+++ b/src/DocumentChecker.java
@@ -1,60 +1,61 @@
import java.util.ArrayList;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
/**
* The first step of the security system where a passenger's documents are checked
* for validity and the passenger is either admitted through or sent to Jail.
*
* @author Anthony Barone
* @author Ryan Clough
* @author Rebecca Dudley
* @author Ryan Mentley
*/
public class DocumentChecker extends UntypedActor {
// Instance variables
private final ArrayList<ActorRef> airportLines;
private final ActorRef jail;
private int currentLineChoice = 0;
/**
* Constructor for the DocumentChecker
*
* @param airportLines - All of the scan queues in the airport
*/
public DocumentChecker( ArrayList<ActorRef> airportLines, ActorRef jail ) {
this.airportLines = airportLines;
this.jail = jail;
}
@Override
public void onReceive( final Object msg ) throws Exception {
if ( msg instanceof Passenger ) {
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + " arrives");
// If msg is a Passenger, perform the document check.
if ( ( Math.random()*100 ) <= TestBedConstants.DOC_CHECK_FAIL_PERCENTAGE ) {
// Document check failed, send passenger to jail!
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + "turned away");
jail.tell( msg );
} else {
// Document check passed, passenger free to advance to ScanQueue
airportLines.get( currentLineChoice % airportLines.size() ).tell( msg );
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + "sent to line " +
- ( currentLineChoice % airportLines.size() ));
+ ( currentLineChoice % airportLines.size() + 1 ) );
+ currentLineChoice++;
}
} else if ( msg instanceof CloseMsg ) {
// If msg is a CloseMsg, relay to all ScanQueues and terminate self.
System.out.println("Document Check: Close sent ");
for (ActorRef line : airportLines) {
line.tell(msg);
}
this.getContext().stop();
System.out.println("Document Check: Closed");
}
}
}
| true | true | public void onReceive( final Object msg ) throws Exception {
if ( msg instanceof Passenger ) {
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + " arrives");
// If msg is a Passenger, perform the document check.
if ( ( Math.random()*100 ) <= TestBedConstants.DOC_CHECK_FAIL_PERCENTAGE ) {
// Document check failed, send passenger to jail!
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + "turned away");
jail.tell( msg );
} else {
// Document check passed, passenger free to advance to ScanQueue
airportLines.get( currentLineChoice % airportLines.size() ).tell( msg );
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + "sent to line " +
( currentLineChoice % airportLines.size() ));
}
} else if ( msg instanceof CloseMsg ) {
// If msg is a CloseMsg, relay to all ScanQueues and terminate self.
System.out.println("Document Check: Close sent ");
for (ActorRef line : airportLines) {
line.tell(msg);
}
this.getContext().stop();
System.out.println("Document Check: Closed");
}
}
| public void onReceive( final Object msg ) throws Exception {
if ( msg instanceof Passenger ) {
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + " arrives");
// If msg is a Passenger, perform the document check.
if ( ( Math.random()*100 ) <= TestBedConstants.DOC_CHECK_FAIL_PERCENTAGE ) {
// Document check failed, send passenger to jail!
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + "turned away");
jail.tell( msg );
} else {
// Document check passed, passenger free to advance to ScanQueue
airportLines.get( currentLineChoice % airportLines.size() ).tell( msg );
System.out.println("Document Check: Passenger " +
((Passenger) msg).getName() + "sent to line " +
( currentLineChoice % airportLines.size() + 1 ) );
currentLineChoice++;
}
} else if ( msg instanceof CloseMsg ) {
// If msg is a CloseMsg, relay to all ScanQueues and terminate self.
System.out.println("Document Check: Close sent ");
for (ActorRef line : airportLines) {
line.tell(msg);
}
this.getContext().stop();
System.out.println("Document Check: Closed");
}
}
|
diff --git a/examples/showcase/src/main/java/org/springside/examples/showcase/demos/cache/guava/GuavaCacheDemo.java b/examples/showcase/src/main/java/org/springside/examples/showcase/demos/cache/guava/GuavaCacheDemo.java
index 0d5d5ada..3213d011 100644
--- a/examples/showcase/src/main/java/org/springside/examples/showcase/demos/cache/guava/GuavaCacheDemo.java
+++ b/examples/showcase/src/main/java/org/springside/examples/showcase/demos/cache/guava/GuavaCacheDemo.java
@@ -1,73 +1,74 @@
package org.springside.examples.showcase.demos.cache.guava;
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springside.examples.showcase.entity.User;
import org.springside.examples.showcase.service.AccountService;
import org.springside.modules.test.data.DataFixtures;
import org.springside.modules.test.log.LogbackListAppender;
import org.springside.modules.test.spring.SpringTransactionalTestCase;
import org.springside.modules.utils.Threads;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* 本地缓存演示,使用GuavaCache.
*
* @author calvin
*/
@ContextConfiguration(locations = { "/applicationContext.xml" })
public class GuavaCacheDemo extends SpringTransactionalTestCase {
private static Logger logger = LoggerFactory.getLogger(GuavaCacheDemo.class);
@Autowired
private AccountService accountService;
@Test
public void demo() throws Exception {
// 设置缓存最大个数为100,缓存过期时间为5秒
LoadingCache<Long, User> cache = CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<Long, User>() {
@Override
public User load(Long key) throws Exception {
logger.info("fetch from database");
return accountService.getUser(key);
}
});
// 初始化数据
- DataFixtures.executeScript(dataSource, "classpath:data/cleanup-data.sql", "classpath:data/import-data.sql");
+ DataFixtures.executeScript(dataSource, "classpath:data/h2/cleanup-data.sql",
+ "classpath:data/h2/import-data.sql");
// 插入appender用于assert。
LogbackListAppender appender = new LogbackListAppender();
appender.addToLogger(GuavaCacheDemo.class);
// 第一次加载会查数据库
User user = cache.get(1L);
assertEquals("admin", user.getLoginName());
assertFalse(appender.isEmpty());
appender.clearLogs();
// 第二次加载时直接从缓存里取
User user2 = cache.get(1L);
assertEquals("admin", user2.getLoginName());
assertTrue(appender.isEmpty());
// 第三次加载时,因为缓存已经过期所以会查数据库
Threads.sleep(10, TimeUnit.SECONDS);
User user3 = cache.get(1L);
assertEquals("admin", user3.getLoginName());
assertFalse(appender.isEmpty());
}
}
| true | true | public void demo() throws Exception {
// 设置缓存最大个数为100,缓存过期时间为5秒
LoadingCache<Long, User> cache = CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<Long, User>() {
@Override
public User load(Long key) throws Exception {
logger.info("fetch from database");
return accountService.getUser(key);
}
});
// 初始化数据
DataFixtures.executeScript(dataSource, "classpath:data/cleanup-data.sql", "classpath:data/import-data.sql");
// 插入appender用于assert。
LogbackListAppender appender = new LogbackListAppender();
appender.addToLogger(GuavaCacheDemo.class);
// 第一次加载会查数据库
User user = cache.get(1L);
assertEquals("admin", user.getLoginName());
assertFalse(appender.isEmpty());
appender.clearLogs();
// 第二次加载时直接从缓存里取
User user2 = cache.get(1L);
assertEquals("admin", user2.getLoginName());
assertTrue(appender.isEmpty());
// 第三次加载时,因为缓存已经过期所以会查数据库
Threads.sleep(10, TimeUnit.SECONDS);
User user3 = cache.get(1L);
assertEquals("admin", user3.getLoginName());
assertFalse(appender.isEmpty());
}
| public void demo() throws Exception {
// 设置缓存最大个数为100,缓存过期时间为5秒
LoadingCache<Long, User> cache = CacheBuilder.newBuilder().maximumSize(100)
.expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<Long, User>() {
@Override
public User load(Long key) throws Exception {
logger.info("fetch from database");
return accountService.getUser(key);
}
});
// 初始化数据
DataFixtures.executeScript(dataSource, "classpath:data/h2/cleanup-data.sql",
"classpath:data/h2/import-data.sql");
// 插入appender用于assert。
LogbackListAppender appender = new LogbackListAppender();
appender.addToLogger(GuavaCacheDemo.class);
// 第一次加载会查数据库
User user = cache.get(1L);
assertEquals("admin", user.getLoginName());
assertFalse(appender.isEmpty());
appender.clearLogs();
// 第二次加载时直接从缓存里取
User user2 = cache.get(1L);
assertEquals("admin", user2.getLoginName());
assertTrue(appender.isEmpty());
// 第三次加载时,因为缓存已经过期所以会查数据库
Threads.sleep(10, TimeUnit.SECONDS);
User user3 = cache.get(1L);
assertEquals("admin", user3.getLoginName());
assertFalse(appender.isEmpty());
}
|
diff --git a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java
index 3653b678..91707e26 100644
--- a/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java
+++ b/jaxrs/server-negotiation/src/main/java/org/javaee7/jaxrs/server/negotiation/MyResource.java
@@ -1,62 +1,62 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.javaee7.jaxrs.server.negotiation;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @author Arun Gupta
*/
@Path("persons")
public class MyResource {
@GET
@Produces({"application/xml; qs=0.75", "application/json; qs=1.0"})
// @Produces({"application/xml", "application/json"})
public Person[] getList() {
Person[] list = new Person[3];
list[0] = new Person("Penny", 1);
- list[1] = new Person("Howard", 2);
+ list[1] = new Person("Leonard", 2);
list[2] = new Person("Sheldon", 3);
return list;
}
}
| true | true | public Person[] getList() {
Person[] list = new Person[3];
list[0] = new Person("Penny", 1);
list[1] = new Person("Howard", 2);
list[2] = new Person("Sheldon", 3);
return list;
}
| public Person[] getList() {
Person[] list = new Person[3];
list[0] = new Person("Penny", 1);
list[1] = new Person("Leonard", 2);
list[2] = new Person("Sheldon", 3);
return list;
}
|
diff --git a/src/org/thedoug/farkle/Farkle.java b/src/org/thedoug/farkle/Farkle.java
index f816e6d..ca7037b 100644
--- a/src/org/thedoug/farkle/Farkle.java
+++ b/src/org/thedoug/farkle/Farkle.java
@@ -1,43 +1,43 @@
package org.thedoug.farkle;
import org.thedoug.farkle.model.GameResult;
import org.thedoug.farkle.model.LukeRulesScorer;
import org.thedoug.farkle.model.RandomRollStrategy;
import org.thedoug.farkle.player.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class Farkle {
public static void main(String[] args) {
RandomRollStrategy rollStrategy = new RandomRollStrategy();
LukeRulesScorer scorer = new LukeRulesScorer(rollStrategy);
- Player[] players = new Player[] {
+ Player[] players = new Player[]{
new RollIfAtLeastNRemainingDicePlayer(1),
new RollIfAtLeastNRemainingDicePlayer(2),
new RollIfAtLeastNRemainingDicePlayer(3), // Champion!
new RollIfAtLeastNRemainingDicePlayer(4),
new RollIfAtLeastNRemainingDicePlayer(5),
new RollAgainOncePlayer(),
new RandomPlayer(),
new ConservativePlayer(),
};
Map<Player, Integer> score = new LinkedHashMap<Player, Integer>();
- for (Player player: players) {
+ for (Player player : players) {
score.put(player, 0);
}
for (int i = 0; i < 10000; i++) {
GameEngine gameEngine = new GameEngine(rollStrategy, scorer, players);
GameResult result = gameEngine.run();
Player winner = result.getWinner();
score.put(winner, score.get(winner) + 1);
}
System.out.println(score);
}
}
| false | true | public static void main(String[] args) {
RandomRollStrategy rollStrategy = new RandomRollStrategy();
LukeRulesScorer scorer = new LukeRulesScorer(rollStrategy);
Player[] players = new Player[] {
new RollIfAtLeastNRemainingDicePlayer(1),
new RollIfAtLeastNRemainingDicePlayer(2),
new RollIfAtLeastNRemainingDicePlayer(3), // Champion!
new RollIfAtLeastNRemainingDicePlayer(4),
new RollIfAtLeastNRemainingDicePlayer(5),
new RollAgainOncePlayer(),
new RandomPlayer(),
new ConservativePlayer(),
};
Map<Player, Integer> score = new LinkedHashMap<Player, Integer>();
for (Player player: players) {
score.put(player, 0);
}
for (int i = 0; i < 10000; i++) {
GameEngine gameEngine = new GameEngine(rollStrategy, scorer, players);
GameResult result = gameEngine.run();
Player winner = result.getWinner();
score.put(winner, score.get(winner) + 1);
}
System.out.println(score);
}
| public static void main(String[] args) {
RandomRollStrategy rollStrategy = new RandomRollStrategy();
LukeRulesScorer scorer = new LukeRulesScorer(rollStrategy);
Player[] players = new Player[]{
new RollIfAtLeastNRemainingDicePlayer(1),
new RollIfAtLeastNRemainingDicePlayer(2),
new RollIfAtLeastNRemainingDicePlayer(3), // Champion!
new RollIfAtLeastNRemainingDicePlayer(4),
new RollIfAtLeastNRemainingDicePlayer(5),
new RollAgainOncePlayer(),
new RandomPlayer(),
new ConservativePlayer(),
};
Map<Player, Integer> score = new LinkedHashMap<Player, Integer>();
for (Player player : players) {
score.put(player, 0);
}
for (int i = 0; i < 10000; i++) {
GameEngine gameEngine = new GameEngine(rollStrategy, scorer, players);
GameResult result = gameEngine.run();
Player winner = result.getWinner();
score.put(winner, score.get(winner) + 1);
}
System.out.println(score);
}
|
diff --git a/src/org/servalproject/rhizome/ManifestEditorActivity.java b/src/org/servalproject/rhizome/ManifestEditorActivity.java
index 4d948546..e48ce30f 100644
--- a/src/org/servalproject/rhizome/ManifestEditorActivity.java
+++ b/src/org/servalproject/rhizome/ManifestEditorActivity.java
@@ -1,86 +1,87 @@
/**
*
*/
package org.servalproject.rhizome;
import org.servalproject.R;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
* @author rbochet
*
* This class displays a form with the required field to create the
* manifest (author, version). The results are sent back to Main.
*
*/
public class ManifestEditorActivity extends Activity implements OnClickListener {
/** TAG for debugging */
public static final String TAG = "R2";
@Override
public void onClick(View v) {
// Extract the data from the form
String author = ((EditText) findViewById(R.id.me_author)).getText()
.toString();
String version = ((EditText) findViewById(R.id.me_version)).getText()
.toString();
String dest = ((EditText) findViewById(R.id.me_name)).getText()
.toString();
// Fill the intent
Intent intent = this.getIntent();
intent.putExtra("author", author);
intent.putExtra("version", version);
intent.putExtra("destinationName", dest);
this.setResult(RESULT_OK, intent);
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manifest_editor);
// Handle the validations
Button validate = (Button) findViewById(R.id.me_validate);
validate.setOnClickListener(this);
Intent intent = getIntent();
String filename = intent.getStringExtra("fileName");
CharSequence destinationName = filename;
int version = 1;
if (filename != null && filename.toLowerCase().endsWith(".apk")) {
PackageManager pm = this.getPackageManager();
- PackageInfo info = pm.getPackageArchiveInfo(filename, 0);
+ PackageInfo info = pm.getPackageArchiveInfo(RhizomeUtils.dirRhizome
+ + "/" + filename, 0);
if (info != null) {
version = info.versionCode;
// see http://code.google.com/p/android/issues/detail?id=9151
if (info.applicationInfo.sourceDir == null)
info.applicationInfo.sourceDir = filename;
if (info.applicationInfo.publicSourceDir == null)
info.applicationInfo.publicSourceDir = filename;
CharSequence label = info.applicationInfo.loadLabel(pm);
if (label != null && !"".equals(label))
destinationName = label + ".apk";
else
destinationName = info.packageName + ".apk";
}
}
((EditText) findViewById(R.id.me_version)).setText(String
.valueOf(version));
((EditText) findViewById(R.id.me_name)).setText(destinationName);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manifest_editor);
// Handle the validations
Button validate = (Button) findViewById(R.id.me_validate);
validate.setOnClickListener(this);
Intent intent = getIntent();
String filename = intent.getStringExtra("fileName");
CharSequence destinationName = filename;
int version = 1;
if (filename != null && filename.toLowerCase().endsWith(".apk")) {
PackageManager pm = this.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(filename, 0);
if (info != null) {
version = info.versionCode;
// see http://code.google.com/p/android/issues/detail?id=9151
if (info.applicationInfo.sourceDir == null)
info.applicationInfo.sourceDir = filename;
if (info.applicationInfo.publicSourceDir == null)
info.applicationInfo.publicSourceDir = filename;
CharSequence label = info.applicationInfo.loadLabel(pm);
if (label != null && !"".equals(label))
destinationName = label + ".apk";
else
destinationName = info.packageName + ".apk";
}
}
((EditText) findViewById(R.id.me_version)).setText(String
.valueOf(version));
((EditText) findViewById(R.id.me_name)).setText(destinationName);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manifest_editor);
// Handle the validations
Button validate = (Button) findViewById(R.id.me_validate);
validate.setOnClickListener(this);
Intent intent = getIntent();
String filename = intent.getStringExtra("fileName");
CharSequence destinationName = filename;
int version = 1;
if (filename != null && filename.toLowerCase().endsWith(".apk")) {
PackageManager pm = this.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(RhizomeUtils.dirRhizome
+ "/" + filename, 0);
if (info != null) {
version = info.versionCode;
// see http://code.google.com/p/android/issues/detail?id=9151
if (info.applicationInfo.sourceDir == null)
info.applicationInfo.sourceDir = filename;
if (info.applicationInfo.publicSourceDir == null)
info.applicationInfo.publicSourceDir = filename;
CharSequence label = info.applicationInfo.loadLabel(pm);
if (label != null && !"".equals(label))
destinationName = label + ".apk";
else
destinationName = info.packageName + ".apk";
}
}
((EditText) findViewById(R.id.me_version)).setText(String
.valueOf(version));
((EditText) findViewById(R.id.me_name)).setText(destinationName);
}
|
diff --git a/src/to/joe/j2mc/fun/command/ClearInventoryCommand.java b/src/to/joe/j2mc/fun/command/ClearInventoryCommand.java
index c1a0e18..071c539 100644
--- a/src/to/joe/j2mc/fun/command/ClearInventoryCommand.java
+++ b/src/to/joe/j2mc/fun/command/ClearInventoryCommand.java
@@ -1,48 +1,48 @@
package to.joe.j2mc.fun.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
import to.joe.j2mc.core.J2MC_Manager;
import to.joe.j2mc.core.command.MasterCommand;
import to.joe.j2mc.core.exceptions.BadPlayerMatchException;
import to.joe.j2mc.fun.J2MC_Fun;
public class ClearInventoryCommand extends MasterCommand {
J2MC_Fun plugin;
public ClearInventoryCommand(J2MC_Fun plugin) {
super(plugin);
this.plugin = plugin;
}
@Override
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
Player target = null;
if (isPlayer && (args.length == 0)) {
target = player;
player.sendMessage(ChatColor.RED + "Inventory emptied");
this.plugin.getLogger().info(ChatColor.RED + player.getName() + " emptied inventory");
} else if ((args.length == 1) && (!isPlayer || J2MC_Manager.getPermissions().hasFlag(player.getName(), 'a'))) {
try {
target = J2MC_Manager.getVisibility().getPlayer(args[0], null);
} catch (final BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return;
}
- this.plugin.getLogger().info(ChatColor.RED + player.getName() + " emptied inventory of " + target.getName());
+ this.plugin.getLogger().info(ChatColor.RED + sender.getName() + " emptied inventory of " + target.getName());
}
if (target != null) {
final PlayerInventory targetInventory = target.getInventory();
targetInventory.clear(36);
targetInventory.clear(37);
targetInventory.clear(38);
targetInventory.clear(39);
targetInventory.clear();
}
}
}
| true | true | public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
Player target = null;
if (isPlayer && (args.length == 0)) {
target = player;
player.sendMessage(ChatColor.RED + "Inventory emptied");
this.plugin.getLogger().info(ChatColor.RED + player.getName() + " emptied inventory");
} else if ((args.length == 1) && (!isPlayer || J2MC_Manager.getPermissions().hasFlag(player.getName(), 'a'))) {
try {
target = J2MC_Manager.getVisibility().getPlayer(args[0], null);
} catch (final BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return;
}
this.plugin.getLogger().info(ChatColor.RED + player.getName() + " emptied inventory of " + target.getName());
}
if (target != null) {
final PlayerInventory targetInventory = target.getInventory();
targetInventory.clear(36);
targetInventory.clear(37);
targetInventory.clear(38);
targetInventory.clear(39);
targetInventory.clear();
}
}
| public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
Player target = null;
if (isPlayer && (args.length == 0)) {
target = player;
player.sendMessage(ChatColor.RED + "Inventory emptied");
this.plugin.getLogger().info(ChatColor.RED + player.getName() + " emptied inventory");
} else if ((args.length == 1) && (!isPlayer || J2MC_Manager.getPermissions().hasFlag(player.getName(), 'a'))) {
try {
target = J2MC_Manager.getVisibility().getPlayer(args[0], null);
} catch (final BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return;
}
this.plugin.getLogger().info(ChatColor.RED + sender.getName() + " emptied inventory of " + target.getName());
}
if (target != null) {
final PlayerInventory targetInventory = target.getInventory();
targetInventory.clear(36);
targetInventory.clear(37);
targetInventory.clear(38);
targetInventory.clear(39);
targetInventory.clear();
}
}
|
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java b/src/webapp/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java
index dec333b2d..5faba3041 100644
--- a/src/webapp/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java
+++ b/src/webapp/src/java/org/wyona/yanel/servlet/menu/impl/YanelWebsiteMenu.java
@@ -1,81 +1,81 @@
package org.wyona.yanel.servlet.menu.impl;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.TranslatableV1;
import org.wyona.yanel.core.api.attributes.VersionableV2;
import org.wyona.yanel.core.attributes.versionable.RevisionInformation;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.core.util.ResourceAttributeHelper;
import org.wyona.yanel.servlet.YanelServlet;
import org.wyona.yanel.servlet.menu.Menu;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.IdentityMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
*/
public class YanelWebsiteMenu extends Menu {
/**
* Get toolbar menus
*/
public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception {
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuffer sb= new StringBuffer();
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>");
sb.append("<ul>");
- sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New</a>   <ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li></ul></li>");
+ sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New   </a><ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li></ul></li>");
sb.append("<li class=\"haschild\">New language   <ul>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) {
TranslatableV1 translatable = (TranslatableV1)resource;
List existingLanguages = Arrays.asList(translatable.getLanguages());
String[] realmLanguages = resource.getRealm().getLanguages();
for (int i = 0; i < realmLanguages.length; i++) {
if (!existingLanguages.contains(realmLanguages[i])) {
sb.append("<li>");
sb.append(realmLanguages[i]);
sb.append("</li>");
}
}
}
//sb.append("<li>German</li><li>Mandarin</li>");
sb.append("</ul></li>");
sb.append("<li>Publish</li>");
sb.append("</ul>");
sb.append("</li></ul>");
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>");
sb.append("<li class=\"haschild\">Open with   <ul><li>Source editor</li><li>WYSIWYG editor</li></ul></li>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions();
if (revisions != null && revisions.length > 0) {
sb.append("<li class=\"haschild\">Revisions   <ul>");
for (int i = 0; i < revisions.length; i++) {
sb.append("<li class=\"haschild\">"+revisions[i].getName()+"   <ul><li><a href=\"?yanel.resource.revision=" + revisions[i].getName() + "\">View</a></li><li>Show diff</li><li>Revert to</li></ul></li>");
}
sb.append("</ul></li>");
}
}
sb.append("</ul>");
sb.append("</li></ul>");
return sb.toString();
}
}
| true | true | public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception {
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuffer sb= new StringBuffer();
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>");
sb.append("<ul>");
sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New</a>   <ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li></ul></li>");
sb.append("<li class=\"haschild\">New language   <ul>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) {
TranslatableV1 translatable = (TranslatableV1)resource;
List existingLanguages = Arrays.asList(translatable.getLanguages());
String[] realmLanguages = resource.getRealm().getLanguages();
for (int i = 0; i < realmLanguages.length; i++) {
if (!existingLanguages.contains(realmLanguages[i])) {
sb.append("<li>");
sb.append(realmLanguages[i]);
sb.append("</li>");
}
}
}
//sb.append("<li>German</li><li>Mandarin</li>");
sb.append("</ul></li>");
sb.append("<li>Publish</li>");
sb.append("</ul>");
sb.append("</li></ul>");
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>");
sb.append("<li class=\"haschild\">Open with   <ul><li>Source editor</li><li>WYSIWYG editor</li></ul></li>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions();
if (revisions != null && revisions.length > 0) {
sb.append("<li class=\"haschild\">Revisions   <ul>");
for (int i = 0; i < revisions.length; i++) {
sb.append("<li class=\"haschild\">"+revisions[i].getName()+"   <ul><li><a href=\"?yanel.resource.revision=" + revisions[i].getName() + "\">View</a></li><li>Show diff</li><li>Revert to</li></ul></li>");
}
sb.append("</ul></li>");
}
}
sb.append("</ul>");
sb.append("</li></ul>");
return sb.toString();
}
| public String getMenus(Resource resource, HttpServletRequest request, Map map, String reservedPrefix) throws ServletException, IOException, Exception {
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(resource.getPath());
StringBuffer sb= new StringBuffer();
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">File</div>");
sb.append("<ul>");
sb.append("<li class=\"haschild\"><a href=\"" + backToRealm + "create-new-page.html\">New   </a><ul><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Axml\">Standard page (XHTML)</a></li><li><a href=\"" + backToRealm + "create-new-page.html?resource-type=http%3A%2F%2Fwww.wyona.org%2Fyanel%2Fresource%2F1.0%3A%3Awiki\">Wiki page</a></li></ul></li>");
sb.append("<li class=\"haschild\">New language   <ul>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Translatable", "1")) {
TranslatableV1 translatable = (TranslatableV1)resource;
List existingLanguages = Arrays.asList(translatable.getLanguages());
String[] realmLanguages = resource.getRealm().getLanguages();
for (int i = 0; i < realmLanguages.length; i++) {
if (!existingLanguages.contains(realmLanguages[i])) {
sb.append("<li>");
sb.append(realmLanguages[i]);
sb.append("</li>");
}
}
}
//sb.append("<li>German</li><li>Mandarin</li>");
sb.append("</ul></li>");
sb.append("<li>Publish</li>");
sb.append("</ul>");
sb.append("</li></ul>");
sb.append("<ul><li>");
sb.append("<div id=\"yaneltoolbar_menutitle\">Edit</div><ul>");
sb.append("<li class=\"haschild\">Open with   <ul><li>Source editor</li><li>WYSIWYG editor</li></ul></li>");
if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Versionable", "2")) {
RevisionInformation[] revisions = ((VersionableV2) resource).getRevisions();
if (revisions != null && revisions.length > 0) {
sb.append("<li class=\"haschild\">Revisions   <ul>");
for (int i = 0; i < revisions.length; i++) {
sb.append("<li class=\"haschild\">"+revisions[i].getName()+"   <ul><li><a href=\"?yanel.resource.revision=" + revisions[i].getName() + "\">View</a></li><li>Show diff</li><li>Revert to</li></ul></li>");
}
sb.append("</ul></li>");
}
}
sb.append("</ul>");
sb.append("</li></ul>");
return sb.toString();
}
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetPanel.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetPanel.java
index ab2b84615..78e769463 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetPanel.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/PatchSetPanel.java
@@ -1,311 +1,314 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import com.google.gerrit.client.FormatUtil;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.AccountDashboardLink;
import com.google.gerrit.common.data.ChangeDetail;
import com.google.gerrit.common.data.PatchSetDetail;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.Branch;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.ChangeMessage;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gerrit.reviewdb.PatchSetInfo;
import com.google.gerrit.reviewdb.Project;
import com.google.gerrit.reviewdb.UserIdentity;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.clippy.client.CopyableLabel;
import java.util.Collections;
import java.util.Set;
class PatchSetPanel extends Composite implements OpenHandler<DisclosurePanel> {
private static final int R_AUTHOR = 0;
private static final int R_COMMITTER = 1;
private static final int R_DOWNLOAD = 2;
private static final int R_CNT = 3;
private final ChangeScreen changeScreen;
private final ChangeDetail changeDetail;
private final PatchSet patchSet;
private final FlowPanel body;
private Grid infoTable;
private Panel actionsPanel;
private PatchTable patchTable;
PatchSetPanel(final ChangeScreen parent, final ChangeDetail detail,
final PatchSet ps) {
changeScreen = parent;
changeDetail = detail;
patchSet = ps;
body = new FlowPanel();
initWidget(body);
}
/**
* Display the table showing the Author, Committer and Download links,
* followed by the action buttons.
*/
public void ensureLoaded(final PatchSetDetail detail) {
infoTable = new Grid(R_CNT, 2);
infoTable.setStyleName("gerrit-InfoBlock");
infoTable.addStyleName("gerrit-PatchSetInfoBlock");
initRow(R_AUTHOR, Util.C.patchSetInfoAuthor());
initRow(R_COMMITTER, Util.C.patchSetInfoCommitter());
initRow(R_DOWNLOAD, Util.C.patchSetInfoDownload());
final CellFormatter itfmt = infoTable.getCellFormatter();
itfmt.addStyleName(0, 0, "topmost");
itfmt.addStyleName(0, 1, "topmost");
itfmt.addStyleName(R_CNT - 1, 0, "bottomheader");
itfmt.addStyleName(R_AUTHOR, 1, "useridentity");
itfmt.addStyleName(R_COMMITTER, 1, "useridentity");
itfmt.addStyleName(R_DOWNLOAD, 1, "command");
final PatchSetInfo info = detail.getInfo();
displayUserIdentity(R_AUTHOR, info.getAuthor());
displayUserIdentity(R_COMMITTER, info.getCommitter());
displayDownload();
patchTable = new PatchTable();
patchTable.setSavePointerId("PatchTable " + patchSet.getId());
patchTable.display(info.getKey(), detail.getPatches());
body.add(infoTable);
actionsPanel = new FlowPanel();
actionsPanel.setStyleName("gerrit-PatchSetActions");
body.add(actionsPanel);
if (Gerrit.isSignedIn()) {
populateCommentAction();
if (changeDetail.isCurrentPatchSet(detail)) {
populateActions(detail);
}
}
body.add(patchTable);
}
private void displayDownload() {
final Branch.NameKey branchKey = changeDetail.getChange().getDest();
final Project.NameKey projectKey = changeDetail.getChange().getProject();
final String projectName = projectKey.get();
final FlowPanel downloads = new FlowPanel();
if (Gerrit.getConfig().isUseRepoDownload()) {
// This site prefers usage of the 'repo' tool, so suggest
// that for easy fetch.
//
final StringBuilder r = new StringBuilder();
r.append("repo download ");
r.append(projectName);
r.append(" ");
r.append(changeDetail.getChange().getChangeId());
r.append("/");
r.append(patchSet.getPatchSetId());
downloads.add(new CopyableLabel(r.toString()));
}
if (changeDetail.isAllowsAnonymous()
&& Gerrit.getConfig().getGitDaemonUrl() != null) {
// Anonymous Git is claimed to be available, and this project
// isn't secured. The anonymous Git daemon will be much more
// efficient than our own SSH daemon, so prefer offering it.
//
final StringBuilder r = new StringBuilder();
r.append("git pull ");
r.append(Gerrit.getConfig().getGitDaemonUrl());
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
downloads.add(new CopyableLabel(r.toString()));
} else if (Gerrit.isSignedIn() && Gerrit.getUserAccount() != null
&& Gerrit.getConfig().getSshdAddress() != null
&& Gerrit.getUserAccount().getSshUserName() != null
&& Gerrit.getUserAccount().getSshUserName().length() > 0) {
// The user is signed in and anonymous access isn't allowed.
// Use our SSH daemon URL as its the only way they can get
// to the project (that we know of anyway).
//
- final String sshAddr = Gerrit.getConfig().getSshdAddress();
+ String sshAddr = Gerrit.getConfig().getSshdAddress();
final StringBuilder r = new StringBuilder();
r.append("git pull ssh://");
r.append(Gerrit.getUserAccount().getSshUserName());
r.append("@");
if (sshAddr.startsWith("*:") || "".equals(sshAddr)) {
r.append(Window.Location.getHostName());
}
+ if (sshAddr.startsWith("*")) {
+ sshAddr = sshAddr.substring(1);
+ }
r.append(sshAddr);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
downloads.add(new CopyableLabel(r.toString()));
}
infoTable.setWidget(R_DOWNLOAD, 1, downloads);
}
private void displayUserIdentity(final int row, final UserIdentity who) {
if (who == null) {
infoTable.clearCell(row, 1);
return;
}
final FlowPanel fp = new FlowPanel();
fp.setStyleName("gerrit-PatchSetUserIdentity");
if (who.getName() != null) {
final Account.Id aId = who.getAccount();
if (aId != null) {
fp.add(new AccountDashboardLink(who.getName(), aId));
} else {
final InlineLabel lbl = new InlineLabel(who.getName());
lbl.setStyleName("gerrit-AccountName");
fp.add(lbl);
}
}
if (who.getEmail() != null) {
fp.add(new InlineLabel("<" + who.getEmail() + ">"));
}
if (who.getDate() != null) {
fp.add(new InlineLabel(FormatUtil.mediumFormat(who.getDate())));
}
infoTable.setWidget(row, 1, fp);
}
private void populateActions(final PatchSetDetail detail) {
final boolean isOpen = changeDetail.getChange().getStatus().isOpen();
Set<ApprovalCategory.Id> allowed = changeDetail.getCurrentActions();
if (allowed == null) {
allowed = Collections.emptySet();
}
if (isOpen && allowed.contains(ApprovalCategory.SUBMIT)) {
final Button b =
new Button(Util.M
.submitPatchSet(detail.getPatchSet().getPatchSetId()));
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
b.setEnabled(false);
Util.MANAGE_SVC.submit(patchSet.getId(),
new GerritCallback<ChangeDetail>() {
public void onSuccess(ChangeDetail result) {
onSubmitResult(result);
}
@Override
public void onFailure(Throwable caught) {
b.setEnabled(true);
super.onFailure(caught);
}
});
}
});
actionsPanel.add(b);
}
if (changeDetail.canAbandon()) {
final Button b = new Button(Util.C.buttonAbandonChangeBegin());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
new AbandonChangeDialog(patchSet.getId(),
new AsyncCallback<ChangeDetail>() {
public void onSuccess(ChangeDetail result) {
changeScreen.display(result);
}
public void onFailure(Throwable caught) {
b.setEnabled(true);
}
}).center();
}
});
actionsPanel.add(b);
}
}
private void populateCommentAction() {
final Button b = new Button(Util.C.buttonPublishCommentsBegin());
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
Gerrit.display("change,publish," + patchSet.getId().toString(),
new PublishCommentScreen(patchSet.getId()));
}
});
actionsPanel.add(b);
}
@Override
public void onOpen(final OpenEvent<DisclosurePanel> event) {
if (infoTable == null) {
Util.DETAIL_SVC.patchSetDetail(patchSet.getId(),
new GerritCallback<PatchSetDetail>() {
public void onSuccess(final PatchSetDetail result) {
ensureLoaded(result);
}
});
}
}
private void initRow(final int row, final String name) {
infoTable.setText(row, 0, name);
infoTable.getCellFormatter().addStyleName(row, 0, "header");
}
private void onSubmitResult(final ChangeDetail result) {
if (result.getChange().getStatus() == Change.Status.NEW) {
// The submit failed. Try to locate the message and display
// it to the user, it should be the last one created by Gerrit.
//
ChangeMessage msg = null;
if (result.getMessages() != null && result.getMessages().size() > 0) {
for (int i = result.getMessages().size() - 1; i >= 0; i--) {
if (result.getMessages().get(i).getAuthor() == null) {
msg = result.getMessages().get(i);
break;
}
}
}
if (msg != null) {
new SubmitFailureDialog(result, msg).center();
}
}
changeScreen.display(result);
}
}
| false | true | private void displayDownload() {
final Branch.NameKey branchKey = changeDetail.getChange().getDest();
final Project.NameKey projectKey = changeDetail.getChange().getProject();
final String projectName = projectKey.get();
final FlowPanel downloads = new FlowPanel();
if (Gerrit.getConfig().isUseRepoDownload()) {
// This site prefers usage of the 'repo' tool, so suggest
// that for easy fetch.
//
final StringBuilder r = new StringBuilder();
r.append("repo download ");
r.append(projectName);
r.append(" ");
r.append(changeDetail.getChange().getChangeId());
r.append("/");
r.append(patchSet.getPatchSetId());
downloads.add(new CopyableLabel(r.toString()));
}
if (changeDetail.isAllowsAnonymous()
&& Gerrit.getConfig().getGitDaemonUrl() != null) {
// Anonymous Git is claimed to be available, and this project
// isn't secured. The anonymous Git daemon will be much more
// efficient than our own SSH daemon, so prefer offering it.
//
final StringBuilder r = new StringBuilder();
r.append("git pull ");
r.append(Gerrit.getConfig().getGitDaemonUrl());
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
downloads.add(new CopyableLabel(r.toString()));
} else if (Gerrit.isSignedIn() && Gerrit.getUserAccount() != null
&& Gerrit.getConfig().getSshdAddress() != null
&& Gerrit.getUserAccount().getSshUserName() != null
&& Gerrit.getUserAccount().getSshUserName().length() > 0) {
// The user is signed in and anonymous access isn't allowed.
// Use our SSH daemon URL as its the only way they can get
// to the project (that we know of anyway).
//
final String sshAddr = Gerrit.getConfig().getSshdAddress();
final StringBuilder r = new StringBuilder();
r.append("git pull ssh://");
r.append(Gerrit.getUserAccount().getSshUserName());
r.append("@");
if (sshAddr.startsWith("*:") || "".equals(sshAddr)) {
r.append(Window.Location.getHostName());
}
r.append(sshAddr);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
downloads.add(new CopyableLabel(r.toString()));
}
infoTable.setWidget(R_DOWNLOAD, 1, downloads);
}
| private void displayDownload() {
final Branch.NameKey branchKey = changeDetail.getChange().getDest();
final Project.NameKey projectKey = changeDetail.getChange().getProject();
final String projectName = projectKey.get();
final FlowPanel downloads = new FlowPanel();
if (Gerrit.getConfig().isUseRepoDownload()) {
// This site prefers usage of the 'repo' tool, so suggest
// that for easy fetch.
//
final StringBuilder r = new StringBuilder();
r.append("repo download ");
r.append(projectName);
r.append(" ");
r.append(changeDetail.getChange().getChangeId());
r.append("/");
r.append(patchSet.getPatchSetId());
downloads.add(new CopyableLabel(r.toString()));
}
if (changeDetail.isAllowsAnonymous()
&& Gerrit.getConfig().getGitDaemonUrl() != null) {
// Anonymous Git is claimed to be available, and this project
// isn't secured. The anonymous Git daemon will be much more
// efficient than our own SSH daemon, so prefer offering it.
//
final StringBuilder r = new StringBuilder();
r.append("git pull ");
r.append(Gerrit.getConfig().getGitDaemonUrl());
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
downloads.add(new CopyableLabel(r.toString()));
} else if (Gerrit.isSignedIn() && Gerrit.getUserAccount() != null
&& Gerrit.getConfig().getSshdAddress() != null
&& Gerrit.getUserAccount().getSshUserName() != null
&& Gerrit.getUserAccount().getSshUserName().length() > 0) {
// The user is signed in and anonymous access isn't allowed.
// Use our SSH daemon URL as its the only way they can get
// to the project (that we know of anyway).
//
String sshAddr = Gerrit.getConfig().getSshdAddress();
final StringBuilder r = new StringBuilder();
r.append("git pull ssh://");
r.append(Gerrit.getUserAccount().getSshUserName());
r.append("@");
if (sshAddr.startsWith("*:") || "".equals(sshAddr)) {
r.append(Window.Location.getHostName());
}
if (sshAddr.startsWith("*")) {
sshAddr = sshAddr.substring(1);
}
r.append(sshAddr);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
downloads.add(new CopyableLabel(r.toString()));
}
infoTable.setWidget(R_DOWNLOAD, 1, downloads);
}
|
diff --git a/shell/src/main/java/org/apache/karaf/cellar/shell/group/GroupPickCommand.java b/shell/src/main/java/org/apache/karaf/cellar/shell/group/GroupPickCommand.java
index a99743bf..ef26cf87 100644
--- a/shell/src/main/java/org/apache/karaf/cellar/shell/group/GroupPickCommand.java
+++ b/shell/src/main/java/org/apache/karaf/cellar/shell/group/GroupPickCommand.java
@@ -1,57 +1,61 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.cellar.shell.group;
import org.apache.karaf.cellar.core.Group;
import org.apache.karaf.cellar.core.Node;
import org.apache.karaf.cellar.core.control.ManageGroupAction;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@Command(scope = "cluster", name = "group-pick", description = "Picks a number of nodes from one cluster group and moves them into an other.")
public class GroupPickCommand extends GroupSupport {
@Argument(index = 0, name = "sourceGroupName", description = "The source cluster group name.", required = true, multiValued = false)
String sourceGroupName;
@Argument(index = 1, name = "targetGroupName", description = "The destination cluster group name.", required = true, multiValued = false)
String targetGroupName;
@Argument(index = 2, name = "count", description = "The number of nodes to transfer.", required = false, multiValued = false)
int count = 1;
@Override
protected Object doExecute() throws Exception {
Group sourceGroup = groupManager.findGroupByName(sourceGroupName);
if (sourceGroup != null) {
Set<Node> groupMembers = sourceGroup.getNodes();
+ int i = 0;
for (Node node : groupMembers) {
+ if (i >= count)
+ break;
List<String> recipients = new LinkedList<String>();
recipients.add(node.getId());
doExecute(ManageGroupAction.SET, targetGroupName, sourceGroup, recipients);
+ i++;
}
doExecute(ManageGroupAction.LIST, null, null, new ArrayList(), false);
} else System.err.println("Cannot find source group with name: " + sourceGroupName);
return null;
}
}
| false | true | protected Object doExecute() throws Exception {
Group sourceGroup = groupManager.findGroupByName(sourceGroupName);
if (sourceGroup != null) {
Set<Node> groupMembers = sourceGroup.getNodes();
for (Node node : groupMembers) {
List<String> recipients = new LinkedList<String>();
recipients.add(node.getId());
doExecute(ManageGroupAction.SET, targetGroupName, sourceGroup, recipients);
}
doExecute(ManageGroupAction.LIST, null, null, new ArrayList(), false);
} else System.err.println("Cannot find source group with name: " + sourceGroupName);
return null;
}
| protected Object doExecute() throws Exception {
Group sourceGroup = groupManager.findGroupByName(sourceGroupName);
if (sourceGroup != null) {
Set<Node> groupMembers = sourceGroup.getNodes();
int i = 0;
for (Node node : groupMembers) {
if (i >= count)
break;
List<String> recipients = new LinkedList<String>();
recipients.add(node.getId());
doExecute(ManageGroupAction.SET, targetGroupName, sourceGroup, recipients);
i++;
}
doExecute(ManageGroupAction.LIST, null, null, new ArrayList(), false);
} else System.err.println("Cannot find source group with name: " + sourceGroupName);
return null;
}
|
diff --git a/mapsforge-map/src/main/java/org/mapsforge/android/maps/mapgenerator/InMemoryTileCache.java b/mapsforge-map/src/main/java/org/mapsforge/android/maps/mapgenerator/InMemoryTileCache.java
index f16a016..c361134 100644
--- a/mapsforge-map/src/main/java/org/mapsforge/android/maps/mapgenerator/InMemoryTileCache.java
+++ b/mapsforge-map/src/main/java/org/mapsforge/android/maps/mapgenerator/InMemoryTileCache.java
@@ -1,160 +1,160 @@
/*
* Copyright 2010, 2011, 2012 mapsforge.org
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.android.maps.mapgenerator;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.util.Log;
import org.mapsforge.core.Tile;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A thread-safe cache for tile images with a fixed size and LRU policy.
*/
public class InMemoryTileCache implements TileCache {
/**
* Load factor of the internal HashMap.
*/
private static final float LOAD_FACTOR = 0.6f;
private static List<Bitmap> createBitmapPool(int poolSize) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (int i = 0; i < poolSize; ++i) {
Bitmap bitmap = Bitmap.createBitmap(Tile.TILE_SIZE, Tile.TILE_SIZE, Config.RGB_565);
bitmaps.add(bitmap);
}
return bitmaps;
}
private static Map<MapGeneratorJob, Bitmap> createMap(final int mapCapacity, final List<Bitmap> bitmapPool) {
int initialCapacity = (int) (mapCapacity / LOAD_FACTOR) + 2;
return new LinkedHashMap<MapGeneratorJob, Bitmap>(initialCapacity, LOAD_FACTOR, true) {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(Map.Entry<MapGeneratorJob, Bitmap> eldestEntry) {
if (size() > mapCapacity) {
remove(eldestEntry.getKey());
bitmapPool.add(eldestEntry.getValue());
}
return false;
}
};
}
private static int getCapacity(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity must not be negative: " + capacity);
}
return capacity;
}
private final List<Bitmap> bitmapPool;
private final ByteBuffer byteBuffer;
private final int capacity;
private final Map<MapGeneratorJob, Bitmap> map;
/**
* @param capacity
* the maximum number of entries in this cache.
* @throws IllegalArgumentException
* if the capacity is negative.
*/
public InMemoryTileCache(int capacity) {
this.capacity = getCapacity(capacity);
this.bitmapPool = createBitmapPool(this.capacity + 1);
this.map = createMap(this.capacity, this.bitmapPool);
this.byteBuffer = ByteBuffer.allocate(Tile.TILE_SIZE_IN_BYTES);
}
@Override
public boolean containsKey(MapGeneratorJob mapGeneratorJob) {
synchronized (this.map) {
return this.map.containsKey(mapGeneratorJob);
}
}
@Override
public void destroy() {
synchronized (this.map) {
for (Bitmap bitmap : this.map.values()) {
bitmap.recycle();
}
this.map.clear();
for (Bitmap bitmap : this.bitmapPool) {
bitmap.recycle();
}
this.bitmapPool.clear();
}
}
@Override
public Bitmap get(MapGeneratorJob mapGeneratorJob) {
synchronized (this.map) {
return this.map.get(mapGeneratorJob);
}
}
@Override
public int getCapacity() {
return this.capacity;
}
@Override
public boolean isPersistent() {
return false;
}
@Override
public void put(MapGeneratorJob mapGeneratorJob, Bitmap bitmap) {
if (this.capacity == 0) {
return;
}
synchronized (this.map) {
if (this.bitmapPool.isEmpty()) {
return;
}
Bitmap pooledBitmap = this.bitmapPool.remove(this.bitmapPool.size() - 1);
+ this.byteBuffer.rewind();
bitmap.copyPixelsToBuffer(this.byteBuffer);
- Log.d("ToureNPlaner","Buffer bytes written: "+this.byteBuffer.position()+" calculated bytes: "+2*Tile.TILE_SIZE);
- this.byteBuffer.rewind();
+ this.byteBuffer.rewind();
pooledBitmap.copyPixelsFromBuffer(this.byteBuffer);
this.map.put(mapGeneratorJob, pooledBitmap);
}
}
@Override
public void setCapacity(int capacity) {
throw new UnsupportedOperationException();
}
@Override
public void setPersistent(boolean persistent) {
throw new UnsupportedOperationException();
}
}
| false | true | public void put(MapGeneratorJob mapGeneratorJob, Bitmap bitmap) {
if (this.capacity == 0) {
return;
}
synchronized (this.map) {
if (this.bitmapPool.isEmpty()) {
return;
}
Bitmap pooledBitmap = this.bitmapPool.remove(this.bitmapPool.size() - 1);
bitmap.copyPixelsToBuffer(this.byteBuffer);
Log.d("ToureNPlaner","Buffer bytes written: "+this.byteBuffer.position()+" calculated bytes: "+2*Tile.TILE_SIZE);
this.byteBuffer.rewind();
pooledBitmap.copyPixelsFromBuffer(this.byteBuffer);
this.map.put(mapGeneratorJob, pooledBitmap);
}
}
| public void put(MapGeneratorJob mapGeneratorJob, Bitmap bitmap) {
if (this.capacity == 0) {
return;
}
synchronized (this.map) {
if (this.bitmapPool.isEmpty()) {
return;
}
Bitmap pooledBitmap = this.bitmapPool.remove(this.bitmapPool.size() - 1);
this.byteBuffer.rewind();
bitmap.copyPixelsToBuffer(this.byteBuffer);
this.byteBuffer.rewind();
pooledBitmap.copyPixelsFromBuffer(this.byteBuffer);
this.map.put(mapGeneratorJob, pooledBitmap);
}
}
|
diff --git a/src/main/java/br/octahedron/straight/controller/ControllerChecker.java b/src/main/java/br/octahedron/straight/controller/ControllerChecker.java
index 4d309d1..5512776 100644
--- a/src/main/java/br/octahedron/straight/controller/ControllerChecker.java
+++ b/src/main/java/br/octahedron/straight/controller/ControllerChecker.java
@@ -1,84 +1,85 @@
/*
* Straight - A system to manage financial demands for small and decentralized
* organizations.
* Copyright (C) 2011 Octahedron
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package br.octahedron.straight.controller;
import static br.octahedron.straight.controller.ControllerFilter.APPLICATION_DOMAIN;
import static br.octahedron.straight.controller.ControllerFilter.BARRA;
import java.util.logging.Logger;
import br.octahedron.commons.database.NamespaceCommons;
import br.octahedron.straight.modules.ManagerBuilder;
import br.octahedron.straight.modules.Module;
import br.octahedron.straight.modules.ModuleSpec;
import br.octahedron.straight.modules.authorization.manager.AuthorizationManager;
import br.octahedron.straight.modules.users.manager.UsersManager;
/**
* @author danilo
*
*/
public class ControllerChecker {
private static final Logger logger = Logger.getLogger(ControllerChecker.class.getName());
private final UsersManager usersManager = (UsersManager) ManagerBuilder.getUserManager();
private final AuthorizationManager authorizationManager = (AuthorizationManager) ManagerBuilder.getAuthorizationManager();
/**
* @throws NotAuthorizedException
*
*/
public void check(String domain, String email, String moduleName, String action) throws NotFoundException, NotLoggedException,
InexistentAccountException, NotAuthorizedException {
logger.info(">>>" + domain + " : " + email + " : " + moduleName + " : " + action);
try {
if (APPLICATION_DOMAIN.equals(domain) && BARRA.equals(moduleName)) {
moduleName = Module.USER.name();
} else if (BARRA.equals(moduleName)) {
- moduleName = Module.CONFIGURATION.name();
+ moduleName = Module.DOMAIN.name();
}
Module module = Module.valueOf(moduleName);
ModuleSpec spec = module.getModuleSpec();
// checks authentication needs
if (spec.needsAuthentication(action)) {
if (email == null && !action.isEmpty()) {
throw new NotLoggedException();
- } else if (email != null && !this.usersManager.existsUser(email) && !"USER_NEW".equals(action)) {
+ } else if (email != null && !this.usersManager.existsUser(email) &&
+ !"USER_NEW".equals(action) && !"USER_CREATE".equals(action)) {
throw new InexistentAccountException();
}
}
// checks authorization
// TODO: "USER_NEW".equals(action) deve lançar exceção
if (spec.needsAuthorization(action)) {
if (!this.authorizationManager.isAuthorized(domain, email, action)) {
throw new NotAuthorizedException();
}
}
if (spec.usesDomainNamespace()) {
NamespaceCommons.changeToNamespace(domain);
}
} catch (IllegalArgumentException e) {
throw new NotFoundException(moduleName);
}
}
}
| false | true | public void check(String domain, String email, String moduleName, String action) throws NotFoundException, NotLoggedException,
InexistentAccountException, NotAuthorizedException {
logger.info(">>>" + domain + " : " + email + " : " + moduleName + " : " + action);
try {
if (APPLICATION_DOMAIN.equals(domain) && BARRA.equals(moduleName)) {
moduleName = Module.USER.name();
} else if (BARRA.equals(moduleName)) {
moduleName = Module.CONFIGURATION.name();
}
Module module = Module.valueOf(moduleName);
ModuleSpec spec = module.getModuleSpec();
// checks authentication needs
if (spec.needsAuthentication(action)) {
if (email == null && !action.isEmpty()) {
throw new NotLoggedException();
} else if (email != null && !this.usersManager.existsUser(email) && !"USER_NEW".equals(action)) {
throw new InexistentAccountException();
}
}
// checks authorization
// TODO: "USER_NEW".equals(action) deve lançar exceção
if (spec.needsAuthorization(action)) {
if (!this.authorizationManager.isAuthorized(domain, email, action)) {
throw new NotAuthorizedException();
}
}
if (spec.usesDomainNamespace()) {
NamespaceCommons.changeToNamespace(domain);
}
} catch (IllegalArgumentException e) {
throw new NotFoundException(moduleName);
}
}
| public void check(String domain, String email, String moduleName, String action) throws NotFoundException, NotLoggedException,
InexistentAccountException, NotAuthorizedException {
logger.info(">>>" + domain + " : " + email + " : " + moduleName + " : " + action);
try {
if (APPLICATION_DOMAIN.equals(domain) && BARRA.equals(moduleName)) {
moduleName = Module.USER.name();
} else if (BARRA.equals(moduleName)) {
moduleName = Module.DOMAIN.name();
}
Module module = Module.valueOf(moduleName);
ModuleSpec spec = module.getModuleSpec();
// checks authentication needs
if (spec.needsAuthentication(action)) {
if (email == null && !action.isEmpty()) {
throw new NotLoggedException();
} else if (email != null && !this.usersManager.existsUser(email) &&
!"USER_NEW".equals(action) && !"USER_CREATE".equals(action)) {
throw new InexistentAccountException();
}
}
// checks authorization
// TODO: "USER_NEW".equals(action) deve lançar exceção
if (spec.needsAuthorization(action)) {
if (!this.authorizationManager.isAuthorized(domain, email, action)) {
throw new NotAuthorizedException();
}
}
if (spec.usesDomainNamespace()) {
NamespaceCommons.changeToNamespace(domain);
}
} catch (IllegalArgumentException e) {
throw new NotFoundException(moduleName);
}
}
|
diff --git a/src/uniol/apt/analysis/synet/SynetSynthesizeDistributedLTS.java b/src/uniol/apt/analysis/synet/SynetSynthesizeDistributedLTS.java
index 12424ce6..7714bca3 100644
--- a/src/uniol/apt/analysis/synet/SynetSynthesizeDistributedLTS.java
+++ b/src/uniol/apt/analysis/synet/SynetSynthesizeDistributedLTS.java
@@ -1,202 +1,202 @@
/*-
* APT - Analysis of Petri Nets and labeled Transition systems
* Copyright (C) 2012-2013 Members of the project group APT
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package uniol.apt.analysis.synet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Set;
import uniol.apt.adt.pn.PetriNet;
import uniol.apt.adt.ts.Arc;
import uniol.apt.adt.ts.TransitionSystem;
import uniol.apt.io.parser.impl.exception.FormatException;
import uniol.apt.io.parser.impl.synet.SynetPNParser;
import uniol.apt.io.renderer.impl.SynetRenderer;
import uniol.apt.module.exception.SynetNotFoundException;
/**
* Creates to a given labeled transition system a petrinet with locations.
*
* @author Sören
*
*/
public class SynetSynthesizeDistributedLTS {
private TransitionSystem ts_;
private PetriNet pn_;
private String errorMsg_;
private String separationErrorMsg_;
private boolean location_;
public SynetSynthesizeDistributedLTS(TransitionSystem ts) {
ts_ = ts;
location_ = false;
}
/**
* Check if the given labeled transition system is synthesizable by Synet.
*
* @return <true> if synthesizable.
* @throws SynetNotFoundException
* @throws IOException
* @throws FormatException
*/
public boolean check() throws SynetNotFoundException, IOException, FormatException {
SynetRenderer synetRen = new SynetRenderer();
String ltsSynetFormat = synetRen.render(ts_);
File tmpAutFile = File.createTempFile("synetAut", ".aut");
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpAutFile));
bw.write(ltsSynetFormat);
bw.close();
File tmpDisFile = File.createTempFile("synetDis", ".dis");
BufferedWriter bw2 = new BufferedWriter(new FileWriter(tmpDisFile));
bw2.write(getDisString());
bw2.close();
File tmpSaveFile = File.createTempFile("synetNet", ".net");
Process p;// -r uses a new algorithm -o creates an output file -d is the
// option for distributed nets with locations
if (location_) {
try {
p = new ProcessBuilder("synet", "-r", "-o", tmpSaveFile.getAbsolutePath(), "-d",
tmpDisFile.getAbsolutePath(), tmpAutFile.getAbsolutePath()).start();
} catch (Exception e) {
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
throw new SynetNotFoundException();
}
} else {
try {
p = new ProcessBuilder("synet", "-r", "-o", tmpSaveFile.getAbsolutePath(), tmpAutFile.getAbsolutePath())
.start();
} catch (Exception e) {
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
throw new SynetNotFoundException();
}
}
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
- if(line.contains("failures") || line.contains("separated")) {
+ if(line.contains("failures") || line.contains("not separated")) {
if(separationErrorMsg_ == null)
separationErrorMsg_ = "";
separationErrorMsg_ += line + "\n";
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pn_ = SynetPNParser.getPetriNet(new FileInputStream(tmpSaveFile.getAbsolutePath()));
String errorStr = error.readLine();
if (errorStr != null) {
errorMsg_ = errorStr;
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
return false;
}
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
return true;
}
/**
* Deletes the created files.
*
* @param tmpSaveFile
* @param tmpDisFile
* @param tmpAutFile
*/
private void deleteCreatedFiles(File tmpAutFile, File tmpDisFile, File tmpSaveFile) {
tmpAutFile.delete();
tmpDisFile.delete();
tmpSaveFile.delete();
}
/**
* Creates a String with locations out of the Apt-format into Synet-format.
*
* @return Location String in .dis-format.
*/
private String getDisString() {
StringBuilder sb = new StringBuilder();
ArrayList<String> labelMem = new ArrayList<String>(0);
Set<Arc> edges = ts_.getEdges();
for (Arc e : edges) {
try {
if (e.getExtension("location") != null && !labelMem.contains(e.getLabel())) {
sb.append("(" + e.getLabel() + "," + e.getExtension("location").toString().replace("\"", "") + ")");
sb.append("\n");
labelMem.add(e.getLabel());
location_ = true;
}
} catch (Exception ex) {
}
}
return sb.toString();
}
/**
* Returns a petrinet which is synthesized out of an location file and an
* labeled transition system by Synet.
*
* @return PetriNet
*/
public PetriNet getPN() {
return pn_;
}
/**
* Error string, created by Synet.
*
* @return String
*/
public String getError() {
return errorMsg_;
}
/**
* Separation error string, created by Synet.
*
* @return String
*/
public String getSeparationError() {
return separationErrorMsg_;
}
}
// vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
| true | true | public boolean check() throws SynetNotFoundException, IOException, FormatException {
SynetRenderer synetRen = new SynetRenderer();
String ltsSynetFormat = synetRen.render(ts_);
File tmpAutFile = File.createTempFile("synetAut", ".aut");
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpAutFile));
bw.write(ltsSynetFormat);
bw.close();
File tmpDisFile = File.createTempFile("synetDis", ".dis");
BufferedWriter bw2 = new BufferedWriter(new FileWriter(tmpDisFile));
bw2.write(getDisString());
bw2.close();
File tmpSaveFile = File.createTempFile("synetNet", ".net");
Process p;// -r uses a new algorithm -o creates an output file -d is the
// option for distributed nets with locations
if (location_) {
try {
p = new ProcessBuilder("synet", "-r", "-o", tmpSaveFile.getAbsolutePath(), "-d",
tmpDisFile.getAbsolutePath(), tmpAutFile.getAbsolutePath()).start();
} catch (Exception e) {
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
throw new SynetNotFoundException();
}
} else {
try {
p = new ProcessBuilder("synet", "-r", "-o", tmpSaveFile.getAbsolutePath(), tmpAutFile.getAbsolutePath())
.start();
} catch (Exception e) {
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
throw new SynetNotFoundException();
}
}
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
if(line.contains("failures") || line.contains("separated")) {
if(separationErrorMsg_ == null)
separationErrorMsg_ = "";
separationErrorMsg_ += line + "\n";
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pn_ = SynetPNParser.getPetriNet(new FileInputStream(tmpSaveFile.getAbsolutePath()));
String errorStr = error.readLine();
if (errorStr != null) {
errorMsg_ = errorStr;
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
return false;
}
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
return true;
}
| public boolean check() throws SynetNotFoundException, IOException, FormatException {
SynetRenderer synetRen = new SynetRenderer();
String ltsSynetFormat = synetRen.render(ts_);
File tmpAutFile = File.createTempFile("synetAut", ".aut");
BufferedWriter bw = new BufferedWriter(new FileWriter(tmpAutFile));
bw.write(ltsSynetFormat);
bw.close();
File tmpDisFile = File.createTempFile("synetDis", ".dis");
BufferedWriter bw2 = new BufferedWriter(new FileWriter(tmpDisFile));
bw2.write(getDisString());
bw2.close();
File tmpSaveFile = File.createTempFile("synetNet", ".net");
Process p;// -r uses a new algorithm -o creates an output file -d is the
// option for distributed nets with locations
if (location_) {
try {
p = new ProcessBuilder("synet", "-r", "-o", tmpSaveFile.getAbsolutePath(), "-d",
tmpDisFile.getAbsolutePath(), tmpAutFile.getAbsolutePath()).start();
} catch (Exception e) {
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
throw new SynetNotFoundException();
}
} else {
try {
p = new ProcessBuilder("synet", "-r", "-o", tmpSaveFile.getAbsolutePath(), tmpAutFile.getAbsolutePath())
.start();
} catch (Exception e) {
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
throw new SynetNotFoundException();
}
}
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
if(line.contains("failures") || line.contains("not separated")) {
if(separationErrorMsg_ == null)
separationErrorMsg_ = "";
separationErrorMsg_ += line + "\n";
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pn_ = SynetPNParser.getPetriNet(new FileInputStream(tmpSaveFile.getAbsolutePath()));
String errorStr = error.readLine();
if (errorStr != null) {
errorMsg_ = errorStr;
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
return false;
}
deleteCreatedFiles(tmpAutFile, tmpDisFile, tmpSaveFile);
return true;
}
|
diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java
index 4ebbb4597..3341f95b2 100644
--- a/main/src/cgeo/geocaching/files/GPXParser.java
+++ b/main/src/cgeo/geocaching/files/GPXParser.java
@@ -1,978 +1,983 @@
package cgeo.geocaching.files;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.DataStore;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.LogEntry;
import cgeo.geocaching.R;
import cgeo.geocaching.Trackable;
import cgeo.geocaching.Waypoint;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.LoadFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.MatcherWrapper;
import cgeo.geocaching.utils.SynchronizedDateFormat;
import org.apache.commons.lang3.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.util.Xml;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
public abstract class GPXParser extends FileParser {
private static final SynchronizedDateFormat formatSimple = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); // 2010-04-20T07:00:00
private static final SynchronizedDateFormat formatSimpleZ = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); // 2010-04-20T07:00:00Z
private static final SynchronizedDateFormat formatTimezone = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US); // 2010-04-20T01:01:03-04:00
/**
* Attention: case sensitive geocode pattern to avoid matching normal words in the name or description of the cache.
*/
private static final Pattern PATTERN_GEOCODE = Pattern.compile("([0-9A-Z]{2,})");
private static final Pattern PATTERN_GUID = Pattern.compile(".*" + Pattern.quote("guid=") + "([0-9a-z\\-]+)", Pattern.CASE_INSENSITIVE);
private static final Pattern PATTERN_URL_GEOCODE = Pattern.compile(".*" + Pattern.quote("wp=") + "([A-Z][0-9A-Z]+)", Pattern.CASE_INSENSITIVE);
/**
* supported groundspeak extensions of the GPX format
*/
private static final String[] GROUNDSPEAK_NAMESPACE = new String[] {
"http://www.groundspeak.com/cache/1/1", // PQ 1.1
"http://www.groundspeak.com/cache/1/0/1", // PQ 1.0.1
"http://www.groundspeak.com/cache/1/0", // PQ 1.0
};
/**
* supported GSAK extension of the GPX format
*/
private static final String[] GSAK_NS = new String[] {
"http://www.gsak.net/xmlv1/4",
"http://www.gsak.net/xmlv1/5",
"http://www.gsak.net/xmlv1/6"
};
/**
* c:geo extensions of the gpx format
*/
private static final String CGEO_NS = "http://www.cgeo.org/wptext/1/0";
private static final Pattern PATTERN_MILLISECONDS = Pattern.compile("\\.\\d{3,7}");
private int listId = StoredList.STANDARD_LIST_ID;
final protected String namespace;
final private String version;
private Geocache cache;
private Trackable trackable = new Trackable();
private LogEntry log = null;
private String type = null;
private String sym = null;
private String name = null;
private String cmt = null;
private String desc = null;
protected final String[] userData = new String[5]; // take 5 cells, that makes indexing 1..4 easier
private String parentCacheCode = null;
private boolean wptVisited = false;
private boolean wptUserDefined = false;
/**
* Parser result. Maps geocode to cache.
*/
private final Set<String> result = new HashSet<String>(100);
private ProgressInputStream progressStream;
/**
* URL contained in the header of the GPX file. Used to guess where the file is coming from.
*/
protected String scriptUrl;
private final class UserDataListener implements EndTextElementListener {
private final int index;
public UserDataListener(int index) {
this.index = index;
}
@Override
public void end(String user) {
userData[index] = validate(user);
}
}
private static final class CacheAttributeTranslator {
// List of cache attributes matching IDs used in GPX files.
// The ID is represented by the position of the String in the array.
// Strings are not used as text but as resource IDs of strings, just to be aware of changes
// made in strings.xml which then will lead to compile errors here and not to runtime errors.
private static final int[] CACHE_ATTRIBUTES = {
-1, // 0
R.string.attribute_dogs_yes, // 1
R.string.attribute_fee_yes, // 2
R.string.attribute_rappelling_yes, // 3
R.string.attribute_boat_yes, // 4
R.string.attribute_scuba_yes, // 5
R.string.attribute_kids_yes, // 6
R.string.attribute_onehour_yes, // 7
R.string.attribute_scenic_yes, // 8
R.string.attribute_hiking_yes, // 9
R.string.attribute_climbing_yes, // 10
R.string.attribute_wading_yes, // 11
R.string.attribute_swimming_yes, // 12
R.string.attribute_available_yes, // 13
R.string.attribute_night_yes, // 14
R.string.attribute_winter_yes, // 15
-1, // 16
R.string.attribute_poisonoak_yes, // 17
R.string.attribute_dangerousanimals_yes, // 18
R.string.attribute_ticks_yes, // 19
R.string.attribute_mine_yes, // 20
R.string.attribute_cliff_yes, // 21
R.string.attribute_hunting_yes, // 22
R.string.attribute_danger_yes, // 23
R.string.attribute_wheelchair_yes, // 24
R.string.attribute_parking_yes, // 25
R.string.attribute_public_yes, // 26
R.string.attribute_water_yes, // 27
R.string.attribute_restrooms_yes, // 28
R.string.attribute_phone_yes, // 29
R.string.attribute_picnic_yes, // 30
R.string.attribute_camping_yes, // 31
R.string.attribute_bicycles_yes, // 32
R.string.attribute_motorcycles_yes, // 33
R.string.attribute_quads_yes, // 34
R.string.attribute_jeeps_yes, // 35
R.string.attribute_snowmobiles_yes, // 36
R.string.attribute_horses_yes, // 37
R.string.attribute_campfires_yes, // 38
R.string.attribute_thorn_yes, // 39
R.string.attribute_stealth_yes, // 40
R.string.attribute_stroller_yes, // 41
R.string.attribute_firstaid_yes, // 42
R.string.attribute_cow_yes, // 43
R.string.attribute_flashlight_yes, // 44
R.string.attribute_landf_yes, // 45
R.string.attribute_rv_yes, // 46
R.string.attribute_field_puzzle_yes, // 47
R.string.attribute_uv_yes, // 48
R.string.attribute_snowshoes_yes, // 49
R.string.attribute_skiis_yes, // 50
R.string.attribute_s_tool_yes, // 51
R.string.attribute_nightcache_yes, // 52
R.string.attribute_parkngrab_yes, // 53
R.string.attribute_abandonedbuilding_yes, // 54
R.string.attribute_hike_short_yes, // 55
R.string.attribute_hike_med_yes, // 56
R.string.attribute_hike_long_yes, // 57
R.string.attribute_fuel_yes, // 58
R.string.attribute_food_yes, // 59
R.string.attribute_wirelessbeacon_yes, // 60
R.string.attribute_partnership_yes, // 61
R.string.attribute_seasonal_yes, // 62
R.string.attribute_touristok_yes, // 63
R.string.attribute_treeclimbing_yes, // 64
R.string.attribute_frontyard_yes, // 65
R.string.attribute_teamwork_yes, // 66
R.string.attribute_geotour_yes, // 67
};
private static final String YES = "_yes";
private static final String NO = "_no";
private static final Pattern BASENAME_PATTERN = Pattern.compile("^.*attribute_(.*)(_yes|_no)");
// map GPX-Attribute-Id to baseName
public static String getBaseName(final int id) {
if (id < 0) {
return null;
}
// get String out of array
if (CACHE_ATTRIBUTES.length <= id) {
return null;
}
final int stringId = CACHE_ATTRIBUTES[id];
if (stringId == -1) {
return null; // id not found
}
// get text for string
String stringName;
try {
stringName = CgeoApplication.getInstance().getResources().getResourceName(stringId);
} catch (final NullPointerException e) {
return null;
}
if (stringName == null) {
return null;
}
// cut out baseName
final MatcherWrapper m = new MatcherWrapper(BASENAME_PATTERN, stringName);
if (!m.matches()) {
return null;
}
return m.group(1);
}
// @return baseName + "_yes" or "_no" e.g. "food_no" or "uv_yes"
public static String getInternalId(final int attributeId, final boolean active) {
final String baseName = CacheAttributeTranslator.getBaseName(attributeId);
if (baseName == null) {
return null;
}
return baseName + (active ? YES : NO);
}
}
protected GPXParser(int listIdIn, String namespaceIn, String versionIn) {
listId = listIdIn;
namespace = namespaceIn;
version = versionIn;
}
static Date parseDate(String inputUntrimmed) throws ParseException {
String input = inputUntrimmed.trim();
// remove milliseconds to reduce number of needed patterns
final MatcherWrapper matcher = new MatcherWrapper(PATTERN_MILLISECONDS, input);
input = matcher.replaceFirst("");
if (input.contains("Z")) {
return formatSimpleZ.parse(input);
}
if (StringUtils.countMatches(input, ":") == 3) {
final String removeColon = input.substring(0, input.length() - 3) + input.substring(input.length() - 2);
return formatTimezone.parse(removeColon);
}
return formatSimple.parse(input);
}
@Override
public Collection<Geocache> parse(final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException {
resetCache();
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
root.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
scriptUrl = body;
}
});
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
final String latitude = attrs.getValue("lat");
final String longitude = attrs.getValue("lon");
// latitude and longitude are required attributes, but we export them empty for waypoints without coordinates
if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
cache.setCoords(new Geopoint(Double.valueOf(latitude),
Double.valueOf(longitude)));
}
}
} catch (final NumberFormatException e) {
Log.w("Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
@Override
public void end() {
// try to find geocode somewhere else
if (StringUtils.isBlank(cache.getGeocode())) {
findGeoCode(name);
findGeoCode(desc);
findGeoCode(cmt);
}
// take the name as code, if nothing else is available
if (StringUtils.isBlank(cache.getGeocode())) {
if (StringUtils.isNotBlank(name)) {
cache.setGeocode(name.trim());
}
}
if (isValidForImport()) {
fixCache(cache);
cache.setListId(listId);
cache.setDetailed(true);
createNoteFromGSAKUserdata();
final String geocode = cache.getGeocode();
if (result.contains(geocode)) {
Log.w("Duplicate geocode during GPX import: " + geocode);
}
// modify cache depending on the use case/connector
afterParsing(cache);
// finally store the cache in the database
result.add(geocode);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
// avoid the cachecache using lots of memory for caches which the user did not actually look at
DataStore.removeAllFromCache();
showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& StringUtils.containsIgnoreCase(type, "waypoint")) {
addWaypointToCache();
}
resetCache();
}
private void addWaypointToCache() {
fixCache(cache);
if (cache.getName().length() > 2 || StringUtils.isNotBlank(parentCacheCode)) {
if (StringUtils.isBlank(parentCacheCode)) {
- parentCacheCode = "GC" + cache.getName().substring(2).toUpperCase(Locale.US);
+ if (StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) {
+ parentCacheCode = cache.getName().substring(2);
+ }
+ else {
+ parentCacheCode = "GC" + cache.getName().substring(2).toUpperCase(Locale.US);
+ }
}
// lookup cache for waypoint in already parsed caches
final Geocache cacheForWaypoint = DataStore.loadCache(parentCacheCode, LoadFlags.LOAD_CACHE_OR_DB);
if (cacheForWaypoint != null) {
final Waypoint waypoint = new Waypoint(cache.getShortDescription(), convertWaypointSym2Type(sym), false);
if (wptUserDefined) {
waypoint.setUserDefined();
}
waypoint.setId(-1);
waypoint.setGeocode(parentCacheCode);
waypoint.setPrefix(cacheForWaypoint.getWaypointPrefix(cache.getName()));
waypoint.setLookup("---");
// there is no lookup code in gpx file
waypoint.setCoords(cache.getCoords());
waypoint.setNote(cache.getDescription());
waypoint.setVisited(wptVisited);
final ArrayList<Waypoint> mergedWayPoints = new ArrayList<Waypoint>();
mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());
final ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>();
newPoints.add(waypoint);
Waypoint.mergeWayPoints(newPoints, mergedWayPoints, true);
cacheForWaypoint.setWaypoints(newPoints, false);
DataStore.saveCache(cacheForWaypoint, EnumSet.of(SaveFlag.SAVE_DB));
showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
});
// waypoint.time
waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setHidden(parseDate(body));
} catch (final Exception e) {
Log.w("Failed to parse cache date", e);
}
}
});
// waypoint.name
waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
name = body;
String content = body.trim();
// extremcaching.com manipulates the GC code by adding GC in front of ECxxx
if (StringUtils.startsWithIgnoreCase(content, "GCEC") && StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) {
content = content.substring(2);
}
cache.setName(content);
findGeoCode(cache.getName());
}
});
// waypoint.desc
waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
desc = body;
cache.setShortDescription(validate(body));
}
});
// waypoint.cmt
waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cmt = body;
cache.setDescription(validate(body));
}
});
// waypoint.getType()
waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase(Locale.US).trim();
}
}
});
// waypoint.sym
waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(final String body) {
sym = body.toLowerCase(Locale.US);
if (sym.contains("geocache") && sym.contains("found")) {
cache.setFound(true);
}
}
});
// waypoint.url
waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String url) {
final MatcherWrapper matcher = new MatcherWrapper(PATTERN_GUID, url);
if (matcher.matches()) {
final String guid = matcher.group(1);
if (StringUtils.isNotBlank(guid)) {
cache.setGuid(guid);
}
}
final MatcherWrapper matcherCode = new MatcherWrapper(PATTERN_URL_GEOCODE, url);
if (matcherCode.matches()) {
final String geocode = matcherCode.group(1);
cache.setGeocode(geocode);
}
}
});
// waypoint.urlname (name for waymarks)
waypoint.getChild(namespace, "urlname").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String urlName) {
if (cache.getName().equals(cache.getGeocode()) && StringUtils.startsWith(cache.getGeocode(), "WM")) {
cache.setName(StringUtils.trim(urlName));
}
}
});
// for GPX 1.0, cache info comes from waypoint node (so called private children,
// for GPX 1.1 from extensions node
final Element cacheParent = getCacheParent(waypoint);
// GSAK extensions
for (final String gsakNamespace : GSAK_NS) {
final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String watchList) {
cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
}
});
gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));
for (int i = 2; i <= 4; i++) {
gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
}
gsak.getChild(gsakNamespace, "Parent").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
parentCacheCode = body;
}
});
}
// c:geo extensions
final Element cgeoVisited = cacheParent.getChild(CGEO_NS, "visited");
cgeoVisited.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String visited) {
wptVisited = Boolean.valueOf(visited.trim());
}
});
final Element cgeoUserDefined = cacheParent.getChild(CGEO_NS, "userdefined");
cgeoUserDefined.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String userDefined) {
wptUserDefined = Boolean.valueOf(userDefined.trim());
}
});
// 3 different versions of the GC schema
for (final String nsGC : GROUNDSPEAK_NAMESPACE) {
// waypoints.cache
final Element gcCache = cacheParent.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.setCacheId(attrs.getValue("id"));
}
if (attrs.getIndex("archived") > -1) {
cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
}
if (attrs.getIndex("available") > -1) {
cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
}
} catch (final RuntimeException e) {
Log.w("Failed to parse cache attributes.");
}
}
});
// waypoint.cache.getName()
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheName) {
cache.setName(validate(cacheName));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String ownerUserId) {
cache.setOwnerUserId(validate(ownerUserId));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "placed_by").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String ownerDisplayName) {
cache.setOwnerDisplayName(validate(ownerDisplayName));
}
});
// waypoint.cache.getType()
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setType(CacheType.getByPattern(validate(body)));
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setSize(CacheSize.getById(validate(body)));
}
});
// waypoint.cache.getAttributes()
// @see issue #299
// <groundspeak:attributes>
// <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
// <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
// where inc = 0 => _no, inc = 1 => _yes
// IDs see array CACHE_ATTRIBUTES
final Element gcAttributes = gcCache.getChild(nsGC, "attributes");
// waypoint.cache.attribute
final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");
gcAttribute.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
final int attributeId = Integer.parseInt(attrs.getValue("id"));
final boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
final String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
if (internalId != null) {
cache.getAttributes().add(internalId);
}
}
} catch (final NumberFormatException e) {
// nothing
}
}
});
// waypoint.cache.getDifficulty()
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setDifficulty(Float.parseFloat(body));
} catch (final NumberFormatException e) {
Log.w("Failed to parse difficulty", e);
}
}
});
// waypoint.cache.getTerrain()
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setTerrain(Float.parseFloat(body));
} catch (final NumberFormatException e) {
Log.w("Failed to parse terrain", e);
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String country) {
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(country));
} else {
cache.setLocation(cache.getLocation() + ", " + country.trim());
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String state) {
final String trimmedState = state.trim();
if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(state));
} else {
cache.setLocation(trimmedState + ", " + cache.getLocation());
}
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String encoded) {
cache.setHint(validate(encoded));
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String shortDesc) {
cache.setShortDescription(validate(shortDesc));
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String desc) {
cache.setDescription(validate(desc));
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
// waypoint.cache.travelbugs.travelbug
gcTB.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
trackable = new Trackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.setGeocode(attrs.getValue("ref"));
}
} catch (final RuntimeException e) {
// nothing
}
}
});
gcTB.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<Trackable>());
}
cache.getInventory().add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.getName()
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String tbName) {
trackable.setName(validate(tbName));
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
log = new LogEntry("", 0, LogType.UNKNOWN, "");
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (final NumberFormatException e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (log.type != LogType.UNKNOWN) {
cache.getLogs().add(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
log.date = parseDate(body).getTime();
} catch (final Exception e) {
Log.w("Failed to parse log date", e);
}
}
});
// waypoint.cache.logs.log.getType()
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String logType = validate(body);
log.type = LogType.getByType(logType);
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String finderName) {
log.author = validate(finderName);
}
});
// waypoint.cache.logs.log.text
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String logText) {
log.log = validate(logText);
}
});
}
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
return DataStore.loadCaches(result, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL));
} catch (final SAXException e) {
throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
}
/**
* @param cache
* currently imported cache
*/
protected void afterParsing(Geocache cache) {
// can be overridden by sub classes
}
/**
* GPX 1.0 and 1.1 use different XML elements to put the cache into, therefore needs to be overwritten in the
* version specific subclasses
*
* @param waypoint
* @return
*/
protected abstract Element getCacheParent(Element waypoint);
protected static String validate(String input) {
if ("nil".equalsIgnoreCase(input)) {
return "";
}
return input.trim();
}
static WaypointType convertWaypointSym2Type(final String sym) {
if ("parking area".equalsIgnoreCase(sym)) {
return WaypointType.PARKING;
}
if ("stages of a multicache".equalsIgnoreCase(sym)) {
return WaypointType.STAGE;
}
if ("question to answer".equalsIgnoreCase(sym)) {
return WaypointType.PUZZLE;
}
if ("trailhead".equalsIgnoreCase(sym)) {
return WaypointType.TRAILHEAD;
}
if ("final location".equalsIgnoreCase(sym)) {
return WaypointType.FINAL;
}
// this is not fully correct, but lets also look for localized waypoint types
for (final WaypointType waypointType : WaypointType.ALL_TYPES_EXCEPT_OWN_AND_ORIGINAL) {
final String localized = waypointType.getL10n();
if (StringUtils.isNotEmpty(localized)) {
if (localized.equalsIgnoreCase(sym)) {
return waypointType;
}
}
}
return WaypointType.WAYPOINT;
}
private void findGeoCode(final String input) {
if (input == null || StringUtils.isNotBlank(cache.getGeocode())) {
return;
}
final String trimmed = input.trim();
final MatcherWrapper matcherGeocode = new MatcherWrapper(PATTERN_GEOCODE, trimmed);
if (matcherGeocode.find()) {
final String geocode = matcherGeocode.group(1);
// a geocode should not be part of a word
if (geocode.length() == trimmed.length() || Character.isWhitespace(trimmed.charAt(geocode.length()))) {
if (ConnectorFactory.canHandle(geocode)) {
cache.setGeocode(geocode);
}
}
}
}
/**
* reset all fields that are used to store cache fields over the duration of parsing a single cache
*/
private void resetCache() {
type = null;
sym = null;
name = null;
desc = null;
cmt = null;
parentCacheCode = null;
wptVisited = false;
wptUserDefined = false;
cache = new Geocache(this);
// explicitly set all properties which could lead to database access, if left as null value
cache.setLocation("");
cache.setDescription("");
cache.setShortDescription("");
cache.setHint("");
for (int i = 0; i < userData.length; i++) {
userData[i] = null;
}
}
/**
* create a cache note from the UserData1 to UserData4 fields supported by GSAK
*/
private void createNoteFromGSAKUserdata() {
if (StringUtils.isBlank(cache.getPersonalNote())) {
final StringBuilder buffer = new StringBuilder();
for (final String anUserData : userData) {
if (StringUtils.isNotBlank(anUserData)) {
buffer.append(' ').append(anUserData);
}
}
final String note = buffer.toString().trim();
if (StringUtils.isNotBlank(note)) {
cache.setPersonalNote(note);
}
}
}
private boolean isValidForImport() {
if (StringUtils.isBlank(cache.getGeocode())) {
return false;
}
if (cache.getCoords() == null) {
return false;
}
return ((type == null && sym == null)
|| StringUtils.contains(type, "geocache")
|| StringUtils.contains(sym, "geocache")
|| StringUtils.containsIgnoreCase(sym, "waymark"));
}
}
| true | true | public Collection<Geocache> parse(final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException {
resetCache();
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
root.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
scriptUrl = body;
}
});
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
final String latitude = attrs.getValue("lat");
final String longitude = attrs.getValue("lon");
// latitude and longitude are required attributes, but we export them empty for waypoints without coordinates
if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
cache.setCoords(new Geopoint(Double.valueOf(latitude),
Double.valueOf(longitude)));
}
}
} catch (final NumberFormatException e) {
Log.w("Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
@Override
public void end() {
// try to find geocode somewhere else
if (StringUtils.isBlank(cache.getGeocode())) {
findGeoCode(name);
findGeoCode(desc);
findGeoCode(cmt);
}
// take the name as code, if nothing else is available
if (StringUtils.isBlank(cache.getGeocode())) {
if (StringUtils.isNotBlank(name)) {
cache.setGeocode(name.trim());
}
}
if (isValidForImport()) {
fixCache(cache);
cache.setListId(listId);
cache.setDetailed(true);
createNoteFromGSAKUserdata();
final String geocode = cache.getGeocode();
if (result.contains(geocode)) {
Log.w("Duplicate geocode during GPX import: " + geocode);
}
// modify cache depending on the use case/connector
afterParsing(cache);
// finally store the cache in the database
result.add(geocode);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
// avoid the cachecache using lots of memory for caches which the user did not actually look at
DataStore.removeAllFromCache();
showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& StringUtils.containsIgnoreCase(type, "waypoint")) {
addWaypointToCache();
}
resetCache();
}
private void addWaypointToCache() {
fixCache(cache);
if (cache.getName().length() > 2 || StringUtils.isNotBlank(parentCacheCode)) {
if (StringUtils.isBlank(parentCacheCode)) {
parentCacheCode = "GC" + cache.getName().substring(2).toUpperCase(Locale.US);
}
// lookup cache for waypoint in already parsed caches
final Geocache cacheForWaypoint = DataStore.loadCache(parentCacheCode, LoadFlags.LOAD_CACHE_OR_DB);
if (cacheForWaypoint != null) {
final Waypoint waypoint = new Waypoint(cache.getShortDescription(), convertWaypointSym2Type(sym), false);
if (wptUserDefined) {
waypoint.setUserDefined();
}
waypoint.setId(-1);
waypoint.setGeocode(parentCacheCode);
waypoint.setPrefix(cacheForWaypoint.getWaypointPrefix(cache.getName()));
waypoint.setLookup("---");
// there is no lookup code in gpx file
waypoint.setCoords(cache.getCoords());
waypoint.setNote(cache.getDescription());
waypoint.setVisited(wptVisited);
final ArrayList<Waypoint> mergedWayPoints = new ArrayList<Waypoint>();
mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());
final ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>();
newPoints.add(waypoint);
Waypoint.mergeWayPoints(newPoints, mergedWayPoints, true);
cacheForWaypoint.setWaypoints(newPoints, false);
DataStore.saveCache(cacheForWaypoint, EnumSet.of(SaveFlag.SAVE_DB));
showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
});
// waypoint.time
waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setHidden(parseDate(body));
} catch (final Exception e) {
Log.w("Failed to parse cache date", e);
}
}
});
// waypoint.name
waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
name = body;
String content = body.trim();
// extremcaching.com manipulates the GC code by adding GC in front of ECxxx
if (StringUtils.startsWithIgnoreCase(content, "GCEC") && StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) {
content = content.substring(2);
}
cache.setName(content);
findGeoCode(cache.getName());
}
});
// waypoint.desc
waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
desc = body;
cache.setShortDescription(validate(body));
}
});
// waypoint.cmt
waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cmt = body;
cache.setDescription(validate(body));
}
});
// waypoint.getType()
waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase(Locale.US).trim();
}
}
});
// waypoint.sym
waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(final String body) {
sym = body.toLowerCase(Locale.US);
if (sym.contains("geocache") && sym.contains("found")) {
cache.setFound(true);
}
}
});
// waypoint.url
waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String url) {
final MatcherWrapper matcher = new MatcherWrapper(PATTERN_GUID, url);
if (matcher.matches()) {
final String guid = matcher.group(1);
if (StringUtils.isNotBlank(guid)) {
cache.setGuid(guid);
}
}
final MatcherWrapper matcherCode = new MatcherWrapper(PATTERN_URL_GEOCODE, url);
if (matcherCode.matches()) {
final String geocode = matcherCode.group(1);
cache.setGeocode(geocode);
}
}
});
// waypoint.urlname (name for waymarks)
waypoint.getChild(namespace, "urlname").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String urlName) {
if (cache.getName().equals(cache.getGeocode()) && StringUtils.startsWith(cache.getGeocode(), "WM")) {
cache.setName(StringUtils.trim(urlName));
}
}
});
// for GPX 1.0, cache info comes from waypoint node (so called private children,
// for GPX 1.1 from extensions node
final Element cacheParent = getCacheParent(waypoint);
// GSAK extensions
for (final String gsakNamespace : GSAK_NS) {
final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String watchList) {
cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
}
});
gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));
for (int i = 2; i <= 4; i++) {
gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
}
gsak.getChild(gsakNamespace, "Parent").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
parentCacheCode = body;
}
});
}
// c:geo extensions
final Element cgeoVisited = cacheParent.getChild(CGEO_NS, "visited");
cgeoVisited.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String visited) {
wptVisited = Boolean.valueOf(visited.trim());
}
});
final Element cgeoUserDefined = cacheParent.getChild(CGEO_NS, "userdefined");
cgeoUserDefined.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String userDefined) {
wptUserDefined = Boolean.valueOf(userDefined.trim());
}
});
// 3 different versions of the GC schema
for (final String nsGC : GROUNDSPEAK_NAMESPACE) {
// waypoints.cache
final Element gcCache = cacheParent.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.setCacheId(attrs.getValue("id"));
}
if (attrs.getIndex("archived") > -1) {
cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
}
if (attrs.getIndex("available") > -1) {
cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
}
} catch (final RuntimeException e) {
Log.w("Failed to parse cache attributes.");
}
}
});
// waypoint.cache.getName()
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheName) {
cache.setName(validate(cacheName));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String ownerUserId) {
cache.setOwnerUserId(validate(ownerUserId));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "placed_by").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String ownerDisplayName) {
cache.setOwnerDisplayName(validate(ownerDisplayName));
}
});
// waypoint.cache.getType()
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setType(CacheType.getByPattern(validate(body)));
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setSize(CacheSize.getById(validate(body)));
}
});
// waypoint.cache.getAttributes()
// @see issue #299
// <groundspeak:attributes>
// <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
// <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
// where inc = 0 => _no, inc = 1 => _yes
// IDs see array CACHE_ATTRIBUTES
final Element gcAttributes = gcCache.getChild(nsGC, "attributes");
// waypoint.cache.attribute
final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");
gcAttribute.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
final int attributeId = Integer.parseInt(attrs.getValue("id"));
final boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
final String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
if (internalId != null) {
cache.getAttributes().add(internalId);
}
}
} catch (final NumberFormatException e) {
// nothing
}
}
});
// waypoint.cache.getDifficulty()
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setDifficulty(Float.parseFloat(body));
} catch (final NumberFormatException e) {
Log.w("Failed to parse difficulty", e);
}
}
});
// waypoint.cache.getTerrain()
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setTerrain(Float.parseFloat(body));
} catch (final NumberFormatException e) {
Log.w("Failed to parse terrain", e);
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String country) {
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(country));
} else {
cache.setLocation(cache.getLocation() + ", " + country.trim());
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String state) {
final String trimmedState = state.trim();
if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(state));
} else {
cache.setLocation(trimmedState + ", " + cache.getLocation());
}
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String encoded) {
cache.setHint(validate(encoded));
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String shortDesc) {
cache.setShortDescription(validate(shortDesc));
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String desc) {
cache.setDescription(validate(desc));
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
// waypoint.cache.travelbugs.travelbug
gcTB.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
trackable = new Trackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.setGeocode(attrs.getValue("ref"));
}
} catch (final RuntimeException e) {
// nothing
}
}
});
gcTB.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<Trackable>());
}
cache.getInventory().add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.getName()
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String tbName) {
trackable.setName(validate(tbName));
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
log = new LogEntry("", 0, LogType.UNKNOWN, "");
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (final NumberFormatException e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (log.type != LogType.UNKNOWN) {
cache.getLogs().add(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
log.date = parseDate(body).getTime();
} catch (final Exception e) {
Log.w("Failed to parse log date", e);
}
}
});
// waypoint.cache.logs.log.getType()
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String logType = validate(body);
log.type = LogType.getByType(logType);
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String finderName) {
log.author = validate(finderName);
}
});
// waypoint.cache.logs.log.text
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String logText) {
log.log = validate(logText);
}
});
}
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
return DataStore.loadCaches(result, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL));
} catch (final SAXException e) {
throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
}
| public Collection<Geocache> parse(final InputStream stream, final CancellableHandler progressHandler) throws IOException, ParserException {
resetCache();
final RootElement root = new RootElement(namespace, "gpx");
final Element waypoint = root.getChild(namespace, "wpt");
root.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
scriptUrl = body;
}
});
// waypoint - attributes
waypoint.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) {
final String latitude = attrs.getValue("lat");
final String longitude = attrs.getValue("lon");
// latitude and longitude are required attributes, but we export them empty for waypoints without coordinates
if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
cache.setCoords(new Geopoint(Double.valueOf(latitude),
Double.valueOf(longitude)));
}
}
} catch (final NumberFormatException e) {
Log.w("Failed to parse waypoint's latitude and/or longitude.");
}
}
});
// waypoint
waypoint.setEndElementListener(new EndElementListener() {
@Override
public void end() {
// try to find geocode somewhere else
if (StringUtils.isBlank(cache.getGeocode())) {
findGeoCode(name);
findGeoCode(desc);
findGeoCode(cmt);
}
// take the name as code, if nothing else is available
if (StringUtils.isBlank(cache.getGeocode())) {
if (StringUtils.isNotBlank(name)) {
cache.setGeocode(name.trim());
}
}
if (isValidForImport()) {
fixCache(cache);
cache.setListId(listId);
cache.setDetailed(true);
createNoteFromGSAKUserdata();
final String geocode = cache.getGeocode();
if (result.contains(geocode)) {
Log.w("Duplicate geocode during GPX import: " + geocode);
}
// modify cache depending on the use case/connector
afterParsing(cache);
// finally store the cache in the database
result.add(geocode);
DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
// avoid the cachecache using lots of memory for caches which the user did not actually look at
DataStore.removeAllFromCache();
showProgressMessage(progressHandler, progressStream.getProgress());
} else if (StringUtils.isNotBlank(cache.getName())
&& StringUtils.containsIgnoreCase(type, "waypoint")) {
addWaypointToCache();
}
resetCache();
}
private void addWaypointToCache() {
fixCache(cache);
if (cache.getName().length() > 2 || StringUtils.isNotBlank(parentCacheCode)) {
if (StringUtils.isBlank(parentCacheCode)) {
if (StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) {
parentCacheCode = cache.getName().substring(2);
}
else {
parentCacheCode = "GC" + cache.getName().substring(2).toUpperCase(Locale.US);
}
}
// lookup cache for waypoint in already parsed caches
final Geocache cacheForWaypoint = DataStore.loadCache(parentCacheCode, LoadFlags.LOAD_CACHE_OR_DB);
if (cacheForWaypoint != null) {
final Waypoint waypoint = new Waypoint(cache.getShortDescription(), convertWaypointSym2Type(sym), false);
if (wptUserDefined) {
waypoint.setUserDefined();
}
waypoint.setId(-1);
waypoint.setGeocode(parentCacheCode);
waypoint.setPrefix(cacheForWaypoint.getWaypointPrefix(cache.getName()));
waypoint.setLookup("---");
// there is no lookup code in gpx file
waypoint.setCoords(cache.getCoords());
waypoint.setNote(cache.getDescription());
waypoint.setVisited(wptVisited);
final ArrayList<Waypoint> mergedWayPoints = new ArrayList<Waypoint>();
mergedWayPoints.addAll(cacheForWaypoint.getWaypoints());
final ArrayList<Waypoint> newPoints = new ArrayList<Waypoint>();
newPoints.add(waypoint);
Waypoint.mergeWayPoints(newPoints, mergedWayPoints, true);
cacheForWaypoint.setWaypoints(newPoints, false);
DataStore.saveCache(cacheForWaypoint, EnumSet.of(SaveFlag.SAVE_DB));
showProgressMessage(progressHandler, progressStream.getProgress());
}
}
}
});
// waypoint.time
waypoint.getChild(namespace, "time").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setHidden(parseDate(body));
} catch (final Exception e) {
Log.w("Failed to parse cache date", e);
}
}
});
// waypoint.name
waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
name = body;
String content = body.trim();
// extremcaching.com manipulates the GC code by adding GC in front of ECxxx
if (StringUtils.startsWithIgnoreCase(content, "GCEC") && StringUtils.containsIgnoreCase(scriptUrl, "extremcaching")) {
content = content.substring(2);
}
cache.setName(content);
findGeoCode(cache.getName());
}
});
// waypoint.desc
waypoint.getChild(namespace, "desc").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
desc = body;
cache.setShortDescription(validate(body));
}
});
// waypoint.cmt
waypoint.getChild(namespace, "cmt").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cmt = body;
cache.setDescription(validate(body));
}
});
// waypoint.getType()
waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String[] content = body.split("\\|");
if (content.length > 0) {
type = content[0].toLowerCase(Locale.US).trim();
}
}
});
// waypoint.sym
waypoint.getChild(namespace, "sym").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(final String body) {
sym = body.toLowerCase(Locale.US);
if (sym.contains("geocache") && sym.contains("found")) {
cache.setFound(true);
}
}
});
// waypoint.url
waypoint.getChild(namespace, "url").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String url) {
final MatcherWrapper matcher = new MatcherWrapper(PATTERN_GUID, url);
if (matcher.matches()) {
final String guid = matcher.group(1);
if (StringUtils.isNotBlank(guid)) {
cache.setGuid(guid);
}
}
final MatcherWrapper matcherCode = new MatcherWrapper(PATTERN_URL_GEOCODE, url);
if (matcherCode.matches()) {
final String geocode = matcherCode.group(1);
cache.setGeocode(geocode);
}
}
});
// waypoint.urlname (name for waymarks)
waypoint.getChild(namespace, "urlname").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String urlName) {
if (cache.getName().equals(cache.getGeocode()) && StringUtils.startsWith(cache.getGeocode(), "WM")) {
cache.setName(StringUtils.trim(urlName));
}
}
});
// for GPX 1.0, cache info comes from waypoint node (so called private children,
// for GPX 1.1 from extensions node
final Element cacheParent = getCacheParent(waypoint);
// GSAK extensions
for (final String gsakNamespace : GSAK_NS) {
final Element gsak = cacheParent.getChild(gsakNamespace, "wptExtension");
gsak.getChild(gsakNamespace, "Watch").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String watchList) {
cache.setOnWatchlist(Boolean.valueOf(watchList.trim()));
}
});
gsak.getChild(gsakNamespace, "UserData").setEndTextElementListener(new UserDataListener(1));
for (int i = 2; i <= 4; i++) {
gsak.getChild(gsakNamespace, "User" + i).setEndTextElementListener(new UserDataListener(i));
}
gsak.getChild(gsakNamespace, "Parent").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
parentCacheCode = body;
}
});
}
// c:geo extensions
final Element cgeoVisited = cacheParent.getChild(CGEO_NS, "visited");
cgeoVisited.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String visited) {
wptVisited = Boolean.valueOf(visited.trim());
}
});
final Element cgeoUserDefined = cacheParent.getChild(CGEO_NS, "userdefined");
cgeoUserDefined.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String userDefined) {
wptUserDefined = Boolean.valueOf(userDefined.trim());
}
});
// 3 different versions of the GC schema
for (final String nsGC : GROUNDSPEAK_NAMESPACE) {
// waypoints.cache
final Element gcCache = cacheParent.getChild(nsGC, "cache");
gcCache.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1) {
cache.setCacheId(attrs.getValue("id"));
}
if (attrs.getIndex("archived") > -1) {
cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true"));
}
if (attrs.getIndex("available") > -1) {
cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true"));
}
} catch (final RuntimeException e) {
Log.w("Failed to parse cache attributes.");
}
}
});
// waypoint.cache.getName()
gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String cacheName) {
cache.setName(validate(cacheName));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String ownerUserId) {
cache.setOwnerUserId(validate(ownerUserId));
}
});
// waypoint.cache.getOwner()
gcCache.getChild(nsGC, "placed_by").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String ownerDisplayName) {
cache.setOwnerDisplayName(validate(ownerDisplayName));
}
});
// waypoint.cache.getType()
gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setType(CacheType.getByPattern(validate(body)));
}
});
// waypoint.cache.container
gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
cache.setSize(CacheSize.getById(validate(body)));
}
});
// waypoint.cache.getAttributes()
// @see issue #299
// <groundspeak:attributes>
// <groundspeak:attribute id="32" inc="1">Bicycles</groundspeak:attribute>
// <groundspeak:attribute id="13" inc="1">Available at all times</groundspeak:attribute>
// where inc = 0 => _no, inc = 1 => _yes
// IDs see array CACHE_ATTRIBUTES
final Element gcAttributes = gcCache.getChild(nsGC, "attributes");
// waypoint.cache.attribute
final Element gcAttribute = gcAttributes.getChild(nsGC, "attribute");
gcAttribute.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
try {
if (attrs.getIndex("id") > -1 && attrs.getIndex("inc") > -1) {
final int attributeId = Integer.parseInt(attrs.getValue("id"));
final boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0;
final String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive);
if (internalId != null) {
cache.getAttributes().add(internalId);
}
}
} catch (final NumberFormatException e) {
// nothing
}
}
});
// waypoint.cache.getDifficulty()
gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setDifficulty(Float.parseFloat(body));
} catch (final NumberFormatException e) {
Log.w("Failed to parse difficulty", e);
}
}
});
// waypoint.cache.getTerrain()
gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
cache.setTerrain(Float.parseFloat(body));
} catch (final NumberFormatException e) {
Log.w("Failed to parse terrain", e);
}
}
});
// waypoint.cache.country
gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String country) {
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(country));
} else {
cache.setLocation(cache.getLocation() + ", " + country.trim());
}
}
});
// waypoint.cache.state
gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String state) {
final String trimmedState = state.trim();
if (StringUtils.isNotEmpty(trimmedState)) { // state can be completely empty
if (StringUtils.isBlank(cache.getLocation())) {
cache.setLocation(validate(state));
} else {
cache.setLocation(trimmedState + ", " + cache.getLocation());
}
}
}
});
// waypoint.cache.encoded_hints
gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String encoded) {
cache.setHint(validate(encoded));
}
});
gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String shortDesc) {
cache.setShortDescription(validate(shortDesc));
}
});
gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String desc) {
cache.setDescription(validate(desc));
}
});
// waypoint.cache.travelbugs
final Element gcTBs = gcCache.getChild(nsGC, "travelbugs");
// waypoint.cache.travelbug
final Element gcTB = gcTBs.getChild(nsGC, "travelbug");
// waypoint.cache.travelbugs.travelbug
gcTB.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
trackable = new Trackable();
try {
if (attrs.getIndex("ref") > -1) {
trackable.setGeocode(attrs.getValue("ref"));
}
} catch (final RuntimeException e) {
// nothing
}
}
});
gcTB.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) {
if (cache.getInventory() == null) {
cache.setInventory(new ArrayList<Trackable>());
}
cache.getInventory().add(trackable);
}
}
});
// waypoint.cache.travelbugs.travelbug.getName()
gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String tbName) {
trackable.setName(validate(tbName));
}
});
// waypoint.cache.logs
final Element gcLogs = gcCache.getChild(nsGC, "logs");
// waypoint.cache.log
final Element gcLog = gcLogs.getChild(nsGC, "log");
gcLog.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attrs) {
log = new LogEntry("", 0, LogType.UNKNOWN, "");
try {
if (attrs.getIndex("id") > -1) {
log.id = Integer.parseInt(attrs.getValue("id"));
}
} catch (final NumberFormatException e) {
// nothing
}
}
});
gcLog.setEndElementListener(new EndElementListener() {
@Override
public void end() {
if (log.type != LogType.UNKNOWN) {
cache.getLogs().add(log);
}
}
});
// waypoint.cache.logs.log.date
gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
try {
log.date = parseDate(body).getTime();
} catch (final Exception e) {
Log.w("Failed to parse log date", e);
}
}
});
// waypoint.cache.logs.log.getType()
gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
final String logType = validate(body);
log.type = LogType.getByType(logType);
}
});
// waypoint.cache.logs.log.finder
gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String finderName) {
log.author = validate(finderName);
}
});
// waypoint.cache.logs.log.text
gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String logText) {
log.log = validate(logText);
}
});
}
try {
progressStream = new ProgressInputStream(stream);
Xml.parse(progressStream, Xml.Encoding.UTF_8, root.getContentHandler());
return DataStore.loadCaches(result, EnumSet.of(LoadFlag.LOAD_DB_MINIMAL));
} catch (final SAXException e) {
throw new ParserException("Cannot parse .gpx file as GPX " + version + ": could not parse XML", e);
}
}
|
diff --git a/ignition-location/ignition-location-lib/src/com/github/ignition/location/utils/IgnitedLegacyLastLocationFinder.java b/ignition-location/ignition-location-lib/src/com/github/ignition/location/utils/IgnitedLegacyLastLocationFinder.java
index 0fb89c5..be552c1 100644
--- a/ignition-location/ignition-location-lib/src/com/github/ignition/location/utils/IgnitedLegacyLastLocationFinder.java
+++ b/ignition-location/ignition-location-lib/src/com/github/ignition/location/utils/IgnitedLegacyLastLocationFinder.java
@@ -1,174 +1,174 @@
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ignition.location.utils;
import java.util.List;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import com.github.ignition.location.annotations.IgnitedLocation;
import com.github.ignition.location.templates.ILastLocationFinder;
/**
* Legacy implementation of Last Location Finder for all Android platforms down to Android 1.6.
*
* This class let's you find the "best" (most accurate and timely) previously detected location
* using whatever providers are available.
*
* Where a timely / accurate previous location is not detected it will return the newest location
* (where one exists) and setup a one-off location update to find the current location.
*/
public class IgnitedLegacyLastLocationFinder implements ILastLocationFinder {
protected static String LOG_TAG = IgnitedLegacyLastLocationFinder.class.getSimpleName();
@SuppressWarnings("unused")
@IgnitedLocation
private Location currentLocation;
protected LocationManager locationManager;
protected Criteria criteria;
protected Context context;
/**
* Construct a new Legacy Last Location Finder.
*
* @param context
* Context
*/
public IgnitedLegacyLastLocationFinder(Context appContext) {
this.context = appContext;
this.locationManager = (LocationManager) appContext
.getSystemService(Context.LOCATION_SERVICE);
this.criteria = new Criteria();
// Coarse accuracy is specified here to get the fastest possible result.
// The calling Activity will likely (or have already) request ongoing
// updates using the Fine location provider.
this.criteria.setAccuracy(Criteria.ACCURACY_COARSE);
}
/**
* Returns the most accurate and timely previously detected location. Where the last result is
* beyond the specified maximum distance or latency a one-off location update is returned via
* the {@link LocationListener} specified in {@link setChangedLocationListener}.
*
* @param minDistance
* Minimum distance before we require a location update.
* @param minTime
* Minimum time required between location updates.
* @return The most accurate and / or timely previously detected location.
*/
@Override
public Location getLastBestLocation(Context context, int minDistance, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MAX_VALUE;
// Iterate through all the providers on the system, keeping
// note of the most accurate result within the acceptable time limit.
// If no result is found within maxTime, return the newest Location.
List<String> matchingProviders = this.locationManager.getAllProviders();
for (String provider : matchingProviders) {
Location location = this.locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if (((time < minTime) && (accuracy < bestAccuracy))) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
} else if ((time > minTime) && (bestAccuracy == Float.MAX_VALUE)
&& (time < bestTime)) {
bestResult = location;
bestTime = time;
}
}
}
// If the best result is beyond the allowed time limit, or the accuracy
// of the best result is wider than the acceptable maximum distance,
// request a single update.
// This check simply implements the same conditions we set when
// requesting regular location updates every [minTime] and
// [minDistance].
// Prior to Gingerbread "one-shot" updates weren't available, so we need
// to implement this manually.
- if ((bestTime > minTime) || (bestAccuracy > minDistance)) {
String provider = this.locationManager.getBestProvider(this.criteria, true);
+ if ((bestTime < minTime) || (bestAccuracy > minDistance)) {
if (provider != null) {
Log.d(LOG_TAG,
"Last location is too old or too inaccurate. Retrieving a new one...");
this.locationManager.requestLocationUpdates(provider, 0, 0,
this.singeUpdateListener, context.getMainLooper());
}
}
if (bestResult != null) {
bestResult.getExtras().putBoolean(LAST_LOCATION_TOO_OLD_EXTRA, true);
}
return bestResult;
}
/**
* This one-off {@link LocationListener} simply listens for a single location update before
* unregistering itself. The one-off location update is returned via the
* {@link LocationListener} specified in {@link setChangedLocationListener}.
*/
protected LocationListener singeUpdateListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d(LOG_TAG,
"Single Location Update Received from " + location.getProvider()
+ " (lat, long): " + location.getLatitude() + ", "
+ location.getLongitude());
setCurrentLocation(location);
}
locationManager.removeUpdates(IgnitedLegacyLastLocationFinder.this.singeUpdateListener);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
/**
* {@inheritDoc}
*/
@Override
public void cancel() {
locationManager.removeUpdates(this.singeUpdateListener);
}
public void setCurrentLocation(Location currentLocation) {
this.currentLocation = currentLocation;
}
}
| false | true | public Location getLastBestLocation(Context context, int minDistance, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MAX_VALUE;
// Iterate through all the providers on the system, keeping
// note of the most accurate result within the acceptable time limit.
// If no result is found within maxTime, return the newest Location.
List<String> matchingProviders = this.locationManager.getAllProviders();
for (String provider : matchingProviders) {
Location location = this.locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if (((time < minTime) && (accuracy < bestAccuracy))) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
} else if ((time > minTime) && (bestAccuracy == Float.MAX_VALUE)
&& (time < bestTime)) {
bestResult = location;
bestTime = time;
}
}
}
// If the best result is beyond the allowed time limit, or the accuracy
// of the best result is wider than the acceptable maximum distance,
// request a single update.
// This check simply implements the same conditions we set when
// requesting regular location updates every [minTime] and
// [minDistance].
// Prior to Gingerbread "one-shot" updates weren't available, so we need
// to implement this manually.
if ((bestTime > minTime) || (bestAccuracy > minDistance)) {
String provider = this.locationManager.getBestProvider(this.criteria, true);
if (provider != null) {
Log.d(LOG_TAG,
"Last location is too old or too inaccurate. Retrieving a new one...");
this.locationManager.requestLocationUpdates(provider, 0, 0,
this.singeUpdateListener, context.getMainLooper());
}
}
if (bestResult != null) {
bestResult.getExtras().putBoolean(LAST_LOCATION_TOO_OLD_EXTRA, true);
}
return bestResult;
}
| public Location getLastBestLocation(Context context, int minDistance, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MAX_VALUE;
// Iterate through all the providers on the system, keeping
// note of the most accurate result within the acceptable time limit.
// If no result is found within maxTime, return the newest Location.
List<String> matchingProviders = this.locationManager.getAllProviders();
for (String provider : matchingProviders) {
Location location = this.locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if (((time < minTime) && (accuracy < bestAccuracy))) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
} else if ((time > minTime) && (bestAccuracy == Float.MAX_VALUE)
&& (time < bestTime)) {
bestResult = location;
bestTime = time;
}
}
}
// If the best result is beyond the allowed time limit, or the accuracy
// of the best result is wider than the acceptable maximum distance,
// request a single update.
// This check simply implements the same conditions we set when
// requesting regular location updates every [minTime] and
// [minDistance].
// Prior to Gingerbread "one-shot" updates weren't available, so we need
// to implement this manually.
String provider = this.locationManager.getBestProvider(this.criteria, true);
if ((bestTime < minTime) || (bestAccuracy > minDistance)) {
if (provider != null) {
Log.d(LOG_TAG,
"Last location is too old or too inaccurate. Retrieving a new one...");
this.locationManager.requestLocationUpdates(provider, 0, 0,
this.singeUpdateListener, context.getMainLooper());
}
}
if (bestResult != null) {
bestResult.getExtras().putBoolean(LAST_LOCATION_TOO_OLD_EXTRA, true);
}
return bestResult;
}
|
diff --git a/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java b/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java
index 5ac2c55f..26c2be14 100644
--- a/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java
+++ b/src/org/mythtv/client/ui/dvr/GuideChannelFragment.java
@@ -1,327 +1,332 @@
/**
*
*/
package org.mythtv.client.ui.dvr;
import java.util.ArrayList;
import java.util.List;
import org.mythtv.R;
import org.mythtv.client.ui.preferences.LocationProfile;
import org.mythtv.client.ui.util.MythtvListFragment;
import org.mythtv.db.channel.ChannelConstants;
import org.mythtv.db.channel.ChannelDaoHelper;
import org.mythtv.services.api.channel.ChannelInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
/**
* @author dmfrey
*
*/
public class GuideChannelFragment extends MythtvListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = GuideChannelFragment.class.getSimpleName();
private SharedPreferences mSharedPreferences;
private boolean downloadIcons;
private ChannelDaoHelper mChannelDaoHelper = ChannelDaoHelper.getInstance();
private ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
private ProgramGuideCursorAdapter mAdapter;
private OnChannelScrollListener mOnChannelScrollListener;
private LocationProfile mLocationProfile;
public interface OnChannelScrollListener {
void channelScroll( int first, int last, int screenCount, int totalCount );
void channelSelect( int channelId );
}
/**
*
*/
public GuideChannelFragment() { }
/**
* @param mOnChannelScrollListener the mOnChannelScrollListener to set
*/
public void setOnChannelScrollListener( OnChannelScrollListener listener ) {
this.mOnChannelScrollListener = listener;
}
public ChannelInfo getChannel( int position ) {
long id = mAdapter.getItemId( position );
return mChannelDaoHelper.findOne( getActivity(), mLocationProfile, id );
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader(int, android.os.Bundle)
*/
@Override
public Loader<Cursor> onCreateLoader( int id, Bundle args ) {
Log.v( TAG, "onCreateLoader : enter" );
String[] projection = null;
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
switch( id ) {
case 0 :
Log.v( TAG, "onCreateLoader : getting channels" );
projection = new String[] { ChannelConstants._ID, ChannelConstants.FIELD_CHAN_ID + " AS " + ChannelConstants.TABLE_NAME + "_" + ChannelConstants.FIELD_CHAN_ID, ChannelConstants.FIELD_CHAN_NUM + " AS " + ChannelConstants.TABLE_NAME + "_" + ChannelConstants.FIELD_CHAN_NUM, ChannelConstants.FIELD_CALLSIGN + " AS " + ChannelConstants.TABLE_NAME + "_" + ChannelConstants.FIELD_CALLSIGN };
selection = ChannelConstants.FIELD_VISIBLE + " = ? AND " + ChannelConstants.FIELD_MASTER_HOSTNAME + " = ?";
selectionArgs = new String[] { "1", mLocationProfile.getHostname() };
sortOrder = ChannelConstants.FIELD_CHAN_NUM_FORMATTED;
Log.v( TAG, "onCreateLoader : exit" );
return new CursorLoader( getActivity(), ChannelConstants.CONTENT_URI, projection, selection, selectionArgs, sortOrder );
default :
Log.v( TAG, "onCreateLoader : exit, invalid id" );
return null;
}
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.support.v4.content.Loader, java.lang.Object)
*/
@Override
public void onLoadFinished( Loader<Cursor> loader, Cursor cursor ) {
Log.v( TAG, "onLoadFinished : enter" );
mAdapter.swapCursor( cursor );
Log.v( TAG, "onLoadFinished : exit" );
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.support.v4.content.Loader)
*/
@Override
public void onLoaderReset( Loader<Cursor> loader ) {
Log.v( TAG, "onLoaderReset : enter" );
mAdapter.swapCursor( null );
Log.v( TAG, "onLoaderReset : exit" );
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@Override
public void onActivityCreated( Bundle savedInstanceState ) {
Log.v( TAG, "onActivityCreated : enter" );
super.onActivityCreated( savedInstanceState );
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences( getActivity() );
downloadIcons = mSharedPreferences.getBoolean( "preference_program_guide_channel_icon_download", false );
Log.v( TAG, "download : downloadIcons=" + downloadIcons );
options = new DisplayImageOptions.Builder()
.cacheInMemory( true )
.cacheOnDisc( true )
.build();
mLocationProfile = mLocationProfileDaoHelper.findConnectedProfile( getActivity() );
mAdapter = new ProgramGuideCursorAdapter( getActivity() );
setListAdapter( mAdapter );
getLoaderManager().initLoader( 0, null, this );
getListView().setFastScrollEnabled( true );
getListView().setOnScrollListener( new PauseOnScrollListener( imageLoader, false, true, new OnScrollListener() {
/* (non-Javadoc)
* @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
*/
@Override
public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount ) {
Log.v( TAG, "onScroll : enter" );
//mOnChannelScrollListener.channelScroll( firstVisibleItem, visibleItemCount, totalItemCount );
Log.v( TAG, "onScroll : exit" );
}
/* (non-Javadoc)
* @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView, int)
*/
@Override
public void onScrollStateChanged( AbsListView view, int scrollState ) {
Log.v( TAG, "onScrollStateChanged : enter" );
Log.v( TAG, "onScrollStateChanged : scrollState=" + scrollState );
int first = view.getFirstVisiblePosition();
int last = view.getLastVisiblePosition();
int count = view.getChildCount();
if( scrollState == SCROLL_STATE_IDLE ) {
mOnChannelScrollListener.channelScroll( first, last, count, mAdapter.getCount() );
}
Log.v( TAG, "onScrollStateChanged : exit" );
}
}));
Log.v( TAG, "onActivityCreated : exit" );
}
// internal helpers
private class ProgramGuideCursorAdapter extends CursorAdapter {
private List<View> selectedViews = new ArrayList<View>();
private Drawable mBackground;
private Drawable mBackgroundSelected;
private ChannelInfo mSelectedChannel;
private LayoutInflater mInflater;
public ProgramGuideCursorAdapter( Context context ) {
super( context, null, false );
mInflater = LayoutInflater.from( context );
mBackground = getResources().getDrawable( R.drawable.program_guide_channel_header_back );
mBackgroundSelected = getResources().getDrawable( R.drawable.program_guide_channel_header_back_selected );
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor)
*/
@Override
public void bindView( View view, Context context, Cursor cursor ) {
final ChannelInfo channel = ChannelDaoHelper.convertCursorToChannelInfo( cursor );
final ViewHolder mHolder = (ViewHolder) view.getTag();
mHolder.channel.setText( channel.getChannelNumber() );
mHolder.callsign.setText( channel.getCallSign() );
- view.setBackgroundDrawable( mSelectedChannel != null && mSelectedChannel.getChannelId() == channel.getChannelId() ? mBackgroundSelected : mBackground );
+ if(mSelectedChannel == null || mSelectedChannel.getChannelId() != channel.getChannelId()){
+ view.setBackgroundDrawable( mBackground );
+ }else {
+ view.setBackgroundDrawable( mBackgroundSelected );
+ selectedViews.add(view);
+ }
if( downloadIcons ) {
String imageUri = mLocationProfileDaoHelper.findConnectedProfile( getActivity() ).getUrl() + "Guide/GetChannelIcon?ChanId=" + channel.getChannelId() + "&Width=32&Height=32";
imageLoader.displayImage( imageUri, mHolder.icon, options, new SimpleImageLoadingListener() {
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingComplete(android.graphics.Bitmap)
*/
@Override
public void onLoadingComplete( String imageUri, View view, Bitmap loadedImage ) {
/* mHolder.icon.setVisibility( View.GONE );
mHolder.icon.setVisibility( View.VISIBLE );
*/ }
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingFailed(com.nostra13.universalimageloader.core.assist.FailReason)
*/
@Override
public void onLoadingFailed( String imageUri, View view, FailReason failReason ) {
/* mHolder.icon.setVisibility( View.VISIBLE );
mHolder.icon.setVisibility( View.GONE );
*/ }
});
}
mHolder.row.setOnClickListener( new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
mOnChannelScrollListener.channelSelect( channel.getChannelId() );
mSelectedChannel = channel;
for( View view : selectedViews ) {
view.setBackgroundDrawable( mBackground );
}
selectedViews.clear();
v.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add( v );
}
});
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mInflater.inflate( R.layout.program_guide_channel_row, parent, false );
ViewHolder refHolder = new ViewHolder();
refHolder.row = (LinearLayout) view.findViewById( R.id.program_guide_channel );
refHolder.channel = (TextView) view.findViewById( R.id.program_guide_channel_number );
refHolder.icon = (ImageView) view.findViewById( R.id.program_guide_channel_icon );
refHolder.callsign = (TextView) view.findViewById( R.id.program_guide_channel_callsign );
view.setTag( refHolder );
return view;
}
}
private static class ViewHolder {
LinearLayout row;
TextView channel;
ImageView icon;
TextView callsign;
}
}
| true | true | public void bindView( View view, Context context, Cursor cursor ) {
final ChannelInfo channel = ChannelDaoHelper.convertCursorToChannelInfo( cursor );
final ViewHolder mHolder = (ViewHolder) view.getTag();
mHolder.channel.setText( channel.getChannelNumber() );
mHolder.callsign.setText( channel.getCallSign() );
view.setBackgroundDrawable( mSelectedChannel != null && mSelectedChannel.getChannelId() == channel.getChannelId() ? mBackgroundSelected : mBackground );
if( downloadIcons ) {
String imageUri = mLocationProfileDaoHelper.findConnectedProfile( getActivity() ).getUrl() + "Guide/GetChannelIcon?ChanId=" + channel.getChannelId() + "&Width=32&Height=32";
imageLoader.displayImage( imageUri, mHolder.icon, options, new SimpleImageLoadingListener() {
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingComplete(android.graphics.Bitmap)
*/
@Override
public void onLoadingComplete( String imageUri, View view, Bitmap loadedImage ) {
/* mHolder.icon.setVisibility( View.GONE );
mHolder.icon.setVisibility( View.VISIBLE );
*/ }
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingFailed(com.nostra13.universalimageloader.core.assist.FailReason)
*/
@Override
public void onLoadingFailed( String imageUri, View view, FailReason failReason ) {
/* mHolder.icon.setVisibility( View.VISIBLE );
mHolder.icon.setVisibility( View.GONE );
*/ }
});
}
mHolder.row.setOnClickListener( new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
mOnChannelScrollListener.channelSelect( channel.getChannelId() );
mSelectedChannel = channel;
for( View view : selectedViews ) {
view.setBackgroundDrawable( mBackground );
}
selectedViews.clear();
v.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add( v );
}
});
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mInflater.inflate( R.layout.program_guide_channel_row, parent, false );
ViewHolder refHolder = new ViewHolder();
refHolder.row = (LinearLayout) view.findViewById( R.id.program_guide_channel );
refHolder.channel = (TextView) view.findViewById( R.id.program_guide_channel_number );
refHolder.icon = (ImageView) view.findViewById( R.id.program_guide_channel_icon );
refHolder.callsign = (TextView) view.findViewById( R.id.program_guide_channel_callsign );
view.setTag( refHolder );
return view;
}
}
private static class ViewHolder {
LinearLayout row;
TextView channel;
ImageView icon;
TextView callsign;
}
}
| public void bindView( View view, Context context, Cursor cursor ) {
final ChannelInfo channel = ChannelDaoHelper.convertCursorToChannelInfo( cursor );
final ViewHolder mHolder = (ViewHolder) view.getTag();
mHolder.channel.setText( channel.getChannelNumber() );
mHolder.callsign.setText( channel.getCallSign() );
if(mSelectedChannel == null || mSelectedChannel.getChannelId() != channel.getChannelId()){
view.setBackgroundDrawable( mBackground );
}else {
view.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add(view);
}
if( downloadIcons ) {
String imageUri = mLocationProfileDaoHelper.findConnectedProfile( getActivity() ).getUrl() + "Guide/GetChannelIcon?ChanId=" + channel.getChannelId() + "&Width=32&Height=32";
imageLoader.displayImage( imageUri, mHolder.icon, options, new SimpleImageLoadingListener() {
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingComplete(android.graphics.Bitmap)
*/
@Override
public void onLoadingComplete( String imageUri, View view, Bitmap loadedImage ) {
/* mHolder.icon.setVisibility( View.GONE );
mHolder.icon.setVisibility( View.VISIBLE );
*/ }
/* (non-Javadoc)
* @see com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener#onLoadingFailed(com.nostra13.universalimageloader.core.assist.FailReason)
*/
@Override
public void onLoadingFailed( String imageUri, View view, FailReason failReason ) {
/* mHolder.icon.setVisibility( View.VISIBLE );
mHolder.icon.setVisibility( View.GONE );
*/ }
});
}
mHolder.row.setOnClickListener( new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick( View v ) {
mOnChannelScrollListener.channelSelect( channel.getChannelId() );
mSelectedChannel = channel;
for( View view : selectedViews ) {
view.setBackgroundDrawable( mBackground );
}
selectedViews.clear();
v.setBackgroundDrawable( mBackgroundSelected );
selectedViews.add( v );
}
});
}
/* (non-Javadoc)
* @see android.support.v4.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView( Context context, Cursor cursor, ViewGroup parent ) {
View view = mInflater.inflate( R.layout.program_guide_channel_row, parent, false );
ViewHolder refHolder = new ViewHolder();
refHolder.row = (LinearLayout) view.findViewById( R.id.program_guide_channel );
refHolder.channel = (TextView) view.findViewById( R.id.program_guide_channel_number );
refHolder.icon = (ImageView) view.findViewById( R.id.program_guide_channel_icon );
refHolder.callsign = (TextView) view.findViewById( R.id.program_guide_channel_callsign );
view.setTag( refHolder );
return view;
}
}
private static class ViewHolder {
LinearLayout row;
TextView channel;
ImageView icon;
TextView callsign;
}
}
|
diff --git a/src/com/qrsphere/SplashScreen.java b/src/com/qrsphere/SplashScreen.java
index 99110a5..88860b6 100644
--- a/src/com/qrsphere/SplashScreen.java
+++ b/src/com/qrsphere/SplashScreen.java
@@ -1,59 +1,59 @@
package com.qrsphere;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
public class SplashScreen extends Activity {
protected boolean _active = true;
protected int _splashTime = 5000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.q_logo);
iv.setBackgroundColor(Color.TRANSPARENT);
setContentView(iv);
Thread splashTread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
// start mainActivity
- startActivity(new Intent("com.example.tabview_test.MainActivity"));
+ startActivity(new Intent("com.qrsphere.MainActivity"));
// stop(); //android does not support stop() any more, following code could be a way to exit
// shouldContinue = false;
// join();
}
}
};
splashTread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
_active = false;
}
return true;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.q_logo);
iv.setBackgroundColor(Color.TRANSPARENT);
setContentView(iv);
Thread splashTread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
// start mainActivity
startActivity(new Intent("com.example.tabview_test.MainActivity"));
// stop(); //android does not support stop() any more, following code could be a way to exit
// shouldContinue = false;
// join();
}
}
};
splashTread.start();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.q_logo);
iv.setBackgroundColor(Color.TRANSPARENT);
setContentView(iv);
Thread splashTread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
// start mainActivity
startActivity(new Intent("com.qrsphere.MainActivity"));
// stop(); //android does not support stop() any more, following code could be a way to exit
// shouldContinue = false;
// join();
}
}
};
splashTread.start();
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java b/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java
index e6ccf6ea..a37c9c97 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java
@@ -1,524 +1,526 @@
package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** Generates js code for invocation expression (named and positional). */
public class InvocationGenerator {
private final GenerateJsVisitor gen;
private final JsIdentifierNames names;
private final RetainedVars retainedVars;
InvocationGenerator(GenerateJsVisitor owner, JsIdentifierNames names, RetainedVars rv) {
gen = owner;
this.names = names;
retainedVars = rv;
}
void generateInvocation(Tree.InvocationExpression that) {
if (that.getNamedArgumentList()!=null) {
Tree.NamedArgumentList argList = that.getNamedArgumentList();
if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.MemberOrTypeExpression
&& ((Tree.MemberOrTypeExpression)that.getPrimary()).getDeclaration() == null) {
final String fname = names.createTempVariable();
gen.out("(", fname, "=");
//Call a native js constructor passing a native js object as parameter
that.getPrimary().visit(gen);
gen.out(",", fname, ".$$===undefined?new ", fname, "(");
nativeObject(argList);
gen.out("):", fname, "(");
nativeObject(argList);
gen.out("))");
} else {
gen.out("(");
Map<String, String> argVarNames = defineNamedArguments(that.getPrimary(), argList);
that.getPrimary().visit(gen);
final Tree.TypeArguments targs;
if (that.getPrimary() instanceof Tree.BaseMemberOrTypeExpression) {
targs = ((Tree.BaseMemberOrTypeExpression)that.getPrimary()).getTypeArguments();
} else if (that.getPrimary() instanceof Tree.QualifiedMemberOrTypeExpression) {
targs = ((Tree.QualifiedMemberOrTypeExpression)that.getPrimary()).getTypeArguments();
} else {
targs = null;
}
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
applyNamedArguments(argList, f, argVarNames, gen.getSuperMemberScope(mte)!=null, targs);
}
}
gen.out(")");
}
}
else {
Tree.PositionalArgumentList argList = that.getPositionalArgumentList();
Tree.Primary typeArgSource = that.getPrimary();
//In nested invocation expressions, use the first invocation as source for type arguments
while (typeArgSource instanceof Tree.InvocationExpression) {
typeArgSource = ((Tree.InvocationExpression)typeArgSource).getPrimary();
}
Tree.TypeArguments targs = typeArgSource instanceof Tree.StaticMemberOrTypeExpression
? ((Tree.StaticMemberOrTypeExpression)typeArgSource).getTypeArguments() : null;
if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.BaseTypeExpression
&& ((Tree.BaseTypeExpression)that.getPrimary()).getDeclaration() == null) {
gen.out("(");
//Could be a dynamic object, or a Ceylon one
//We might need to call "new" so we need to get all the args to pass directly later
final List<String> argnames = generatePositionalArguments(that.getPrimary(),
argList, argList.getPositionalArguments(), false, true);
if (!argnames.isEmpty()) {
gen.out(",");
}
final String fname = names.createTempVariable();
gen.out(fname,"=");
that.getPrimary().visit(gen);
String fuckingargs = "";
if (!argnames.isEmpty()) {
fuckingargs = argnames.toString().substring(1);
fuckingargs = fuckingargs.substring(0, fuckingargs.length()-1);
}
gen.out(",", fname, ".$$===undefined?new ", fname, "(", fuckingargs, "):", fname, "(", fuckingargs, "))");
//TODO we lose type args for now
return;
} else {
if (that.getPrimary() instanceof Tree.BaseMemberExpression) {
BmeGenerator.generateBme((Tree.BaseMemberExpression)that.getPrimary(), gen, true);
} else {
that.getPrimary().visit(gen);
}
if (gen.opts.isOptimize() && (gen.getSuperMemberScope(that.getPrimary()) != null)) {
gen.out(".call(this");
if (!argList.getPositionalArguments().isEmpty()) {
gen.out(",");
}
} else {
gen.out("(");
}
//Check if args have params
boolean fillInParams = !argList.getPositionalArguments().isEmpty();
for (Tree.PositionalArgument arg : argList.getPositionalArguments()) {
fillInParams &= arg.getParameter() == null;
}
if (fillInParams) {
//Get the callable and try to assign params from there
ProducedType callable = that.getPrimary().getTypeModel().getSupertype(
gen.getTypeUtils().callable);
if (callable != null) {
//This is a tuple with the arguments to the callable
//(can be union with empty if first param is defaulted)
ProducedType callableArgs = callable.getTypeArgumentList().get(1);
boolean isUnion=false;
if (callableArgs.getDeclaration() instanceof UnionType) {
if (callableArgs.getCaseTypes().size() == 2) {
callableArgs = callableArgs.minus(gen.getTypeUtils().empty.getType());
}
isUnion=callableArgs.getDeclaration() instanceof UnionType;
}
//This is the type of the first argument
boolean isSequenced = !(isUnion || gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()));
- ProducedType argtype = isUnion ? callableArgs : callableArgs.getTypeArgumentList().get(
+ ProducedType argtype = isUnion ? callableArgs :
+ callableArgs.getDeclaration() instanceof TypeParameter ? callableArgs :
+ callableArgs.getTypeArgumentList().get(
isSequenced ? 0 : 1);
Parameter p = null;
int c = 0;
for (Tree.PositionalArgument arg : argList.getPositionalArguments()) {
if (p == null) {
p = new Parameter();
p.setName("arg"+c);
p.setDeclaration(that.getPrimary().getTypeModel().getDeclaration());
Value v = new Value();
v.setContainer(that.getPositionalArgumentList().getScope());
v.setType(argtype);
p.setModel(v);
if (callableArgs == null || isSequenced) {
p.setSequenced(true);
} else if (!isSequenced) {
ProducedType next = isUnion ? null : callableArgs.getTypeArgumentList().get(2);
if (next != null && next.getSupertype(gen.getTypeUtils().tuple) == null) {
//It's not a tuple, so no more regular parms. It can be:
//empty|tuple if defaulted params
//empty if no more params
//sequential if sequenced param
if (next.getDeclaration() instanceof UnionType) {
//empty|tuple
callableArgs = next.minus(gen.getTypeUtils().empty.getType());
isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration());
argtype = callableArgs.getTypeArgumentList().get(isSequenced ? 0 : 1);
} else {
//we'll bet on sequential (if it's empty we don't care anyway)
argtype = next;
callableArgs = null;
}
} else {
//If it's a tuple then there are more params
callableArgs = next;
argtype = callableArgs == null ? null : callableArgs.getTypeArgumentList().get(1);
}
}
}
arg.setParameter(p);
c++;
if (!p.isSequenced()) {
p = null;
}
}
}
}
generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, false);
}
if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) {
if (argList.getPositionalArguments().size() > 0) {
gen.out(",");
}
Declaration bmed = ((Tree.StaticMemberOrTypeExpression)typeArgSource).getDeclaration();
if (bmed instanceof Functional) {
//If there are fewer arguments than there are parameters...
final int argsSize = argList.getPositionalArguments().size();
int paramArgDiff = ((Functional) bmed).getParameterLists().get(0).getParameters().size() - argsSize;
if (paramArgDiff > 0) {
final Tree.PositionalArgument parg = argsSize > 0 ? argList.getPositionalArguments().get(argsSize-1) : null;
if (parg instanceof Tree.Comprehension || parg instanceof Tree.SpreadArgument) {
paramArgDiff--;
}
for (int i=0; i < paramArgDiff; i++) {
gen.out("undefined,");
}
}
if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) {
Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments(
((Functional) bmed).getTypeParameters(), targs.getTypeModels());
if (invargs != null) {
TypeUtils.printTypeArguments(typeArgSource, invargs, gen);
} else {
gen.out("/*TARGS != TPARAMS!!!! WTF?????*/");
}
}
}
}
gen.out(")");
}
}
/** Generates the code to evaluate the expressions in the named argument list and assign them
* to variables, then returns a map with the parameter names and the corresponding variable names. */
Map<String, String> defineNamedArguments(Tree.Primary primary, Tree.NamedArgumentList argList) {
Map<String, String> argVarNames = new HashMap<String, String>();
for (Tree.NamedArgument arg: argList.getNamedArguments()) {
Parameter p = arg.getParameter();
final String paramName;
if (p == null && gen.isInDynamicBlock()) {
paramName = arg.getIdentifier().getText();
} else {
paramName = arg.getParameter().getName();
}
String varName = names.createTempVariable(paramName);
argVarNames.put(paramName, varName);
retainedVars.add(varName);
gen.out(varName, "=");
arg.visit(gen);
gen.out(",");
}
Tree.SequencedArgument sarg = argList.getSequencedArgument();
if (sarg!=null) {
String paramName = sarg.getParameter().getName();
String varName = names.createTempVariable(paramName);
argVarNames.put(paramName, varName);
retainedVars.add(varName);
gen.out(varName, "=");
generatePositionalArguments(primary, argList, sarg.getPositionalArguments(), true, false);
gen.out(",");
}
return argVarNames;
}
void applyNamedArguments(Tree.NamedArgumentList argList, Functional func,
Map<String, String> argVarNames, boolean superAccess, Tree.TypeArguments targs) {
boolean firstList = true;
for (com.redhat.ceylon.compiler.typechecker.model.ParameterList plist : func.getParameterLists()) {
boolean first=true;
if (firstList && superAccess) {
gen.out(".call(this");
if (!plist.getParameters().isEmpty()) { gen.out(","); }
}
else {
gen.out("(");
}
for (Parameter p : plist.getParameters()) {
if (!first) gen.out(",");
final String vname = argVarNames.get(p.getName());
if (vname == null) {
if (p.isDefaulted()) {
gen.out("undefined");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "getEmpty()");
}
} else {
gen.out(vname);
}
first = false;
}
if (targs != null && !targs.getTypeModels().isEmpty()) {
Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments(
func.getTypeParameters(), targs.getTypeModels());
if (!first) gen.out(",");
TypeUtils.printTypeArguments(argList, invargs, gen);
}
gen.out(")");
firstList = false;
}
}
/** Generate a list of PositionalArguments, optionally assigning a variable name to each one
* and returning the variable names. */
List<String> generatePositionalArguments(final Tree.Primary primary, final Tree.ArgumentList that,
final List<Tree.PositionalArgument> args,
final boolean forceSequenced, final boolean generateVars) {
if (!args.isEmpty()) {
final List<String> argvars = new ArrayList<String>(args.size());
boolean first=true;
boolean opened=false;
ProducedType sequencedType=null;
for (Tree.PositionalArgument arg : args) {
Tree.Expression expr;
final Parameter pd = arg.getParameter();
if (arg instanceof Tree.ListedArgument) {
if (!first) gen.out(",");
expr = ((Tree.ListedArgument) arg).getExpression();
ProducedType exprType = expr.getTypeModel();
boolean dyncheck = gen.isInDynamicBlock() && !TypeUtils.isUnknown(pd)
&& exprType.containsUnknowns();
if (forceSequenced || (pd != null && pd.isSequenced())) {
if (dyncheck) {
//We don't have a real type so get the one declared in the parameter
exprType = pd.getType();
}
if (sequencedType == null) {
sequencedType=exprType;
} else {
ArrayList<ProducedType> cases = new ArrayList<ProducedType>(2);
Util.addToUnion(cases, sequencedType);
Util.addToUnion(cases, exprType);
if (cases.size() > 1) {
UnionType ut = new UnionType(that.getUnit());
ut.setCaseTypes(cases);
sequencedType = ut.getType();
} else {
sequencedType = cases.get(0);
}
}
if (!opened) {
if (generateVars) {
final String argvar = names.createTempVariable();
argvars.add(argvar);
gen.out(argvar, "=");
}
gen.out("[");
}
opened=true;
} else if (generateVars) {
final String argvar = names.createTempVariable();
argvars.add(argvar);
gen.out(argvar, "=");
}
TypedDeclaration decl = pd == null ? null : pd.getModel();
int boxType = gen.boxUnboxStart(expr.getTerm(), decl);
if (dyncheck) {
TypeUtils.generateDynamicCheck(((Tree.ListedArgument) arg).getExpression(),
pd.getType(), gen);
} else {
arg.visit(gen);
}
if (boxType == 4) {
gen.out(",");
//Add parameters
describeMethodParameters(expr.getTerm());
gen.out(",");
TypeUtils.printTypeArguments(arg, arg.getTypeModel().getTypeArguments(), gen);
}
gen.boxUnboxEnd(boxType);
} else if (arg instanceof Tree.SpreadArgument || arg instanceof Tree.Comprehension) {
if (arg instanceof Tree.SpreadArgument) {
expr = ((Tree.SpreadArgument) arg).getExpression();
} else {
expr = null;
}
if (opened) {
gen.closeSequenceWithReifiedType(that,
gen.getTypeUtils().wrapAsIterableArguments(sequencedType));
gen.out(".chain(");
sequencedType=null;
} else if (!first) {
gen.out(",");
}
if (arg instanceof Tree.SpreadArgument) {
TypedDeclaration td = pd == null ? null : pd.getModel();
int boxType = gen.boxUnboxStart(expr.getTerm(), td);
if (boxType == 4) {
arg.visit(gen);
gen.out(",");
describeMethodParameters(expr.getTerm());
gen.out(",");
TypeUtils.printTypeArguments(arg, arg.getTypeModel().getTypeArguments(), gen);
} else if (pd == null) {
if (gen.isInDynamicBlock() && primary instanceof Tree.MemberOrTypeExpression
&& ((Tree.MemberOrTypeExpression)primary).getDeclaration() == null
&& arg.getTypeModel() != null && arg.getTypeModel().getDeclaration().inherits((gen.getTypeUtils().tuple))) {
//Spread dynamic parameter
ProducedType tupleType = arg.getTypeModel();
ProducedType targ = tupleType.getTypeArgumentList().get(2);
arg.visit(gen);
gen.out(".$get(0)");
int i = 1;
while (!targ.getDeclaration().inherits(gen.getTypeUtils().empty)) {
gen.out(",");
arg.visit(gen);
gen.out(".$get("+(i++)+")");
targ = targ.getTypeArgumentList().get(2);
}
} else {
arg.visit(gen);
}
} else if (pd.isSequenced()) {
arg.visit(gen);
} else {
arg.visit(gen);
gen.out(".$get(0)");
//Find out if there are more params
final List<Parameter> moreParams;
final Declaration pdd = pd.getDeclaration();
boolean found = false;
if (pdd instanceof Method) {
moreParams = ((Method)pdd).getParameterLists().get(0).getParameters();
} else if (pdd instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
moreParams = ((com.redhat.ceylon.compiler.typechecker.model.Class)pdd).getParameterList().getParameters();
} else {
//Check the parameters of the primary (obviously a callable, so this is a Tuple)
List<Parameter> cparms = gen.getTypeUtils().convertTupleToParameters(
primary.getTypeModel().getTypeArgumentList().get(1));
cparms.remove(0);
moreParams = cparms;
found = true;
}
if (moreParams != null) {
int c = 1;
for (Parameter restp : moreParams) {
if (found) {
gen.out(",");
arg.visit(gen);
gen.out(".$get(", Integer.toString(c++), ")||undefined");
} else {
found = restp.equals(pd);
}
}
}
}
gen.boxUnboxEnd(boxType);
} else {
((Tree.Comprehension)arg).visit(gen);
}
if (opened) {
gen.out(",");
if (expr == null) {
//it's a comprehension
TypeUtils.printTypeArguments(that,
gen.getTypeUtils().wrapAsIterableArguments(arg.getTypeModel()), gen);
} else {
ProducedType spreadType = TypeUtils.findSupertype(gen.getTypeUtils().sequential,
expr.getTypeModel());
TypeUtils.printTypeArguments(that, spreadType.getTypeArguments(), gen);
}
gen.out(")");
}
if (arg instanceof Tree.Comprehension) {
break;
}
}
first = false;
}
if (sequencedType != null) {
gen.closeSequenceWithReifiedType(that,
gen.getTypeUtils().wrapAsIterableArguments(sequencedType));
}
return argvars;
}
return Collections.emptyList();
}
/** Generate the code to create a native js object. */
void nativeObject(Tree.NamedArgumentList argList) {
if (argList.getSequencedArgument() == null) {
gen.out("{");
boolean first = true;
for (Tree.NamedArgument arg : argList.getNamedArguments()) {
if (first) { first = false; } else { gen.out(","); }
gen.out(arg.getIdentifier().getText(), ":");
arg.visit(gen);
}
gen.out("}");
} else {
String arr = null;
if (argList.getNamedArguments().size() > 0) {
gen.out("function()");
gen.beginBlock();
arr = names.createTempVariable();
gen.out("var ", arr, "=");
}
gen.out("[");
boolean first = true;
for (Tree.PositionalArgument arg : argList.getSequencedArgument().getPositionalArguments()) {
if (first) { first = false; } else { gen.out(","); }
arg.visit(gen);
}
gen.out("]");
if (argList.getNamedArguments().size() > 0) {
gen.endLine(true);
for (Tree.NamedArgument arg : argList.getNamedArguments()) {
gen.out(arr, ".", arg.getIdentifier().getText(), "=");
arg.visit(gen);
gen.endLine(true);
}
gen.out("return ", arr,";");
gen.endBlock();
gen.out("()");
}
}
}
private void describeMethodParameters(Tree.Term term) {
Method _m = null;
if (term instanceof Tree.FunctionArgument) {
_m = (((Tree.FunctionArgument)term).getDeclarationModel());
} else if (term instanceof Tree.MemberOrTypeExpression) {
if (((Tree.MemberOrTypeExpression)term).getDeclaration() instanceof Method) {
_m = (Method)((Tree.MemberOrTypeExpression)term).getDeclaration();
}
} else if (term instanceof Tree.InvocationExpression) {
TypeUtils.encodeCallableArgumentsAsParameterListForRuntime(term.getTypeModel(), gen);
return;
} else {
gen.out("/*WARNING4 Callable EXPR of type ", term.getClass().getName(), "*/");
}
if (_m == null) {
gen.out("[]");
} else {
TypeUtils.encodeParameterListForRuntime(term, _m.getParameterLists().get(0), gen);
}
}
}
| true | true | void generateInvocation(Tree.InvocationExpression that) {
if (that.getNamedArgumentList()!=null) {
Tree.NamedArgumentList argList = that.getNamedArgumentList();
if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.MemberOrTypeExpression
&& ((Tree.MemberOrTypeExpression)that.getPrimary()).getDeclaration() == null) {
final String fname = names.createTempVariable();
gen.out("(", fname, "=");
//Call a native js constructor passing a native js object as parameter
that.getPrimary().visit(gen);
gen.out(",", fname, ".$$===undefined?new ", fname, "(");
nativeObject(argList);
gen.out("):", fname, "(");
nativeObject(argList);
gen.out("))");
} else {
gen.out("(");
Map<String, String> argVarNames = defineNamedArguments(that.getPrimary(), argList);
that.getPrimary().visit(gen);
final Tree.TypeArguments targs;
if (that.getPrimary() instanceof Tree.BaseMemberOrTypeExpression) {
targs = ((Tree.BaseMemberOrTypeExpression)that.getPrimary()).getTypeArguments();
} else if (that.getPrimary() instanceof Tree.QualifiedMemberOrTypeExpression) {
targs = ((Tree.QualifiedMemberOrTypeExpression)that.getPrimary()).getTypeArguments();
} else {
targs = null;
}
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
applyNamedArguments(argList, f, argVarNames, gen.getSuperMemberScope(mte)!=null, targs);
}
}
gen.out(")");
}
}
else {
Tree.PositionalArgumentList argList = that.getPositionalArgumentList();
Tree.Primary typeArgSource = that.getPrimary();
//In nested invocation expressions, use the first invocation as source for type arguments
while (typeArgSource instanceof Tree.InvocationExpression) {
typeArgSource = ((Tree.InvocationExpression)typeArgSource).getPrimary();
}
Tree.TypeArguments targs = typeArgSource instanceof Tree.StaticMemberOrTypeExpression
? ((Tree.StaticMemberOrTypeExpression)typeArgSource).getTypeArguments() : null;
if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.BaseTypeExpression
&& ((Tree.BaseTypeExpression)that.getPrimary()).getDeclaration() == null) {
gen.out("(");
//Could be a dynamic object, or a Ceylon one
//We might need to call "new" so we need to get all the args to pass directly later
final List<String> argnames = generatePositionalArguments(that.getPrimary(),
argList, argList.getPositionalArguments(), false, true);
if (!argnames.isEmpty()) {
gen.out(",");
}
final String fname = names.createTempVariable();
gen.out(fname,"=");
that.getPrimary().visit(gen);
String fuckingargs = "";
if (!argnames.isEmpty()) {
fuckingargs = argnames.toString().substring(1);
fuckingargs = fuckingargs.substring(0, fuckingargs.length()-1);
}
gen.out(",", fname, ".$$===undefined?new ", fname, "(", fuckingargs, "):", fname, "(", fuckingargs, "))");
//TODO we lose type args for now
return;
} else {
if (that.getPrimary() instanceof Tree.BaseMemberExpression) {
BmeGenerator.generateBme((Tree.BaseMemberExpression)that.getPrimary(), gen, true);
} else {
that.getPrimary().visit(gen);
}
if (gen.opts.isOptimize() && (gen.getSuperMemberScope(that.getPrimary()) != null)) {
gen.out(".call(this");
if (!argList.getPositionalArguments().isEmpty()) {
gen.out(",");
}
} else {
gen.out("(");
}
//Check if args have params
boolean fillInParams = !argList.getPositionalArguments().isEmpty();
for (Tree.PositionalArgument arg : argList.getPositionalArguments()) {
fillInParams &= arg.getParameter() == null;
}
if (fillInParams) {
//Get the callable and try to assign params from there
ProducedType callable = that.getPrimary().getTypeModel().getSupertype(
gen.getTypeUtils().callable);
if (callable != null) {
//This is a tuple with the arguments to the callable
//(can be union with empty if first param is defaulted)
ProducedType callableArgs = callable.getTypeArgumentList().get(1);
boolean isUnion=false;
if (callableArgs.getDeclaration() instanceof UnionType) {
if (callableArgs.getCaseTypes().size() == 2) {
callableArgs = callableArgs.minus(gen.getTypeUtils().empty.getType());
}
isUnion=callableArgs.getDeclaration() instanceof UnionType;
}
//This is the type of the first argument
boolean isSequenced = !(isUnion || gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()));
ProducedType argtype = isUnion ? callableArgs : callableArgs.getTypeArgumentList().get(
isSequenced ? 0 : 1);
Parameter p = null;
int c = 0;
for (Tree.PositionalArgument arg : argList.getPositionalArguments()) {
if (p == null) {
p = new Parameter();
p.setName("arg"+c);
p.setDeclaration(that.getPrimary().getTypeModel().getDeclaration());
Value v = new Value();
v.setContainer(that.getPositionalArgumentList().getScope());
v.setType(argtype);
p.setModel(v);
if (callableArgs == null || isSequenced) {
p.setSequenced(true);
} else if (!isSequenced) {
ProducedType next = isUnion ? null : callableArgs.getTypeArgumentList().get(2);
if (next != null && next.getSupertype(gen.getTypeUtils().tuple) == null) {
//It's not a tuple, so no more regular parms. It can be:
//empty|tuple if defaulted params
//empty if no more params
//sequential if sequenced param
if (next.getDeclaration() instanceof UnionType) {
//empty|tuple
callableArgs = next.minus(gen.getTypeUtils().empty.getType());
isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration());
argtype = callableArgs.getTypeArgumentList().get(isSequenced ? 0 : 1);
} else {
//we'll bet on sequential (if it's empty we don't care anyway)
argtype = next;
callableArgs = null;
}
} else {
//If it's a tuple then there are more params
callableArgs = next;
argtype = callableArgs == null ? null : callableArgs.getTypeArgumentList().get(1);
}
}
}
arg.setParameter(p);
c++;
if (!p.isSequenced()) {
p = null;
}
}
}
}
generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, false);
}
if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) {
if (argList.getPositionalArguments().size() > 0) {
gen.out(",");
}
Declaration bmed = ((Tree.StaticMemberOrTypeExpression)typeArgSource).getDeclaration();
if (bmed instanceof Functional) {
//If there are fewer arguments than there are parameters...
final int argsSize = argList.getPositionalArguments().size();
int paramArgDiff = ((Functional) bmed).getParameterLists().get(0).getParameters().size() - argsSize;
if (paramArgDiff > 0) {
final Tree.PositionalArgument parg = argsSize > 0 ? argList.getPositionalArguments().get(argsSize-1) : null;
if (parg instanceof Tree.Comprehension || parg instanceof Tree.SpreadArgument) {
paramArgDiff--;
}
for (int i=0; i < paramArgDiff; i++) {
gen.out("undefined,");
}
}
if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) {
Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments(
((Functional) bmed).getTypeParameters(), targs.getTypeModels());
if (invargs != null) {
TypeUtils.printTypeArguments(typeArgSource, invargs, gen);
} else {
gen.out("/*TARGS != TPARAMS!!!! WTF?????*/");
}
}
}
}
gen.out(")");
}
}
| void generateInvocation(Tree.InvocationExpression that) {
if (that.getNamedArgumentList()!=null) {
Tree.NamedArgumentList argList = that.getNamedArgumentList();
if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.MemberOrTypeExpression
&& ((Tree.MemberOrTypeExpression)that.getPrimary()).getDeclaration() == null) {
final String fname = names.createTempVariable();
gen.out("(", fname, "=");
//Call a native js constructor passing a native js object as parameter
that.getPrimary().visit(gen);
gen.out(",", fname, ".$$===undefined?new ", fname, "(");
nativeObject(argList);
gen.out("):", fname, "(");
nativeObject(argList);
gen.out("))");
} else {
gen.out("(");
Map<String, String> argVarNames = defineNamedArguments(that.getPrimary(), argList);
that.getPrimary().visit(gen);
final Tree.TypeArguments targs;
if (that.getPrimary() instanceof Tree.BaseMemberOrTypeExpression) {
targs = ((Tree.BaseMemberOrTypeExpression)that.getPrimary()).getTypeArguments();
} else if (that.getPrimary() instanceof Tree.QualifiedMemberOrTypeExpression) {
targs = ((Tree.QualifiedMemberOrTypeExpression)that.getPrimary()).getTypeArguments();
} else {
targs = null;
}
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration() instanceof Functional) {
Functional f = (Functional) mte.getDeclaration();
applyNamedArguments(argList, f, argVarNames, gen.getSuperMemberScope(mte)!=null, targs);
}
}
gen.out(")");
}
}
else {
Tree.PositionalArgumentList argList = that.getPositionalArgumentList();
Tree.Primary typeArgSource = that.getPrimary();
//In nested invocation expressions, use the first invocation as source for type arguments
while (typeArgSource instanceof Tree.InvocationExpression) {
typeArgSource = ((Tree.InvocationExpression)typeArgSource).getPrimary();
}
Tree.TypeArguments targs = typeArgSource instanceof Tree.StaticMemberOrTypeExpression
? ((Tree.StaticMemberOrTypeExpression)typeArgSource).getTypeArguments() : null;
if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.BaseTypeExpression
&& ((Tree.BaseTypeExpression)that.getPrimary()).getDeclaration() == null) {
gen.out("(");
//Could be a dynamic object, or a Ceylon one
//We might need to call "new" so we need to get all the args to pass directly later
final List<String> argnames = generatePositionalArguments(that.getPrimary(),
argList, argList.getPositionalArguments(), false, true);
if (!argnames.isEmpty()) {
gen.out(",");
}
final String fname = names.createTempVariable();
gen.out(fname,"=");
that.getPrimary().visit(gen);
String fuckingargs = "";
if (!argnames.isEmpty()) {
fuckingargs = argnames.toString().substring(1);
fuckingargs = fuckingargs.substring(0, fuckingargs.length()-1);
}
gen.out(",", fname, ".$$===undefined?new ", fname, "(", fuckingargs, "):", fname, "(", fuckingargs, "))");
//TODO we lose type args for now
return;
} else {
if (that.getPrimary() instanceof Tree.BaseMemberExpression) {
BmeGenerator.generateBme((Tree.BaseMemberExpression)that.getPrimary(), gen, true);
} else {
that.getPrimary().visit(gen);
}
if (gen.opts.isOptimize() && (gen.getSuperMemberScope(that.getPrimary()) != null)) {
gen.out(".call(this");
if (!argList.getPositionalArguments().isEmpty()) {
gen.out(",");
}
} else {
gen.out("(");
}
//Check if args have params
boolean fillInParams = !argList.getPositionalArguments().isEmpty();
for (Tree.PositionalArgument arg : argList.getPositionalArguments()) {
fillInParams &= arg.getParameter() == null;
}
if (fillInParams) {
//Get the callable and try to assign params from there
ProducedType callable = that.getPrimary().getTypeModel().getSupertype(
gen.getTypeUtils().callable);
if (callable != null) {
//This is a tuple with the arguments to the callable
//(can be union with empty if first param is defaulted)
ProducedType callableArgs = callable.getTypeArgumentList().get(1);
boolean isUnion=false;
if (callableArgs.getDeclaration() instanceof UnionType) {
if (callableArgs.getCaseTypes().size() == 2) {
callableArgs = callableArgs.minus(gen.getTypeUtils().empty.getType());
}
isUnion=callableArgs.getDeclaration() instanceof UnionType;
}
//This is the type of the first argument
boolean isSequenced = !(isUnion || gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()));
ProducedType argtype = isUnion ? callableArgs :
callableArgs.getDeclaration() instanceof TypeParameter ? callableArgs :
callableArgs.getTypeArgumentList().get(
isSequenced ? 0 : 1);
Parameter p = null;
int c = 0;
for (Tree.PositionalArgument arg : argList.getPositionalArguments()) {
if (p == null) {
p = new Parameter();
p.setName("arg"+c);
p.setDeclaration(that.getPrimary().getTypeModel().getDeclaration());
Value v = new Value();
v.setContainer(that.getPositionalArgumentList().getScope());
v.setType(argtype);
p.setModel(v);
if (callableArgs == null || isSequenced) {
p.setSequenced(true);
} else if (!isSequenced) {
ProducedType next = isUnion ? null : callableArgs.getTypeArgumentList().get(2);
if (next != null && next.getSupertype(gen.getTypeUtils().tuple) == null) {
//It's not a tuple, so no more regular parms. It can be:
//empty|tuple if defaulted params
//empty if no more params
//sequential if sequenced param
if (next.getDeclaration() instanceof UnionType) {
//empty|tuple
callableArgs = next.minus(gen.getTypeUtils().empty.getType());
isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration());
argtype = callableArgs.getTypeArgumentList().get(isSequenced ? 0 : 1);
} else {
//we'll bet on sequential (if it's empty we don't care anyway)
argtype = next;
callableArgs = null;
}
} else {
//If it's a tuple then there are more params
callableArgs = next;
argtype = callableArgs == null ? null : callableArgs.getTypeArgumentList().get(1);
}
}
}
arg.setParameter(p);
c++;
if (!p.isSequenced()) {
p = null;
}
}
}
}
generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, false);
}
if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) {
if (argList.getPositionalArguments().size() > 0) {
gen.out(",");
}
Declaration bmed = ((Tree.StaticMemberOrTypeExpression)typeArgSource).getDeclaration();
if (bmed instanceof Functional) {
//If there are fewer arguments than there are parameters...
final int argsSize = argList.getPositionalArguments().size();
int paramArgDiff = ((Functional) bmed).getParameterLists().get(0).getParameters().size() - argsSize;
if (paramArgDiff > 0) {
final Tree.PositionalArgument parg = argsSize > 0 ? argList.getPositionalArguments().get(argsSize-1) : null;
if (parg instanceof Tree.Comprehension || parg instanceof Tree.SpreadArgument) {
paramArgDiff--;
}
for (int i=0; i < paramArgDiff; i++) {
gen.out("undefined,");
}
}
if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) {
Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments(
((Functional) bmed).getTypeParameters(), targs.getTypeModels());
if (invargs != null) {
TypeUtils.printTypeArguments(typeArgSource, invargs, gen);
} else {
gen.out("/*TARGS != TPARAMS!!!! WTF?????*/");
}
}
}
}
gen.out(")");
}
}
|
diff --git a/src/org/apache/xerces/validators/common/XMLValidator.java b/src/org/apache/xerces/validators/common/XMLValidator.java
index c340d4846..15ab58928 100644
--- a/src/org/apache/xerces/validators/common/XMLValidator.java
+++ b/src/org/apache/xerces/validators/common/XMLValidator.java
@@ -1,3531 +1,3536 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999,2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.common;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.framework.XMLContentSpec;
import org.apache.xerces.framework.XMLDocumentHandler;
import org.apache.xerces.framework.XMLDocumentScanner;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.readers.DefaultEntityHandler;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.utils.ChunkyCharArray;
import org.apache.xerces.utils.Hash2intTable;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.utils.ImplementationMessages;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.EntityResolver;
import org.xml.sax.Locator;
import org.xml.sax.helpers.LocatorImpl;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.xerces.validators.dtd.DTDGrammar;
import org.apache.xerces.validators.schema.EquivClassComparator;
import org.apache.xerces.validators.schema.SchemaGrammar;
import org.apache.xerces.validators.schema.SchemaMessageProvider;
import org.apache.xerces.validators.schema.SchemaSymbols;
import org.apache.xerces.validators.schema.TraverseSchema;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.validators.datatype.StateMessageDatatype;
import org.apache.xerces.validators.datatype.IDREFDatatypeValidator;
import org.apache.xerces.validators.datatype.IDDatatypeValidator;
import org.apache.xerces.validators.datatype.ENTITYDatatypeValidator;
/**
* This class is the super all-in-one validator used by the parser.
*
* @version $Id$
*/
public final class XMLValidator
implements DefaultEntityHandler.EventHandler,
XMLEntityHandler.CharDataHandler,
XMLDocumentScanner.EventHandler,
NamespacesScope.NamespacesHandler {
//
// Constants
//
// debugging
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
private static final boolean DEBUG_PRINT_ATTRIBUTES = false;
private static final boolean DEBUG_PRINT_CONTENT = false;
private static final boolean DEBUG_SCHEMA_VALIDATION = false;
private static final boolean DEBUG_ELEMENT_CHILDREN = false;
// Chunk size constants
private static final int CHUNK_SHIFT = 8; // 2^8 = 256
private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT);
private static final int CHUNK_MASK = CHUNK_SIZE - 1;
private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k
private Hashtable fIdDefs = null;
private StateMessageDatatype fStoreIDRef = new StateMessageDatatype() {
private Hashtable fIdDefs;
public Object getDatatypeObject(){
return(Object) fIdDefs;
}
public int getDatatypeState(){
return IDREFDatatypeValidator.IDREF_STORE;
}
public void setDatatypeObject( Object data ){
fIdDefs = (Hashtable) data;
}
};
private StateMessageDatatype fResetID = new StateMessageDatatype() {
public Object getDatatypeObject(){
return(Object) null;
}
public int getDatatypeState(){
return IDDatatypeValidator.ID_CLEAR;
}
public void setDatatypeObject( Object data ){
}
};
private StateMessageDatatype fResetIDRef = new StateMessageDatatype() {
public Object getDatatypeObject(){
return(Object) null;
}
public int getDatatypeState(){
return IDREFDatatypeValidator.IDREF_CLEAR;
}
public void setDatatypeObject( Object data ){
}
};
private StateMessageDatatype fValidateIDRef = new StateMessageDatatype() {
public Object getDatatypeObject(){
return(Object) null;
}
public int getDatatypeState(){
return IDREFDatatypeValidator.IDREF_VALIDATE;
}
public void setDatatypeObject( Object data ){
}
};
private StateMessageDatatype fValidateENTITYMsg = new StateMessageDatatype() {
private Object packagedMessage = null;
public Object getDatatypeObject(){
return packagedMessage;
}
public int getDatatypeState(){
return ENTITYDatatypeValidator.ENTITY_INITIALIZE;//No state
}
public void setDatatypeObject( Object data ){
packagedMessage = data;// Set Entity Handler
}
};
/*
private StateMessageDatatype fValidateNOTATIONMsg = new StateMessageDatatype() {
private Object packagedMessage = null;
public Object getDatatypeObject(){
return packagedMessage;
}
public int getDatatypeState(){
return NOTATIONDatatypeValidator.ENTITY_INITIALIZE;//No state
}
public void setDatatypeObject( Object data ){
packagedMessage = data;// Set Entity Handler
}
};
*/
//
// Data
//
// REVISIT: The data should be regrouped and re-organized so that
// it's easier to find a meaningful field.
// debugging
// private static boolean DEBUG = false;
// other
// attribute validators
private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION();
private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION();
private AttributeValidator fAttValidatorDATATYPE = null;
// Package access for use by AttributeValidator classes.
StringPool fStringPool = null;
boolean fValidating = false;
boolean fInElementContent = false;
int fStandaloneReader = -1;
// settings
private boolean fValidationEnabled = false;
private boolean fDynamicValidation = false;
private boolean fSchemaValidation = true;
private boolean fValidationEnabledByDynamic = false;
private boolean fDynamicDisabledByValidation = false;
private boolean fWarningOnDuplicateAttDef = false;
private boolean fWarningOnUndeclaredElements = false;
private boolean fLoadDTDGrammar = true;
// declarations
private int fDeclaration[];
private XMLErrorReporter fErrorReporter = null;
private DefaultEntityHandler fEntityHandler = null;
private QName fCurrentElement = new QName();
private ContentLeafNameTypeVector[] fContentLeafStack = new ContentLeafNameTypeVector[8];
private int[] fValidationFlagStack = new int[8];
private int[] fScopeStack = new int[8];
private int[] fGrammarNameSpaceIndexStack = new int[8];
private int[] fElementEntityStack = new int[8];
private int[] fElementIndexStack = new int[8];
private int[] fContentSpecTypeStack = new int[8];
private static final int sizeQNameParts = 8;
private QName[] fElementQNamePartsStack = new QName[sizeQNameParts];
private QName[] fElementChildren = new QName[32];
private int fElementChildrenLength = 0;
private int[] fElementChildrenOffsetStack = new int[32];
private int fElementDepth = -1;
private boolean fNamespacesEnabled = false;
private NamespacesScope fNamespacesScope = null;
private int fNamespacesPrefix = -1;
private QName fRootElement = new QName();
private int fAttrListHandle = -1;
private int fCurrentElementEntity = -1;
private int fCurrentElementIndex = -1;
private int fCurrentContentSpecType = -1;
private boolean fSeenDoctypeDecl = false;
private final int TOP_LEVEL_SCOPE = -1;
private int fCurrentScope = TOP_LEVEL_SCOPE;
private int fCurrentSchemaURI = -1;
private int fEmptyURI = - 1;
private int fXsiPrefix = - 1;
private int fXsiURI = -2;
private int fXsiTypeAttValue = -1;
private DatatypeValidator fXsiTypeValidator = null;
private Grammar fGrammar = null;
private int fGrammarNameSpaceIndex = -1;
private GrammarResolver fGrammarResolver = null;
// state and stuff
private boolean fScanningDTD = false;
private XMLDocumentScanner fDocumentScanner = null;
private boolean fCalledStartDocument = false;
private XMLDocumentHandler fDocumentHandler = null;
private XMLDocumentHandler.DTDHandler fDTDHandler = null;
private boolean fSeenRootElement = false;
private XMLAttrList fAttrList = null;
private int fXMLLang = -1;
private LocatorImpl fAttrNameLocator = null;
private boolean fCheckedForSchema = false;
private boolean fDeclsAreExternal = false;
private StringPool.CharArrayRange fCurrentElementCharArrayRange = null;
private char[] fCharRefData = null;
private boolean fSendCharDataAsCharArray = false;
private boolean fBufferDatatype = false;
private StringBuffer fDatatypeBuffer = new StringBuffer();
private QName fTempQName = new QName();
private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl();
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private boolean fGrammarIsDTDGrammar = false;
private boolean fGrammarIsSchemaGrammar = false;
private boolean fNeedValidationOff = false;
// symbols
private int fEMPTYSymbol = -1;
private int fANYSymbol = -1;
private int fMIXEDSymbol = -1;
private int fCHILDRENSymbol = -1;
private int fCDATASymbol = -1;
private int fIDSymbol = -1;
private int fIDREFSymbol = -1;
private int fIDREFSSymbol = -1;
private int fENTITYSymbol = -1;
private int fENTITIESSymbol = -1;
private int fNMTOKENSymbol = -1;
private int fNMTOKENSSymbol = -1;
private int fNOTATIONSymbol = -1;
private int fENUMERATIONSymbol = -1;
private int fREQUIREDSymbol = -1;
private int fFIXEDSymbol = -1;
private int fDATATYPESymbol = -1;
private int fEpsilonIndex = -1;
//Datatype Registry
private DatatypeValidatorFactoryImpl fDataTypeReg =
DatatypeValidatorFactoryImpl.getDatatypeRegistry();
private DatatypeValidator fValID = this.fDataTypeReg.getDatatypeValidator("ID" );
private DatatypeValidator fValIDRef = this.fDataTypeReg.getDatatypeValidator("IDREF" );
private DatatypeValidator fValIDRefs = this.fDataTypeReg.getDatatypeValidator("IDREFS" );
private DatatypeValidator fValENTITY = this.fDataTypeReg.getDatatypeValidator("ENTITY" );
private DatatypeValidator fValENTITIES = this.fDataTypeReg.getDatatypeValidator("ENTITIES" );
private DatatypeValidator fValNMTOKEN = this.fDataTypeReg.getDatatypeValidator("NMTOKEN");
private DatatypeValidator fValNMTOKENS = this.fDataTypeReg.getDatatypeValidator("NMTOKENS");
private DatatypeValidator fValNOTATION = this.fDataTypeReg.getDatatypeValidator("NOTATION" );
//
// Constructors
//
/** Constructs an XML validator. */
public XMLValidator(StringPool stringPool,
XMLErrorReporter errorReporter,
DefaultEntityHandler entityHandler,
XMLDocumentScanner documentScanner) {
// keep references
fStringPool = stringPool;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fDocumentScanner = documentScanner;
fEmptyURI = fStringPool.addSymbol("");
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
// initialize
fAttrList = new XMLAttrList(fStringPool);
entityHandler.setEventHandler(this);
entityHandler.setCharDataHandler(this);
fDocumentScanner.setEventHandler(this);
for (int i = 0; i < sizeQNameParts; i++) {
fElementQNamePartsStack[i] = new QName();
}
init();
} // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner)
public void setGrammarResolver(GrammarResolver grammarResolver){
fGrammarResolver = grammarResolver;
}
//
// Public methods
//
// initialization
/** Set char data processing preference and handlers. */
public void initHandlers(boolean sendCharDataAsCharArray,
XMLDocumentHandler docHandler,
XMLDocumentHandler.DTDHandler dtdHandler) {
fSendCharDataAsCharArray = sendCharDataAsCharArray;
fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray);
fDocumentHandler = docHandler;
fDTDHandler = dtdHandler;
} // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler)
/** Reset or copy. */
public void resetOrCopy(StringPool stringPool) throws Exception {
fAttrList = new XMLAttrList(stringPool);
resetCommon(stringPool);
}
/** Reset. */
public void reset(StringPool stringPool) throws Exception {
fAttrList.reset(stringPool);
resetCommon(stringPool);
}
// settings
/**
* Turning on validation/dynamic turns on validation if it is off, and
* this is remembered. Turning off validation DISABLES validation/dynamic
* if it is on. Turning off validation/dynamic DOES NOT turn off
* validation if it was explicitly turned on, only if it was turned on
* BECAUSE OF the call to turn validation/dynamic on. Turning on
* validation will REENABLE and turn validation/dynamic back on if it
* was disabled by a call that turned off validation while
* validation/dynamic was enabled.
*/
public void setValidationEnabled(boolean flag) throws Exception {
fValidationEnabled = flag;
fValidationEnabledByDynamic = false;
if (fValidationEnabled) {
if (fDynamicDisabledByValidation) {
fDynamicValidation = true;
fDynamicDisabledByValidation = false;
}
} else if (fDynamicValidation) {
fDynamicValidation = false;
fDynamicDisabledByValidation = true;
}
fValidating = fValidationEnabled;
}
/** Returns true if validation is enabled. */
public boolean getValidationEnabled() {
return fValidationEnabled;
}
/** Sets whether Schema support is on/off. */
public void setSchemaValidationEnabled(boolean flag) {
fSchemaValidation = flag;
}
/** Returns true if Schema support is on. */
public boolean getSchemaValidationEnabled() {
return fSchemaValidation;
}
/** Sets whether validation is dynamic. */
public void setDynamicValidationEnabled(boolean flag) throws Exception {
fDynamicValidation = flag;
fDynamicDisabledByValidation = false;
if (!fDynamicValidation) {
if (fValidationEnabledByDynamic) {
fValidationEnabled = false;
fValidationEnabledByDynamic = false;
}
} else if (!fValidationEnabled) {
fValidationEnabled = true;
fValidationEnabledByDynamic = true;
}
fValidating = fValidationEnabled;
}
/** Returns true if validation is dynamic. */
public boolean getDynamicValidationEnabled() {
return fDynamicValidation;
}
/** Sets fLoadDTDGrammar when validation is off **/
public void setLoadDTDGrammar(boolean loadDG){
if (fValidating) {
fLoadDTDGrammar = true;
} else {
fLoadDTDGrammar = loadDG;
}
}
/** Returns fLoadDTDGrammar **/
public boolean getLoadDTDGrammar() {
return fLoadDTDGrammar;
}
/** Sets whether namespaces are enabled. */
public void setNamespacesEnabled(boolean flag) {
fNamespacesEnabled = flag;
}
/** Returns true if namespaces are enabled. */
public boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
/** Sets whether duplicate attribute definitions signal a warning. */
public void setWarningOnDuplicateAttDef(boolean flag) {
fWarningOnDuplicateAttDef = flag;
}
/** Returns true if duplicate attribute definitions signal a warning. */
public boolean getWarningOnDuplicateAttDef() {
return fWarningOnDuplicateAttDef;
}
/** Sets whether undeclared elements signal a warning. */
public void setWarningOnUndeclaredElements(boolean flag) {
fWarningOnUndeclaredElements = flag;
}
/** Returns true if undeclared elements signal a warning. */
public boolean getWarningOnUndeclaredElements() {
return fWarningOnUndeclaredElements;
}
//
// DefaultEntityHandler.EventHandler methods
//
/** Start entity reference. */
public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception {
fDocumentHandler.startEntityReference(entityName, entityType, entityContext);
}
/** End entity reference. */
public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception {
fDocumentHandler.endEntityReference(entityName, entityType, entityContext);
}
/** Send end of input notification. */
public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception {
fDocumentScanner.endOfInput(entityName, moreToFollow);
/***
if (fScanningDTD) {
fDTDImporter.sendEndOfInputNotifications(entityName, moreToFollow);
}
/***/
}
/** Send reader change notifications. */
public void sendReaderChangeNotifications(XMLEntityHandler.EntityReader reader, int readerId) throws Exception {
fDocumentScanner.readerChange(reader, readerId);
/***
if (fScanningDTD) {
fDTDImporter.sendReaderChangeNotifications(reader, readerId);
}
/***/
}
/** External entity standalone check. */
public boolean externalEntityStandaloneCheck() {
return(fStandaloneReader != -1 && fValidating);
}
/** Return true if validating. */
public boolean getValidating() {
return fValidating;
}
//
// XMLEntityHandler.CharDataHandler methods
//
/** Process characters. */
public void processCharacters(char[] chars, int offset, int length) throws Exception {
if (fValidating) {
if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
if (fBufferDatatype) {
fDatatypeBuffer.append(chars, offset, length);
}
}
fDocumentHandler.characters(chars, offset, length);
}
/** Process characters. */
public void processCharacters(int data) throws Exception {
if (fValidating) {
if (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
if (fBufferDatatype) {
fDatatypeBuffer.append(fStringPool.toString(data));
}
}
fDocumentHandler.characters(data);
}
/** Process whitespace. */
public void processWhitespace(char[] chars, int offset, int length)
throws Exception {
if (fInElementContent) {
if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
fDocumentHandler.ignorableWhitespace(chars, offset, length);
} else {
if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
fDocumentHandler.characters(chars, offset, length);
}
} // processWhitespace(char[],int,int)
/** Process whitespace. */
public void processWhitespace(int data) throws Exception {
if (fInElementContent) {
if (fStandaloneReader != -1 && fValidating && getElementDeclIsExternal(fCurrentElementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
fDocumentHandler.ignorableWhitespace(data);
} else {
if (fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY) {
charDataInContent();
}
fDocumentHandler.characters(data);
}
} // processWhitespace(int)
//
// XMLDocumentScanner.EventHandler methods
//
/** Scans element type. */
public void scanElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
} else {
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
}
} // scanElementType(XMLEntityHandler.EntityReader,char,QName)
/** Scans expected element type. */
public boolean scanExpectedElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element)
throws Exception {
if (fCurrentElementCharArrayRange == null) {
fCurrentElementCharArrayRange = fStringPool.createCharArrayRange();
}
fStringPool.getCharArrayRange(fCurrentElement.rawname, fCurrentElementCharArrayRange);
return entityReader.scanExpectedName(fastchar, fCurrentElementCharArrayRange);
} // scanExpectedElementType(XMLEntityHandler.EntityReader,char,QName)
/** Scans attribute name. */
public void scanAttributeName(XMLEntityHandler.EntityReader entityReader,
QName element, QName attribute)
throws Exception {
if (!fSeenRootElement) {
fSeenRootElement = true;
rootElementSpecified(element);
fStringPool.resetShuffleCount();
}
if (!fNamespacesEnabled) {
attribute.clear();
attribute.localpart = entityReader.scanName('=');
attribute.rawname = attribute.localpart;
} else {
entityReader.scanQName('=', attribute);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
}
} // scanAttributeName(XMLEntityHandler.EntityReader,QName,QName)
/** Call start document. */
public void callStartDocument() throws Exception {
if (!fCalledStartDocument) {
fDocumentHandler.startDocument();
fCalledStartDocument = true;
}
}
/** Call end document. */
public void callEndDocument() throws Exception {
if (fCalledStartDocument) {
fDocumentHandler.endDocument();
}
}
/** Call XML declaration. */
public void callXMLDecl(int version, int encoding, int standalone) throws Exception {
fDocumentHandler.xmlDecl(version, encoding, standalone);
}
public void callStandaloneIsYes() throws Exception {
// standalone = "yes". said XMLDocumentScanner.
fStandaloneReader = fEntityHandler.getReaderId() ;
}
/** Call text declaration. */
public void callTextDecl(int version, int encoding) throws Exception {
fDocumentHandler.textDecl(version, encoding);
}
/**
* Signal the scanning of an element name in a start element tag.
*
* @param element Element name scanned.
*/
public void element(QName element) throws Exception {
fAttrListHandle = -1;
}
/**
* Signal the scanning of an attribute associated to the previous
* start element tag.
*
* @param element Element name scanned.
* @param attrName Attribute name scanned.
* @param attrValue The string pool index of the attribute value.
*/
public boolean attribute(QName element, QName attrName, int attrValue) throws Exception {
if (fAttrListHandle == -1) {
fAttrListHandle = fAttrList.startAttrList();
}
// if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element.
// specified: true, search : true
return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1;
}
/** Call start element. */
public void callStartElement(QName element) throws Exception {
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart));
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) add default attrs (FIXED and NOT_FIXED)
//
if (!fSeenRootElement) {
fSeenRootElement = true;
rootElementSpecified(element);
fStringPool.resetShuffleCount();
}
if (fGrammar != null && fGrammarIsDTDGrammar) {
fAttrListHandle = addDTDDefaultAttributes(element, fAttrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
fCheckedForSchema = true;
if (fNamespacesEnabled) {
bindNamespacesToElementAndAttributes(element, fAttrList);
}
validateElementAndAttributes(element, fAttrList);
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
fDocumentHandler.startElement(element, fAttrList, fAttrListHandle);
fAttrListHandle = -1;
//before we increment the element depth, add this element's QName to its enclosing element 's children list
fElementDepth++;
//if (fElementDepth >= 0) {
if (fValidating) {
// push current length onto stack
if (fElementChildrenOffsetStack.length < fElementDepth) {
int newarray[] = new int[fElementChildrenOffsetStack.length * 2];
System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length);
fElementChildrenOffsetStack = newarray;
}
fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength;
// add this element to children
if (fElementChildren.length <= fElementChildrenLength) {
QName[] newarray = new QName[fElementChildrenLength * 2];
System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length);
fElementChildren = newarray;
}
QName qname = fElementChildren[fElementChildrenLength];
if (qname == null) {
for (int i = fElementChildrenLength; i < fElementChildren.length; i++) {
fElementChildren[i] = new QName();
}
qname = fElementChildren[fElementChildrenLength];
}
qname.setValues(element);
fElementChildrenLength++;
if (DEBUG_ELEMENT_CHILDREN) {
printChildren();
printStack();
}
}
// One more level of depth
//fElementDepth++;
ensureStackCapacity(fElementDepth);
fCurrentElement.setValues(element);
fCurrentElementEntity = fEntityHandler.getReaderId();
fElementQNamePartsStack[fElementDepth].setValues(fCurrentElement);
fElementEntityStack[fElementDepth] = fCurrentElementEntity;
fElementIndexStack[fElementDepth] = fCurrentElementIndex;
fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType;
if (fNeedValidationOff) {
fValidating = false;
fNeedValidationOff = false;
}
if (fValidating && fGrammarIsSchemaGrammar) {
pushContentLeafStack();
}
fValidationFlagStack[fElementDepth] = fValidating ? 0 : -1;
fScopeStack[fElementDepth] = fCurrentScope;
fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex;
} // callStartElement(QName)
private void pushContentLeafStack() throws Exception {
int contentType = getContentSpecType(fCurrentElementIndex);
if ( contentType == XMLElementDecl.TYPE_CHILDREN) {
XMLContentModel cm = getElementContentModel(fCurrentElementIndex);
ContentLeafNameTypeVector cv = cm.getContentLeafNameTypeVector();
if (cm != null) {
fContentLeafStack[fElementDepth] = cv;
}
}
}
private void ensureStackCapacity ( int newElementDepth) {
if (newElementDepth == fElementQNamePartsStack.length ) {
int[] newStack = new int[newElementDepth * 2];
System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth);
fScopeStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth);
fGrammarNameSpaceIndexStack = newStack;
QName[] newStackOfQueue = new QName[newElementDepth * 2];
System.arraycopy(this.fElementQNamePartsStack, 0, newStackOfQueue, 0, newElementDepth );
fElementQNamePartsStack = newStackOfQueue;
QName qname = fElementQNamePartsStack[newElementDepth];
if (qname == null) {
for (int i = newElementDepth; i < fElementQNamePartsStack.length; i++) {
fElementQNamePartsStack[i] = new QName();
}
}
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth);
fElementEntityStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth);
fElementIndexStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth);
fContentSpecTypeStack = newStack;
newStack = new int[newElementDepth * 2];
System.arraycopy(fValidationFlagStack, 0, newStack, 0, newElementDepth);
fValidationFlagStack = newStack;
ContentLeafNameTypeVector[] newStackV = new ContentLeafNameTypeVector[newElementDepth * 2];
System.arraycopy(fContentLeafStack, 0, newStackV, 0, newElementDepth);
fContentLeafStack = newStackV;
}
}
/** Call end element. */
public void callEndElement(int readerId) throws Exception {
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n");
int prefixIndex = fCurrentElement.prefix;
int elementType = fCurrentElement.rawname;
if (fCurrentElementEntity != readerId) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH,
XMLMessages.P78_NOT_WELLFORMED,
new Object[] { fStringPool.toString(elementType)},
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
fElementDepth--;
if (fValidating) {
int elementIndex = fCurrentElementIndex;
if (elementIndex != -1 && fCurrentContentSpecType != -1) {
QName children[] = fElementChildren;
int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1;
int childrenLength = fElementChildrenLength - childrenOffset;
if (DEBUG_ELEMENT_CHILDREN) {
System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')');
System.out.println("fCurrentContentSpecType : " + fCurrentContentSpecType );
System.out.print("offset: ");
System.out.print(childrenOffset);
System.out.print(", length: ");
System.out.print(childrenLength);
System.out.println();
printChildren();
printStack();
}
int result = checkContent(elementIndex,
children, childrenOffset, childrenLength);
if ( DEBUG_SCHEMA_VALIDATION )
System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result);
if (result != -1) {
int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE;
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
if (fTempElementDecl.type == XMLElementDecl.TYPE_EMPTY) {
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementType),
"EMPTY");
} else
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementType),
XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex));
}
}
fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1;
}
fDocumentHandler.endElement(fCurrentElement);
if (fNamespacesEnabled) {
fNamespacesScope.decreaseDepth();
}
// now pop this element off the top of the element stack
//if (fElementDepth-- < 0) {
if (fElementDepth < -1) {
throw new RuntimeException("FWK008 Element stack underflow");
}
if (fElementDepth < 0) {
fCurrentElement.clear();
fCurrentElementEntity = -1;
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
//
// Check after document is fully parsed
// (1) check that there was an element with a matching id for every
// IDREF and IDREFS attr (V_IDREF0)
//
if (fValidating ) {
try {
this.fValIDRef.validate( null, this.fValidateIDRef );
this.fValIDRefs.validate( null, this.fValidateIDRef );
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError( ex.getMajorCode(), ex.getMinorCode(),
ex.getMessage() );
}
}
try {//Reset datatypes state
this.fValID.validate( null, this.fResetID );
this.fValIDRef.validate(null, this.fResetIDRef );
this.fValIDRefs.validate(null, this.fResetIDRef );
} catch ( InvalidDatatypeValueException ex ) {
System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" );
}
return;
}
//restore enclosing element to all the "current" variables
// REVISIT: Validation. This information needs to be stored.
fCurrentElement.prefix = -1;
if (fNamespacesEnabled) { //If Namespace enable then localName != rawName
fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].localpart;
} else {//REVISIT - jeffreyr - This is so we still do old behavior when namespace is off
fCurrentElement.localpart = fElementQNamePartsStack[fElementDepth].rawname;
}
fCurrentElement.rawname = fElementQNamePartsStack[fElementDepth].rawname;
fCurrentElement.uri = fElementQNamePartsStack[fElementDepth].uri;
fCurrentElement.prefix = fElementQNamePartsStack[fElementDepth].prefix;
fCurrentElementEntity = fElementEntityStack[fElementDepth];
fCurrentElementIndex = fElementIndexStack[fElementDepth];
fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth];
fValidating = fValidationFlagStack[fElementDepth] == 0 ? true : false;
fCurrentScope = fScopeStack[fElementDepth];
//if ( DEBUG_SCHEMA_VALIDATION ) {
/****
System.out.println("+++++ currentElement : " + fStringPool.toString(elementType)+
"\n fCurrentElementIndex : " + fCurrentElementIndex +
"\n fCurrentScope : " + fCurrentScope +
"\n fCurrentContentSpecType : " + fCurrentContentSpecType +
"\n++++++++++++++++++++++++++++++++++++++++++++++++" );
/****/
//}
// if enclosing element's Schema is different, need to switch "context"
if ( fGrammarNameSpaceIndex != fGrammarNameSpaceIndexStack[fElementDepth] ) {
fGrammarNameSpaceIndex = fGrammarNameSpaceIndexStack[fElementDepth];
if ( fValidating && fGrammarIsSchemaGrammar )
if ( !switchGrammar(fGrammarNameSpaceIndex) ) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 1: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if (fValidating) {
fBufferDatatype = false;
}
fInElementContent = (fCurrentContentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // callEndElement(int)
/** Call start CDATA section. */
public void callStartCDATA() throws Exception {
fDocumentHandler.startCDATA();
}
/** Call end CDATA section. */
public void callEndCDATA() throws Exception {
fDocumentHandler.endCDATA();
}
/** Call characters. */
public void callCharacters(int ch) throws Exception {
if (fCharRefData == null) {
fCharRefData = new char[2];
}
int count = (ch < 0x10000) ? 1 : 2;
if (count == 1) {
fCharRefData[0] = (char)ch;
} else {
fCharRefData[0] = (char)(((ch-0x00010000)>>10)+0xd800);
fCharRefData[1] = (char)(((ch-0x00010000)&0x3ff)+0xdc00);
}
if (fValidating && (fInElementContent || fCurrentContentSpecType == XMLElementDecl.TYPE_EMPTY)) {
charDataInContent();
}
if (fValidating) {
if (fBufferDatatype) {
fDatatypeBuffer.append(fCharRefData,0,1);
}
}
if (fSendCharDataAsCharArray) {
fDocumentHandler.characters(fCharRefData, 0, count);
} else {
int index = fStringPool.addString(new String(fCharRefData, 0, count));
fDocumentHandler.characters(index);
}
} // callCharacters(int)
/** Call processing instruction. */
public void callProcessingInstruction(int target, int data) throws Exception {
fDocumentHandler.processingInstruction(target, data);
}
/** Call comment. */
public void callComment(int comment) throws Exception {
fDocumentHandler.comment(comment);
}
//
// NamespacesScope.NamespacesHandler methods
//
/** Start a new namespace declaration scope. */
public void startNamespaceDeclScope(int prefix, int uri) throws Exception {
fDocumentHandler.startNamespaceDeclScope(prefix, uri);
}
/** End a namespace declaration scope. */
public void endNamespaceDeclScope(int prefix) throws Exception {
fDocumentHandler.endNamespaceDeclScope(prefix);
}
// attributes
// other
/** Sets the root element. */
public void setRootElementType(QName rootElement) {
fRootElement.setValues(rootElement);
}
/**
* Returns true if the element declaration is external.
* <p>
* <strong>Note:</strong> This method is primarilly useful for
* DTDs with internal and external subsets.
*/
private boolean getElementDeclIsExternal(int elementIndex) {
/*if (elementIndex < 0 || elementIndex >= fElementCount) {
return false;
}
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return (fElementDeclIsExternal[chunk][index] != 0);
*/
if (fGrammarIsDTDGrammar ) {
return((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex);
}
return false;
}
/** Returns the content spec type for an element index. */
public int getContentSpecType(int elementIndex) {
int contentSpecType = -1;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentSpecType = fTempElementDecl.type;
}
}
return contentSpecType;
}
/** Returns the content spec handle for an element index. */
public int getContentSpecHandle(int elementIndex) {
int contentSpecHandle = -1;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentSpecHandle = fTempElementDecl.contentSpecIndex;
}
}
return contentSpecHandle;
}
//
// Protected methods
//
// error reporting
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode)
throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1) throws Exception {
Object[] args = { string1};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1, int stringIndex2)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2)
throws Exception {
Object[] args = { string1, string2};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2,
String string3) throws Exception {
Object[] args = { string1, string2, string3};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String,String)
// content spec
/**
* Returns information about which elements can be placed at a particular point
* in the passed element's content model.
* <p>
* Note that the incoming content model to test must be valid at least up to
* the insertion point. If not, then -1 will be returned and the info object
* will not have been filled in.
* <p>
* If, on return, the info.isValidEOC flag is set, then the 'insert after'
* elemement is a valid end of content, i.e. nothing needs to be inserted
* after it to make the parent element's content model valid.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of the
* element which is being querying.
* @param fullyValid Only return elements that can be inserted and still
* maintain the validity of subsequent elements past the
* insertion point (if any). If the insertion point is at
* the end, and this is true, then only elements that can
* be legal final states will be returned.
* @param info An object that contains the required input data for the method,
* and which will contain the output information if successful.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed before the insertion point. If the value
* returned is equal to the number of children, then the specified
* children are valid but additional content is required to reach a
* valid ending state.
*
* @exception Exception Thrown on error.
*
* @see InsertableElementsInfo
*/
protected int whatCanGoHere(int elementIndex, boolean fullyValid,
InsertableElementsInfo info) throws Exception {
//
// Do some basic sanity checking on the info packet. First, make sure
// that insertAt is not greater than the child count. It can be equal,
// which means to get appendable elements, but not greater. Or, if
// the current children array is null, that's bad too.
//
// Since the current children array must have a blank spot for where
// the insert is going to be, the child count must always be at least
// one.
//
// Make sure that the child count is not larger than the current children
// array. It can be equal, which means get appendable elements, but not
// greater.
//
if (info.insertAt > info.childCount || info.curChildren == null ||
info.childCount < 1 || info.childCount > info.curChildren.length) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_WCGHI,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
int retVal = 0;
try {
// Get the content model for this element
final XMLContentModel cmElem = getElementContentModel(elementIndex);
// And delegate this call to it
retVal = cmElem.whatCanGoHere(fullyValid, info);
} catch (CMException excToCatch) {
// REVISIT - Translate caught error to the protected error handler interface
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
throw excToCatch;
}
return retVal;
} // whatCanGoHere(int,boolean,InsertableElementsInfo):int
// attribute information
/** Protected for use by AttributeValidator classes. */
protected boolean getAttDefIsExternal(QName element, QName attribute) {
int attDefIndex = getAttDef(element, attribute);
if (fGrammarIsDTDGrammar ) {
return((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex);
}
return false;
}
//
// Private methods
//
// other
/** Returns true if using a standalone reader. */
private boolean usingStandaloneReader() {
return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader;
}
/** Returns a locator implementation. */
private LocatorImpl getLocatorImpl(LocatorImpl fillin) {
Locator here = fErrorReporter.getLocator();
if (fillin == null)
return new LocatorImpl(here);
fillin.setPublicId(here.getPublicId());
fillin.setSystemId(here.getSystemId());
fillin.setLineNumber(here.getLineNumber());
fillin.setColumnNumber(here.getColumnNumber());
return fillin;
} // getLocatorImpl(LocatorImpl):LocatorImpl
// initialization
/** Reset pool. */
private void poolReset() {
try {
//System.out.println("We reset" );
this.fValID.validate( null, this.fResetID );
this.fValIDRef.validate(null, this.fResetIDRef );
this.fValIDRefs.validate(null, this.fResetIDRef );
} catch ( InvalidDatatypeValueException ex ) {
System.err.println("Error re-Initializing: ID,IDRef,IDRefs pools" );
}
} // poolReset()
/** Reset common. */
private void resetCommon(StringPool stringPool) throws Exception {
fStringPool = stringPool;
fValidating = fValidationEnabled;
fValidationEnabledByDynamic = false;
fDynamicDisabledByValidation = false;
poolReset();
fCalledStartDocument = false;
fStandaloneReader = -1;
fElementChildrenLength = 0;
fElementDepth = -1;
fSeenRootElement = false;
fSeenDoctypeDecl = false;
fNamespacesScope = null;
fNamespacesPrefix = -1;
fRootElement.clear();
fAttrListHandle = -1;
fCheckedForSchema = false;
fCurrentScope = TOP_LEVEL_SCOPE;
fCurrentSchemaURI = -1;
fEmptyURI = - 1;
fXsiPrefix = - 1;
fXsiTypeValidator = null;
fGrammar = null;
fGrammarNameSpaceIndex = -1;
//fGrammarResolver = null;
if (fGrammarResolver != null) {
fGrammarResolver.clearGrammarResolver();
}
fGrammarIsDTDGrammar = false;
fGrammarIsSchemaGrammar = false;
init();
} // resetCommon(StringPool)
/** Initialize. */
private void init() {
fEmptyURI = fStringPool.addSymbol("");
fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI);
fEMPTYSymbol = fStringPool.addSymbol("EMPTY");
fANYSymbol = fStringPool.addSymbol("ANY");
fMIXEDSymbol = fStringPool.addSymbol("MIXED");
fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN");
fCDATASymbol = fStringPool.addSymbol("CDATA");
fIDSymbol = fStringPool.addSymbol("ID");
fIDREFSymbol = fStringPool.addSymbol("IDREF");
fIDREFSSymbol = fStringPool.addSymbol("IDREFS");
fENTITYSymbol = fStringPool.addSymbol("ENTITY");
fENTITIESSymbol = fStringPool.addSymbol("ENTITIES");
fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN");
fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS");
fNOTATIONSymbol = fStringPool.addSymbol("NOTATION");
fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION");
fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED");
fFIXEDSymbol = fStringPool.addSymbol("#FIXED");
fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>");
fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>");
fXMLLang = fStringPool.addSymbol("xml:lang");
try {//Initialize ENTITIES and ENTITY Validators
Object[] packageArgsEntityVal = { (Object) this.fEntityHandler,
(Object) this.fStringPool};
fValidateENTITYMsg.setDatatypeObject( (Object ) packageArgsEntityVal);
fValENTITIES.validate( null, fValidateENTITYMsg );
fValENTITY.validate( null, fValidateENTITYMsg );
} catch ( InvalidDatatypeValueException ex ) {
System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen
}
} // init()
// other
// default attribute
/** addDefaultAttributes. */
private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception {
//System.out.println("XMLValidator#addDefaultAttributes");
//System.out.print(" ");
//fGrammar.printAttributes(elementIndex);
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) check that FIXED attrs have matching value (V_TAGd)
// (3) add default attrs (FIXED and NOT_FIXED)
//
fGrammar.getElementDecl(elementIndex,fTempElementDecl);
int elementNameIndex = fTempElementDecl.name.localpart;
int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
int firstCheck = attrIndex;
int lastCheck = -1;
while (attlistIndex != -1) {
fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl);
int attPrefix = fTempAttDecl.name.prefix;
int attName = fTempAttDecl.name.localpart;
int attType = attributeTypeName(fTempAttDecl);
int attDefType =fTempAttDecl.defaultType;
int attValue = -1 ;
if (fTempAttDecl.defaultValue != null ) {
attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue);
}
boolean specified = false;
boolean required = attDefType == XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
if (firstCheck != -1) {
boolean cdata = attType == fCDATASymbol;
if (!cdata || required || attValue != -1) {
int i = attrList.getFirstAttr(firstCheck);
while (i != -1 && (lastCheck == -1 || i <= lastCheck)) {
if ( (fGrammarIsDTDGrammar && (attrList.getAttrName(i) == fTempAttDecl.name.rawname)) ||
( fStringPool.equalNames(attrList.getAttrLocalpart(i), attName)
&& fStringPool.equalNames(attrList.getAttrURI(i), fTempAttDecl.name.uri) ) ) {
if (validationEnabled && attDefType == XMLAttributeDecl.DEFAULT_TYPE_FIXED) {
int alistValue = attrList.getAttValue(i);
if (alistValue != attValue &&
!fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName),
fStringPool.toString(alistValue),
fStringPool.toString(attValue)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_FIXED_ATTVALUE_INVALID,
XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
specified = true;
break;
}
i = attrList.getNextAttr(i);
}
}
}
if (!specified) {
if (required) {
if (validationEnabled) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_REQUIRED_ATTRIBUTE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
} else if (attValue != -1) {
if (validationEnabled && standalone )
if ( fGrammarIsDTDGrammar
&& ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
if (attType == fIDREFSymbol) {
this.fValIDRef.validate( fStringPool.toString(attValue), this.fStoreIDRef );
} else if (attType == fIDREFSSymbol) {
this.fValIDRefs.validate( fStringPool.toString(attValue), this.fStoreIDRef );
}
if (attrIndex == -1) {
attrIndex = attrList.startAttrList();
}
// REVISIT: Validation. What should the prefix be?
fTempQName.setValues(attPrefix, attName, attName, fTempAttDecl.name.uri);
int newAttr = attrList.addAttr(fTempQName,
attValue, attType,
false, false);
if (lastCheck == -1) {
lastCheck = newAttr;
}
}
}
attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex);
}
return attrIndex;
} // addDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int
/** addDTDDefaultAttributes. */
private int addDTDDefaultAttributes(QName element, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception {
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) check that FIXED attrs have matching value (V_TAGd)
// (3) add default attrs (FIXED and NOT_FIXED)
//
int elementIndex = fGrammar.getElementDeclIndex(element, -1);
if (elementIndex == -1) {
return attrIndex;
}
fGrammar.getElementDecl(elementIndex,fTempElementDecl);
int elementNameIndex = fTempElementDecl.name.rawname;
int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
int firstCheck = attrIndex;
int lastCheck = -1;
while (attlistIndex != -1) {
fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl);
// TO DO: For ericye Debug only
/***
if (fTempAttDecl != null) {
XMLElementDecl element = new XMLElementDecl();
fGrammar.getElementDecl(elementIndex, element);
System.out.println("element: "+fStringPool.toString(element.name.localpart));
System.out.println("attlistIndex " + attlistIndex + "\n"+
"attName : '"+fStringPool.toString(fTempAttDecl.name.localpart) + "'\n"
+ "attType : "+fTempAttDecl.type + "\n"
+ "attDefaultType : "+fTempAttDecl.defaultType + "\n"
+ "attDefaultValue : '"+fTempAttDecl.defaultValue + "'\n"
+ attrList.getLength() +"\n"
);
}
/***/
int attPrefix = fTempAttDecl.name.prefix;
int attName = fTempAttDecl.name.rawname;
int attLocalpart = fTempAttDecl.name.localpart;
int attType = attributeTypeName(fTempAttDecl);
int attDefType =fTempAttDecl.defaultType;
int attValue = -1 ;
if (fTempAttDecl.defaultValue != null ) {
attValue = fStringPool.addSymbol(fTempAttDecl.defaultValue);
}
boolean specified = false;
boolean required = attDefType == XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
/****
if (fValidating && fGrammar != null && fGrammarIsDTDGrammar && attValue != -1) {
normalizeAttValue(null, fTempAttDecl.name,
attValue,attType,fTempAttDecl.list,
fTempAttDecl.enumeration);
}
/****/
if (firstCheck != -1) {
boolean cdata = attType == fCDATASymbol;
if (!cdata || required || attValue != -1) {
int i = attrList.getFirstAttr(firstCheck);
while (i != -1 && (lastCheck == -1 || i <= lastCheck)) {
if ( attrList.getAttrName(i) == fTempAttDecl.name.rawname ) {
if (validationEnabled && attDefType == XMLAttributeDecl.DEFAULT_TYPE_FIXED) {
int alistValue = attrList.getAttValue(i);
if (alistValue != attValue &&
!fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName),
fStringPool.toString(alistValue),
fStringPool.toString(attValue)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_FIXED_ATTVALUE_INVALID,
XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
specified = true;
break;
}
i = attrList.getNextAttr(i);
}
}
}
if (!specified) {
if (required) {
if (validationEnabled) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_REQUIRED_ATTRIBUTE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
} else if (attValue != -1) {
if (validationEnabled && standalone )
if ( fGrammarIsDTDGrammar
&& ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attlistIndex) ) {
Object[] args = { fStringPool.toString(elementNameIndex),
fStringPool.toString(attName)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
if (attType == fIDREFSymbol) {
this.fValIDRef.validate( fStringPool.toString(attValue), this.fStoreIDRef );
} else if (attType == fIDREFSSymbol) {
this.fValIDRefs.validate( fStringPool.toString(attValue), this.fStoreIDRef );
}
if (attrIndex == -1) {
attrIndex = attrList.startAttrList();
}
fTempQName.setValues(attPrefix, attLocalpart, attName, fTempAttDecl.name.uri);
int newAttr = attrList.addAttr(fTempQName,
attValue, attType,
false, false);
if (lastCheck == -1) {
lastCheck = newAttr;
}
}
}
attlistIndex = fGrammar.getNextAttributeDeclIndex(attlistIndex);
}
return attrIndex;
} // addDTDDefaultAttributes(int,XMLAttrList,int,boolean,boolean):int
// content models
/** Queries the content model for the specified element index. */
private XMLContentModel getElementContentModel(int elementIndex) throws CMException {
XMLContentModel contentModel = null;
if ( elementIndex > -1) {
if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) {
contentModel = fGrammar.getElementContentModel(elementIndex);
}
}
//return fGrammar.getElementContentModel(elementIndex);
return contentModel;
}
// query attribute information
/** Returns an attribute definition for an element type. */
// this is only used by DTD validation.
private int getAttDef(QName element, QName attribute) {
if (fGrammar != null) {
int scope = fCurrentScope;
if (element.uri > -1) {
scope = TOP_LEVEL_SCOPE;
}
int elementIndex = fGrammar.getElementDeclIndex(element,scope);
if (elementIndex == -1) {
return -1;
}
int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attDefIndex != -1) {
fGrammar.getAttributeDecl(attDefIndex, fTempAttributeDecl);
if (fTempAttributeDecl.name.localpart == attribute.localpart &&
fTempAttributeDecl.name.uri == attribute.uri ) {
return attDefIndex;
}
attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
return -1;
} // getAttDef(QName,QName)
/** Returns an attribute definition for an element type. */
private int getAttDefByElementIndex(int elementIndex, QName attribute) {
if (fGrammar != null && elementIndex > -1) {
if (elementIndex == -1) {
return -1;
}
int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex);
while (attDefIndex != -1) {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
if (fGrammarIsDTDGrammar) {
if (fTempAttDecl.name.rawname == attribute.rawname )
return attDefIndex;
} else
if (fTempAttDecl.name.localpart == attribute.localpart &&
fTempAttDecl.name.uri == attribute.uri ) {
return attDefIndex;
}
if (fGrammarIsSchemaGrammar) {
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY) {
return attDefIndex;
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL) {
if (attribute.uri == -1) {
return attDefIndex;
}
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) {
if (attribute.uri != fTempAttDecl.name.uri) {
return attDefIndex;
}
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST) {
if (fStringPool.stringInList(fTempAttDecl.enumeration, attribute.uri)) {
return attDefIndex;
}
}
}
attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex);
}
}
return -1;
} // getAttDef(QName,QName)
// validation
/** Root element specified. */
private void rootElementSpecified(QName rootElement) throws Exception {
// this is what it used to be
//if (fDynamicValidation && !fSeenDoctypeDecl) {
//fValidating = false;
//}
if ( fLoadDTDGrammar )
// initialize the grammar to be the default one,
// it definitely should be a DTD Grammar at this case;
if (fGrammar == null) {
fGrammar = fGrammarResolver.getGrammar("");
//TO DO, for ericye debug only
if (fGrammar == null && DEBUG_SCHEMA_VALIDATION) {
System.out.println("Oops! no grammar is found for validation");
}
if (fDynamicValidation && fGrammar==null) {
fValidating = false;
}
if (fGrammar != null) {
if (fGrammar instanceof DTDGrammar) {
fGrammarIsDTDGrammar = true;
fGrammarIsSchemaGrammar = false;
} else if ( fGrammar instanceof SchemaGrammar ) {
fGrammarIsSchemaGrammar = true;
fGrammarIsDTDGrammar = false;
}
fGrammarNameSpaceIndex = fEmptyURI;
}
}
if (fValidating) {
if ( fGrammarIsDTDGrammar &&
((DTDGrammar) fGrammar).getRootElementQName(fRootElement) ) {
String root1 = fStringPool.toString(fRootElement.rawname);
String root2 = fStringPool.toString(rootElement.rawname);
if (!root1.equals(root2)) {
reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE,
XMLMessages.VC_ROOT_ELEMENT_TYPE,
fRootElement.rawname,
rootElement.rawname);
}
}
}
if (fNamespacesEnabled) {
if (fNamespacesScope == null) {
fNamespacesScope = new NamespacesScope(this);
fNamespacesPrefix = fStringPool.addSymbol("xmlns");
fNamespacesScope.setNamespaceForPrefix(fNamespacesPrefix, -1);
int xmlSymbol = fStringPool.addSymbol("xml");
int xmlNamespace = fStringPool.addSymbol("http://www.w3.org/XML/1998/namespace");
fNamespacesScope.setNamespaceForPrefix(xmlSymbol, xmlNamespace);
}
}
} // rootElementSpecified(QName)
/** Switchs to correct validating symbol tables when Schema changes.*/
private boolean switchGrammar(int newGrammarNameSpaceIndex) throws Exception {
Grammar tempGrammar = fGrammarResolver.getGrammar(fStringPool.toString(newGrammarNameSpaceIndex));
if (tempGrammar == null) {
// This is a case where namespaces is on with a DTD grammar.
tempGrammar = fGrammarResolver.getGrammar("");
}
if (tempGrammar == null) {
return false;
} else {
fGrammar = tempGrammar;
if (fGrammar instanceof DTDGrammar) {
fGrammarIsDTDGrammar = true;
fGrammarIsSchemaGrammar = false;
} else if ( fGrammar instanceof SchemaGrammar ) {
fGrammarIsSchemaGrammar = true;
fGrammarIsDTDGrammar = false;
}
return true;
}
}
/** Binds namespaces to the element and attributes. */
private void bindNamespacesToElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
fNamespacesScope.increaseDepth();
//Vector schemaCandidateURIs = null;
Hashtable locationUriPairs = null;
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
int attPrefix = attrList.getAttrPrefix(index);
if (fStringPool.equalNames(attName, fXMLLang)) {
/***
// NOTE: This check is done in the validateElementsAndAttributes
// method.
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
/***/
} else if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, uri);
} else {
if (attPrefix == fNamespacesPrefix) {
int nsPrefix = attrList.getAttrLocalpart(index);
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(nsPrefix, uri);
if (fValidating && fSchemaValidation) {
boolean seeXsi = false;
String attrValue = fStringPool.toString(attrList.getAttValue(index));
if (attrValue.equals(SchemaSymbols.URI_XSI)) {
fXsiPrefix = nsPrefix;
seeXsi = true;
}
if (!seeXsi) {
/***
if (schemaCandidateURIs == null) {
schemaCandidateURIs = new Vector();
}
schemaCandidateURIs.addElement( fStringPool.toString(uri) );
/***/
}
}
}
}
index = attrList.getNextAttr(index);
}
// if validating, walk through the list again to deal with "xsi:...."
if (fValidating && fSchemaValidation) {
fXsiTypeAttValue = -1;
index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
int attPrefix = attrList.getAttrPrefix(index);
if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
// REVISIT
} else {
if ( DEBUG_SCHEMA_VALIDATION ) {
System.out.println("deal with XSI");
System.out.println("before find XSI: "+fStringPool.toString(attPrefix)
+","+fStringPool.toString(fXsiPrefix) );
}
if ( fXsiPrefix != -1 && attPrefix == fXsiPrefix ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("find XSI: "+fStringPool.toString(attPrefix)
+","+fStringPool.toString(attName) );
}
int localpart = attrList.getAttrLocalpart(index);
if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_SCHEMALOCACTION)) {
if (locationUriPairs == null) {
locationUriPairs = new Hashtable();
}
parseSchemaLocation(fStringPool.toString(attrList.getAttValue(index)), locationUriPairs);
} else if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_NONAMESPACESCHEMALOCACTION)) {
if (locationUriPairs == null) {
locationUriPairs = new Hashtable();
}
locationUriPairs.put(fStringPool.toString(attrList.getAttValue(index)), "");
if (fNamespacesScope != null) {
//bind prefix "" to URI "" in this case
fNamespacesScope.setNamespaceForPrefix( fStringPool.addSymbol(""),
fStringPool.addSymbol(""));
}
} else if (localpart == fStringPool.addSymbol(SchemaSymbols.XSI_TYPE)) {
fXsiTypeAttValue = attrList.getAttValue(index);
}
// REVISIT: should we break here?
//break;
}
}
index = attrList.getNextAttr(index);
}
// try to resolve all the grammars here
if (locationUriPairs != null) {
Enumeration locations = locationUriPairs.keys();
while (locations.hasMoreElements()) {
String loc = (String) locations.nextElement();
String uri = (String) locationUriPairs.get(loc);
resolveSchemaGrammar( loc, uri);
//schemaCandidateURIs.removeElement(uri);
}
}
//TO DO: This should be a feature that can be turned on or off
/*****
for (int i=0; i< schemaCandidateURIs.size(); i++) {
String uri = (String) schemaCandidateURIs.elementAt(i);
resolveSchemaGrammar(uri);
}
/*****/
}
}
// bind element to URI
int prefix = element.prefix != -1 ? element.prefix : 0;
int uri = fNamespacesScope.getNamespaceForPrefix(prefix);
if (element.prefix != -1 || uri != -1) {
element.uri = uri;
if (element.uri == -1) {
Object[] args = { fStringPool.toString(element.prefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1 ) {
int attrUri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (attrUri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, attrUri);
}
}
}
index = attrList.getNextAttr(index);
}
}
} // bindNamespacesToElementAndAttributes(QName,XMLAttrList)
void parseSchemaLocation(String schemaLocationStr, Hashtable locationUriPairs){
if (locationUriPairs != null) {
StringTokenizer tokenizer = new StringTokenizer(schemaLocationStr, " \n\t\r", false);
int tokenTotal = tokenizer.countTokens();
if (tokenTotal % 2 != 0 ) {
// TO DO: report warning - malformed schemaLocation string
} else {
while (tokenizer.hasMoreTokens()) {
String uri = tokenizer.nextToken();
String location = tokenizer.nextToken();
locationUriPairs.put(location, uri);
}
}
} else {
// TO DO: should report internal error here
}
}// parseSchemaLocaltion(String, Hashtable)
private void resolveSchemaGrammar( String loc, String uri) throws Exception {
SchemaGrammar grammar = (SchemaGrammar) fGrammarResolver.getGrammar(uri);
if (grammar == null) {
DOMParser parser = new DOMParser();
parser.setEntityResolver( new Resolver(fEntityHandler) );
parser.setErrorHandler( new ErrorHandler() );
try {
parser.setFeature("http://xml.org/sax/features/validation", false);
parser.setFeature("http://xml.org/sax/features/namespaces", true);
parser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
} catch ( org.xml.sax.SAXNotRecognizedException e ) {
e.printStackTrace();
} catch ( org.xml.sax.SAXNotSupportedException e ) {
e.printStackTrace();
}
// expand it before passing it to the parser
InputSource source = null;
EntityResolver currentER = parser.getEntityResolver();
if (currentER != null) {
source = currentER.resolveEntity("", loc);
}
if (source == null) {
loc = fEntityHandler.expandSystemId(loc);
source = new InputSource(loc);
}
try {
parser.parse( source );
} catch ( IOException e ) {
e.printStackTrace();
} catch ( SAXException e ) {
//System.out.println("loc = "+loc);
//e.printStackTrace();
reportRecoverableXMLError( XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR, e.getMessage() );
}
Document document = parser.getDocument(); //Our Grammar
TraverseSchema tst = null;
try {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("I am geting the Schema Document");
}
Element root = document.getDocumentElement();// This is what we pass to TraverserSchema
if (root == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Can't get back Schema document's root element :" + loc);
} else {
if (uri == null || !uri.equals(root.getAttribute(SchemaSymbols.ATT_TARGETNAMESPACE)) ) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR, "Schema in " + loc + " has a different target namespace " +
"from the one specified in the instance document :" + uri);
}
grammar = new SchemaGrammar();
grammar.setGrammarDocument(document);
tst = new TraverseSchema( root, fStringPool, (SchemaGrammar)grammar, fGrammarResolver, fErrorReporter, source.getSystemId());
fGrammarResolver.putGrammar(document.getDocumentElement().getAttribute("targetNamespace"), grammar);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private void resolveSchemaGrammar(String uri) throws Exception{
resolveSchemaGrammar(uri, uri);
}
static class Resolver implements EntityResolver {
//
// Constants
//
private static final String SYSTEM[] = {
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/structures.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/datatypes.dtd",
"http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/versionInfo.ent",
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
"versionInfo.ent",
};
//
// Data
//
private DefaultEntityHandler fEntityHandler;
//
// Constructors
//
public Resolver(DefaultEntityHandler handler) {
fEntityHandler = handler;
}
//
// EntityResolver methods
//
public InputSource resolveEntity(String publicId, String systemId)
throws IOException, SAXException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// first try to resolve using user's entity resolver
EntityResolver resolver = fEntityHandler.getEntityResolver();
if (resolver != null) {
InputSource source = resolver.resolveEntity(publicId, systemId);
if (source != null) {
return source;
}
}
// use default resolution
return new InputSource(fEntityHandler.expandSystemId(systemId));
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
//throw ex;
}
//
// Private methods
//
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
private int attributeTypeName(XMLAttributeDecl attrDecl) {
switch (attrDecl.type) {
case XMLAttributeDecl.TYPE_ENTITY: {
return attrDecl.list ? fENTITIESSymbol : fENTITYSymbol;
}
case XMLAttributeDecl.TYPE_ENUMERATION: {
String enumeration = fStringPool.stringListAsString(attrDecl.enumeration);
return fStringPool.addString(enumeration);
}
case XMLAttributeDecl.TYPE_ID: {
return fIDSymbol;
}
case XMLAttributeDecl.TYPE_IDREF: {
return attrDecl.list ? fIDREFSSymbol : fIDREFSymbol;
}
case XMLAttributeDecl.TYPE_NMTOKEN: {
return attrDecl.list ? fNMTOKENSSymbol : fNMTOKENSSymbol;
}
case XMLAttributeDecl.TYPE_NOTATION: {
return fNOTATIONSymbol;
}
}
return fCDATASymbol;
}
/** Validates element and attributes. */
private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if ((fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )||
(fGrammar == null && !fValidating && !fNamespacesEnabled) ) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
int contentSpecType = -1;
boolean skipThisOne = false;
boolean laxThisOne = false;
if ( fGrammarIsSchemaGrammar && fContentLeafStack[fElementDepth] != null ) {
ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth];
QName[] fElemMap = cv.leafNames;
for (int i=0; i<cv.leafCount; i++) {
int type = cv.leafTypes[i] ;
//System.out.println("******* see a ANY_OTHER_SKIP, "+type+","+element+","+fElemMap[i]+"\n*******");
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
if (fElemMap[i].uri==element.uri
&& fElemMap[i].localpart == element.localpart)
break;
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (element.uri == -1) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if (fElemMap[i].uri != element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) {
if (element.uri == -1) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) {
if (fElemMap[i].uri != element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) {
if (element.uri == -1) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) {
if (fElemMap[i].uri != element.uri) {
laxThisOne = true;
break;
}
}
}
}
if (skipThisOne) {
fNeedValidationOff = true;
} else {
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
boolean success = switchGrammar(fGrammarNameSpaceIndex);
if (!success && !laxThisOne) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if ( fGrammar != null ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+
"localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope+"\n");
}
elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope);
if (elementIndex == -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
int aGrammarNSIndex = fGrammarNameSpaceIndex;
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
// update the current Grammar NS index if resolving element succeed.
fGrammarNameSpaceIndex = aGrammarNSIndex;
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
- String baseTName = baseTypeInfo.typeName;
- if (!baseTName.startsWith("#")) {
- int comma = baseTName.indexOf(',');
- aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
- if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
- if ( !switchGrammar(aGrammarNSIndex) ) {
- break; //exit the loop in this case
+ if (baseTypeInfo != null) {
+ String baseTName = baseTypeInfo.typeName;
+ if (!baseTName.startsWith("#")) {
+ int comma = baseTName.indexOf(',');
+ aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
+ if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
+ if ( !switchGrammar(aGrammarNSIndex) ) {
+ break; //exit the loop in this case
+ }
}
}
}
}
+ if (elementIndex == -1) {
+ switchGrammar(fGrammarNameSpaceIndex);
+ }
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1) {
if (laxThisOne) {
fNeedValidationOff = true;
} else
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart +
"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri +
"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
}
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+
" and the current enclosing scope: " + fCurrentScope);
}
}
contentSpecType = getContentSpecType(elementIndex);
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
// handle "xsi:type" right here
if (fXsiTypeAttValue > -1) {
String xsiType = fStringPool.toString(fXsiTypeAttValue);
int colonP = xsiType.indexOf(":");
String prefix = "";
String localpart = xsiType;
if (colonP > -1) {
prefix = xsiType.substring(0,colonP);
localpart = xsiType.substring(colonP+1);
}
String uri = "";
int uriIndex = -1;
if (fNamespacesScope != null) {
uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix));
if (uriIndex > -1) {
uri = fStringPool.toString(uriIndex);
if (uriIndex != fGrammarNameSpaceIndex) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex;
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 3: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
}
Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry();
DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry();
if (complexRegistry==null || dataTypeReg == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
fErrorReporter.getLocator().getSystemId()
+" line"+fErrorReporter.getLocator().getLineNumber()
+", canot resolve xsi:type = " + xsiType+" ---2");
} else {
TraverseSchema.ComplexTypeInfo typeInfo =
(TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart);
//TO DO:
// here need to check if this substitution is legal based on the current active grammar,
// this should be easy, cause we already saved final, block and base type information in
// the SchemaGrammar.
if (typeInfo==null) {
if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) {
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart);
} else
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart);
if ( fXsiTypeValidator == null )
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"unresolved type : "+uri+","+localpart
+" found in xsi:type handling");
} else
elementIndex = typeInfo.templateElementIndex;
}
fXsiTypeAttValue = -1;
}
//Change the current scope to be the one defined by this element.
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex);
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
//before switch Grammar, set the elementIndex to be the template elementIndex of its type
if (contentSpecType != -1
&& contentSpecType != XMLElementDecl.TYPE_EMPTY ) {
TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex);
if (typeInfo != null) {
elementIndex = typeInfo.templateElementIndex;
}
}
// now switch the grammar
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 4: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) {
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1 && !fNeedValidationOff ) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fGrammar != null) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1 ) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
} else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fValidating) {
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
// check to see if this attribute matched an attribute wildcard
else if ( fGrammarIsSchemaGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) {
if (fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_SKIP) {
// attribute should just be bypassed,
} else if ( fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT
|| fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_LAX) {
boolean reportError = false;
boolean processContentStrict =
fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (fTempQName.uri == -1) {
if (processContentStrict) {
reportError = true;
}
} else {
Grammar aGrammar =
fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri));
if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) {
if (processContentStrict) {
reportError = true;
}
} else {
SchemaGrammar sGrammar = (SchemaGrammar) aGrammar;
Hashtable attRegistry = sGrammar.getAttirubteDeclRegistry();
if (attRegistry == null) {
if (processContentStrict) {
reportError = true;
}
} else {
XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart));
if (attDecl == null) {
if (processContentStrict) {
reportError = true;
}
} else {
DatatypeValidator attDV = attDecl.datatypeValidator;
if (attDV == null) {
if (processContentStrict) {
reportError = true;
}
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (attDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
}
if (attDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
attDV.validate(value, this.fStoreIDRef );
} else
attDV.validate(unTrimValue, null );
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
}
}
if (reportError) {
Object[] args = { fStringPool.toString(element.rawname),
"ANY---"+fStringPool.toString(attrList.getAttrName(index))};
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
fTempAttDecl.datatypeValidator.validate(value, this.fStoreIDRef );
} else {
fTempAttDecl.datatypeValidator.validate(unTrimValue, null );
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // end of if (fValidating)
} // end of if (attDefIndex == -1) else
}// end of if (fGrammar != null)
index = fAttrList.getNextAttr(index);
}
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
//validate attributes in DTD fashion
private void validateDTDattribute(QName element, int attValue,
XMLAttributeDecl attributeDecl) throws Exception{
AttributeValidator av = null;
switch (attributeDecl.type) {
case XMLAttributeDecl.TYPE_ENTITY:
{
boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
//System.out.println("value = " + value );
//changes fTempAttDef
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
if ( isAlistAttribute ) {
fValENTITIES.validate( value, null );
} else {
fValENTITY.validate( value, null );
}
} catch ( InvalidDatatypeValueException ex ) {
if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
} else {
System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen
}
}
/*if (attributeDecl.list) {
av = fAttValidatorENTITIES;
}
else {
av = fAttValidatorENTITY;
}*/
}
break;
case XMLAttributeDecl.TYPE_ENUMERATION:
av = fAttValidatorENUMERATION;
break;
case XMLAttributeDecl.TYPE_ID:
{
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
//this.fIdDefs = (Hashtable) fValID.validate( value, null );
//System.out.println("this.fIdDefs = " + this.fIdDefs );
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
fValIDRef.validate( value, this.fStoreIDRef ); //just in case we called id after IDREF
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
}
}
break;
case XMLAttributeDecl.TYPE_IDREF:
{
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef
//changes fTempAttDef
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
if ( isAlistAttribute ) {
fValIDRefs.validate( value, this.fStoreIDRef );
} else {
fValIDRef.validate( value, this.fStoreIDRef );
}
} catch ( InvalidDatatypeValueException ex ) {
if ( ex.getMajorCode() != 1 && ex.getMinorCode() != -1 ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
} else {
System.err.println("Error: " + ex.getLocalizedMessage() );//Should not happen
}
}
}
break;
case XMLAttributeDecl.TYPE_NOTATION:
{
/* WIP
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
//this.fIdDefs = (Hashtable) fValID.validate( value, null );
//System.out.println("this.fIdDefs = " + this.fIdDefs );
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError(ex.getMajorCode(),
ex.getMinorCode(),
fStringPool.toString( attributeDecl.name.rawname), value );
}
}
*/
av = fAttValidatorNOTATION;
}
break;
case XMLAttributeDecl.TYPE_NMTOKEN:
{
String unTrimValue = fStringPool.toString(attValue);
String value = unTrimValue.trim();
boolean isAlistAttribute = attributeDecl.list;//Caveat - Save this information because invalidStandaloneAttDef
//changes fTempAttDef
if (fValidationEnabled) {
if (value != unTrimValue) {
if (invalidStandaloneAttDef(element, attributeDecl.name)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attributeDecl.name.rawname), unTrimValue, value);
}
}
}
try {
if ( isAlistAttribute ) {
fValNMTOKENS.validate( value, null );
} else {
fValNMTOKEN.validate( value, null );
}
} catch ( InvalidDatatypeValueException ex ) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attributeDecl.name.rawname), value);//TODO NMTOKENS messge
}
}
break;
}
if ( av != null )
av.normalize(element, attributeDecl.name, attValue,
attributeDecl.type, attributeDecl.enumeration);
}
/** Character data in content. */
private void charDataInContent() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.println("charDataInContent()");
}
if (fElementChildren.length <= fElementChildrenLength) {
QName[] newarray = new QName[fElementChildren.length * 2];
System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length);
fElementChildren = newarray;
}
QName qname = fElementChildren[fElementChildrenLength];
if (qname == null) {
for (int i = fElementChildrenLength; i < fElementChildren.length; i++) {
fElementChildren[i] = new QName();
}
qname = fElementChildren[fElementChildrenLength];
}
qname.clear();
fElementChildrenLength++;
} // charDataInCount()
/**
* Check that the content of an element is valid.
* <p>
* This is the method of primary concern to the validator. This method is called
* upon the scanner reaching the end tag of an element. At that time, the
* element's children must be structurally validated, so it calls this method.
* The index of the element being checked (in the decl pool), is provided as
* well as an array of element name indexes of the children. The validator must
* confirm that this element can have these children in this order.
* <p>
* This can also be called to do 'what if' testing of content models just to see
* if they would be valid.
* <p>
* Note that the element index is an index into the element decl pool, whereas
* the children indexes are name indexes, i.e. into the string pool.
* <p>
* A value of -1 in the children array indicates a PCDATA node. All other
* indexes will be positive and represent child elements. The count can be
* zero, since some elements have the EMPTY content model and that must be
* confirmed.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of this
* element.
* @param childCount The number of entries in the <code>children</code> array.
* @param children The children of this element. Each integer is an index within
* the <code>StringPool</code> of the child element name. An index
* of -1 is used to indicate an occurrence of non-whitespace character
* data.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed. If the value returned is equal to the number
* of children, then additional content is required to reach a valid
* ending state.
*
* @exception Exception Thrown on error.
*/
private int checkContent(int elementIndex,
QName[] children,
int childOffset,
int childCount) throws Exception {
// Get the element name index from the element
// REVISIT: Validation
final int elementType = fCurrentElement.rawname;
if (DEBUG_PRINT_CONTENT) {
String strTmp = fStringPool.toString(elementType);
System.out.println("Name: "+strTmp+", "+
"Count: "+childCount+", "+
"ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex));
for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) {
if (index == 0) {
System.out.print(" (");
}
String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart);
if (index + 1 == childCount) {
System.out.println(childName + ")");
} else if (index + 1 == 10) {
System.out.println(childName + ",...)");
} else {
System.out.print(childName + ",");
}
}
}
// Get out the content spec for this element
final int contentType = fCurrentContentSpecType;
// debugging
//System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType);
//
// Deal with the possible types of content. We try to optimized here
// by dealing specially with content models that don't require the
// full DFA treatment.
//
if (contentType == XMLElementDecl.TYPE_EMPTY) {
//
// If the child count is greater than zero, then this is
// an error right off the bat at index 0.
//
if (childCount != 0) {
return 0;
}
} else if (contentType == XMLElementDecl.TYPE_ANY) {
//
// This one is open game so we don't pass any judgement on it
// at all. Its assumed to fine since it can hold anything.
//
} else if (contentType == XMLElementDecl.TYPE_MIXED ||
contentType == XMLElementDecl.TYPE_CHILDREN) {
// Get the content model for this element, faulting it in if needed
XMLContentModel cmElem = null;
try {
cmElem = getElementContentModel(elementIndex);
int result = cmElem.validateContent(children, childOffset, childCount);
if (result != -1 && fGrammarIsSchemaGrammar) {
// REVISIT: not optimized for performance,
EquivClassComparator comparator = new EquivClassComparator(fGrammarResolver, fStringPool);
cmElem.setEquivClassComparator(comparator);
result = cmElem.validateContentSpecial(children, childOffset, childCount);
}
return result;
} catch (CMException excToCatch) {
// REVISIT - Translate the caught exception to the protected error API
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
} else if (contentType == -1) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
} else if (contentType == XMLElementDecl.TYPE_SIMPLE ) {
XMLContentModel cmElem = null;
if (childCount > 0) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+
"Can not have element children within a simple type content"},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} else {
try {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
DatatypeValidator dv = fTempElementDecl.datatypeValidator;
// If there is xsi:type validator, substitute it.
if ( fXsiTypeValidator != null ) {
dv = fXsiTypeValidator;
fXsiTypeValidator = null;
}
if (dv == null) {
System.out.println("Internal Error: this element have a simpletype "+
"but no datatypevalidator was found, element "+fTempElementDecl.name
+",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart));
} else {
dv.validate(fDatatypeBuffer.toString(), null);
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { "In element '"+fStringPool.toString(elementType)+"' : "+idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else {
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_CST,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
// We succeeded
return -1;
} // checkContent(int,int,int[]):int
/**
* Checks that all declared elements refer to declared elements
* in their content models. This method calls out to the error
* handler to indicate warnings.
*/
/*private void checkDeclaredElements() throws Exception {
//****DEBUG****
if (DEBUG) print("(???) XMLValidator.checkDeclaredElements\n");
//****DEBUG****
for (int i = 0; i < fElementCount; i++) {
int type = fGrammar.getContentSpecType(i);
if (type == XMLElementDecl.TYPE_MIXED || type == XMLElementDecl.TYPE_CHILDREN) {
int chunk = i >> CHUNK_SHIFT;
int index = i & CHUNK_MASK;
int contentSpecIndex = fContentSpec[chunk][index];
checkDeclaredElements(i, contentSpecIndex);
}
}
}
*/
private void printChildren() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.print('[');
for (int i = 0; i < fElementChildrenLength; i++) {
System.out.print(' ');
QName qname = fElementChildren[i];
if (qname != null) {
System.out.print(fStringPool.toString(qname.rawname));
} else {
System.out.print("null");
}
if (i < fElementChildrenLength - 1) {
System.out.print(", ");
}
System.out.flush();
}
System.out.print(" ]");
System.out.println();
}
}
private void printStack() {
if (DEBUG_ELEMENT_CHILDREN) {
System.out.print('{');
for (int i = 0; i <= fElementDepth; i++) {
System.out.print(' ');
System.out.print(fElementChildrenOffsetStack[i]);
if (i < fElementDepth) {
System.out.print(", ");
}
System.out.flush();
}
System.out.print(" }");
System.out.println();
}
}
//
// Interfaces
//
/**
* AttributeValidator.
*/
public interface AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValue, int attType, int enumHandle)
throws Exception;
} // interface AttributeValidator
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
//
// Classes
//
/**
* AttValidatorNOTATION.
*/
final class AttValidatorNOTATION
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// NOTATION - check that the value is in the AttDef enumeration (V_TAGo)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_NOTATION_ATTRIBUTES,
fStringPool.toString(attribute.rawname),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorNOTATION
/**
* AttValidatorENUMERATION.
*/
final class AttValidatorENUMERATION
implements AttributeValidator {
//
// AttributeValidator methods
//
/** Normalize. */
public int normalize(QName element, QName attribute,
int attValueHandle, int attType,
int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(element, attribute)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attribute.rawname), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// ENUMERATION - check that value is in the AttDef enumeration (V_TAG9)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_ENUMERATION,
fStringPool.toString(attribute.rawname),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
} // normalize(QName,QName,int,int,int):int
//
// Package methods
//
/** Returns true if invalid standalone attribute definition. */
boolean invalidStandaloneAttDef(QName element, QName attribute) {
if (fStandaloneReader == -1) {
return false;
}
// we are normalizing a default att value... this ok?
if (element.rawname == -1) {
return false;
}
return getAttDefIsExternal(element, attribute);
}
} // class AttValidatorENUMERATION
} // class XMLValidator
| false | true | private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if ((fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )||
(fGrammar == null && !fValidating && !fNamespacesEnabled) ) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
int contentSpecType = -1;
boolean skipThisOne = false;
boolean laxThisOne = false;
if ( fGrammarIsSchemaGrammar && fContentLeafStack[fElementDepth] != null ) {
ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth];
QName[] fElemMap = cv.leafNames;
for (int i=0; i<cv.leafCount; i++) {
int type = cv.leafTypes[i] ;
//System.out.println("******* see a ANY_OTHER_SKIP, "+type+","+element+","+fElemMap[i]+"\n*******");
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
if (fElemMap[i].uri==element.uri
&& fElemMap[i].localpart == element.localpart)
break;
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (element.uri == -1) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if (fElemMap[i].uri != element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) {
if (element.uri == -1) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) {
if (fElemMap[i].uri != element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) {
if (element.uri == -1) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) {
if (fElemMap[i].uri != element.uri) {
laxThisOne = true;
break;
}
}
}
}
if (skipThisOne) {
fNeedValidationOff = true;
} else {
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
boolean success = switchGrammar(fGrammarNameSpaceIndex);
if (!success && !laxThisOne) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if ( fGrammar != null ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+
"localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope+"\n");
}
elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope);
if (elementIndex == -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
int aGrammarNSIndex = fGrammarNameSpaceIndex;
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
// update the current Grammar NS index if resolving element succeed.
fGrammarNameSpaceIndex = aGrammarNSIndex;
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
String baseTName = baseTypeInfo.typeName;
if (!baseTName.startsWith("#")) {
int comma = baseTName.indexOf(',');
aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
if ( !switchGrammar(aGrammarNSIndex) ) {
break; //exit the loop in this case
}
}
}
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1) {
if (laxThisOne) {
fNeedValidationOff = true;
} else
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart +
"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri +
"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
}
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+
" and the current enclosing scope: " + fCurrentScope);
}
}
contentSpecType = getContentSpecType(elementIndex);
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
// handle "xsi:type" right here
if (fXsiTypeAttValue > -1) {
String xsiType = fStringPool.toString(fXsiTypeAttValue);
int colonP = xsiType.indexOf(":");
String prefix = "";
String localpart = xsiType;
if (colonP > -1) {
prefix = xsiType.substring(0,colonP);
localpart = xsiType.substring(colonP+1);
}
String uri = "";
int uriIndex = -1;
if (fNamespacesScope != null) {
uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix));
if (uriIndex > -1) {
uri = fStringPool.toString(uriIndex);
if (uriIndex != fGrammarNameSpaceIndex) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex;
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 3: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
}
Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry();
DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry();
if (complexRegistry==null || dataTypeReg == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
fErrorReporter.getLocator().getSystemId()
+" line"+fErrorReporter.getLocator().getLineNumber()
+", canot resolve xsi:type = " + xsiType+" ---2");
} else {
TraverseSchema.ComplexTypeInfo typeInfo =
(TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart);
//TO DO:
// here need to check if this substitution is legal based on the current active grammar,
// this should be easy, cause we already saved final, block and base type information in
// the SchemaGrammar.
if (typeInfo==null) {
if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) {
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart);
} else
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart);
if ( fXsiTypeValidator == null )
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"unresolved type : "+uri+","+localpart
+" found in xsi:type handling");
} else
elementIndex = typeInfo.templateElementIndex;
}
fXsiTypeAttValue = -1;
}
//Change the current scope to be the one defined by this element.
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex);
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
//before switch Grammar, set the elementIndex to be the template elementIndex of its type
if (contentSpecType != -1
&& contentSpecType != XMLElementDecl.TYPE_EMPTY ) {
TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex);
if (typeInfo != null) {
elementIndex = typeInfo.templateElementIndex;
}
}
// now switch the grammar
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 4: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) {
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1 && !fNeedValidationOff ) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fGrammar != null) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1 ) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
} else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fValidating) {
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
// check to see if this attribute matched an attribute wildcard
else if ( fGrammarIsSchemaGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) {
if (fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_SKIP) {
// attribute should just be bypassed,
} else if ( fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT
|| fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_LAX) {
boolean reportError = false;
boolean processContentStrict =
fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (fTempQName.uri == -1) {
if (processContentStrict) {
reportError = true;
}
} else {
Grammar aGrammar =
fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri));
if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) {
if (processContentStrict) {
reportError = true;
}
} else {
SchemaGrammar sGrammar = (SchemaGrammar) aGrammar;
Hashtable attRegistry = sGrammar.getAttirubteDeclRegistry();
if (attRegistry == null) {
if (processContentStrict) {
reportError = true;
}
} else {
XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart));
if (attDecl == null) {
if (processContentStrict) {
reportError = true;
}
} else {
DatatypeValidator attDV = attDecl.datatypeValidator;
if (attDV == null) {
if (processContentStrict) {
reportError = true;
}
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (attDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
}
if (attDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
attDV.validate(value, this.fStoreIDRef );
} else
attDV.validate(unTrimValue, null );
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
}
}
if (reportError) {
Object[] args = { fStringPool.toString(element.rawname),
"ANY---"+fStringPool.toString(attrList.getAttrName(index))};
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
fTempAttDecl.datatypeValidator.validate(value, this.fStoreIDRef );
} else {
fTempAttDecl.datatypeValidator.validate(unTrimValue, null );
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // end of if (fValidating)
} // end of if (attDefIndex == -1) else
}// end of if (fGrammar != null)
index = fAttrList.getNextAttr(index);
}
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
| private void validateElementAndAttributes(QName element,
XMLAttrList attrList)
throws Exception {
if ((fElementDepth >= 0 && fValidationFlagStack[fElementDepth] != 0 )||
(fGrammar == null && !fValidating && !fNamespacesEnabled) ) {
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
fInElementContent = false;
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
if (fStringPool.equalNames(fAttrList.getAttrName(index), fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(fAttrList.getAttValue(index));
break;
}
index = fAttrList.getNextAttr(index);
}
}
return;
}
int elementIndex = -1;
int contentSpecType = -1;
boolean skipThisOne = false;
boolean laxThisOne = false;
if ( fGrammarIsSchemaGrammar && fContentLeafStack[fElementDepth] != null ) {
ContentLeafNameTypeVector cv = fContentLeafStack[fElementDepth];
QName[] fElemMap = cv.leafNames;
for (int i=0; i<cv.leafCount; i++) {
int type = cv.leafTypes[i] ;
//System.out.println("******* see a ANY_OTHER_SKIP, "+type+","+element+","+fElemMap[i]+"\n*******");
if (type == XMLContentSpec.CONTENTSPECNODE_LEAF) {
if (fElemMap[i].uri==element.uri
&& fElemMap[i].localpart == element.localpart)
break;
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL) {
if (element.uri == -1) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER) {
if (fElemMap[i].uri != element.uri) {
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_SKIP) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_SKIP) {
if (element.uri == -1) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_SKIP) {
if (fElemMap[i].uri != element.uri) {
skipThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LAX) {
int uri = fElemMap[i].uri;
if (uri == -1 || uri == element.uri) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_LOCAL_LAX) {
if (element.uri == -1) {
laxThisOne = true;
break;
}
} else if (type == XMLContentSpec.CONTENTSPECNODE_ANY_OTHER_LAX) {
if (fElemMap[i].uri != element.uri) {
laxThisOne = true;
break;
}
}
}
}
if (skipThisOne) {
fNeedValidationOff = true;
} else {
//REVISIT: is this the right place to check on if the Schema has changed?
if ( fNamespacesEnabled && fValidating && element.uri != fGrammarNameSpaceIndex && element.uri != -1 ) {
fGrammarNameSpaceIndex = element.uri;
boolean success = switchGrammar(fGrammarNameSpaceIndex);
if (!success && !laxThisOne) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR, XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 2: " + fStringPool.toString(fGrammarNameSpaceIndex)
+ " , can not found");
}
}
if ( fGrammar != null ) {
if (DEBUG_SCHEMA_VALIDATION) {
System.out.println("*******Lookup element: uri: " + fStringPool.toString(element.uri)+
"localpart: '" + fStringPool.toString(element.localpart)
+"' and scope : " + fCurrentScope+"\n");
}
elementIndex = fGrammar.getElementDeclIndex(element,fCurrentScope);
if (elementIndex == -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element, TOP_LEVEL_SCOPE);
}
if (elementIndex == -1) {
// if validating based on a Schema, try to resolve the element again by searching in its type's ancestor types
if (fGrammarIsSchemaGrammar && fCurrentElementIndex != -1) {
TraverseSchema.ComplexTypeInfo baseTypeInfo = null;
baseTypeInfo = ((SchemaGrammar)fGrammar).getElementComplexTypeInfo(fCurrentElementIndex);
int aGrammarNSIndex = fGrammarNameSpaceIndex;
while (baseTypeInfo != null) {
elementIndex = fGrammar.getElementDeclIndex(element, baseTypeInfo.scopeDefined);
if (elementIndex > -1 ) {
// update the current Grammar NS index if resolving element succeed.
fGrammarNameSpaceIndex = aGrammarNSIndex;
break;
}
baseTypeInfo = baseTypeInfo.baseComplexTypeInfo;
if (baseTypeInfo != null) {
String baseTName = baseTypeInfo.typeName;
if (!baseTName.startsWith("#")) {
int comma = baseTName.indexOf(',');
aGrammarNSIndex = fStringPool.addSymbol(baseTName.substring(0,comma).trim());
if (aGrammarNSIndex != fGrammarNameSpaceIndex) {
if ( !switchGrammar(aGrammarNSIndex) ) {
break; //exit the loop in this case
}
}
}
}
}
if (elementIndex == -1) {
switchGrammar(fGrammarNameSpaceIndex);
}
}
//if still can't resolve it, try TOP_LEVEL_SCOPE AGAIN
/****
if ( element.uri == -1 && elementIndex == -1
&& fNamespacesScope != null
&& fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING) != -1 ) {
elementIndex = fGrammar.getElementDeclIndex(element.localpart, TOP_LEVEL_SCOPE);
// REVISIT:
// this is a hack to handle the situation where namespace prefix "" is bound to nothing, and there
// is a "noNamespaceSchemaLocation" specified, and element
element.uri = StringPool.EMPTY_STRING;
}
/****/
/****/
if (elementIndex == -1) {
if (laxThisOne) {
fNeedValidationOff = true;
} else
if (DEBUG_SCHEMA_VALIDATION)
System.out.println("!!! can not find elementDecl in the grammar, " +
" the element localpart: " + element.localpart +
"["+fStringPool.toString(element.localpart) +"]" +
" the element uri: " + element.uri +
"["+fStringPool.toString(element.uri) +"]" +
" and the current enclosing scope: " + fCurrentScope );
}
/****/
}
if (DEBUG_SCHEMA_VALIDATION) {
fGrammar.getElementDecl(elementIndex, fTempElementDecl);
System.out.println("elementIndex: " + elementIndex+" \n and itsName : '"
+ fStringPool.toString(fTempElementDecl.name.localpart)
+"' \n its ContentType:" + fTempElementDecl.type
+"\n its ContentSpecIndex : " + fTempElementDecl.contentSpecIndex +"\n"+
" and the current enclosing scope: " + fCurrentScope);
}
}
contentSpecType = getContentSpecType(elementIndex);
if (fGrammarIsSchemaGrammar && elementIndex != -1) {
// handle "xsi:type" right here
if (fXsiTypeAttValue > -1) {
String xsiType = fStringPool.toString(fXsiTypeAttValue);
int colonP = xsiType.indexOf(":");
String prefix = "";
String localpart = xsiType;
if (colonP > -1) {
prefix = xsiType.substring(0,colonP);
localpart = xsiType.substring(colonP+1);
}
String uri = "";
int uriIndex = -1;
if (fNamespacesScope != null) {
uriIndex = fNamespacesScope.getNamespaceForPrefix(fStringPool.addSymbol(prefix));
if (uriIndex > -1) {
uri = fStringPool.toString(uriIndex);
if (uriIndex != fGrammarNameSpaceIndex) {
fGrammarNameSpaceIndex = fCurrentSchemaURI = uriIndex;
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 3: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
}
Hashtable complexRegistry = ((SchemaGrammar)fGrammar).getComplexTypeRegistry();
DatatypeValidatorFactoryImpl dataTypeReg = ((SchemaGrammar)fGrammar).getDatatypeRegistry();
if (complexRegistry==null || dataTypeReg == null) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
fErrorReporter.getLocator().getSystemId()
+" line"+fErrorReporter.getLocator().getLineNumber()
+", canot resolve xsi:type = " + xsiType+" ---2");
} else {
TraverseSchema.ComplexTypeInfo typeInfo =
(TraverseSchema.ComplexTypeInfo) complexRegistry.get(uri+","+localpart);
//TO DO:
// here need to check if this substitution is legal based on the current active grammar,
// this should be easy, cause we already saved final, block and base type information in
// the SchemaGrammar.
if (typeInfo==null) {
if (uri.length() == 0 || uri.equals(SchemaSymbols.URI_SCHEMAFORSCHEMA) ) {
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(localpart);
} else
fXsiTypeValidator = dataTypeReg.getDatatypeValidator(uri+","+localpart);
if ( fXsiTypeValidator == null )
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"unresolved type : "+uri+","+localpart
+" found in xsi:type handling");
} else
elementIndex = typeInfo.templateElementIndex;
}
fXsiTypeAttValue = -1;
}
//Change the current scope to be the one defined by this element.
fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(elementIndex);
// here need to check if we need to switch Grammar by asking SchemaGrammar whether
// this element actually is of a type in another Schema.
String anotherSchemaURI = ((SchemaGrammar)fGrammar).getElementFromAnotherSchemaURI(elementIndex);
if (anotherSchemaURI != null) {
//before switch Grammar, set the elementIndex to be the template elementIndex of its type
if (contentSpecType != -1
&& contentSpecType != XMLElementDecl.TYPE_EMPTY ) {
TraverseSchema.ComplexTypeInfo typeInfo = ((SchemaGrammar) fGrammar).getElementComplexTypeInfo(elementIndex);
if (typeInfo != null) {
elementIndex = typeInfo.templateElementIndex;
}
}
// now switch the grammar
fGrammarNameSpaceIndex = fCurrentSchemaURI = fStringPool.addSymbol(anotherSchemaURI);
boolean success = switchGrammar(fCurrentSchemaURI);
if (!success && !fNeedValidationOff) {
reportRecoverableXMLError(XMLMessages.MSG_GENERIC_SCHEMA_ERROR,
XMLMessages.SCHEMA_GENERIC_ERROR,
"Grammar with uri 4: "
+ fStringPool.toString(fCurrentSchemaURI)
+ " , can not found");
}
}
}
if (contentSpecType == -1 && fValidating && !fNeedValidationOff ) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
element.rawname);
}
if (fGrammar != null && fGrammarIsSchemaGrammar && elementIndex != -1) {
fAttrListHandle = addDefaultAttributes(elementIndex, attrList, fAttrListHandle, fValidating, fStandaloneReader != -1);
}
if (fAttrListHandle != -1) {
fAttrList.endAttrList();
}
if (DEBUG_PRINT_ATTRIBUTES) {
String elementStr = fStringPool.toString(element.rawname);
System.out.print("startElement: <" + elementStr);
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
// REVISIT: Validation. Do we need to recheck for the xml:lang
// attribute? It was already checked above -- perhaps
// this is to check values that are defaulted in? If
// so, this check could move to the attribute decl
// callback so we can check the default value before
// it is used.
if (fAttrListHandle != -1 && !fNeedValidationOff ) {
int index = fAttrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attrNameIndex = attrList.getAttrName(index);
if (fStringPool.equalNames(attrNameIndex, fXMLLang)) {
fDocumentScanner.checkXMLLangAttributeValue(attrList.getAttValue(index));
// break;
}
// here, we validate every "user-defined" attributes
int _xmlns = fStringPool.addSymbol("xmlns");
if (attrNameIndex != _xmlns && attrList.getAttrPrefix(index) != _xmlns)
if (fGrammar != null) {
fAttrNameLocator = getLocatorImpl(fAttrNameLocator);
fTempQName.setValues(attrList.getAttrPrefix(index),
attrList.getAttrLocalpart(index),
attrList.getAttrName(index),
attrList.getAttrURI(index) );
int attDefIndex = getAttDefByElementIndex(elementIndex, fTempQName);
if (fTempQName.uri != fXsiURI)
if (attDefIndex == -1 ) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
/*****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/******/
}
} else {
fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl);
int attributeType = attributeTypeName(fTempAttDecl);
attrList.setAttType(index, attributeType);
if (fValidating) {
if (fGrammarIsDTDGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ENTITY ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ENUMERATION ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NMTOKEN ||
fTempAttDecl.type == XMLAttributeDecl.TYPE_NOTATION)
) {
validateDTDattribute(element, attrList.getAttValue(index), fTempAttDecl);
}
// check to see if this attribute matched an attribute wildcard
else if ( fGrammarIsSchemaGrammar &&
(fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_ANY
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LIST
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_LOCAL
||fTempAttDecl.type == XMLAttributeDecl.TYPE_ANY_OTHER) ) {
if (fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_SKIP) {
// attribute should just be bypassed,
} else if ( fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT
|| fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_LAX) {
boolean reportError = false;
boolean processContentStrict =
fTempAttDecl.defaultType == XMLAttributeDecl.PROCESSCONTENTS_STRICT;
if (fTempQName.uri == -1) {
if (processContentStrict) {
reportError = true;
}
} else {
Grammar aGrammar =
fGrammarResolver.getGrammar(fStringPool.toString(fTempQName.uri));
if (aGrammar == null || !(aGrammar instanceof SchemaGrammar) ) {
if (processContentStrict) {
reportError = true;
}
} else {
SchemaGrammar sGrammar = (SchemaGrammar) aGrammar;
Hashtable attRegistry = sGrammar.getAttirubteDeclRegistry();
if (attRegistry == null) {
if (processContentStrict) {
reportError = true;
}
} else {
XMLAttributeDecl attDecl = (XMLAttributeDecl) attRegistry.get(fStringPool.toString(fTempQName.localpart));
if (attDecl == null) {
if (processContentStrict) {
reportError = true;
}
} else {
DatatypeValidator attDV = attDecl.datatypeValidator;
if (attDV == null) {
if (processContentStrict) {
reportError = true;
}
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (attDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
}
if (attDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
attDV.validate(value, this.fStoreIDRef );
} else
attDV.validate(unTrimValue, null );
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
}
}
}
if (reportError) {
Object[] args = { fStringPool.toString(element.rawname),
"ANY---"+fStringPool.toString(attrList.getAttrName(index))};
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} else if (fTempAttDecl.datatypeValidator == null) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(attrList.getAttrName(index))};
System.out.println("[Error] Datatypevalidator for attribute " + fStringPool.toString(attrList.getAttrName(index))
+ " not found in element type " + fStringPool.toString(element.rawname));
//REVISIT : is this the right message?
/****/
fErrorReporter.reportError(fAttrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
/****/
} else {
try {
String unTrimValue = fStringPool.toString(attrList.getAttValue(index));
String value = unTrimValue.trim();
if (fTempAttDecl.type == XMLAttributeDecl.TYPE_ID ) {
this.fStoreIDRef.setDatatypeObject( fValID.validate( value, null ) );
} else if (fTempAttDecl.type == XMLAttributeDecl.TYPE_IDREF ) {
fTempAttDecl.datatypeValidator.validate(value, this.fStoreIDRef );
} else {
fTempAttDecl.datatypeValidator.validate(unTrimValue, null );
}
} catch (InvalidDatatypeValueException idve) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
SchemaMessageProvider.DatatypeError,
SchemaMessageProvider.MSG_NONE,
new Object [] { idve.getMessage()},
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
} // end of if (fValidating)
} // end of if (attDefIndex == -1) else
}// end of if (fGrammar != null)
index = fAttrList.getNextAttr(index);
}
}
}
if (fAttrListHandle != -1) {
int index = attrList.getFirstAttr(fAttrListHandle);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = attrList.getAttrPrefix(index);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix)};
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
attrList.setAttrURI(index, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
if (fValidating && contentSpecType == XMLElementDecl.TYPE_SIMPLE) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
fInElementContent = (contentSpecType == XMLElementDecl.TYPE_CHILDREN);
} // validateElementAndAttributes(QName,XMLAttrList)
|
diff --git a/core/src/main/java/org/apache/mahout/clustering/kmeans/RandomSeedGenerator.java b/core/src/main/java/org/apache/mahout/clustering/kmeans/RandomSeedGenerator.java
index 67afd1d46..a89b03b1a 100644
--- a/core/src/main/java/org/apache/mahout/clustering/kmeans/RandomSeedGenerator.java
+++ b/core/src/main/java/org/apache/mahout/clustering/kmeans/RandomSeedGenerator.java
@@ -1,121 +1,121 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.clustering.kmeans;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists;
import com.google.common.io.Closeables;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.mahout.common.HadoopUtil;
import org.apache.mahout.common.Pair;
import org.apache.mahout.common.RandomUtils;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.common.iterator.sequencefile.PathFilters;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileIterable;
import org.apache.mahout.math.VectorWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Given an Input Path containing a {@link org.apache.hadoop.io.SequenceFile}, randomly select k vectors and
* write them to the output file as a {@link org.apache.mahout.clustering.kmeans.Cluster} representing the
* initial centroid to use.
*/
public final class RandomSeedGenerator {
private static final Logger log = LoggerFactory.getLogger(RandomSeedGenerator.class);
public static final String K = "k";
private RandomSeedGenerator() {
}
public static Path buildRandom(Configuration conf,
Path input,
Path output,
int k,
DistanceMeasure measure) throws IOException {
// delete the output directory
FileSystem fs = FileSystem.get(output.toUri(), conf);
HadoopUtil.delete(conf, output);
Path outFile = new Path(output, "part-randomSeed");
boolean newFile = fs.createNewFile(outFile);
if (newFile) {
Path inputPathPattern;
if (fs.getFileStatus(input).isDir()) {
inputPathPattern = new Path(input, "*");
} else {
inputPathPattern = input;
}
FileStatus[] inputFiles = fs.globStatus(inputPathPattern, PathFilters.logsCRCFilter());
SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, outFile, Text.class, Cluster.class);
Random random = RandomUtils.getRandom();
List<Text> chosenTexts = Lists.newArrayListWithCapacity(k);
List<Cluster> chosenClusters = Lists.newArrayListWithCapacity(k);
int nextClusterId = 0;
for (FileStatus fileStatus : inputFiles) {
if (fileStatus.isDir()) {
continue;
}
for (Pair<Writable,VectorWritable> record
: new SequenceFileIterable<Writable,VectorWritable>(fileStatus.getPath(), true, conf)) {
Writable key = record.getFirst();
VectorWritable value = record.getSecond();
Cluster newCluster = new Cluster(value.get(), nextClusterId++, measure);
newCluster.observe(value.get(), 1);
Text newText = new Text(key.toString());
int currentSize = chosenTexts.size();
if (currentSize < k) {
chosenTexts.add(newText);
chosenClusters.add(newCluster);
- } else if (random.nextInt(currentSize + 1) == 0) { // with chance 1/(currentSize+1) pick new element
+ } else if (random.nextInt(currentSize + 1) != 0) { // with chance 1/(currentSize+1) pick new element
int indexToRemove = random.nextInt(currentSize); // evict one chosen randomly
chosenTexts.remove(indexToRemove);
chosenClusters.remove(indexToRemove);
chosenTexts.add(newText);
chosenClusters.add(newCluster);
}
}
}
try {
- for (int i = 0; i < k; i++) {
+ for (int i = 0; i < chosenTexts.size(); i++) {
writer.append(chosenTexts.get(i), chosenClusters.get(i));
}
log.info("Wrote {} vectors to {}", k, outFile);
} finally {
Closeables.closeQuietly(writer);
}
}
return outFile;
}
}
| false | true | public static Path buildRandom(Configuration conf,
Path input,
Path output,
int k,
DistanceMeasure measure) throws IOException {
// delete the output directory
FileSystem fs = FileSystem.get(output.toUri(), conf);
HadoopUtil.delete(conf, output);
Path outFile = new Path(output, "part-randomSeed");
boolean newFile = fs.createNewFile(outFile);
if (newFile) {
Path inputPathPattern;
if (fs.getFileStatus(input).isDir()) {
inputPathPattern = new Path(input, "*");
} else {
inputPathPattern = input;
}
FileStatus[] inputFiles = fs.globStatus(inputPathPattern, PathFilters.logsCRCFilter());
SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, outFile, Text.class, Cluster.class);
Random random = RandomUtils.getRandom();
List<Text> chosenTexts = Lists.newArrayListWithCapacity(k);
List<Cluster> chosenClusters = Lists.newArrayListWithCapacity(k);
int nextClusterId = 0;
for (FileStatus fileStatus : inputFiles) {
if (fileStatus.isDir()) {
continue;
}
for (Pair<Writable,VectorWritable> record
: new SequenceFileIterable<Writable,VectorWritable>(fileStatus.getPath(), true, conf)) {
Writable key = record.getFirst();
VectorWritable value = record.getSecond();
Cluster newCluster = new Cluster(value.get(), nextClusterId++, measure);
newCluster.observe(value.get(), 1);
Text newText = new Text(key.toString());
int currentSize = chosenTexts.size();
if (currentSize < k) {
chosenTexts.add(newText);
chosenClusters.add(newCluster);
} else if (random.nextInt(currentSize + 1) == 0) { // with chance 1/(currentSize+1) pick new element
int indexToRemove = random.nextInt(currentSize); // evict one chosen randomly
chosenTexts.remove(indexToRemove);
chosenClusters.remove(indexToRemove);
chosenTexts.add(newText);
chosenClusters.add(newCluster);
}
}
}
try {
for (int i = 0; i < k; i++) {
writer.append(chosenTexts.get(i), chosenClusters.get(i));
}
log.info("Wrote {} vectors to {}", k, outFile);
} finally {
Closeables.closeQuietly(writer);
}
}
return outFile;
}
| public static Path buildRandom(Configuration conf,
Path input,
Path output,
int k,
DistanceMeasure measure) throws IOException {
// delete the output directory
FileSystem fs = FileSystem.get(output.toUri(), conf);
HadoopUtil.delete(conf, output);
Path outFile = new Path(output, "part-randomSeed");
boolean newFile = fs.createNewFile(outFile);
if (newFile) {
Path inputPathPattern;
if (fs.getFileStatus(input).isDir()) {
inputPathPattern = new Path(input, "*");
} else {
inputPathPattern = input;
}
FileStatus[] inputFiles = fs.globStatus(inputPathPattern, PathFilters.logsCRCFilter());
SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, outFile, Text.class, Cluster.class);
Random random = RandomUtils.getRandom();
List<Text> chosenTexts = Lists.newArrayListWithCapacity(k);
List<Cluster> chosenClusters = Lists.newArrayListWithCapacity(k);
int nextClusterId = 0;
for (FileStatus fileStatus : inputFiles) {
if (fileStatus.isDir()) {
continue;
}
for (Pair<Writable,VectorWritable> record
: new SequenceFileIterable<Writable,VectorWritable>(fileStatus.getPath(), true, conf)) {
Writable key = record.getFirst();
VectorWritable value = record.getSecond();
Cluster newCluster = new Cluster(value.get(), nextClusterId++, measure);
newCluster.observe(value.get(), 1);
Text newText = new Text(key.toString());
int currentSize = chosenTexts.size();
if (currentSize < k) {
chosenTexts.add(newText);
chosenClusters.add(newCluster);
} else if (random.nextInt(currentSize + 1) != 0) { // with chance 1/(currentSize+1) pick new element
int indexToRemove = random.nextInt(currentSize); // evict one chosen randomly
chosenTexts.remove(indexToRemove);
chosenClusters.remove(indexToRemove);
chosenTexts.add(newText);
chosenClusters.add(newCluster);
}
}
}
try {
for (int i = 0; i < chosenTexts.size(); i++) {
writer.append(chosenTexts.get(i), chosenClusters.get(i));
}
log.info("Wrote {} vectors to {}", k, outFile);
} finally {
Closeables.closeQuietly(writer);
}
}
return outFile;
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/utilities/packets/BossHealthBar.java b/src/main/java/net/aufdemrand/denizen/utilities/packets/BossHealthBar.java
index a562b35d2..60caf72a1 100644
--- a/src/main/java/net/aufdemrand/denizen/utilities/packets/BossHealthBar.java
+++ b/src/main/java/net/aufdemrand/denizen/utilities/packets/BossHealthBar.java
@@ -1,226 +1,226 @@
package net.aufdemrand.denizen.utilities.packets;
import java.lang.reflect.Field;
import java.util.HashMap;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.minecraft.server.v1_7_R1.DataWatcher;
import net.minecraft.server.v1_7_R1.EntityPlayer;
import net.minecraft.server.v1_7_R1.Packet;
import net.minecraft.server.v1_7_R1.PacketPlayInClientCommand;
import net.minecraft.server.v1_7_R1.PacketPlayOutSpawnEntityLiving;
import net.minecraft.server.v1_7_R1.PacketPlayOutEntityDestroy;
import net.minecraft.server.v1_7_R1.PacketPlayOutEntityMetadata;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_7_R1.entity.CraftPlayer;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
// Retrieved from https://forums.bukkit.org/threads/tutorial-utilizing-the-boss-health-bar.158018/
// Modified for usage by Denizen
// Original code by chasechocolate
// Modified by ftbastler for Minecraft 1.7
public class BossHealthBar {
public static final int ENTITY_ID = 1234567;
private static HashMap<String, Boolean> hasHealthBar = new HashMap<String, Boolean>();
public static void sendPacket(Player player, Packet packet) {
EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
entityPlayer.playerConnection.sendPacket(packet);
}
public static Field getField(Class<?> cl, String field_name) {
try {
Field field = cl.getDeclaredField(field_name);
return field;
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
//Accessing packets
@SuppressWarnings("deprecation")
public static PacketPlayOutSpawnEntityLiving getMobPacket(String text, Location loc) {
PacketPlayOutSpawnEntityLiving mobPacket = new PacketPlayOutSpawnEntityLiving();
try {
Field a = getField(mobPacket.getClass(), "a");
a.setAccessible(true);
a.set(mobPacket, ENTITY_ID);
Field b = getField(mobPacket.getClass(), "b");
b.setAccessible(true);
- b.set(mobPacket, (byte) EntityType.WITHER.getTypeId());
+ b.set(mobPacket, (byte) EntityType.ENDER_DRAGON.getTypeId());
Field c = getField(mobPacket.getClass(), "c");
c.setAccessible(true);
c.set(mobPacket, (int) Math.floor(loc.getBlockX() * 32.0D));
Field d = getField(mobPacket.getClass(), "d");
d.setAccessible(true);
- d.set(mobPacket, (int) Math.floor(loc.getBlockY() * 32.0D));
+ d.set(mobPacket, -256 * 32); // Y
Field e = getField(mobPacket.getClass(), "e");
e.setAccessible(true);
e.set(mobPacket, (int) Math.floor(loc.getBlockZ() * 32.0D));
Field f = getField(mobPacket.getClass(), "f");
f.setAccessible(true);
f.set(mobPacket, (byte) 0);
Field g = getField(mobPacket.getClass(), "g");
g.setAccessible(true);
g.set(mobPacket, (byte) 0);
Field h = getField(mobPacket.getClass(), "h");
h.setAccessible(true);
h.set(mobPacket, (byte) 0);
Field i = getField(mobPacket.getClass(), "i");
i.setAccessible(true);
i.set(mobPacket, (byte) 0);
Field j = getField(mobPacket.getClass(), "j");
j.setAccessible(true);
j.set(mobPacket, (byte) 0);
Field k = getField(mobPacket.getClass(), "k");
k.setAccessible(true);
k.set(mobPacket, (byte) 0);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
DataWatcher watcher = getWatcher(text, 300);
try {
Field t = PacketPlayOutSpawnEntityLiving.class.getDeclaredField("l");
t.setAccessible(true);
t.set(mobPacket, watcher);
} catch (Exception ex) {
ex.printStackTrace();
}
return mobPacket;
}
public static PacketPlayOutEntityDestroy getDestroyEntityPacket() {
PacketPlayOutEntityDestroy packet = new PacketPlayOutEntityDestroy();
Field a = getField(packet.getClass(), "a");
a.setAccessible(true);
try {
a.set(packet, new int[]{ENTITY_ID});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return packet;
}
public static PacketPlayOutEntityMetadata getMetadataPacket(DataWatcher watcher) {
PacketPlayOutEntityMetadata metaPacket = new PacketPlayOutEntityMetadata();
Field a = getField(metaPacket.getClass(), "a");
a.setAccessible(true);
try {
a.set(metaPacket, ENTITY_ID);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
try {
Field b = PacketPlayOutEntityMetadata.class.getDeclaredField("b");
b.setAccessible(true);
b.set(metaPacket, watcher.c());
} catch (Exception e) {
e.printStackTrace();
}
return metaPacket;
}
public static PacketPlayInClientCommand getRespawnPacket() {
PacketPlayInClientCommand packet = new PacketPlayInClientCommand();
Field a = getField(packet.getClass(), "a");
a.setAccessible(true);
try {
a.set(packet, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return packet;
}
public static DataWatcher getWatcher(String text, int health) {
DataWatcher watcher = new DataWatcher(null);
watcher.a(0, (Byte) (byte) 0x20); //Flags, 0x20 = invisible
watcher.a(6, (float) health);
watcher.a(10, text); //Entity name
watcher.a(11, (Byte) (byte) 1); //Show name, 1 = show, 0 = don't show
//watcher.a(16, (Integer) (int) health); //Wither health, 300 = full health
return watcher;
}
//Other methods
public static void displayTextBar(String text, final Player player) {
PacketPlayOutSpawnEntityLiving mobPacket = getMobPacket(text, player.getLocation());
sendPacket(player, mobPacket);
hasHealthBar.put(player.getName(), true);
}
public static void removeTextBar(Player player) {
if (hasHealthBar.containsKey(player.getName())) {
PacketPlayOutEntityDestroy destroyEntityPacket = getDestroyEntityPacket();
sendPacket(player, destroyEntityPacket);
hasHealthBar.put(player.getName(), false);
}
}
public static void displayLoadingBar(final String text, final String completeText, final Player player, final int healthAdd, final long delay, final boolean loadUp) {
PacketPlayOutSpawnEntityLiving mobPacket = getMobPacket(text, player.getLocation());
sendPacket(player, mobPacket);
hasHealthBar.put(player.getName(), true);
new BukkitRunnable() {
int health = (loadUp ? 0 : 300);
@Override
public void run() {
if ((loadUp ? health < 300 : health > 0)) {
DataWatcher watcher = getWatcher(text, health);
PacketPlayOutEntityMetadata metaPacket = getMetadataPacket(watcher);
sendPacket(player, metaPacket);
if (loadUp) {
health += healthAdd;
} else {
health -= healthAdd;
}
} else {
DataWatcher watcher = getWatcher(text, (loadUp ? 300 : 0));
PacketPlayOutEntityMetadata metaPacket = getMetadataPacket(watcher);
PacketPlayOutEntityDestroy destroyEntityPacket = getDestroyEntityPacket();
sendPacket(player, metaPacket);
sendPacket(player, destroyEntityPacket);
hasHealthBar.put(player.getName(), false);
//Complete text
PacketPlayOutSpawnEntityLiving mobPacket = getMobPacket(completeText, player.getLocation());
sendPacket(player, mobPacket);
hasHealthBar.put(player.getName(), true);
DataWatcher watcher2 = getWatcher(completeText, 300);
PacketPlayOutEntityMetadata metaPacket2 = getMetadataPacket(watcher2);
sendPacket(player, metaPacket2);
new BukkitRunnable() {
@Override
public void run() {
PacketPlayOutEntityDestroy destroyEntityPacket = getDestroyEntityPacket();
sendPacket(player, destroyEntityPacket);
hasHealthBar.put(player.getName(), false);
}
}.runTaskLater(DenizenAPI.getCurrentInstance(), 40L);
this.cancel();
}
}
}.runTaskTimer(DenizenAPI.getCurrentInstance(), delay, delay);
}
public static void displayLoadingBar(final String text, final String completeText, final Player player, final int secondsDelay, final boolean loadUp) {
final int healthChangePerSecond = 300 / secondsDelay;
displayLoadingBar(text, completeText, player, healthChangePerSecond, 20L, loadUp);
}
}
| false | true | public static PacketPlayOutSpawnEntityLiving getMobPacket(String text, Location loc) {
PacketPlayOutSpawnEntityLiving mobPacket = new PacketPlayOutSpawnEntityLiving();
try {
Field a = getField(mobPacket.getClass(), "a");
a.setAccessible(true);
a.set(mobPacket, ENTITY_ID);
Field b = getField(mobPacket.getClass(), "b");
b.setAccessible(true);
b.set(mobPacket, (byte) EntityType.WITHER.getTypeId());
Field c = getField(mobPacket.getClass(), "c");
c.setAccessible(true);
c.set(mobPacket, (int) Math.floor(loc.getBlockX() * 32.0D));
Field d = getField(mobPacket.getClass(), "d");
d.setAccessible(true);
d.set(mobPacket, (int) Math.floor(loc.getBlockY() * 32.0D));
Field e = getField(mobPacket.getClass(), "e");
e.setAccessible(true);
e.set(mobPacket, (int) Math.floor(loc.getBlockZ() * 32.0D));
Field f = getField(mobPacket.getClass(), "f");
f.setAccessible(true);
f.set(mobPacket, (byte) 0);
Field g = getField(mobPacket.getClass(), "g");
g.setAccessible(true);
g.set(mobPacket, (byte) 0);
Field h = getField(mobPacket.getClass(), "h");
h.setAccessible(true);
h.set(mobPacket, (byte) 0);
Field i = getField(mobPacket.getClass(), "i");
i.setAccessible(true);
i.set(mobPacket, (byte) 0);
Field j = getField(mobPacket.getClass(), "j");
j.setAccessible(true);
j.set(mobPacket, (byte) 0);
Field k = getField(mobPacket.getClass(), "k");
k.setAccessible(true);
k.set(mobPacket, (byte) 0);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
DataWatcher watcher = getWatcher(text, 300);
try {
Field t = PacketPlayOutSpawnEntityLiving.class.getDeclaredField("l");
t.setAccessible(true);
t.set(mobPacket, watcher);
} catch (Exception ex) {
ex.printStackTrace();
}
return mobPacket;
}
| public static PacketPlayOutSpawnEntityLiving getMobPacket(String text, Location loc) {
PacketPlayOutSpawnEntityLiving mobPacket = new PacketPlayOutSpawnEntityLiving();
try {
Field a = getField(mobPacket.getClass(), "a");
a.setAccessible(true);
a.set(mobPacket, ENTITY_ID);
Field b = getField(mobPacket.getClass(), "b");
b.setAccessible(true);
b.set(mobPacket, (byte) EntityType.ENDER_DRAGON.getTypeId());
Field c = getField(mobPacket.getClass(), "c");
c.setAccessible(true);
c.set(mobPacket, (int) Math.floor(loc.getBlockX() * 32.0D));
Field d = getField(mobPacket.getClass(), "d");
d.setAccessible(true);
d.set(mobPacket, -256 * 32); // Y
Field e = getField(mobPacket.getClass(), "e");
e.setAccessible(true);
e.set(mobPacket, (int) Math.floor(loc.getBlockZ() * 32.0D));
Field f = getField(mobPacket.getClass(), "f");
f.setAccessible(true);
f.set(mobPacket, (byte) 0);
Field g = getField(mobPacket.getClass(), "g");
g.setAccessible(true);
g.set(mobPacket, (byte) 0);
Field h = getField(mobPacket.getClass(), "h");
h.setAccessible(true);
h.set(mobPacket, (byte) 0);
Field i = getField(mobPacket.getClass(), "i");
i.setAccessible(true);
i.set(mobPacket, (byte) 0);
Field j = getField(mobPacket.getClass(), "j");
j.setAccessible(true);
j.set(mobPacket, (byte) 0);
Field k = getField(mobPacket.getClass(), "k");
k.setAccessible(true);
k.set(mobPacket, (byte) 0);
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
DataWatcher watcher = getWatcher(text, 300);
try {
Field t = PacketPlayOutSpawnEntityLiving.class.getDeclaredField("l");
t.setAccessible(true);
t.set(mobPacket, watcher);
} catch (Exception ex) {
ex.printStackTrace();
}
return mobPacket;
}
|
diff --git a/drools-planner-core/src/main/java/org/drools/planner/core/score/director/AbstractScoreDirectorFactory.java b/drools-planner-core/src/main/java/org/drools/planner/core/score/director/AbstractScoreDirectorFactory.java
index 64979359..dc30b514 100644
--- a/drools-planner-core/src/main/java/org/drools/planner/core/score/director/AbstractScoreDirectorFactory.java
+++ b/drools-planner-core/src/main/java/org/drools/planner/core/score/director/AbstractScoreDirectorFactory.java
@@ -1,69 +1,71 @@
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.planner.core.score.director;
import org.drools.planner.core.domain.solution.SolutionDescriptor;
import org.drools.planner.core.score.Score;
import org.drools.planner.core.score.definition.ScoreDefinition;
import org.drools.planner.core.solution.Solution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract superclass for {@link ScoreDirectorFactory}.
* @see ScoreDirectorFactory
*/
public abstract class AbstractScoreDirectorFactory implements ScoreDirectorFactory {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected SolutionDescriptor solutionDescriptor;
protected ScoreDefinition scoreDefinition;
public SolutionDescriptor getSolutionDescriptor() {
return solutionDescriptor;
}
public void setSolutionDescriptor(SolutionDescriptor solutionDescriptor) {
this.solutionDescriptor = solutionDescriptor;
}
public ScoreDefinition getScoreDefinition() {
return scoreDefinition;
}
public void setScoreDefinition(ScoreDefinition scoreDefinition) {
this.scoreDefinition = scoreDefinition;
}
// ************************************************************************
// Complex methods
// ************************************************************************
public void assertScore(Solution solution) {
+ // Get the score before uncorruptedScoreDirector.calculateScore() modifies it
+ Score score = solution.getScore();
ScoreDirector uncorruptedScoreDirector = buildScoreDirector();
uncorruptedScoreDirector.setWorkingSolution(solution);
Score uncorruptedScore = uncorruptedScoreDirector.calculateScore();
uncorruptedScoreDirector.dispose();
- if (!solution.getScore().equals(uncorruptedScore)) {
+ if (!score.equals(uncorruptedScore)) {
throw new IllegalStateException(
- "Score corruption: the solution's score (" + solution.getScore() + ") is not the uncorruptedScore ("
+ "Score corruption: the solution's score (" + score + ") is not the uncorruptedScore ("
+ uncorruptedScore + ").");
}
}
}
| false | true | public void assertScore(Solution solution) {
ScoreDirector uncorruptedScoreDirector = buildScoreDirector();
uncorruptedScoreDirector.setWorkingSolution(solution);
Score uncorruptedScore = uncorruptedScoreDirector.calculateScore();
uncorruptedScoreDirector.dispose();
if (!solution.getScore().equals(uncorruptedScore)) {
throw new IllegalStateException(
"Score corruption: the solution's score (" + solution.getScore() + ") is not the uncorruptedScore ("
+ uncorruptedScore + ").");
}
}
| public void assertScore(Solution solution) {
// Get the score before uncorruptedScoreDirector.calculateScore() modifies it
Score score = solution.getScore();
ScoreDirector uncorruptedScoreDirector = buildScoreDirector();
uncorruptedScoreDirector.setWorkingSolution(solution);
Score uncorruptedScore = uncorruptedScoreDirector.calculateScore();
uncorruptedScoreDirector.dispose();
if (!score.equals(uncorruptedScore)) {
throw new IllegalStateException(
"Score corruption: the solution's score (" + score + ") is not the uncorruptedScore ("
+ uncorruptedScore + ").");
}
}
|
diff --git a/charon/charon-core/src/main/java/org/wso2/charon/core/objects/ListedResource.java b/charon/charon-core/src/main/java/org/wso2/charon/core/objects/ListedResource.java
index d80155a4..3820ffb4 100644
--- a/charon/charon-core/src/main/java/org/wso2/charon/core/objects/ListedResource.java
+++ b/charon/charon-core/src/main/java/org/wso2/charon/core/objects/ListedResource.java
@@ -1,123 +1,123 @@
/*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.charon.core.objects;
import org.wso2.charon.core.attributes.Attribute;
import org.wso2.charon.core.attributes.MultiValuedAttribute;
import org.wso2.charon.core.attributes.SimpleAttribute;
import org.wso2.charon.core.exceptions.CharonException;
import org.wso2.charon.core.exceptions.NotFoundException;
import org.wso2.charon.core.schema.SCIMConstants;
import org.wso2.charon.core.schema.SCIMSchemaDefinitions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListedResource implements SCIMObject {
/*Collection of attributes which constitute this resource.*/
protected Map<String, Attribute> attributeList = new HashMap<String, Attribute>();
/*Once a retrieve/list/filter response is retrieved, store the decoded objects here*/
protected List<SCIMObject> scimObjects = new ArrayList<SCIMObject>();
/*List of schemas where the attributes of this resource, are defined.*/
protected List<String> schemaList = new ArrayList<String>();
/*Specifies what is the type(i.e User,Group) contained in the listed resource.*/
protected int listedResourceType;
public List<SCIMObject> getScimObjects() {
return scimObjects;
}
public void setScimObjects(List<SCIMObject> scimObjects) {
this.scimObjects = scimObjects;
}
public int getListedResourceType() {
return listedResourceType;
}
public void setListedResourceType(int listedResourceType) {
this.listedResourceType = listedResourceType;
}
@Override
public Attribute getAttribute(String attributeName) throws NotFoundException {
if (attributeList.containsKey(attributeName)) {
return attributeList.get(attributeName);
} else {
throw new NotFoundException();
}
}
@Override
public void deleteAttribute(String attributeName) throws NotFoundException {
if (attributeList.containsKey(attributeName)) {
attributeList.remove(attributeName);
}
}
@Override
public List<String> getSchemaList() {
return schemaList;
}
@Override
public Map<String, Attribute> getAttributeList() {
return attributeList;
}
public void setTotalResults(int totalResults) throws CharonException {
if (!isAttributeExist(SCIMConstants.ListedResourcesConstants.TOTAL_RESULTS)) {
SimpleAttribute totalResultsAttribute =
new SimpleAttribute(SCIMConstants.ListedResourcesConstants.TOTAL_RESULTS, null,
totalResults, SCIMSchemaDefinitions.DataType.INTEGER);
attributeList.put(SCIMConstants.ListedResourcesConstants.TOTAL_RESULTS, totalResultsAttribute);
} else {
((SimpleAttribute) attributeList.get(SCIMConstants.ListedResourcesConstants.TOTAL_RESULTS))
.updateValue(totalResults, SCIMSchemaDefinitions.DataType.INTEGER);
}
}
public void setResources(Map<String, Attribute> valueWithAttributes) {
if (!isAttributeExist(SCIMConstants.ListedResourcesConstants.RESOURCES)) {
MultiValuedAttribute resourcesAttribute =
new MultiValuedAttribute(SCIMConstants.ListedResourcesConstants.RESOURCES);
resourcesAttribute.setComplexValueWithSetOfSubAttributes(valueWithAttributes);
for (Attribute attribute : valueWithAttributes.values()) {
- if (!schemaList.contains(attribute.getSchemaName())) {
+ if ((attribute.getSchemaName() != null) && (!schemaList.contains(attribute.getSchemaName()))) {
schemaList.add(attribute.getSchemaName());
}
}
attributeList.put(SCIMConstants.ListedResourcesConstants.RESOURCES, resourcesAttribute);
} else {
((MultiValuedAttribute) attributeList.get(SCIMConstants.ListedResourcesConstants.RESOURCES))
.setComplexValueWithSetOfSubAttributes(valueWithAttributes);
}
}
private boolean isAttributeExist(String attributeName) {
return attributeList.containsKey(attributeName);
}
}
| true | true | public void setResources(Map<String, Attribute> valueWithAttributes) {
if (!isAttributeExist(SCIMConstants.ListedResourcesConstants.RESOURCES)) {
MultiValuedAttribute resourcesAttribute =
new MultiValuedAttribute(SCIMConstants.ListedResourcesConstants.RESOURCES);
resourcesAttribute.setComplexValueWithSetOfSubAttributes(valueWithAttributes);
for (Attribute attribute : valueWithAttributes.values()) {
if (!schemaList.contains(attribute.getSchemaName())) {
schemaList.add(attribute.getSchemaName());
}
}
attributeList.put(SCIMConstants.ListedResourcesConstants.RESOURCES, resourcesAttribute);
} else {
((MultiValuedAttribute) attributeList.get(SCIMConstants.ListedResourcesConstants.RESOURCES))
.setComplexValueWithSetOfSubAttributes(valueWithAttributes);
}
}
| public void setResources(Map<String, Attribute> valueWithAttributes) {
if (!isAttributeExist(SCIMConstants.ListedResourcesConstants.RESOURCES)) {
MultiValuedAttribute resourcesAttribute =
new MultiValuedAttribute(SCIMConstants.ListedResourcesConstants.RESOURCES);
resourcesAttribute.setComplexValueWithSetOfSubAttributes(valueWithAttributes);
for (Attribute attribute : valueWithAttributes.values()) {
if ((attribute.getSchemaName() != null) && (!schemaList.contains(attribute.getSchemaName()))) {
schemaList.add(attribute.getSchemaName());
}
}
attributeList.put(SCIMConstants.ListedResourcesConstants.RESOURCES, resourcesAttribute);
} else {
((MultiValuedAttribute) attributeList.get(SCIMConstants.ListedResourcesConstants.RESOURCES))
.setComplexValueWithSetOfSubAttributes(valueWithAttributes);
}
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java
index 8a073c7ec..36c04171d 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java
@@ -1,325 +1,329 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.proxy;
import gov.nist.javax.sip.header.HeaderFactoryExt;
import gov.nist.javax.sip.header.ims.PathHeader;
import gov.nist.javax.sip.message.MessageExt;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.stack.SIPTransaction;
import java.util.Iterator;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.URI;
import javax.sip.ListeningPoint;
import javax.sip.Transaction;
import javax.sip.address.Address;
import javax.sip.header.Header;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
import org.mobicents.servlet.sip.address.SipURIImpl;
import org.mobicents.servlet.sip.address.URIImpl;
import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.message.SipServletResponseImpl;
/**
* TODO: Use outbound interface from ProxyParams.outboundInterface when adding local
* listening point addresses.
*
*/
public class ProxyUtils {
private static final Logger logger = Logger.getLogger(ProxyUtils.class);
public static Request createProxiedRequest(SipServletRequestImpl originalRequest, ProxyBranchImpl proxyBranch, URI destination, SipURI outboundInterface, SipURI routeRecord, SipURI path)
{
try {
final Request clonedRequest = (Request) originalRequest.getMessage().clone();
final String method = clonedRequest.getMethod();
final ProxyImpl proxy = (ProxyImpl) proxyBranch.getProxy();
final SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl();
((SIPMessage)clonedRequest).setApplicationData(null);
// The target is null when proxying subsequent requests (the Route header is already there)
if(destination != null)
{
if(logger.isDebugEnabled()){
logger.debug("request URI on the request to proxy : " + destination);
}
- //only set the request URI if the request has no Route headers
- //see RFC3261 16.12
+ // only set the request URI if the request has no Route headers
+ // see RFC3261 16.12
+ // see http://code.google.com/p/mobicents/issues/detail?id=1847
Header route = clonedRequest.getHeader("Route");
- if(route == null)
+ if(route == null ||
+ // it was decided that initial requests
+ // should have their RURI changed to pass TCK testGetAddToPath001
+ originalRequest.isInitial())
{
if(logger.isDebugEnabled()){
logger.debug("setting request uri as cloned request has no Route headers: " + destination);
}
//this way everything is copied even the port but might not work for TelURI...
clonedRequest.setRequestURI(((URIImpl)destination).getURI());
}
else
{
if(logger.isDebugEnabled()){
logger.debug("NOT setting request uri as cloned request has at least one Route header: " + route);
}
}
// // Add route header
// javax.sip.address.SipURI routeUri = SipFactories.addressFactory.createSipURI(
// params.destination.getUser(), params.destination.getHost());
// routeUri.setPort(params.destination.getPort());
// routeUri.setLrParam();
// javax.sip.address.Address address = SipFactories.addressFactory.createAddress(params.destination.getUser(),
// routeUri);
// RouteHeader rheader = SipFactories.headerFactory.createRouteHeader(address);
//
// clonedRequest.setHeader(rheader);
}
else
{
// CANCELs are hop-by-hop, so here must remove any existing Via
// headers,
// Record-Route headers. We insert Via header below so we will
// get response.
if (method.equals(Request.CANCEL)) {
clonedRequest.removeHeader(ViaHeader.NAME);
clonedRequest.removeHeader(RecordRouteHeader.NAME);
}
}
// Decrease max forwards if available
MaxForwardsHeader mf = (MaxForwardsHeader) clonedRequest
.getHeader(MaxForwardsHeader.NAME);
if (mf == null) {
mf = SipFactories.headerFactory.createMaxForwardsHeader(70);
clonedRequest.addHeader(mf);
} else {
mf.setMaxForwards(mf.getMaxForwards() - 1);
}
if (method.equals(Request.CANCEL)) {
// Cancel is hop by hop so remove all other via headers.
clonedRequest.removeHeader(ViaHeader.NAME);
}
final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey();
final String appName = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName());
final SipServletRequestImpl proxyBranchRequest = (SipServletRequestImpl) proxyBranch.getRequest();
//Add via header
ViaHeader viaHeader = proxyBranch.viaHeader;
if(viaHeader == null) {
if(proxy.getOutboundInterface() == null) {
String branchId = null;
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
}
// Issue
viaHeader = JainSipUtils.createViaHeader(
sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, branchId, null);
} else {
//If outbound interface is specified use it
String outboundTransport = proxy.getOutboundInterface().getTransportParam();
if(outboundTransport == null) {
if(proxy.getOutboundInterface().isSecure()) {
outboundTransport = ListeningPoint.TCP;
} else {
outboundTransport = ListeningPoint.UDP;
}
}
String branchId = null;
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
}
viaHeader = SipFactories.headerFactory.createViaHeader(
proxy.getOutboundInterface().getHost(),
proxy.getOutboundInterface().getPort(),
outboundTransport,
branchId);
}
proxyBranch.viaHeader = viaHeader;
} else {
String branchId = null;
viaHeader = (ViaHeader) viaHeader.clone();
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
} else {
branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName);
}
viaHeader.setBranch(branchId);
}
clonedRequest.addHeader(viaHeader);
//Add route-record header, if enabled and if needed (if not null)
if(routeRecord != null && !Request.REGISTER.equalsIgnoreCase(method)) {
javax.sip.address.SipURI rrURI = null;
if(proxy.getOutboundInterface() == null) {
rrURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest);
} else {
rrURI = ((SipURIImpl) proxy.getOutboundInterface()).getSipURI();
}
if(originalRequest.getTransport() != null) rrURI.setTransportParam(originalRequest.getTransport());
final Iterator<String> paramNames = routeRecord.getParameterNames();
// Copy the parameters set by the user
while(paramNames.hasNext()) {
String paramName = paramNames.next();
rrURI.setParameter(paramName,
routeRecord.getParameter(paramName));
}
rrURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME,
appName);
rrURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP,
"true");
rrURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId());
rrURI.setLrParam();
final Address rraddress = SipFactories.addressFactory
.createAddress(null, rrURI);
final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory
.createRecordRouteHeader(rraddress);
clonedRequest.addFirst(recordRouteHeader);
}
// Add path header
if(path != null && Request.REGISTER.equalsIgnoreCase(method))
{
final javax.sip.address.SipURI pathURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest);
final Iterator<String> paramNames = path.getParameterNames();
// Copy the parameters set by the user
while(paramNames.hasNext()) {
String paramName = paramNames.next();
pathURI.setParameter(paramName,
path.getParameter(paramName));
}
final Address pathAddress = SipFactories.addressFactory
.createAddress(null, pathURI);
// Here I need to reference the header factory impl class because can't create path header otherwise
final PathHeader pathHeader = ((HeaderFactoryExt)SipFactories.headerFactory)
.createPathHeader(pathAddress);
clonedRequest.addFirst(pathHeader);
}
return clonedRequest;
} catch (Exception e) {
throw new RuntimeException("Problem while creating the proxied request for message " + originalRequest.getMessage(), e);
}
}
public static SipServletResponseImpl createProxiedResponse(SipServletResponseImpl sipServetResponse, ProxyBranchImpl proxyBranch)
{
final Response response = (Response)sipServetResponse.getMessage();
final Response clonedResponse = (Response) response.clone();
((MessageExt)clonedResponse).setApplicationData(null);
final Transaction transaction = sipServetResponse.getTransaction();
final int status = response.getStatusCode();
// 1. Update timer C for provisional non retransmission responses
if(transaction != null && ((SIPTransaction)transaction).getMethod().equals(Request.INVITE)) {
if(Response.TRYING == status) {
proxyBranch.cancel1xxTimer();
}
if(Response.TRYING < status && status < Response.OK) {
proxyBranch.updateTimer(true);
} else if(status >= Response.OK) {
//remove it if response is final
proxyBranch.cancel1xxTimer();
proxyBranch.cancelTimer();
}
}
// 2. Remove topmost via
final Iterator<ViaHeader> viaHeaderIt = clonedResponse.getHeaders(ViaHeader.NAME);
viaHeaderIt.next();
viaHeaderIt.remove();
if (!viaHeaderIt.hasNext()) {
return null; // response was meant for this proxy
}
final ProxyImpl proxy = (ProxyImpl) proxyBranch.getProxy();
final SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl();
SipServletRequestImpl originalRequest =
(SipServletRequestImpl) proxy.getOriginalRequest();
if(Request.PRACK.equals(sipServetResponse.getMethod())) {
originalRequest =
(SipServletRequestImpl) proxyBranch.getPrackOriginalRequest();
}
SipServletResponseImpl newServletResponseImpl = null;
if(transaction != null && originalRequest != null) {
// non retransmission case
newServletResponseImpl = new SipServletResponseImpl(clonedResponse,
sipFactoryImpl,
originalRequest.getTransaction(),
originalRequest.getSipSession(),
sipServetResponse.getDialog(),
false,
sipServetResponse.isRetransmission());
} else {
// retransmission case
newServletResponseImpl = new SipServletResponseImpl(clonedResponse,
sipFactoryImpl,
null,
sipServetResponse.getSipSession(),
sipServetResponse.getDialog(),
false,
sipServetResponse.isRetransmission());
}
newServletResponseImpl.setOriginalRequest(originalRequest);
newServletResponseImpl.setProxiedResponse(true);
return newServletResponseImpl;
}
public static String toHexString(byte[] b) {
int pos = 0;
char[] c = new char[b.length * 2];
for (int i = 0; i < b.length; i++) {
c[pos++] = toHex[(b[i] >> 4) & 0x0F];
c[pos++] = toHex[b[i] & 0x0f];
}
return new String(c);
}
private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
| false | true | public static Request createProxiedRequest(SipServletRequestImpl originalRequest, ProxyBranchImpl proxyBranch, URI destination, SipURI outboundInterface, SipURI routeRecord, SipURI path)
{
try {
final Request clonedRequest = (Request) originalRequest.getMessage().clone();
final String method = clonedRequest.getMethod();
final ProxyImpl proxy = (ProxyImpl) proxyBranch.getProxy();
final SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl();
((SIPMessage)clonedRequest).setApplicationData(null);
// The target is null when proxying subsequent requests (the Route header is already there)
if(destination != null)
{
if(logger.isDebugEnabled()){
logger.debug("request URI on the request to proxy : " + destination);
}
//only set the request URI if the request has no Route headers
//see RFC3261 16.12
Header route = clonedRequest.getHeader("Route");
if(route == null)
{
if(logger.isDebugEnabled()){
logger.debug("setting request uri as cloned request has no Route headers: " + destination);
}
//this way everything is copied even the port but might not work for TelURI...
clonedRequest.setRequestURI(((URIImpl)destination).getURI());
}
else
{
if(logger.isDebugEnabled()){
logger.debug("NOT setting request uri as cloned request has at least one Route header: " + route);
}
}
// // Add route header
// javax.sip.address.SipURI routeUri = SipFactories.addressFactory.createSipURI(
// params.destination.getUser(), params.destination.getHost());
// routeUri.setPort(params.destination.getPort());
// routeUri.setLrParam();
// javax.sip.address.Address address = SipFactories.addressFactory.createAddress(params.destination.getUser(),
// routeUri);
// RouteHeader rheader = SipFactories.headerFactory.createRouteHeader(address);
//
// clonedRequest.setHeader(rheader);
}
else
{
// CANCELs are hop-by-hop, so here must remove any existing Via
// headers,
// Record-Route headers. We insert Via header below so we will
// get response.
if (method.equals(Request.CANCEL)) {
clonedRequest.removeHeader(ViaHeader.NAME);
clonedRequest.removeHeader(RecordRouteHeader.NAME);
}
}
// Decrease max forwards if available
MaxForwardsHeader mf = (MaxForwardsHeader) clonedRequest
.getHeader(MaxForwardsHeader.NAME);
if (mf == null) {
mf = SipFactories.headerFactory.createMaxForwardsHeader(70);
clonedRequest.addHeader(mf);
} else {
mf.setMaxForwards(mf.getMaxForwards() - 1);
}
if (method.equals(Request.CANCEL)) {
// Cancel is hop by hop so remove all other via headers.
clonedRequest.removeHeader(ViaHeader.NAME);
}
final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey();
final String appName = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName());
final SipServletRequestImpl proxyBranchRequest = (SipServletRequestImpl) proxyBranch.getRequest();
//Add via header
ViaHeader viaHeader = proxyBranch.viaHeader;
if(viaHeader == null) {
if(proxy.getOutboundInterface() == null) {
String branchId = null;
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
}
// Issue
viaHeader = JainSipUtils.createViaHeader(
sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, branchId, null);
} else {
//If outbound interface is specified use it
String outboundTransport = proxy.getOutboundInterface().getTransportParam();
if(outboundTransport == null) {
if(proxy.getOutboundInterface().isSecure()) {
outboundTransport = ListeningPoint.TCP;
} else {
outboundTransport = ListeningPoint.UDP;
}
}
String branchId = null;
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
}
viaHeader = SipFactories.headerFactory.createViaHeader(
proxy.getOutboundInterface().getHost(),
proxy.getOutboundInterface().getPort(),
outboundTransport,
branchId);
}
proxyBranch.viaHeader = viaHeader;
} else {
String branchId = null;
viaHeader = (ViaHeader) viaHeader.clone();
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
} else {
branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName);
}
viaHeader.setBranch(branchId);
}
clonedRequest.addHeader(viaHeader);
//Add route-record header, if enabled and if needed (if not null)
if(routeRecord != null && !Request.REGISTER.equalsIgnoreCase(method)) {
javax.sip.address.SipURI rrURI = null;
if(proxy.getOutboundInterface() == null) {
rrURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest);
} else {
rrURI = ((SipURIImpl) proxy.getOutboundInterface()).getSipURI();
}
if(originalRequest.getTransport() != null) rrURI.setTransportParam(originalRequest.getTransport());
final Iterator<String> paramNames = routeRecord.getParameterNames();
// Copy the parameters set by the user
while(paramNames.hasNext()) {
String paramName = paramNames.next();
rrURI.setParameter(paramName,
routeRecord.getParameter(paramName));
}
rrURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME,
appName);
rrURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP,
"true");
rrURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId());
rrURI.setLrParam();
final Address rraddress = SipFactories.addressFactory
.createAddress(null, rrURI);
final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory
.createRecordRouteHeader(rraddress);
clonedRequest.addFirst(recordRouteHeader);
}
// Add path header
if(path != null && Request.REGISTER.equalsIgnoreCase(method))
{
final javax.sip.address.SipURI pathURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest);
final Iterator<String> paramNames = path.getParameterNames();
// Copy the parameters set by the user
while(paramNames.hasNext()) {
String paramName = paramNames.next();
pathURI.setParameter(paramName,
path.getParameter(paramName));
}
final Address pathAddress = SipFactories.addressFactory
.createAddress(null, pathURI);
// Here I need to reference the header factory impl class because can't create path header otherwise
final PathHeader pathHeader = ((HeaderFactoryExt)SipFactories.headerFactory)
.createPathHeader(pathAddress);
clonedRequest.addFirst(pathHeader);
}
return clonedRequest;
} catch (Exception e) {
throw new RuntimeException("Problem while creating the proxied request for message " + originalRequest.getMessage(), e);
}
}
| public static Request createProxiedRequest(SipServletRequestImpl originalRequest, ProxyBranchImpl proxyBranch, URI destination, SipURI outboundInterface, SipURI routeRecord, SipURI path)
{
try {
final Request clonedRequest = (Request) originalRequest.getMessage().clone();
final String method = clonedRequest.getMethod();
final ProxyImpl proxy = (ProxyImpl) proxyBranch.getProxy();
final SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl();
((SIPMessage)clonedRequest).setApplicationData(null);
// The target is null when proxying subsequent requests (the Route header is already there)
if(destination != null)
{
if(logger.isDebugEnabled()){
logger.debug("request URI on the request to proxy : " + destination);
}
// only set the request URI if the request has no Route headers
// see RFC3261 16.12
// see http://code.google.com/p/mobicents/issues/detail?id=1847
Header route = clonedRequest.getHeader("Route");
if(route == null ||
// it was decided that initial requests
// should have their RURI changed to pass TCK testGetAddToPath001
originalRequest.isInitial())
{
if(logger.isDebugEnabled()){
logger.debug("setting request uri as cloned request has no Route headers: " + destination);
}
//this way everything is copied even the port but might not work for TelURI...
clonedRequest.setRequestURI(((URIImpl)destination).getURI());
}
else
{
if(logger.isDebugEnabled()){
logger.debug("NOT setting request uri as cloned request has at least one Route header: " + route);
}
}
// // Add route header
// javax.sip.address.SipURI routeUri = SipFactories.addressFactory.createSipURI(
// params.destination.getUser(), params.destination.getHost());
// routeUri.setPort(params.destination.getPort());
// routeUri.setLrParam();
// javax.sip.address.Address address = SipFactories.addressFactory.createAddress(params.destination.getUser(),
// routeUri);
// RouteHeader rheader = SipFactories.headerFactory.createRouteHeader(address);
//
// clonedRequest.setHeader(rheader);
}
else
{
// CANCELs are hop-by-hop, so here must remove any existing Via
// headers,
// Record-Route headers. We insert Via header below so we will
// get response.
if (method.equals(Request.CANCEL)) {
clonedRequest.removeHeader(ViaHeader.NAME);
clonedRequest.removeHeader(RecordRouteHeader.NAME);
}
}
// Decrease max forwards if available
MaxForwardsHeader mf = (MaxForwardsHeader) clonedRequest
.getHeader(MaxForwardsHeader.NAME);
if (mf == null) {
mf = SipFactories.headerFactory.createMaxForwardsHeader(70);
clonedRequest.addHeader(mf);
} else {
mf.setMaxForwards(mf.getMaxForwards() - 1);
}
if (method.equals(Request.CANCEL)) {
// Cancel is hop by hop so remove all other via headers.
clonedRequest.removeHeader(ViaHeader.NAME);
}
final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey();
final String appName = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName());
final SipServletRequestImpl proxyBranchRequest = (SipServletRequestImpl) proxyBranch.getRequest();
//Add via header
ViaHeader viaHeader = proxyBranch.viaHeader;
if(viaHeader == null) {
if(proxy.getOutboundInterface() == null) {
String branchId = null;
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
}
// Issue
viaHeader = JainSipUtils.createViaHeader(
sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, branchId, null);
} else {
//If outbound interface is specified use it
String outboundTransport = proxy.getOutboundInterface().getTransportParam();
if(outboundTransport == null) {
if(proxy.getOutboundInterface().isSecure()) {
outboundTransport = ListeningPoint.TCP;
} else {
outboundTransport = ListeningPoint.UDP;
}
}
String branchId = null;
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
}
viaHeader = SipFactories.headerFactory.createViaHeader(
proxy.getOutboundInterface().getHost(),
proxy.getOutboundInterface().getPort(),
outboundTransport,
branchId);
}
proxyBranch.viaHeader = viaHeader;
} else {
String branchId = null;
viaHeader = (ViaHeader) viaHeader.clone();
if(Request.ACK.equals(method) && proxyBranchRequest != null && proxyBranchRequest.getTransaction() != null) {
branchId = proxyBranchRequest.getTransaction().getBranchId();
logger.debug("reusing original branch id " + branchId);
} else {
branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName);
}
viaHeader.setBranch(branchId);
}
clonedRequest.addHeader(viaHeader);
//Add route-record header, if enabled and if needed (if not null)
if(routeRecord != null && !Request.REGISTER.equalsIgnoreCase(method)) {
javax.sip.address.SipURI rrURI = null;
if(proxy.getOutboundInterface() == null) {
rrURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest);
} else {
rrURI = ((SipURIImpl) proxy.getOutboundInterface()).getSipURI();
}
if(originalRequest.getTransport() != null) rrURI.setTransportParam(originalRequest.getTransport());
final Iterator<String> paramNames = routeRecord.getParameterNames();
// Copy the parameters set by the user
while(paramNames.hasNext()) {
String paramName = paramNames.next();
rrURI.setParameter(paramName,
routeRecord.getParameter(paramName));
}
rrURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME,
appName);
rrURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP,
"true");
rrURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId());
rrURI.setLrParam();
final Address rraddress = SipFactories.addressFactory
.createAddress(null, rrURI);
final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory
.createRecordRouteHeader(rraddress);
clonedRequest.addFirst(recordRouteHeader);
}
// Add path header
if(path != null && Request.REGISTER.equalsIgnoreCase(method))
{
final javax.sip.address.SipURI pathURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest);
final Iterator<String> paramNames = path.getParameterNames();
// Copy the parameters set by the user
while(paramNames.hasNext()) {
String paramName = paramNames.next();
pathURI.setParameter(paramName,
path.getParameter(paramName));
}
final Address pathAddress = SipFactories.addressFactory
.createAddress(null, pathURI);
// Here I need to reference the header factory impl class because can't create path header otherwise
final PathHeader pathHeader = ((HeaderFactoryExt)SipFactories.headerFactory)
.createPathHeader(pathAddress);
clonedRequest.addFirst(pathHeader);
}
return clonedRequest;
} catch (Exception e) {
throw new RuntimeException("Problem while creating the proxied request for message " + originalRequest.getMessage(), e);
}
}
|
diff --git a/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/GuestBookResponseServiceBean.java b/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/GuestBookResponseServiceBean.java
index e4f9cdcab..44a861e3e 100644
--- a/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/GuestBookResponseServiceBean.java
+++ b/dvn-app/trunk/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/GuestBookResponseServiceBean.java
@@ -1,277 +1,276 @@
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.1.
*/
package edu.harvard.iq.dvn.core.vdc;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyFile;
import edu.harvard.iq.dvn.core.web.common.LoginBean;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author skraffmiller
*/
@Stateless
public class GuestBookResponseServiceBean {
@PersistenceContext(unitName="VDCNet-ejbPU")
private EntityManager em;
public List<GuestBookResponse> findAll() {
return em.createQuery("select object(o) from GuestBookResponse as o order by o.responseTime desc").getResultList();
}
public List<Long> findAllIds() {
return findAllIds(null);
}
public List<Long> findAllIds(Long vdcId) {
if (vdcId == null){
return em.createQuery("select o.id from GuestBookResponse as o order by o.responseTime desc").getResultList();
}
return em.createQuery("select o.id from GuestBookResponse o, Study s where o.study.id = s.id and s.owner.id = " + vdcId + " order by o.responseTime desc").getResultList();
}
public List<Long> findAllIds30Days() {
return findAllIds30Days(null);
}
public List<Long> findAllIds30Days(Long vdcId) {
String beginTime;
String endTime;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -30);
beginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()); // Use yesterday as default value
cal.add(Calendar.DAY_OF_YEAR, 31);
endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
String queryString = "select o.id from GuestBookResponse as o ";
if (vdcId != null){
queryString += ", Study s where o.study.id = s.id and s.owner.id = " + vdcId + " and " ;
} else {
queryString += " where ";
}
queryString += " o.responseTime >='" + beginTime + "'";
queryString += " and o.responseTime<='" + endTime + "'";
queryString += " order by o.responseTime desc";
Query query = em.createQuery(queryString);
return query.getResultList();
}
public Long findCount30Days(){
return findCount30Days(null);
}
public Long findCount30Days(Long vdcId) {
String beginTime;
String endTime;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -30);
beginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()); // Use yesterday as default value
cal.add(Calendar.DAY_OF_YEAR, 31);
endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
String queryString = "select count(o.id) from GuestBookResponse as o ";
if (vdcId != null){
queryString += ", Study s where o.study_id = s.id and s.owner_id = " + vdcId + " and " ;
} else {
queryString += " where ";
}
queryString += " o.responseTime >='" + beginTime + "'";
queryString += " and o.responseTime<='" + endTime + "'";
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
public Long findCountAll(){
return findCountAll(null);
}
public Long findCountAll(Long vdcId) {
String queryString = "";
if (vdcId !=null){
queryString = "select count(o.id) from GuestBookResponse o, Study s where o.study_id = s.id and s.owner_id = " + vdcId + " ";
} else {
queryString = "select count(o.id) from GuestBookResponse o ";
}
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
public List<GuestBookResponse> findAllByVdc(Long vdcId) {
return em.createQuery("select object(o) from GuestBookResponse o, Study s where o.study.id = s.id and s.owner.id = " + vdcId + " order by o.responseTime desc").getResultList();
}
public List<GuestBookResponse> findAllWithin30Days() {
return findAllWithin30Days(null);
}
public List<GuestBookResponse> findAllWithin30Days(Long vdcId) {
String beginTime;
String endTime;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -30);
beginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()); // Use yesterday as default value
cal.add(Calendar.DAY_OF_YEAR, 31);
endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
String queryString = "select object(o) from GuestBookResponse as o ";
if (vdcId != null){
queryString += ", Study s where o.study.id = s.id and s.owner.id = " + vdcId + " and " ;
} else {
queryString += " where ";
}
queryString += " o.responseTime >='" + beginTime + "'";
queryString += " and o.responseTime<='" + endTime + "'";
queryString += " order by o.responseTime desc";
Query query = em.createQuery(queryString);
return query.getResultList();
}
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) {
for (Object[] item : list) {
item[index] = new Long( (Integer) item[index]);
}
return list;
}
private String generateTempTableString(List<Long> studyIds) {
// first step: create the temp table with the ids
em.createNativeQuery(" BEGIN; SET TRANSACTION READ WRITE; DROP TABLE IF EXISTS tempid; END;").executeUpdate();
em.createNativeQuery(" BEGIN; SET TRANSACTION READ WRITE; CREATE TEMPORARY TABLE tempid (tempid integer primary key, orderby integer); END;").executeUpdate();
em.createNativeQuery(" BEGIN; SET TRANSACTION READ WRITE; INSERT INTO tempid VALUES " + generateIDsforTempInsert(studyIds) + "; END;").executeUpdate();
return "select tempid from tempid";
}
private String generateIDsforTempInsert(List idList) {
int count = 0;
StringBuffer sb = new StringBuffer();
Iterator iter = idList.iterator();
while (iter.hasNext()) {
Long id = (Long) iter.next();
sb.append("(").append(id).append(",").append(count++).append(")");
if (iter.hasNext()) {
sb.append(",");
}
}
return sb.toString();
}
public List<Object[]> findDownloadInfoAll(List<Long> gbrIds) {
//this query will return multiple rows per response where the study name has changed over version
//these multiples are filtered out by the method that actually writes the download csv,
String varString = "(" + generateTempTableString(gbrIds) + ") ";
String gbrDownloadQueryString = "select u.username, gbr.sessionid, "
+ " gbr.firstname, gbr.lastname, gbr.email, gbr.institution, "
+ " vdc.name, s.protocol, s.authority, m.title, fmd.label, gbr.responsetime, gbr.position, gbr.study_id, gbr.id, gbr.downloadType "
+ " from guestbookresponse gbr LEFT OUTER JOIN vdcuser u ON "
+ "(gbr.vdcuser_id =u.id), "
- + " vdc, study s, studyversion sv, metadata m, studyfile sf, filemetadata fmd "
+ + " vdc, study s, studyversion sv, metadata m, filemetadata fmd "
+ "where gbr.study_id = s.id "
+ "and s.owner_id = vdc.id "
+ "and s.id = sv.study_id "
+ "and sv.metadata_id = m.id "
+ "and gbr.studyfile_id = fmd.studyfile_id "
+ "and sv.id = fmd.studyversion_id "
- + "and sv.id = fmd.studyversion_id "
+ " and gbr.id in " + varString
+ " group by u.username, gbr.sessionid, "
+ " gbr.firstname, gbr.lastname, gbr.email, gbr.institution, "
+ " vdc.name, s.protocol, s.authority, m.title, fmd.label, gbr.responsetime, gbr.position, gbr.study_id, gbr.id, s.id, gbr.downloadType " +
"order by s.id, gbr.id, max(sv.versionNumber) desc ";
Query query = em.createNativeQuery(gbrDownloadQueryString);
return convertIntegerToLong(query.getResultList(),14);
}
public List<Object[]> findCustomResponsePerGuestbookResponse(Long gbrId) {
String gbrCustomQuestionQueryString = "select response, cq.id "
+ " from guestbookresponse gbr, customquestion cq, customquestionresponse cqr "
+ "where gbr.guestbookquestionnaire_id = cq.guestbookquestionnaire_id "
+ " and gbr.id = cqr.guestbookresponse_id "
+ "and cq.id = cqr.customquestion_id "
+ " and cqr.guestbookresponse_id = " + gbrId;
Query query = em.createNativeQuery(gbrCustomQuestionQueryString);
return convertIntegerToLong(query.getResultList(),1);
}
private GuestBookQuestionnaire findNetworkQuestionniare(){
GuestBookQuestionnaire questionniare = new GuestBookQuestionnaire();
String queryStr = "SELECT gbq FROM GuestBookQuestionnaire gbq WHERE gbq.vdc is null; ";
Query query = em.createQuery(queryStr);
List resultList = query.getResultList();
if (resultList.size() >= 1) {
questionniare = (GuestBookQuestionnaire) resultList.get(0);
}
return questionniare;
}
public GuestBookResponse initNetworkGuestBookResponse(Study study, StudyFile studyFile, LoginBean loginBean) {
GuestBookResponse guestBookResponse = new GuestBookResponse();
guestBookResponse.setGuestBookQuestionnaire(findNetworkQuestionniare());
guestBookResponse.setStudy(study);
guestBookResponse.setResponseTime(new Date());
if (loginBean != null) {
guestBookResponse.setEmail(loginBean.getUser().getEmail());
guestBookResponse.setFirstname(loginBean.getUser().getFirstName());
guestBookResponse.setLastname(loginBean.getUser().getLastName());
guestBookResponse.setInstitution(loginBean.getUser().getInstitution());
guestBookResponse.setPosition(loginBean.getUser().getPosition());
guestBookResponse.setVdcUser(loginBean.getUser());
} else {
guestBookResponse.setEmail("");
guestBookResponse.setFirstname("");
guestBookResponse.setLastname("");
guestBookResponse.setInstitution("");
guestBookResponse.setPosition("");
guestBookResponse.setVdcUser(null);
}
return guestBookResponse;
}
public GuestBookResponse findById(Long id) {
return em.find(GuestBookResponse.class,id);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void update(GuestBookResponse guestBookResponse) {
em.persist(guestBookResponse);
}
}
| false | true | public List<Object[]> findDownloadInfoAll(List<Long> gbrIds) {
//this query will return multiple rows per response where the study name has changed over version
//these multiples are filtered out by the method that actually writes the download csv,
String varString = "(" + generateTempTableString(gbrIds) + ") ";
String gbrDownloadQueryString = "select u.username, gbr.sessionid, "
+ " gbr.firstname, gbr.lastname, gbr.email, gbr.institution, "
+ " vdc.name, s.protocol, s.authority, m.title, fmd.label, gbr.responsetime, gbr.position, gbr.study_id, gbr.id, gbr.downloadType "
+ " from guestbookresponse gbr LEFT OUTER JOIN vdcuser u ON "
+ "(gbr.vdcuser_id =u.id), "
+ " vdc, study s, studyversion sv, metadata m, studyfile sf, filemetadata fmd "
+ "where gbr.study_id = s.id "
+ "and s.owner_id = vdc.id "
+ "and s.id = sv.study_id "
+ "and sv.metadata_id = m.id "
+ "and gbr.studyfile_id = fmd.studyfile_id "
+ "and sv.id = fmd.studyversion_id "
+ "and sv.id = fmd.studyversion_id "
+ " and gbr.id in " + varString
+ " group by u.username, gbr.sessionid, "
+ " gbr.firstname, gbr.lastname, gbr.email, gbr.institution, "
+ " vdc.name, s.protocol, s.authority, m.title, fmd.label, gbr.responsetime, gbr.position, gbr.study_id, gbr.id, s.id, gbr.downloadType " +
"order by s.id, gbr.id, max(sv.versionNumber) desc ";
Query query = em.createNativeQuery(gbrDownloadQueryString);
return convertIntegerToLong(query.getResultList(),14);
}
| public List<Object[]> findDownloadInfoAll(List<Long> gbrIds) {
//this query will return multiple rows per response where the study name has changed over version
//these multiples are filtered out by the method that actually writes the download csv,
String varString = "(" + generateTempTableString(gbrIds) + ") ";
String gbrDownloadQueryString = "select u.username, gbr.sessionid, "
+ " gbr.firstname, gbr.lastname, gbr.email, gbr.institution, "
+ " vdc.name, s.protocol, s.authority, m.title, fmd.label, gbr.responsetime, gbr.position, gbr.study_id, gbr.id, gbr.downloadType "
+ " from guestbookresponse gbr LEFT OUTER JOIN vdcuser u ON "
+ "(gbr.vdcuser_id =u.id), "
+ " vdc, study s, studyversion sv, metadata m, filemetadata fmd "
+ "where gbr.study_id = s.id "
+ "and s.owner_id = vdc.id "
+ "and s.id = sv.study_id "
+ "and sv.metadata_id = m.id "
+ "and gbr.studyfile_id = fmd.studyfile_id "
+ "and sv.id = fmd.studyversion_id "
+ " and gbr.id in " + varString
+ " group by u.username, gbr.sessionid, "
+ " gbr.firstname, gbr.lastname, gbr.email, gbr.institution, "
+ " vdc.name, s.protocol, s.authority, m.title, fmd.label, gbr.responsetime, gbr.position, gbr.study_id, gbr.id, s.id, gbr.downloadType " +
"order by s.id, gbr.id, max(sv.versionNumber) desc ";
Query query = em.createNativeQuery(gbrDownloadQueryString);
return convertIntegerToLong(query.getResultList(),14);
}
|
diff --git a/java/me/walkable/RefreshYelp.java b/java/me/walkable/RefreshYelp.java
index 3a642a9..dbdf044 100644
--- a/java/me/walkable/RefreshYelp.java
+++ b/java/me/walkable/RefreshYelp.java
@@ -1,106 +1,110 @@
/**
*
*/
package me.walkable;
import java.sql.Connection;
import java.sql.SQLException;
import me.walkable.db.DatabaseUtil;
import me.walkable.db.Deal;
import me.walkable.db.ExpireDeals;
import me.walkable.util.CategoryTree;
import me.walkable.yelp.Yelp;
import me.walkable.yelp.YelpCategory;
import me.walkable.yelp.YelpDealObject;
import me.walkable.yelp.YelpParse;
/**
* @author Christopher Butera
*
*/
public class RefreshYelp {
public static int yelpCategoryIterate(Yelp yelp, CategoryTree tree) throws Exception{
int numDeals = 0;
if (tree.isLeaf()){
YelpDealObject yObj = yelp.getDeals(Yelp.CHICAGO, "0", tree.getCategory());
if (yObj != null) {
System.out.println("Found " + yObj.getTotalNumberOfDeals() + " in leaf category: " + tree.getCategory());
YelpParse.InsertYelpData(yObj);
if (yObj.getNumberOfDeals() != yObj.getTotalNumberOfDeals()){
if (yObj.getTotalNumberOfDeals() <= 40){
yObj = yelp.getDeals(Yelp.CHICAGO, "20", tree.getCategory());
yObj = YelpParse.parse(tree.getUnparsedDeals());
YelpParse.InsertYelpData(yObj);
}
else {
throw new Exception("More than 40 deals for child category. Found " + yObj.getNumberOfDeals() + " " + tree.getCategory() + " in Yelp");
}
}
- numDeals += yObj.getNumberOfDeals();
+ if (yObj != null){
+ numDeals += yObj.getNumberOfDeals();
+ }
}
}
else {
YelpDealObject yObj = yelp.getDeals(Yelp.CHICAGO, "0", tree.getCategory());
if (yObj != null){
System.out.println("Found " + yObj.getTotalNumberOfDeals() + " in branch category: " + tree.getCategory());
if (yObj.getNumberOfDeals() == yObj.getTotalNumberOfDeals() || yObj.getTotalNumberOfDeals() < 40){
YelpParse.InsertYelpData(yObj);
}
else if (yObj.getNumberOfDeals() != yObj.getTotalNumberOfDeals() && yObj.getTotalNumberOfDeals() < 40) {
YelpParse.InsertYelpData(yObj);
yObj = yelp.getDeals(Yelp.CHICAGO, "20", tree.getCategory());
YelpParse.InsertYelpData(yObj);
}
else { //Over 40 deals
for (CategoryTree subTree : tree.getSubCategories()){
yelpCategoryIterate(yelp, subTree);
}
}
- numDeals += yObj.getNumberOfDeals();
+ if (yObj != null){
+ numDeals += yObj.getNumberOfDeals();
+ }
}
}
return numDeals;
}
public static int getYelp() throws Exception{
int numDeals = 0;
Yelp yelp = new Yelp();
YelpCategory ycats = new YelpCategory();
for (CategoryTree subTree :ycats.getCategories()){
numDeals += yelpCategoryIterate(yelp, subTree);
}
return numDeals;
}
public static void main(String[] args) {
Connection conn = null;
try {
int numDeals = getYelp();
if (numDeals > 0){
System.out.println("Processed " + numDeals + " total deals");
conn = DatabaseUtil.getConnection();
ExpireDeals.expireDealsByDate(conn);
ExpireDeals.expireRemovedDeals(conn, Deal.VENDOR_YELP);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) { /*ignored*/ }
}
}
}
}
| false | true | public static int yelpCategoryIterate(Yelp yelp, CategoryTree tree) throws Exception{
int numDeals = 0;
if (tree.isLeaf()){
YelpDealObject yObj = yelp.getDeals(Yelp.CHICAGO, "0", tree.getCategory());
if (yObj != null) {
System.out.println("Found " + yObj.getTotalNumberOfDeals() + " in leaf category: " + tree.getCategory());
YelpParse.InsertYelpData(yObj);
if (yObj.getNumberOfDeals() != yObj.getTotalNumberOfDeals()){
if (yObj.getTotalNumberOfDeals() <= 40){
yObj = yelp.getDeals(Yelp.CHICAGO, "20", tree.getCategory());
yObj = YelpParse.parse(tree.getUnparsedDeals());
YelpParse.InsertYelpData(yObj);
}
else {
throw new Exception("More than 40 deals for child category. Found " + yObj.getNumberOfDeals() + " " + tree.getCategory() + " in Yelp");
}
}
numDeals += yObj.getNumberOfDeals();
}
}
else {
YelpDealObject yObj = yelp.getDeals(Yelp.CHICAGO, "0", tree.getCategory());
if (yObj != null){
System.out.println("Found " + yObj.getTotalNumberOfDeals() + " in branch category: " + tree.getCategory());
if (yObj.getNumberOfDeals() == yObj.getTotalNumberOfDeals() || yObj.getTotalNumberOfDeals() < 40){
YelpParse.InsertYelpData(yObj);
}
else if (yObj.getNumberOfDeals() != yObj.getTotalNumberOfDeals() && yObj.getTotalNumberOfDeals() < 40) {
YelpParse.InsertYelpData(yObj);
yObj = yelp.getDeals(Yelp.CHICAGO, "20", tree.getCategory());
YelpParse.InsertYelpData(yObj);
}
else { //Over 40 deals
for (CategoryTree subTree : tree.getSubCategories()){
yelpCategoryIterate(yelp, subTree);
}
}
numDeals += yObj.getNumberOfDeals();
}
}
return numDeals;
}
| public static int yelpCategoryIterate(Yelp yelp, CategoryTree tree) throws Exception{
int numDeals = 0;
if (tree.isLeaf()){
YelpDealObject yObj = yelp.getDeals(Yelp.CHICAGO, "0", tree.getCategory());
if (yObj != null) {
System.out.println("Found " + yObj.getTotalNumberOfDeals() + " in leaf category: " + tree.getCategory());
YelpParse.InsertYelpData(yObj);
if (yObj.getNumberOfDeals() != yObj.getTotalNumberOfDeals()){
if (yObj.getTotalNumberOfDeals() <= 40){
yObj = yelp.getDeals(Yelp.CHICAGO, "20", tree.getCategory());
yObj = YelpParse.parse(tree.getUnparsedDeals());
YelpParse.InsertYelpData(yObj);
}
else {
throw new Exception("More than 40 deals for child category. Found " + yObj.getNumberOfDeals() + " " + tree.getCategory() + " in Yelp");
}
}
if (yObj != null){
numDeals += yObj.getNumberOfDeals();
}
}
}
else {
YelpDealObject yObj = yelp.getDeals(Yelp.CHICAGO, "0", tree.getCategory());
if (yObj != null){
System.out.println("Found " + yObj.getTotalNumberOfDeals() + " in branch category: " + tree.getCategory());
if (yObj.getNumberOfDeals() == yObj.getTotalNumberOfDeals() || yObj.getTotalNumberOfDeals() < 40){
YelpParse.InsertYelpData(yObj);
}
else if (yObj.getNumberOfDeals() != yObj.getTotalNumberOfDeals() && yObj.getTotalNumberOfDeals() < 40) {
YelpParse.InsertYelpData(yObj);
yObj = yelp.getDeals(Yelp.CHICAGO, "20", tree.getCategory());
YelpParse.InsertYelpData(yObj);
}
else { //Over 40 deals
for (CategoryTree subTree : tree.getSubCategories()){
yelpCategoryIterate(yelp, subTree);
}
}
if (yObj != null){
numDeals += yObj.getNumberOfDeals();
}
}
}
return numDeals;
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java b/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
index 425434b0..79a91e90 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java
@@ -1,685 +1,685 @@
package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.loader.MetamodelGenerator;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** A convenience class to help with the handling of certain type declarations. */
public class TypeUtils {
final TypeDeclaration tuple;
final TypeDeclaration iterable;
final TypeDeclaration sequential;
final TypeDeclaration numeric;
final TypeDeclaration _integer;
final TypeDeclaration _float;
final TypeDeclaration _null;
final TypeDeclaration anything;
final TypeDeclaration callable;
final TypeDeclaration empty;
final TypeDeclaration metaClass;
TypeUtils(Module languageModule) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage("ceylon.language");
tuple = (TypeDeclaration)pkg.getMember("Tuple", null, false);
iterable = (TypeDeclaration)pkg.getMember("Iterable", null, false);
sequential = (TypeDeclaration)pkg.getMember("Sequential", null, false);
numeric = (TypeDeclaration)pkg.getMember("Numeric", null, false);
_integer = (TypeDeclaration)pkg.getMember("Integer", null, false);
_float = (TypeDeclaration)pkg.getMember("Float", null, false);
_null = (TypeDeclaration)pkg.getMember("Null", null, false);
anything = (TypeDeclaration)pkg.getMember("Anything", null, false);
callable = (TypeDeclaration)pkg.getMember("Callable", null, false);
empty = (TypeDeclaration)pkg.getMember("Empty", null, false);
pkg = languageModule.getPackage("ceylon.language.model");
metaClass = (TypeDeclaration)pkg.getMember("Class", null, false);
}
/** Prints the type arguments, usually for their reification. */
public static void printTypeArguments(Node node, Map<TypeParameter,ProducedType> targs, GenerateJsVisitor gen) {
gen.out("{");
boolean first = true;
for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) {
if (first) {
first = false;
} else {
gen.out(",");
}
gen.out(e.getKey().getName(), ":");
final ProducedType pt = e.getValue();
if (pt == null) {
gen.out("'", e.getKey().getName(), "'");
continue;
}
final TypeDeclaration d = pt.getDeclaration();
boolean composite = d instanceof UnionType || d instanceof IntersectionType;
boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty();
boolean closeBracket = false;
if (composite) {
outputTypeList(node, d, gen, true);
} else if (d instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)d, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(
gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()),
pt, gen);
closeBracket = true;
}
if (hasParams) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
if (closeBracket) {
gen.out("}");
}
}
gen.out("}");
}
static void outputQualifiedTypename(final boolean imported, ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration t = pt.getDeclaration();
final String qname = t.getQualifiedNameString();
if (qname.equals("ceylon.language::Nothing")) {
//Hack in the model means hack here as well
gen.out(GenerateJsVisitor.getClAlias(), "Nothing");
} else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) {
gen.out(GenerateJsVisitor.getClAlias(), "Null");
} else if (pt.isUnknown()) {
gen.out(GenerateJsVisitor.getClAlias(), "Anything");
} else {
if (t.isAlias()) {
t = t.getExtendedTypeDeclaration();
}
boolean qual = false;
if (t.getScope() instanceof ClassOrInterface) {
List<ClassOrInterface> parents = new ArrayList<>();
ClassOrInterface parent = (ClassOrInterface)t.getScope();
parents.add(0, parent);
while (parent.getScope() instanceof ClassOrInterface) {
parent = (ClassOrInterface)parent.getScope();
parents.add(0, parent);
}
qual = true;
for (ClassOrInterface p : parents) {
gen.out(gen.getNames().name(p), ".");
}
} else if (imported) {
//This wasn't needed but now we seem to get imported decls with no package when compiling ceylon.language.model types
final String modAlias = gen.getNames().moduleAlias(t.getUnit().getPackage().getModule());
if (modAlias != null && !modAlias.isEmpty()) {
gen.out(modAlias, ".");
}
qual = true;
}
String tname = gen.getNames().name(t);
if (!qual && isReservedTypename(tname)) {
gen.out(tname, "$");
} else {
gen.out(tname);
}
}
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void typeNameOrList(Node node, ProducedType pt, GenerateJsVisitor gen, boolean typeReferences) {
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputTypeList(node, type, gen, typeReferences);
} else if (typeReferences) {
if (type instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)type, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen);
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
gen.out("}");
}
} else {
gen.out("'", type.getQualifiedNameString(), "'");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputTypeList(Node node, TypeDeclaration type, GenerateJsVisitor gen, boolean typeReferences) {
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
typeNameOrList(node, t, gen, typeReferences);
first = false;
}
gen.out("]}");
}
/** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */
static void resolveTypeParameter(Node node, TypeParameter tp, GenerateJsVisitor gen) {
Scope parent = node.getScope();
while (parent != null && parent != tp.getContainer()) {
parent = parent.getScope();
}
if (tp.getContainer() instanceof ClassOrInterface) {
if (parent == tp.getContainer()) {
if (((ClassOrInterface)tp.getContainer()).isAlias()) {
//when resolving for aliases we just take the type arguments from the alias call
gen.out("$$targs$$.", tp.getName());
} else {
gen.self((ClassOrInterface)tp.getContainer());
gen.out(".$$targs$$.", tp.getName());
}
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT*/t:", GenerateJsVisitor.getClAlias(), "Anything}");
}
} else {
//it has to be a method, right?
//We need to find the index of the parameter where the argument occurs
//...and it could be null...
int plistCount = -1;
ProducedType type = null;
for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator();
type == null && iter0.hasNext();) {
plistCount++;
for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator();
type == null && iter1.hasNext();) {
if (type == null) {
type = typeContainsTypeParameter(iter1.next().getType(), tp);
}
}
}
//The ProducedType that we find corresponds to a parameter, whose type can be:
//A type parameter in the method, in which case we just use the argument's type (may be null)
//A component of a union/intersection type, in which case we just use the argument's type (may be null)
//A type argument of the argument's type, in which case we must get the reified generic from the argument
if (tp.getContainer() == parent) {
gen.out("$$$mptypes.", tp.getName());
} else {
gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#",
tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "'");
}
}
}
static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) {
TypeDeclaration d = td.getDeclaration();
if (d == tp) {
return td;
} else if (d instanceof UnionType || d instanceof IntersectionType) {
List<ProducedType> comps = td.getCaseTypes();
if (comps == null) comps = td.getSupertypes();
for (ProducedType sub : comps) {
td = typeContainsTypeParameter(sub, tp);
if (td != null) {
return td;
}
}
} else if (d instanceof ClassOrInterface) {
for (ProducedType sub : td.getTypeArgumentList()) {
if (typeContainsTypeParameter(sub, tp) != null) {
return td;
}
}
}
return null;
}
static boolean isReservedTypename(String typeName) {
return JsCompiler.compilingLanguageModule && (typeName.equals("Object") || typeName.equals("Number")
|| typeName.equals("Array")) || typeName.equals("String") || typeName.equals("Boolean");
}
/** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */
static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) {
if (pt.getDeclaration().equals(d)) {
return pt;
}
List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes();
for (ProducedType t : list) {
if (t.getDeclaration().equals(d)) {
return t;
}
}
return null;
}
static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) {
if (params != null && targs != null && params.size() == targs.size()) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
for (int i = 0; i < targs.size(); i++) {
r.put(params.get(i), targs.get(i));
}
return r;
}
return null;
}
Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
r.put(iterable.getTypeParameters().get(0), pt);
r.put(iterable.getTypeParameters().get(1), _null.getType());
return r;
}
static boolean isUnknown(ProducedType pt) {
return pt == null || pt.isUnknown();
}
static boolean isUnknown(Parameter param) {
return param == null || isUnknown(param.getType());
}
static boolean isUnknown(Declaration d) {
return d == null || d.getQualifiedNameString().equals("UnknownType");
}
/** Generates the code to throw an Exception if a dynamic object is not of the specified type. */
static void generateDynamicCheck(Tree.Term term, final ProducedType t, final GenerateJsVisitor gen) {
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
gen.out(",", GenerateJsVisitor.getClAlias(), "isOfType(", tmp, ",");
TypeUtils.typeNameOrList(term, t, gen, true);
gen.out(")?", tmp, ":");
gen.generateThrow("dynamic objects cannot be used here", term);
gen.out(")");
}
static void encodeParameterListForRuntime(ParameterList plist, GenerateJsVisitor gen) {
boolean first = true;
gen.out("[");
for (Parameter p : plist.getParameters()) {
if (first) first=false; else gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getName(), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
if (p.isSequenced()) {
gen.out("seq:1,");
}
if (p.isDefaulted()) {
gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
metamodelTypeNameOrList(gen.getCurrentPackage(), p.getType(), gen);
gen.out("}");
}
gen.out("]");
}
/** This method encodes the type parameters of a Tuple (taken from a Callable) in the same way
* as a parameter list for runtime. */
void encodeTupleAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) {
if (!_callable.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
gen.out("[/*WARNING: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]");
return;
}
List<ProducedType> targs = _callable.getTypeArgumentList();
if (targs == null || targs.size() != 2) {
gen.out("[/*WARNING: missing argument types for Callable*/]");
return;
}
ProducedType _tuple = targs.get(1);
gen.out("[");
int pos = 1;
while (!(empty.equals(_tuple.getDeclaration()) || _tuple.getDeclaration() instanceof TypeParameter)) {
if (pos > 1) gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos++), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
gen.out(MetamodelGenerator.KEY_TYPE, ":");
if (tuple.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen);
_tuple = _tuple.getTypeArgumentList().get(2);
} else if (sequential.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen);
_tuple = _tuple.getTypeArgumentList().get(0);
} else {
System.out.println("WTF? Tuple is actually " + _tuple.getProducedTypeQualifiedName() + ", " + _tuple.getClass().getName());
if (pos > 100) {
System.exit(1);
}
}
gen.out("}");
}
gen.out("]");
}
static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen) {
if (d.getAnnotations() == null || d.getAnnotations().isEmpty()) {
encodeForRuntime(d, gen, null);
} else {
encodeForRuntime(d, gen, new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return[");
boolean first = true;
for (Annotation a : d.getAnnotations()) {
if (first) first=false; else gen.out(",");
Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false);
if (ad instanceof Method) {
gen.qualify(null, ad);
gen.out(gen.getNames().name(ad), "(");
if (a.getPositionalArguments() == null) {
for (Parameter p : ((Method)ad).getParameterLists().get(0).getParameters()) {
String v = a.getNamedArguments().get(p.getName());
gen.out(v == null ? "undefined" : v);
}
} else {
boolean farg = true;
for (String s : a.getPositionalArguments()) {
if (farg)farg=false; else gen.out(",");
gen.out(s);
}
}
gen.out(")");
} else {
gen.out("null/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/");
}
}
gen.out("];}");
}
});
}
}
/** Output a metamodel map for runtime use. */
static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
final boolean include = annotations != null && !annotations.getAnnotations().isEmpty();
encodeForRuntime(d, gen, include ? new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":");
outputAnnotationsFunction(annotations, gen);
}
} : null);
}
static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
- boolean comma = false;
for(TypeParameter tp : tparms) {
+ boolean comma = false;
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void metamodelTypeNameOrList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
if (pt == null) {
//In dynamic blocks we sometimes get a null producedType
pt = ((TypeDeclaration)pkg.getModule().getLanguageModule().getDirectPackage(
"ceylon.language").getDirectMember("Anything", null, false)).getType();
}
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputMetamodelTypeList(pkg, pt, gen);
} else if (type instanceof TypeParameter) {
gen.out("'", type.getNameAsString(), "'");
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(pkg, type), pt, gen);
//Type Parameters
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:{");
boolean first = true;
for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) {
if (first) first=false; else gen.out(",");
gen.out(e.getKey().getNameAsString(), ":");
metamodelTypeNameOrList(pkg, e.getValue(), gen);
}
gen.out("}");
}
gen.out("}");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration type = pt.getDeclaration();
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
metamodelTypeNameOrList(pkg, t, gen);
first = false;
}
gen.out("]}");
}
ProducedType tupleFromParameters(List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
if (params == null || params.isEmpty()) {
return empty.getType();
}
ProducedType tt = empty.getType();
ProducedType et = null;
for (int i = params.size()-1; i>=0; i--) {
com.redhat.ceylon.compiler.typechecker.model.Parameter p = params.get(i);
if (et == null) {
et = p.getType();
} else {
UnionType ut = new UnionType(p.getModel().getUnit());
ArrayList<ProducedType> types = new ArrayList<>();
if (et.getCaseTypes() == null || et.getCaseTypes().isEmpty()) {
types.add(et);
} else {
types.addAll(et.getCaseTypes());
}
types.add(p.getType());
ut.setCaseTypes(types);
et = ut.getType();
}
Map<TypeParameter,ProducedType> args = new HashMap<>();
for (TypeParameter tp : tuple.getTypeParameters()) {
if ("First".equals(tp.getName())) {
args.put(tp, p.getType());
} else if ("Element".equals(tp.getName())) {
args.put(tp, et);
} else if ("Rest".equals(tp.getName())) {
args.put(tp, tt);
}
}
if (i == params.size()-1) {
tt = tuple.getType();
}
tt = tt.substitute(args);
}
return tt;
}
/** Outputs a function that returns the specified annotations, so that they can be loaded lazily. */
static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
if (annotations == null || annotations.getAnnotations().isEmpty()) {
gen.out("[]");
} else {
gen.out("function(){return[");
boolean first = true;
for (Tree.Annotation a : annotations.getAnnotations()) {
if (first) first=false; else gen.out(",");
gen.getInvoker().generateInvocation(a);
}
gen.out("];}");
}
}
/** Abstraction for a callback that generates the runtime annotations list as part of the metamodel. */
static interface RuntimeMetamodelAnnotationGenerator {
public void generateAnnotations();
}
}
| false | true | static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
boolean comma = false;
for(TypeParameter tp : tparms) {
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
| static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) {
gen.out("function(){return{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
boolean comma = false;
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out'");
comma = true;
} else if (tp.isContravariant()) {
gen.out("'var':'in'");
comma = true;
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
if (comma)gen.out(",");
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
comma = true;
}
if (tp.getDefaultTypeArgument() != null) {
if (comma)gen.out(",");
gen.out("'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annGen != null) {
annGen.generateAnnotations();
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("};}");
}
|
diff --git a/src/eu/livotov/labs/android/robotools/api/RTApiError.java b/src/eu/livotov/labs/android/robotools/api/RTApiError.java
index 25f7133..03acf83 100644
--- a/src/eu/livotov/labs/android/robotools/api/RTApiError.java
+++ b/src/eu/livotov/labs/android/robotools/api/RTApiError.java
@@ -1,99 +1,101 @@
package eu.livotov.labs.android.robotools.api;
import eu.livotov.labs.android.robotools.net.RTHTTPError;
import java.io.IOException;
/**
* (c) Livotov Labs Ltd. 2012
* Date: 29.01.13
*/
public class RTApiError extends RuntimeException {
private int errorCode;
private String responseBody;
public RTApiError(Throwable internal) {
super("Internal application error: " + internal.getMessage(), internal);
analyzeAndSetErrorCode();
}
public RTApiError(int bawErrorCode) {
super((bawErrorCode < ErrorCodes.InternalError ? "API error: " : "Error: ") + bawErrorCode);
errorCode = bawErrorCode;
}
public RTApiError(int bawErrorCode, final String details) {
super((bawErrorCode < ErrorCodes.InternalError ? "API error: " : "Error: ") + bawErrorCode + ", " + details);
errorCode = bawErrorCode;
}
public RTApiError(RTHTTPError httpError) {
super(httpError.getMessage(), httpError);
this.responseBody = httpError.getResponseBody();
analyzeAndSetErrorCode();
}
private void analyzeAndSetErrorCode() {
errorCode = ErrorCodes.InternalError;
Throwable cause = getCause();
if (cause != null) {
if (cause instanceof RTHTTPError) {
if (cause.getCause() != null) {
Throwable rootCause = cause.getCause();
if (rootCause instanceof IOException) {
errorCode = ErrorCodes.NetworkError;
return;
}
+ } else{
+ errorCode = ((RTHTTPError) cause).getStatusCode();
}
}
if (cause instanceof IOException) {
errorCode = ErrorCodes.NetworkError;
return;
}
}
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public boolean isInternalError() {
return getErrorCode() >= ErrorCodes.InternalError;
}
public static class ErrorCodes {
public final static int InternalError = 100000;
public final static int NetworkError = InternalError + 1;
public final static int JsonError = InternalError + 2;
}
public static void rethrow(Object err) {
if (err instanceof Throwable) {
if (err instanceof RTApiError) {
throw (RTApiError) err;
} else {
throw new RTApiError((Throwable) err);
}
}
}
public static RTApiError wrap(Throwable err) {
if (err instanceof RTApiError) {
return (RTApiError) err;
} else {
return new RTApiError(err);
}
}
public String getResponseBody()
{
return responseBody;
}
}
| true | true | private void analyzeAndSetErrorCode() {
errorCode = ErrorCodes.InternalError;
Throwable cause = getCause();
if (cause != null) {
if (cause instanceof RTHTTPError) {
if (cause.getCause() != null) {
Throwable rootCause = cause.getCause();
if (rootCause instanceof IOException) {
errorCode = ErrorCodes.NetworkError;
return;
}
}
}
if (cause instanceof IOException) {
errorCode = ErrorCodes.NetworkError;
return;
}
}
}
| private void analyzeAndSetErrorCode() {
errorCode = ErrorCodes.InternalError;
Throwable cause = getCause();
if (cause != null) {
if (cause instanceof RTHTTPError) {
if (cause.getCause() != null) {
Throwable rootCause = cause.getCause();
if (rootCause instanceof IOException) {
errorCode = ErrorCodes.NetworkError;
return;
}
} else{
errorCode = ((RTHTTPError) cause).getStatusCode();
}
}
if (cause instanceof IOException) {
errorCode = ErrorCodes.NetworkError;
return;
}
}
}
|
diff --git a/apps/ibis/apps/sor/explicit/SOR.java b/apps/ibis/apps/sor/explicit/SOR.java
index 1e353994..5e3413d0 100644
--- a/apps/ibis/apps/sor/explicit/SOR.java
+++ b/apps/ibis/apps/sor/explicit/SOR.java
@@ -1,268 +1,268 @@
/*
* SOR.java
* Successive over relaxation
* SUN RMI version implementing a red-black SOR, based on earlier Orca source.
* with cluster optimization, and split phase optimization, reusing a thread
* each Wide-Area send. (All switchable)
*
* Rob van Nieuwpoort & Jason Maassen
*
*/
import ibis.ipl.*;
class SOR {
private static final double TOLERANCE = 0.00001; /* termination criterion */
private static final double LOCAL_STEPS = 0;
private static final boolean PREV = true;
private static final boolean NEXT = false;
private final double r;
private final double omega;
private final double stopdiff;
private final int ncol;
private final int nrow; /* number of rows and columns */
private final int size;
private final int rank; /* process ranks */
private final int lb;
private final int ub; /* lower and upper bound of grid stripe [lb ... ub] -> NOTE: ub is inclusive*/
private final double[][] g;
private final SendPort leftS;
private final SendPort rightS;
private final ReceivePort leftR;
private final ReceivePort rightR;
private final SendPort reduceS;
private final ReceivePort reduceR;
SOR(int nrow, int ncol, int N, int rank, int size,
SendPort leftS, SendPort rightS,
ReceivePort leftR, ReceivePort rightR,
SendPort reduceS, ReceivePort reduceR) {
this.nrow = nrow;
this.ncol = ncol;
this.leftS = leftS;
this.rightS = rightS;
this.leftR = leftR;
this.rightR = rightR;
this.reduceS = reduceS;
this.reduceR = reduceR;
/* ranks of predecessor and successor for row exchanges */
this.size = size;
this.rank = rank;
// getBounds
int n = N-1;
int nlarge = n % size;
int nsmall = size - nlarge;
int size_small = n / size;
int size_large = size_small + 1;
int temp_lb;
if (rank < nlarge) {
temp_lb = rank * size_large;
ub = temp_lb + size_large;
} else {
temp_lb = nlarge * size_large + (rank - nlarge) * size_small;
ub = temp_lb + size_small;
}
if (temp_lb == 0) {
lb = 1; /* row 0 is static */
} else {
lb = temp_lb;
}
r = 0.5 * ( Math.cos( Math.PI / (ncol) ) + Math.cos( Math.PI / (nrow) ) );
double temp_omega = 2.0 / ( 1.0 + Math.sqrt( 1.0 - r * r ) );
stopdiff = TOLERANCE / ( 2.0 - temp_omega );
omega = temp_omega*0.8; /* magic factor */
g = createGrid();
}
private double [][] createGrid() {
double [][] g = new double[nrow][];
for (int i = lb-1; i<=ub; i++) {
g[i] = new double[ncol]; /* malloc the own range plus one more line */
/* of overlap on each border */
}
/* initialize the grid */
for (int i = lb-1; i <=ub; i++){
for (int j = 0; j < ncol; j++){
if (i == 0) g[i][j] = 4.56;
else if (i == nrow-1) g[i][j] = 9.85;
else if (j == 0) g[i][j] = 7.32;
else if (j == ncol-1) g[i][j] = 6.88;
else g[i][j] = 0.0;
}
}
return g;
}
private double stencil (int row, int col) {
return ( g[row-1][col] + g[row+1][col] + g[row][col-1] + g[row][col+1] ) / 4.0;
}
private int even (int i) {
return ( ( ( i / 2 ) * 2 ) == i ) ? 1 : 0;
}
private void send(boolean dest, double[] col) throws Exception {
/* Two cases here: sync and async */
WriteMessage m;
if (dest == PREV) {
m = leftS.newMessage();
} else {
m = rightS.newMessage();
}
m.writeArray(col);
m.send();
m.finish();
}
private void receive(boolean source, double [] col) throws Exception {
ReadMessage m;
if (source == PREV) {
m = leftR.receive();
} else {
m = rightR.receive();
}
m.readArray(col);
m.finish();
}
private double reduce(double value) throws Exception {
if (rank == 0) {
for (int i=1;i<size;i++) {
ReadMessage rm = reduceR.receive();
double temp = rm.readDouble();
if (value < temp) value = temp;
rm.finish();
}
WriteMessage wm = reduceS.newMessage();
wm.writeDouble(value);
wm.send();
wm.finish();
} else {
WriteMessage wm = reduceS.newMessage();
wm.writeDouble(value);
wm.send();
wm.finish();
ReadMessage rm = reduceR.receive();
value = rm.readDouble();
rm.finish();
}
return value;
}
public void start () throws Exception {
long t_start,t_end; /* time values */
double maxdiff;
if(rank==0) {
System.out.println("Problem parameters");
System.out.println("r : " + r);
System.out.println("omega : " + omega);
System.out.println("stopdiff: " + stopdiff);
System.out.println("lb : " + lb);
System.out.println("ub : " + ub);
System.out.println("");
}
// abuse the reduce as a barrier
if (size > 1) {
reduce(42.0);
}
if (rank == 0) {
- System.out.println("... and there off !");
+ System.out.println("... and they're off !");
System.out.flush();
}
/* now do the "real" computation */
t_start = System.currentTimeMillis();
int iteration = 0;
do {
if (even(rank) == 1) {
if(rank != 0) send(PREV, g[lb]);
if(rank != size-1) send(NEXT, g[ub-1]);
if(rank != 0) receive(PREV, g[lb-1]);
if(rank != size-1) receive(NEXT, g[ub]);
} else {
if(rank != size-1) receive(NEXT, g[ub]);
if(rank != 0) receive(PREV, g[lb-1]);
if(rank != size-1) send(NEXT, g[ub-1]);
if(rank != 0) send(PREV, g[lb]);
}
maxdiff = 0.0;
for (int phase = 0; phase < 2 ; phase++){
for (int i = lb ; i < ub ; i++) {
for (int j = 1 + (even(i) ^ phase); j < ncol-1 ; j += 2) {
double gNew = stencil(i,j);
double diff = Math.abs(gNew - g[i][j]);
if ( diff > maxdiff ) {
maxdiff = diff;
}
g[i][j] = g[i][j] + omega * (gNew-g[i][j]);
}
}
}
if (size > 1) {
maxdiff = reduce(maxdiff);
}
// if(rank==0) {
// System.err.println(iteration + "");
// }
iteration++;
} while (maxdiff > stopdiff);
t_end = System.currentTimeMillis();
// if (size > 1) {
// maxdiff = global.reduceDiff(maxdiff);
// }
if (rank == 0){
System.out.println("SOR " + nrow + " x " + ncol + " took " + ((t_end - t_start)/1000.0) + " sec.");
System.out.println("using " + iteration + " iterations, diff is " + maxdiff + " (allowed diff " + stopdiff + ")");
}
}
}
| true | true | public void start () throws Exception {
long t_start,t_end; /* time values */
double maxdiff;
if(rank==0) {
System.out.println("Problem parameters");
System.out.println("r : " + r);
System.out.println("omega : " + omega);
System.out.println("stopdiff: " + stopdiff);
System.out.println("lb : " + lb);
System.out.println("ub : " + ub);
System.out.println("");
}
// abuse the reduce as a barrier
if (size > 1) {
reduce(42.0);
}
if (rank == 0) {
System.out.println("... and there off !");
System.out.flush();
}
/* now do the "real" computation */
t_start = System.currentTimeMillis();
int iteration = 0;
do {
if (even(rank) == 1) {
if(rank != 0) send(PREV, g[lb]);
if(rank != size-1) send(NEXT, g[ub-1]);
if(rank != 0) receive(PREV, g[lb-1]);
if(rank != size-1) receive(NEXT, g[ub]);
} else {
if(rank != size-1) receive(NEXT, g[ub]);
if(rank != 0) receive(PREV, g[lb-1]);
if(rank != size-1) send(NEXT, g[ub-1]);
if(rank != 0) send(PREV, g[lb]);
}
maxdiff = 0.0;
for (int phase = 0; phase < 2 ; phase++){
for (int i = lb ; i < ub ; i++) {
for (int j = 1 + (even(i) ^ phase); j < ncol-1 ; j += 2) {
double gNew = stencil(i,j);
double diff = Math.abs(gNew - g[i][j]);
if ( diff > maxdiff ) {
maxdiff = diff;
}
g[i][j] = g[i][j] + omega * (gNew-g[i][j]);
}
}
}
if (size > 1) {
maxdiff = reduce(maxdiff);
}
// if(rank==0) {
// System.err.println(iteration + "");
// }
iteration++;
} while (maxdiff > stopdiff);
t_end = System.currentTimeMillis();
// if (size > 1) {
// maxdiff = global.reduceDiff(maxdiff);
// }
if (rank == 0){
System.out.println("SOR " + nrow + " x " + ncol + " took " + ((t_end - t_start)/1000.0) + " sec.");
System.out.println("using " + iteration + " iterations, diff is " + maxdiff + " (allowed diff " + stopdiff + ")");
}
}
| public void start () throws Exception {
long t_start,t_end; /* time values */
double maxdiff;
if(rank==0) {
System.out.println("Problem parameters");
System.out.println("r : " + r);
System.out.println("omega : " + omega);
System.out.println("stopdiff: " + stopdiff);
System.out.println("lb : " + lb);
System.out.println("ub : " + ub);
System.out.println("");
}
// abuse the reduce as a barrier
if (size > 1) {
reduce(42.0);
}
if (rank == 0) {
System.out.println("... and they're off !");
System.out.flush();
}
/* now do the "real" computation */
t_start = System.currentTimeMillis();
int iteration = 0;
do {
if (even(rank) == 1) {
if(rank != 0) send(PREV, g[lb]);
if(rank != size-1) send(NEXT, g[ub-1]);
if(rank != 0) receive(PREV, g[lb-1]);
if(rank != size-1) receive(NEXT, g[ub]);
} else {
if(rank != size-1) receive(NEXT, g[ub]);
if(rank != 0) receive(PREV, g[lb-1]);
if(rank != size-1) send(NEXT, g[ub-1]);
if(rank != 0) send(PREV, g[lb]);
}
maxdiff = 0.0;
for (int phase = 0; phase < 2 ; phase++){
for (int i = lb ; i < ub ; i++) {
for (int j = 1 + (even(i) ^ phase); j < ncol-1 ; j += 2) {
double gNew = stencil(i,j);
double diff = Math.abs(gNew - g[i][j]);
if ( diff > maxdiff ) {
maxdiff = diff;
}
g[i][j] = g[i][j] + omega * (gNew-g[i][j]);
}
}
}
if (size > 1) {
maxdiff = reduce(maxdiff);
}
// if(rank==0) {
// System.err.println(iteration + "");
// }
iteration++;
} while (maxdiff > stopdiff);
t_end = System.currentTimeMillis();
// if (size > 1) {
// maxdiff = global.reduceDiff(maxdiff);
// }
if (rank == 0){
System.out.println("SOR " + nrow + " x " + ncol + " took " + ((t_end - t_start)/1000.0) + " sec.");
System.out.println("using " + iteration + " iterations, diff is " + maxdiff + " (allowed diff " + stopdiff + ")");
}
}
|
diff --git a/server/vc/src/main/java/com/vmware/aurora/vc/VcUtil.java b/server/vc/src/main/java/com/vmware/aurora/vc/VcUtil.java
index d0cbdc75..10491323 100644
--- a/server/vc/src/main/java/com/vmware/aurora/vc/VcUtil.java
+++ b/server/vc/src/main/java/com/vmware/aurora/vc/VcUtil.java
@@ -1,253 +1,255 @@
/***************************************************************************
* Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.aurora.vc;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.vmware.aurora.global.Configuration;
import com.vmware.aurora.util.CommonUtil;
import com.vmware.aurora.vc.VcTask.TaskType;
import com.vmware.aurora.vc.VcTaskMgr.IVcTaskBody;
import com.vmware.aurora.vc.vcservice.VcContext;
import com.vmware.vim.binding.impl.vim.alarm.AlarmSettingImpl;
import com.vmware.vim.binding.impl.vim.alarm.AlarmSpecImpl;
import com.vmware.vim.binding.impl.vim.alarm.AlarmTriggeringActionImpl;
import com.vmware.vim.binding.impl.vim.alarm.EventAlarmExpressionImpl;
import com.vmware.vim.binding.impl.vim.alarm.OrAlarmExpressionImpl;
import com.vmware.vim.binding.impl.vmodl.TypeNameImpl;
import com.vmware.vim.binding.vim.Folder;
import com.vmware.vim.binding.vim.HostSystem;
import com.vmware.vim.binding.vim.ManagedEntity;
import com.vmware.vim.binding.vim.ResourceAllocationInfo;
import com.vmware.vim.binding.vim.ManagedEntity.Status;
import com.vmware.vim.binding.vim.alarm.Alarm;
import com.vmware.vim.binding.vim.alarm.AlarmExpression;
import com.vmware.vim.binding.vim.alarm.AlarmManager;
import com.vmware.vim.binding.vim.alarm.AlarmSetting;
import com.vmware.vim.binding.vim.alarm.AlarmSpec;
import com.vmware.vim.binding.vim.alarm.AlarmTriggeringAction;
import com.vmware.vim.binding.vim.alarm.EventAlarmExpression;
import com.vmware.vim.binding.vim.alarm.OrAlarmExpression;
import com.vmware.vim.binding.vim.alarm.AlarmTriggeringAction.TransitionSpec;
import com.vmware.vim.binding.vim.fault.DuplicateName;
import com.vmware.vim.binding.vim.fault.InvalidName;
import com.vmware.vim.binding.vim.vm.ConfigSpec;
import com.vmware.vim.binding.vmodl.ManagedObjectReference;
import com.vmware.vim.binding.vmodl.fault.ManagedObjectNotFound;
/**
* VC related static functions.
*/
public class VcUtil {
private static final Logger logger = Logger.getLogger(VcUtil.class);
/**
* Checks if the allocation info is valid for a resource bundle RP.
*
* @param cpu
* The cpu alloc info.
* @param mem
* The mem alloc info.
* @return reasons for incompatible.
*/
protected static List<String> getCPUMemAllocIncompatReasons(
ResourceAllocationInfo cpu, ResourceAllocationInfo mem) {
List<String> reasons = new ArrayList<String>();
if (!Configuration.getBoolean("vc.skipRpCheck", false)) {
CommonUtil.checkCond((cpu.getLimit().equals(cpu.getReservation())),
reasons, "CPU limit is not equal to reservation.");
CommonUtil.checkCond((mem.getLimit().equals(mem.getReservation())),
reasons, "Memory limit is not equal to reservation.");
CommonUtil.checkCond((cpu.getReservation() > 0), reasons,
"CPU reservation is equal to zero.");
CommonUtil.checkCond((mem.getReservation() > 0), reasons,
"Memory reservation is equal to zero.");
} // else return empty reasons list
return reasons;
}
public static List<String> getIncompatReasonsForSysRp(VcResourcePool sysRp) {
List<String> reasons = new ArrayList<String>();
ResourceAllocationInfo cpu = sysRp.getCpuAllocationInfo();
ResourceAllocationInfo mem = sysRp.getMemAllocationInfo();
if (sysRp.isRootRP()) {
CommonUtil.checkCond((cpu.getReservation() > 0), reasons,
"No available CPU resource.");
CommonUtil.checkCond((mem.getReservation() > 0), reasons,
"No available Memory resource.");
} else {
CommonUtil
.checkCond((cpu.getReservation() > 0 || (cpu
.getExpandableReservation() && cpu.getLimit() > 0)),
reasons, "No available CPU resource.");
CommonUtil
.checkCond((mem.getReservation() > 0 || (mem
.getExpandableReservation() && mem.getLimit() > 0)),
reasons, "No available Memory resource.");
}
return reasons;
}
public static List<String> getIncompatReasonsForDatastore(
VcDatastore datastore) {
List<String> reasons = new ArrayList<String>();
CommonUtil.checkCond(!datastore.isInStoragePod(), reasons,
"The datastore can't be in storage pod.");
CommonUtil
.checkCond(
!datastore.isVmfs() || datastore.isSupportedVmfsVersion(),
reasons,
"The datastore file system is not supported. Data Director requires VMFS 5 or greater.");
return reasons;
}
public static boolean isValidAllocationForResourceBundleRP(
ResourceAllocationInfo cpu, ResourceAllocationInfo mem) {
return getCPUMemAllocIncompatReasons(cpu, mem).isEmpty();
}
public static boolean isValidAllocationForResourceBundleRP(
VcResourcePool rp, boolean forSysRb) {
ResourceAllocationInfo cpu = rp.getCpuAllocationInfo();
ResourceAllocationInfo mem = rp.getMemAllocationInfo();
if (forSysRb) {
return getIncompatReasonsForSysRp(rp).isEmpty();
} else {
return getCPUMemAllocIncompatReasons(cpu, mem).isEmpty();
}
}
public static VcVirtualMachine createVm(final Folder parentFolder,
final ConfigSpec spec, final VcResourcePool rp, final HostSystem host,
final IVcTaskCallback callback) throws Exception {
VcTask task = VcContext.getTaskMgr().execute(new IVcTaskBody() {
public VcTask body() throws Exception {
ManagedObjectReference hostRef =
host != null ? host._getRef() : null;
ManagedObjectReference taskRef =
parentFolder.createVm(spec, rp.getMoRef(), hostRef);
return new VcTask(TaskType.CreateVm, taskRef, callback);
}
});
task.waitForCompletion();
return (VcVirtualMachine) task.getResult();
}
public static void processNotFoundException(ManagedObjectNotFound e,
String moId, Logger logger) throws Exception {
ManagedObjectReference moRef = e.getObj();
if (MoUtil.morefToString(moRef).equals(moId)) {
logger.error("VC object " + MoUtil.morefToString(moRef)
+ " is already deleted from VC. Purge from vc cache");
// in case the event is lost
VcCache.purge(moRef);
ManagedObjectReference rpMoRef = VcCache.removeVmRpPair(moRef);
if (rpMoRef != null) {
VcCache.refresh(rpMoRef);
}
} else {
throw e;
}
}
public static void configureAlarm(Folder rootFolder) throws Exception {
AlarmManager alarmManager = VcContext.getService().getAlarmManager();
// Create the alarm for VHM
String SERENGETI_UUID = rootFolder.getName(); /* should be the name of the folder clusters get deployed into */
String ALARM_CLEARED_MSG = "all health issues previously reported by Big Data Extensions are in remission";
EventAlarmExpression raiseExpression = new EventAlarmExpressionImpl();
raiseExpression.setEventType(new TypeNameImpl("vim.event.EventEx"));
raiseExpression.setEventTypeId("com.vmware.vhadoop.vhm.vc.events.warning");
raiseExpression.setStatus(ManagedEntity.Status.yellow);
+ raiseExpression.setObjectType(new TypeNameImpl("vim.VirtualMachine"));
EventAlarmExpression clearExpression = new EventAlarmExpressionImpl();
clearExpression.setEventType(new TypeNameImpl("vim.event.EventEx"));
clearExpression.setEventTypeId("com.vmware.vhadoop.vhm.vc.events.info");
clearExpression.setComparisons(new EventAlarmExpressionImpl.ComparisonImpl[] {
new EventAlarmExpressionImpl.ComparisonImpl("message", "endsWith", ALARM_CLEARED_MSG)
});
clearExpression.setStatus(ManagedEntity.Status.green);
+ clearExpression.setObjectType(new TypeNameImpl("vim.VirtualMachine"));
OrAlarmExpression or = new OrAlarmExpressionImpl();
or.setExpression(new AlarmExpression[] {raiseExpression, clearExpression});
AlarmTriggeringAction alarmAction = new AlarmTriggeringActionImpl();
alarmAction.setAction(null);
TransitionSpec tSpec = new AlarmTriggeringActionImpl.TransitionSpecImpl();
tSpec.setRepeats(false);
tSpec.setStartState(Status.green);
tSpec.setFinalState(Status.yellow);
alarmAction.setTransitionSpecs(new TransitionSpec[] { tSpec });
alarmAction.setGreen2yellow(true);
AlarmSpec spec = new AlarmSpecImpl();
spec.setActionFrequency(0);
spec.setExpression(or);
/* the name has to be unique, but we need a way to find any matching
alarms later so we use a known prefix */
String alarmName = "BDE Health " + SERENGETI_UUID;
if (alarmName.length() > 80) {
alarmName = alarmName.substring(0, 80);
}
spec.setName(alarmName);
spec.setSystemName(null);
spec.setDescription("Indicates a health issue with a compute VM managed by Big Data Extensions. The specific health issue is detailed in a warning event in the event log.");
spec.setEnabled(true);
AlarmSetting as = new AlarmSettingImpl();
as.setReportingFrequency(0);
as.setToleranceRange(0);
spec.setSetting(as);
ManagedObjectReference[] existingAlarms = alarmManager.getAlarm(rootFolder._getRef());
Alarm existing = null;
try {
if (existingAlarms != null) {
for (ManagedObjectReference m : existingAlarms) {
Alarm a = MoUtil.getManagedObject(m);
if (a.getInfo().getName().equals(alarmName)) {
existing = a;
break;
}
}
}
} catch (NullPointerException e) {
// this just saves a lot of null checks
logger.error("Got NullPointerException when querying alarms", e);
}
try {
if (existing != null) {
existing.reconfigure(spec);
logger.info("Alarm " + alarmName + " exists");
} else {
ManagedObjectReference alarmMoref = alarmManager.create(rootFolder._getRef(), spec);
logger.info("Create " + alarmMoref.getValue() + " " + alarmName);
}
} catch (InvalidName e) {
logger.error("Invalid alarm name", e);
} catch (DuplicateName e) {
logger.error("Duplicate alarm name", e);
}
}
}
| false | true | public static void configureAlarm(Folder rootFolder) throws Exception {
AlarmManager alarmManager = VcContext.getService().getAlarmManager();
// Create the alarm for VHM
String SERENGETI_UUID = rootFolder.getName(); /* should be the name of the folder clusters get deployed into */
String ALARM_CLEARED_MSG = "all health issues previously reported by Big Data Extensions are in remission";
EventAlarmExpression raiseExpression = new EventAlarmExpressionImpl();
raiseExpression.setEventType(new TypeNameImpl("vim.event.EventEx"));
raiseExpression.setEventTypeId("com.vmware.vhadoop.vhm.vc.events.warning");
raiseExpression.setStatus(ManagedEntity.Status.yellow);
EventAlarmExpression clearExpression = new EventAlarmExpressionImpl();
clearExpression.setEventType(new TypeNameImpl("vim.event.EventEx"));
clearExpression.setEventTypeId("com.vmware.vhadoop.vhm.vc.events.info");
clearExpression.setComparisons(new EventAlarmExpressionImpl.ComparisonImpl[] {
new EventAlarmExpressionImpl.ComparisonImpl("message", "endsWith", ALARM_CLEARED_MSG)
});
clearExpression.setStatus(ManagedEntity.Status.green);
OrAlarmExpression or = new OrAlarmExpressionImpl();
or.setExpression(new AlarmExpression[] {raiseExpression, clearExpression});
AlarmTriggeringAction alarmAction = new AlarmTriggeringActionImpl();
alarmAction.setAction(null);
TransitionSpec tSpec = new AlarmTriggeringActionImpl.TransitionSpecImpl();
tSpec.setRepeats(false);
tSpec.setStartState(Status.green);
tSpec.setFinalState(Status.yellow);
alarmAction.setTransitionSpecs(new TransitionSpec[] { tSpec });
alarmAction.setGreen2yellow(true);
AlarmSpec spec = new AlarmSpecImpl();
spec.setActionFrequency(0);
spec.setExpression(or);
/* the name has to be unique, but we need a way to find any matching
alarms later so we use a known prefix */
String alarmName = "BDE Health " + SERENGETI_UUID;
if (alarmName.length() > 80) {
alarmName = alarmName.substring(0, 80);
}
spec.setName(alarmName);
spec.setSystemName(null);
spec.setDescription("Indicates a health issue with a compute VM managed by Big Data Extensions. The specific health issue is detailed in a warning event in the event log.");
spec.setEnabled(true);
AlarmSetting as = new AlarmSettingImpl();
as.setReportingFrequency(0);
as.setToleranceRange(0);
spec.setSetting(as);
ManagedObjectReference[] existingAlarms = alarmManager.getAlarm(rootFolder._getRef());
Alarm existing = null;
try {
if (existingAlarms != null) {
for (ManagedObjectReference m : existingAlarms) {
Alarm a = MoUtil.getManagedObject(m);
if (a.getInfo().getName().equals(alarmName)) {
existing = a;
break;
}
}
}
} catch (NullPointerException e) {
// this just saves a lot of null checks
logger.error("Got NullPointerException when querying alarms", e);
}
try {
if (existing != null) {
existing.reconfigure(spec);
logger.info("Alarm " + alarmName + " exists");
} else {
ManagedObjectReference alarmMoref = alarmManager.create(rootFolder._getRef(), spec);
logger.info("Create " + alarmMoref.getValue() + " " + alarmName);
}
} catch (InvalidName e) {
logger.error("Invalid alarm name", e);
} catch (DuplicateName e) {
logger.error("Duplicate alarm name", e);
}
}
| public static void configureAlarm(Folder rootFolder) throws Exception {
AlarmManager alarmManager = VcContext.getService().getAlarmManager();
// Create the alarm for VHM
String SERENGETI_UUID = rootFolder.getName(); /* should be the name of the folder clusters get deployed into */
String ALARM_CLEARED_MSG = "all health issues previously reported by Big Data Extensions are in remission";
EventAlarmExpression raiseExpression = new EventAlarmExpressionImpl();
raiseExpression.setEventType(new TypeNameImpl("vim.event.EventEx"));
raiseExpression.setEventTypeId("com.vmware.vhadoop.vhm.vc.events.warning");
raiseExpression.setStatus(ManagedEntity.Status.yellow);
raiseExpression.setObjectType(new TypeNameImpl("vim.VirtualMachine"));
EventAlarmExpression clearExpression = new EventAlarmExpressionImpl();
clearExpression.setEventType(new TypeNameImpl("vim.event.EventEx"));
clearExpression.setEventTypeId("com.vmware.vhadoop.vhm.vc.events.info");
clearExpression.setComparisons(new EventAlarmExpressionImpl.ComparisonImpl[] {
new EventAlarmExpressionImpl.ComparisonImpl("message", "endsWith", ALARM_CLEARED_MSG)
});
clearExpression.setStatus(ManagedEntity.Status.green);
clearExpression.setObjectType(new TypeNameImpl("vim.VirtualMachine"));
OrAlarmExpression or = new OrAlarmExpressionImpl();
or.setExpression(new AlarmExpression[] {raiseExpression, clearExpression});
AlarmTriggeringAction alarmAction = new AlarmTriggeringActionImpl();
alarmAction.setAction(null);
TransitionSpec tSpec = new AlarmTriggeringActionImpl.TransitionSpecImpl();
tSpec.setRepeats(false);
tSpec.setStartState(Status.green);
tSpec.setFinalState(Status.yellow);
alarmAction.setTransitionSpecs(new TransitionSpec[] { tSpec });
alarmAction.setGreen2yellow(true);
AlarmSpec spec = new AlarmSpecImpl();
spec.setActionFrequency(0);
spec.setExpression(or);
/* the name has to be unique, but we need a way to find any matching
alarms later so we use a known prefix */
String alarmName = "BDE Health " + SERENGETI_UUID;
if (alarmName.length() > 80) {
alarmName = alarmName.substring(0, 80);
}
spec.setName(alarmName);
spec.setSystemName(null);
spec.setDescription("Indicates a health issue with a compute VM managed by Big Data Extensions. The specific health issue is detailed in a warning event in the event log.");
spec.setEnabled(true);
AlarmSetting as = new AlarmSettingImpl();
as.setReportingFrequency(0);
as.setToleranceRange(0);
spec.setSetting(as);
ManagedObjectReference[] existingAlarms = alarmManager.getAlarm(rootFolder._getRef());
Alarm existing = null;
try {
if (existingAlarms != null) {
for (ManagedObjectReference m : existingAlarms) {
Alarm a = MoUtil.getManagedObject(m);
if (a.getInfo().getName().equals(alarmName)) {
existing = a;
break;
}
}
}
} catch (NullPointerException e) {
// this just saves a lot of null checks
logger.error("Got NullPointerException when querying alarms", e);
}
try {
if (existing != null) {
existing.reconfigure(spec);
logger.info("Alarm " + alarmName + " exists");
} else {
ManagedObjectReference alarmMoref = alarmManager.create(rootFolder._getRef(), spec);
logger.info("Create " + alarmMoref.getValue() + " " + alarmName);
}
} catch (InvalidName e) {
logger.error("Invalid alarm name", e);
} catch (DuplicateName e) {
logger.error("Duplicate alarm name", e);
}
}
|
diff --git a/public/java/test/org/broadinstitute/sting/gatk/walkers/variantutils/VCFStreamingIntegrationTest.java b/public/java/test/org/broadinstitute/sting/gatk/walkers/variantutils/VCFStreamingIntegrationTest.java
index 132a11273..3801e132d 100644
--- a/public/java/test/org/broadinstitute/sting/gatk/walkers/variantutils/VCFStreamingIntegrationTest.java
+++ b/public/java/test/org/broadinstitute/sting/gatk/walkers/variantutils/VCFStreamingIntegrationTest.java
@@ -1,107 +1,107 @@
/*
* Copyright (c) 2011, The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.walkers.variantutils;
import org.broadinstitute.sting.WalkerTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
/**
* Test the generic VCF streaming workflow with a few basic VCF routines.
*/
public class VCFStreamingIntegrationTest extends WalkerTest {
@Test
public void testSimpleVCFStreaming() throws IOException {
// Create a FIFO. This seems to be the only way to create an interprocess FIFO in Java (java.nio.Pipe is intraprocess only).
File tmpFifo = File.createTempFile("vcfstreaming","");
Runtime.getRuntime().exec(new String[] {"mkfifo",tmpFifo.getAbsolutePath()});
// Copy VCF data from the test file into the FIFO.
String testFile = validationDataLocation + "yri.trio.gatk.ug.head.vcf";
FileInputStream inputStream = new FileInputStream(testFile);
FileOutputStream outputStream = new FileOutputStream(tmpFifo);
outputStream.getChannel().transferFrom(inputStream.getChannel(),0,inputStream.getChannel().size());
outputStream.close();
inputStream.close();
WalkerTestSpec spec = new WalkerTestSpec(
"-T SelectVariants" +
" -R " + b36KGReference +
" --variant:vcf3,storage=STREAM " + tmpFifo.getAbsolutePath() +
" --NO_HEADER" +
" -o %s",
1,
Arrays.asList("658f580f7a294fd334bd897102616fed")
);
executeTest("testSimpleVCFStreaming", spec);
tmpFifo.delete();
}
@Test
public void testVCFStreamingChain() throws IOException {
// Create a FIFO. This seems to be the only way to create an interprocess FIFO in Java (java.nio.Pipe is intraprocess only).
File tmpFifo = File.createTempFile("vcfstreaming","");
Runtime.getRuntime().exec(new String[] {"mkfifo",tmpFifo.getAbsolutePath()});
String testFile = validationDataLocation + "yri.trio.gatk.ug.head.vcf";
// Output select to FIFO
WalkerTestSpec selectTestSpec = new WalkerTestSpec(
"-T SelectVariants" +
" -R " + b36KGReference +
" --variant:vcf3,storage=STREAM " + testFile +
" --NO_HEADER" +
" -select 'QD > 2.0'" +
" -o " + tmpFifo.getAbsolutePath(),
0,
Collections.<String>emptyList()
);
executeTest("testVCFStreamingChain", selectTestSpec);
// Eval compare the full set to the subselection.
selectTestSpec = new WalkerTestSpec(
"-T VariantEval" +
" -R " + b36KGReference +
- " --eval,vcf3 " + testFile +
- " --comp,vcf,storage=STREAM " + tmpFifo.getAbsolutePath() +
+ " --eval:vcf3 " + testFile +
+ " --comp:vcf,storage=STREAM " + tmpFifo.getAbsolutePath() +
" -EV CompOverlap -noEV -noST" +
" -o %s",
1,
Arrays.asList("ea09bf764adba9765b99921c5ba2c709")
);
executeTest("testVCFStreamingChain", selectTestSpec);
tmpFifo.delete();
}
}
| true | true | public void testVCFStreamingChain() throws IOException {
// Create a FIFO. This seems to be the only way to create an interprocess FIFO in Java (java.nio.Pipe is intraprocess only).
File tmpFifo = File.createTempFile("vcfstreaming","");
Runtime.getRuntime().exec(new String[] {"mkfifo",tmpFifo.getAbsolutePath()});
String testFile = validationDataLocation + "yri.trio.gatk.ug.head.vcf";
// Output select to FIFO
WalkerTestSpec selectTestSpec = new WalkerTestSpec(
"-T SelectVariants" +
" -R " + b36KGReference +
" --variant:vcf3,storage=STREAM " + testFile +
" --NO_HEADER" +
" -select 'QD > 2.0'" +
" -o " + tmpFifo.getAbsolutePath(),
0,
Collections.<String>emptyList()
);
executeTest("testVCFStreamingChain", selectTestSpec);
// Eval compare the full set to the subselection.
selectTestSpec = new WalkerTestSpec(
"-T VariantEval" +
" -R " + b36KGReference +
" --eval,vcf3 " + testFile +
" --comp,vcf,storage=STREAM " + tmpFifo.getAbsolutePath() +
" -EV CompOverlap -noEV -noST" +
" -o %s",
1,
Arrays.asList("ea09bf764adba9765b99921c5ba2c709")
);
executeTest("testVCFStreamingChain", selectTestSpec);
tmpFifo.delete();
}
| public void testVCFStreamingChain() throws IOException {
// Create a FIFO. This seems to be the only way to create an interprocess FIFO in Java (java.nio.Pipe is intraprocess only).
File tmpFifo = File.createTempFile("vcfstreaming","");
Runtime.getRuntime().exec(new String[] {"mkfifo",tmpFifo.getAbsolutePath()});
String testFile = validationDataLocation + "yri.trio.gatk.ug.head.vcf";
// Output select to FIFO
WalkerTestSpec selectTestSpec = new WalkerTestSpec(
"-T SelectVariants" +
" -R " + b36KGReference +
" --variant:vcf3,storage=STREAM " + testFile +
" --NO_HEADER" +
" -select 'QD > 2.0'" +
" -o " + tmpFifo.getAbsolutePath(),
0,
Collections.<String>emptyList()
);
executeTest("testVCFStreamingChain", selectTestSpec);
// Eval compare the full set to the subselection.
selectTestSpec = new WalkerTestSpec(
"-T VariantEval" +
" -R " + b36KGReference +
" --eval:vcf3 " + testFile +
" --comp:vcf,storage=STREAM " + tmpFifo.getAbsolutePath() +
" -EV CompOverlap -noEV -noST" +
" -o %s",
1,
Arrays.asList("ea09bf764adba9765b99921c5ba2c709")
);
executeTest("testVCFStreamingChain", selectTestSpec);
tmpFifo.delete();
}
|
diff --git a/src/com/android/browser/BaseUi.java b/src/com/android/browser/BaseUi.java
index 5deb3353..568a7e97 100644
--- a/src/com/android/browser/BaseUi.java
+++ b/src/com/android/browser/BaseUi.java
@@ -1,682 +1,682 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import com.android.browser.Tab.LockIcon;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.util.List;
/**
* UI interface definitions
*/
public abstract class BaseUi implements UI, WebViewFactory {
private static final String LOGTAG = "BaseUi";
protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
protected static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
Activity mActivity;
UiController mUiController;
TabControl mTabControl;
private Tab mActiveTab;
private InputMethodManager mInputManager;
private Drawable mSecLockIcon;
private Drawable mMixLockIcon;
private FrameLayout mBrowserFrameLayout;
protected FrameLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private CombinedBookmarkHistoryView mComboView;
private LinearLayout mErrorConsoleContainer = null;
private Toast mStopToast;
// the default <video> poster
private Bitmap mDefaultVideoPoster;
// the video progress view
private View mVideoProgressView;
private boolean mActivityPaused;
public BaseUi(Activity browser, UiController controller) {
mActivity = browser;
mUiController = controller;
mTabControl = controller.getTabControl();
Resources res = mActivity.getResources();
mInputManager = (InputMethodManager)
browser.getSystemService(Activity.INPUT_METHOD_SERVICE);
mSecLockIcon = res.getDrawable(R.drawable.ic_secure_holo_dark);
mMixLockIcon = res.getDrawable(R.drawable.ic_partial_secure);
FrameLayout frameLayout = (FrameLayout) mActivity.getWindow()
.getDecorView().findViewById(android.R.id.content);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(mActivity)
.inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
R.id.main_content);
mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
.findViewById(R.id.error_console);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
.findViewById(R.id.fullscreen_custom_content);
frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
}
/**
* common webview initialization
* @param w the webview to initialize
*/
protected void initWebViewSettings(WebView w) {
w.setScrollbarFadingEnabled(true);
w.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
w.setMapTrackballToArrowKeys(false); // use trackball directly
// Enable the built-in zoom
w.getSettings().setBuiltInZoomControls(true);
// Add this WebView to the settings observer list and update the
// settings
final BrowserSettings s = BrowserSettings.getInstance();
s.addObserver(w.getSettings()).update(s, null);
}
private void cancelStopToast() {
if (mStopToast != null) {
mStopToast.cancel();
mStopToast = null;
}
}
// lifecycle
public void onPause() {
if (isCustomViewShowing()) {
onHideCustomView();
}
cancelStopToast();
mActivityPaused = true;
}
public void onResume() {
mActivityPaused = false;
}
protected boolean isActivityPaused() {
return mActivityPaused;
}
public void onConfigurationChanged(Configuration config) {
}
// key handling
@Override
public boolean onBackKey() {
if (mComboView != null) {
if (!mComboView.onBackPressed()) {
mUiController.removeComboView();
}
return true;
}
if (mCustomView != null) {
mUiController.hideCustomView();
return true;
}
return false;
}
// Tab callbacks
@Override
public void onTabDataChanged(Tab tab) {
setUrlTitle(tab);
setFavicon(tab);
updateLockIconToLatest(tab);
updateNavigationState(tab);
}
@Override
public void bookmarkedStatusHasChanged(Tab tab) {
// no op in base case
}
@Override
public void onPageStopped(Tab tab) {
cancelStopToast();
if (tab.inForeground()) {
mStopToast = Toast
.makeText(mActivity, R.string.stopping, Toast.LENGTH_SHORT);
mStopToast.show();
}
}
@Override
public boolean needsRestoreAllTabs() {
return false;
}
@Override
public void addTab(Tab tab) {
}
@Override
public void setActiveTab(Tab tab) {
if ((tab != mActiveTab) && (mActiveTab != null)) {
removeTabFromContentView(mActiveTab);
}
mActiveTab = tab;
attachTabToContentView(tab);
setShouldShowErrorConsole(tab, mUiController.shouldShowErrorConsole());
onTabDataChanged(tab);
onProgressChanged(tab);
boolean incognito = mActiveTab.getWebView().isPrivateBrowsingEnabled();
getEmbeddedTitleBar().setIncognitoMode(incognito);
getFakeTitleBar().setIncognitoMode(incognito);
}
Tab getActiveTab() {
return mActiveTab;
}
@Override
public void updateTabs(List<Tab> tabs) {
}
@Override
public void removeTab(Tab tab) {
if (mActiveTab == tab) {
removeTabFromContentView(tab);
mActiveTab = null;
}
}
@Override
public void detachTab(Tab tab) {
removeTabFromContentView(tab);
}
@Override
public void attachTab(Tab tab) {
attachTabToContentView(tab);
}
private void attachTabToContentView(Tab tab) {
- if (tab.getWebView() == null) {
+ if ((tab == null) || (tab.getWebView() == null)) {
return;
}
View container = tab.getViewContainer();
WebView mainView = tab.getWebView();
// Attach the WebView to the container and then attach the
// container to the content view.
FrameLayout wrapper =
(FrameLayout) container.findViewById(R.id.webview_wrapper);
ViewGroup parent = (ViewGroup) mainView.getParent();
if (parent != wrapper) {
if (parent != null) {
Log.w(LOGTAG, "mMainView already has a parent in"
+ " attachTabToContentView!");
parent.removeView(mainView);
}
wrapper.addView(mainView);
} else {
Log.w(LOGTAG, "mMainView is already attached to wrapper in"
+ " attachTabToContentView!");
}
parent = (ViewGroup) container.getParent();
if (parent != mContentView) {
if (parent != null) {
Log.w(LOGTAG, "mContainer already has a parent in"
+ " attachTabToContentView!");
parent.removeView(container);
}
mContentView.addView(container, COVER_SCREEN_PARAMS);
} else {
Log.w(LOGTAG, "mContainer is already attached to content in"
+ " attachTabToContentView!");
}
mUiController.attachSubWindow(tab);
}
private void removeTabFromContentView(Tab tab) {
// Remove the container that contains the main WebView.
WebView mainView = tab.getWebView();
View container = tab.getViewContainer();
if (mainView == null) {
return;
}
// Remove the container from the content and then remove the
// WebView from the container. This will trigger a focus change
// needed by WebView.
FrameLayout wrapper =
(FrameLayout) container.findViewById(R.id.webview_wrapper);
wrapper.removeView(mainView);
mContentView.removeView(container);
mUiController.endActionMode();
mUiController.removeSubWindow(tab);
ErrorConsoleView errorConsole = tab.getErrorConsole(false);
if (errorConsole != null) {
mErrorConsoleContainer.removeView(errorConsole);
}
mainView.setEmbeddedTitleBar(null);
}
@Override
public void onSetWebView(Tab tab, WebView webView) {
View container = tab.getViewContainer();
if (container == null) {
// The tab consists of a container view, which contains the main
// WebView, as well as any other UI elements associated with the tab.
container = mActivity.getLayoutInflater().inflate(R.layout.tab,
null);
tab.setViewContainer(container);
}
if (tab.getWebView() != webView) {
// Just remove the old one.
FrameLayout wrapper =
(FrameLayout) container.findViewById(R.id.webview_wrapper);
wrapper.removeView(tab.getWebView());
}
}
/**
* create a sub window container and webview for the tab
* Note: this methods operates through side-effects for now
* it sets both the subView and subViewContainer for the given tab
* @param tab tab to create the sub window for
* @param subView webview to be set as a subwindow for the tab
*/
@Override
public void createSubWindow(Tab tab, WebView subView) {
View subViewContainer = mActivity.getLayoutInflater().inflate(
R.layout.browser_subwindow, null);
ViewGroup inner = (ViewGroup) subViewContainer
.findViewById(R.id.inner_container);
inner.addView(subView, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
final ImageButton cancel = (ImageButton) subViewContainer
.findViewById(R.id.subwindow_close);
final WebView cancelSubView = subView;
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
cancelSubView.getWebChromeClient().onCloseWindow(cancelSubView);
}
});
tab.setSubWebView(subView);
tab.setSubViewContainer(subViewContainer);
}
/**
* Remove the sub window from the content view.
*/
@Override
public void removeSubWindow(View subviewContainer) {
mContentView.removeView(subviewContainer);
mUiController.endActionMode();
}
/**
* Attach the sub window to the content view.
*/
@Override
public void attachSubWindow(View container) {
if (container.getParent() != null) {
// already attached, remove first
((ViewGroup) container.getParent()).removeView(container);
}
mContentView.addView(container, COVER_SCREEN_PARAMS);
}
void showFakeTitleBar() {
if (!isFakeTitleBarShowing() && !isActivityPaused()) {
WebView mainView = mUiController.getCurrentWebView();
// if there is no current WebView, don't show the faked title bar;
if (mainView == null) {
return;
}
// Do not need to check for null, since the current tab will have
// at least a main WebView, or we would have returned above.
if (mUiController.isInCustomActionMode()) {
// Do not show the fake title bar, while a custom ActionMode
// (i.e. find or select) is showing.
return;
}
attachFakeTitleBar(mainView);
}
}
protected abstract void attachFakeTitleBar(WebView mainView);
protected abstract void hideFakeTitleBar();
protected abstract boolean isFakeTitleBarShowing();
protected abstract TitleBarBase getFakeTitleBar();
protected abstract TitleBarBase getEmbeddedTitleBar();
@Override
public void showVoiceTitleBar(String title) {
getEmbeddedTitleBar().setInVoiceMode(true);
getEmbeddedTitleBar().setDisplayTitle(title);
getFakeTitleBar().setInVoiceMode(true);
getFakeTitleBar().setDisplayTitle(title);
}
@Override
public void revertVoiceTitleBar(Tab tab) {
getEmbeddedTitleBar().setInVoiceMode(false);
String url = tab.getUrl();
getEmbeddedTitleBar().setDisplayTitle(url);
getFakeTitleBar().setInVoiceMode(false);
getFakeTitleBar().setDisplayTitle(url);
}
@Override
public void showComboView(boolean startWithHistory, Bundle extras) {
if (mComboView != null) {
return;
}
mComboView = new CombinedBookmarkHistoryView(mActivity,
mUiController,
startWithHistory ?
CombinedBookmarkHistoryView.FRAGMENT_ID_HISTORY
: CombinedBookmarkHistoryView.FRAGMENT_ID_BOOKMARKS,
extras);
FrameLayout wrapper =
(FrameLayout) mContentView.findViewById(R.id.webview_wrapper);
wrapper.setVisibility(View.GONE);
hideFakeTitleBar();
dismissIME();
if (mActiveTab != null) {
WebView web = mActiveTab.getWebView();
mActiveTab.putInBackground();
}
mContentView.addView(mComboView, COVER_SCREEN_PARAMS);
}
/**
* dismiss the ComboPage
*/
@Override
public void hideComboView() {
if (mComboView != null) {
mContentView.removeView(mComboView);
FrameLayout wrapper =
(FrameLayout) mContentView.findViewById(R.id.webview_wrapper);
wrapper.setVisibility(View.VISIBLE);
mComboView = null;
}
if (mActiveTab != null) {
mActiveTab.putInForeground();
}
mActivity.invalidateOptionsMenu();
}
@Override
public void showCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// Hide the content view.
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
setStatusBarVisibility(false);
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
@Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
setStatusBarVisibility(true);
mContentView.setVisibility(View.VISIBLE);
}
@Override
public boolean isCustomViewShowing() {
return mCustomView != null;
}
protected void dismissIME() {
if (mInputManager.isActive()) {
mInputManager.hideSoftInputFromWindow(mContentView.getWindowToken(),
0);
}
}
@Override
public boolean showsWeb() {
return mCustomView == null
&& mComboView == null;
}
// -------------------------------------------------------------------------
protected void updateNavigationState(Tab tab) {
}
/**
* Update the lock icon to correspond to our latest state.
*/
protected void updateLockIconToLatest(Tab t) {
if (t != null && t.inForeground()) {
updateLockIconImage(t.getLockIconType());
}
}
/**
* Updates the lock-icon image in the title-bar.
*/
private void updateLockIconImage(LockIcon lockIconType) {
Drawable d = null;
if (lockIconType == LockIcon.LOCK_ICON_SECURE) {
d = mSecLockIcon;
} else if (lockIconType == LockIcon.LOCK_ICON_MIXED) {
d = mMixLockIcon;
}
getEmbeddedTitleBar().setLock(d);
getFakeTitleBar().setLock(d);
}
protected void setUrlTitle(Tab tab) {
String url = tab.getUrl();
String title = tab.getTitle();
if (TextUtils.isEmpty(title)) {
title = url;
}
if (tab.isInVoiceSearchMode()) return;
if (tab.inForeground()) {
getEmbeddedTitleBar().setDisplayTitle(url);
getFakeTitleBar().setDisplayTitle(url);
}
}
// Set the favicon in the title bar.
protected void setFavicon(Tab tab) {
if (tab.inForeground()) {
Bitmap icon = tab.getFavicon();
getEmbeddedTitleBar().setFavicon(icon);
getFakeTitleBar().setFavicon(icon);
}
}
@Override
public void onActionModeFinished(boolean inLoad) {
if (inLoad) {
// the titlebar was removed when the CAB was shown
// if the page is loading, show it again
showFakeTitleBar();
}
}
// active tabs page
public void showActiveTabsPage() {
}
/**
* Remove the active tabs page.
*/
public void removeActiveTabsPage() {
}
// menu handling callbacks
@Override
public void onOptionsMenuOpened() {
}
@Override
public void onExtendedMenuOpened() {
}
@Override
public void onOptionsMenuClosed(boolean inLoad) {
}
@Override
public void onExtendedMenuClosed(boolean inLoad) {
}
@Override
public void onContextMenuCreated(Menu menu) {
}
@Override
public void onContextMenuClosed(Menu menu, boolean inLoad) {
}
// error console
@Override
public void setShouldShowErrorConsole(Tab tab, boolean flag) {
ErrorConsoleView errorConsole = tab.getErrorConsole(true);
if (flag) {
// Setting the show state of the console will cause it's the layout
// to be inflated.
if (errorConsole.numberOfErrors() > 0) {
errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
} else {
errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
}
if (errorConsole.getParent() != null) {
mErrorConsoleContainer.removeView(errorConsole);
}
// Now we can add it to the main view.
mErrorConsoleContainer.addView(errorConsole,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
mErrorConsoleContainer.removeView(errorConsole);
}
}
private void setStatusBarVisibility(boolean visible) {
int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
mActivity.getWindow().setFlags(flag,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// -------------------------------------------------------------------------
// Helper function for WebChromeClient
// -------------------------------------------------------------------------
@Override
public Bitmap getDefaultVideoPoster() {
if (mDefaultVideoPoster == null) {
mDefaultVideoPoster = BitmapFactory.decodeResource(
mActivity.getResources(), R.drawable.default_video_poster);
}
return mDefaultVideoPoster;
}
@Override
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(mActivity);
mVideoProgressView = inflater.inflate(
R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
@Override
public void showMaxTabsWarning() {
Toast warning = Toast.makeText(mActivity,
mActivity.getString(R.string.max_tabs_warning),
Toast.LENGTH_SHORT);
warning.show();
}
}
| true | true | private void attachTabToContentView(Tab tab) {
if (tab.getWebView() == null) {
return;
}
View container = tab.getViewContainer();
WebView mainView = tab.getWebView();
// Attach the WebView to the container and then attach the
// container to the content view.
FrameLayout wrapper =
(FrameLayout) container.findViewById(R.id.webview_wrapper);
ViewGroup parent = (ViewGroup) mainView.getParent();
if (parent != wrapper) {
if (parent != null) {
Log.w(LOGTAG, "mMainView already has a parent in"
+ " attachTabToContentView!");
parent.removeView(mainView);
}
wrapper.addView(mainView);
} else {
Log.w(LOGTAG, "mMainView is already attached to wrapper in"
+ " attachTabToContentView!");
}
parent = (ViewGroup) container.getParent();
if (parent != mContentView) {
if (parent != null) {
Log.w(LOGTAG, "mContainer already has a parent in"
+ " attachTabToContentView!");
parent.removeView(container);
}
mContentView.addView(container, COVER_SCREEN_PARAMS);
} else {
Log.w(LOGTAG, "mContainer is already attached to content in"
+ " attachTabToContentView!");
}
mUiController.attachSubWindow(tab);
}
| private void attachTabToContentView(Tab tab) {
if ((tab == null) || (tab.getWebView() == null)) {
return;
}
View container = tab.getViewContainer();
WebView mainView = tab.getWebView();
// Attach the WebView to the container and then attach the
// container to the content view.
FrameLayout wrapper =
(FrameLayout) container.findViewById(R.id.webview_wrapper);
ViewGroup parent = (ViewGroup) mainView.getParent();
if (parent != wrapper) {
if (parent != null) {
Log.w(LOGTAG, "mMainView already has a parent in"
+ " attachTabToContentView!");
parent.removeView(mainView);
}
wrapper.addView(mainView);
} else {
Log.w(LOGTAG, "mMainView is already attached to wrapper in"
+ " attachTabToContentView!");
}
parent = (ViewGroup) container.getParent();
if (parent != mContentView) {
if (parent != null) {
Log.w(LOGTAG, "mContainer already has a parent in"
+ " attachTabToContentView!");
parent.removeView(container);
}
mContentView.addView(container, COVER_SCREEN_PARAMS);
} else {
Log.w(LOGTAG, "mContainer is already attached to content in"
+ " attachTabToContentView!");
}
mUiController.attachSubWindow(tab);
}
|
diff --git a/src/org/gridlab/gridsphere/portlets/core/subscription/SubscriptionPortlet.java b/src/org/gridlab/gridsphere/portlets/core/subscription/SubscriptionPortlet.java
index 40431b8c2..9ae92d4a6 100644
--- a/src/org/gridlab/gridsphere/portlets/core/subscription/SubscriptionPortlet.java
+++ b/src/org/gridlab/gridsphere/portlets/core/subscription/SubscriptionPortlet.java
@@ -1,197 +1,197 @@
/*
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.portlets.core.subscription;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.portlet.service.PortletServiceException;
import org.gridlab.gridsphere.provider.event.FormEvent;
import org.gridlab.gridsphere.provider.portlet.ActionPortlet;
import org.gridlab.gridsphere.provider.portletui.beans.*;
import org.gridlab.gridsphere.provider.portletui.model.DefaultTableModel;
import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService;
import org.gridlab.gridsphere.services.core.layout.LayoutManagerService;
import org.gridlab.gridsphere.services.core.registry.impl.PortletManager;
import org.gridlab.gridsphere.portletcontainer.PortletRegistry;
import org.gridlab.gridsphere.portletcontainer.ApplicationPortlet;
import org.gridlab.gridsphere.portletcontainer.ConcretePortlet;
import javax.servlet.UnavailableException;
import java.util.*;
public class SubscriptionPortlet extends ActionPortlet {
// JSP pages used by this portlet
public static final String VIEW_JSP = "subscription/view.jsp";
public static final String HELP_JSP = "subscription/help.jsp";
// Portlet services
private AccessControlManagerService aclService = null;
private LayoutManagerService layoutMgr = null;
private PortletManager portletMgr = null;
private PortletRegistry portletRegistry = null;
private List gsPortlets = new Vector();
public void init(PortletConfig config) throws UnavailableException {
super.init(config);
this.log.debug("Entering initServices()");
try {
this.layoutMgr = (LayoutManagerService)config.getContext().getService(LayoutManagerService.class);
this.aclService = (AccessControlManagerService)config.getContext().getService(AccessControlManagerService.class);
} catch (PortletServiceException e) {
log.error("Unable to initialize services!", e);
}
this.log.debug("Exiting initServices()");
portletRegistry = PortletRegistry.getInstance();
portletMgr = PortletManager.getInstance();
DEFAULT_VIEW_PAGE = "doViewSubscription";
DEFAULT_HELP_PAGE = HELP_JSP;
}
public void initConcrete(PortletSettings settings) throws UnavailableException {
super.initConcrete(settings);
}
public void doViewSubscription(FormEvent event) {
PortletRequest req = event.getPortletRequest();
gsPortlets.clear();
User user = req.getUser();
List myNames = layoutMgr.getSubscribedPortlets(req);
List groups = aclService.getGroups(user);
Iterator it = groups.iterator();
PanelBean panel = event.getPanelBean("panel");
PortletRole role = req.getRole();
while (it.hasNext()) {
FrameBean frame = new FrameBean();
DefaultTableModel model = new DefaultTableModel();
PortletGroup g = (PortletGroup)it.next();
TableRowBean tr = new TableRowBean();
tr.setHeader(true);
TableCellBean tc3 = new TableCellBean();
TextBean text3 = new TextBean();
text3.setValue(this.getLocalizedText(req, "SUBSCRIPTION_SUBSCRIBE"));
tc3.addBean(text3);
tr.addBean(tc3);
TableCellBean tc = new TableCellBean();
TextBean text = new TextBean();
text.setValue(portletMgr.getPortletWebApplicationDescription(g.getName()));
tc.addBean(text);
tr.addBean(tc);
tc = new TableCellBean();
text = new TextBean();
text.setValue(this.getLocalizedText(req, "SUBSCRIPTION_DESC"));
tc.addBean(text);
tr.addBean(tc);
model.addTableRowBean(tr);
Collection appColl = portletRegistry.getApplicationPortlets(g.getName());
Iterator appIt = appColl.iterator();
while (appIt.hasNext()) {
ApplicationPortlet app = (ApplicationPortlet)appIt.next();
List concPortlets = app.getConcretePortlets();
Iterator cit = concPortlets.iterator();
while (cit.hasNext()) {
ConcretePortlet conc = (ConcretePortlet)cit.next();
String concID = conc.getConcretePortletID();
PortletRole reqrole = conc.getConcretePortletConfig().getRequiredRole();
log.debug("subscribed to portlet: " + concID + " " + reqrole);
if (role.compare(role, reqrole) >= 0) {
// build an interface
CheckBoxBean cb = new CheckBoxBean(req, "portletsCB");
cb.setValue(concID);
if (myNames.contains(concID)) {
cb.setSelected(true);
}
// don't allow core portlets to be changed
if (g.equals(PortletGroupFactory.GRIDSPHERE_GROUP)) {
gsPortlets.add(concID);
cb.setDisabled(true);
cb.setSelected(true);
}
TableRowBean newtr = new TableRowBean();
TableCellBean newtc = new TableCellBean();
newtc.addBean(cb);
newtr.addBean(newtc);
TableCellBean newtc2 = new TableCellBean();
TextBean tb = new TextBean();
// set 2nd column to portlet display name from concrete portlet
Locale loc = req.getLocale();
- concID = conc.getDisplayName(loc);
+ // concID = conc.getDisplayName(loc);
tb.setValue(concID);
newtc2.addBean(tb);
newtr.addBean(newtc2);
newtc = new TableCellBean();
TextBean tb2 = new TextBean();
// set 3rd column to portlet description from concrete portlet
- tb2.setValue(conc.getDescription(loc));
+ // tb2.setValue(conc.getDescription(loc));
newtc.addBean(tb2);
newtr.addBean(newtc);
model.addTableRowBean(newtr);
}
}
}
frame.setTableModel(model);
panel.addBean(frame);
}
setNextState(req, VIEW_JSP);
}
public void applyChanges(FormEvent event) {
PortletRequest req = event.getPortletRequest();
CheckBoxBean cb = event.getCheckBoxBean("portletsCB");
List newlist = cb.getSelectedValues();
List newportlets = new Vector();
List removePortlets = new Vector();
// compare to orig list
List oldlist = layoutMgr.getSubscribedPortlets(req);
// check if new list has new portlets to add
Iterator it = newlist.iterator();
while (it.hasNext()) {
String pid = (String)it.next();
if (!oldlist.contains(pid)) {
newportlets.add(pid);
//layoutMgr.addSubscribedPortlet(req, pid);
}
}
// check if new list no longer has entries that oldlist has
it = oldlist.iterator();
while (it.hasNext()) {
String pid = (String)it.next();
// don't allow users to remove core portlets
if (!newlist.contains(pid) && (!gsPortlets.contains(pid))) {
removePortlets.add(pid);
//System.err.println("removing " + pid);
}
}
layoutMgr.removeSubscribedPortlets(req, removePortlets);
// remove portlets
if (!removePortlets.isEmpty()) {
log.info("removing portlets");
for (int i = 0; i < removePortlets.size(); i++) {
log.info(" " + removePortlets.get(i));
}
layoutMgr.removePortlets(req, removePortlets);
layoutMgr.reloadPage(req);
}
}
}
| false | true | public void doViewSubscription(FormEvent event) {
PortletRequest req = event.getPortletRequest();
gsPortlets.clear();
User user = req.getUser();
List myNames = layoutMgr.getSubscribedPortlets(req);
List groups = aclService.getGroups(user);
Iterator it = groups.iterator();
PanelBean panel = event.getPanelBean("panel");
PortletRole role = req.getRole();
while (it.hasNext()) {
FrameBean frame = new FrameBean();
DefaultTableModel model = new DefaultTableModel();
PortletGroup g = (PortletGroup)it.next();
TableRowBean tr = new TableRowBean();
tr.setHeader(true);
TableCellBean tc3 = new TableCellBean();
TextBean text3 = new TextBean();
text3.setValue(this.getLocalizedText(req, "SUBSCRIPTION_SUBSCRIBE"));
tc3.addBean(text3);
tr.addBean(tc3);
TableCellBean tc = new TableCellBean();
TextBean text = new TextBean();
text.setValue(portletMgr.getPortletWebApplicationDescription(g.getName()));
tc.addBean(text);
tr.addBean(tc);
tc = new TableCellBean();
text = new TextBean();
text.setValue(this.getLocalizedText(req, "SUBSCRIPTION_DESC"));
tc.addBean(text);
tr.addBean(tc);
model.addTableRowBean(tr);
Collection appColl = portletRegistry.getApplicationPortlets(g.getName());
Iterator appIt = appColl.iterator();
while (appIt.hasNext()) {
ApplicationPortlet app = (ApplicationPortlet)appIt.next();
List concPortlets = app.getConcretePortlets();
Iterator cit = concPortlets.iterator();
while (cit.hasNext()) {
ConcretePortlet conc = (ConcretePortlet)cit.next();
String concID = conc.getConcretePortletID();
PortletRole reqrole = conc.getConcretePortletConfig().getRequiredRole();
log.debug("subscribed to portlet: " + concID + " " + reqrole);
if (role.compare(role, reqrole) >= 0) {
// build an interface
CheckBoxBean cb = new CheckBoxBean(req, "portletsCB");
cb.setValue(concID);
if (myNames.contains(concID)) {
cb.setSelected(true);
}
// don't allow core portlets to be changed
if (g.equals(PortletGroupFactory.GRIDSPHERE_GROUP)) {
gsPortlets.add(concID);
cb.setDisabled(true);
cb.setSelected(true);
}
TableRowBean newtr = new TableRowBean();
TableCellBean newtc = new TableCellBean();
newtc.addBean(cb);
newtr.addBean(newtc);
TableCellBean newtc2 = new TableCellBean();
TextBean tb = new TextBean();
// set 2nd column to portlet display name from concrete portlet
Locale loc = req.getLocale();
concID = conc.getDisplayName(loc);
tb.setValue(concID);
newtc2.addBean(tb);
newtr.addBean(newtc2);
newtc = new TableCellBean();
TextBean tb2 = new TextBean();
// set 3rd column to portlet description from concrete portlet
tb2.setValue(conc.getDescription(loc));
newtc.addBean(tb2);
newtr.addBean(newtc);
model.addTableRowBean(newtr);
}
}
}
frame.setTableModel(model);
panel.addBean(frame);
}
setNextState(req, VIEW_JSP);
}
| public void doViewSubscription(FormEvent event) {
PortletRequest req = event.getPortletRequest();
gsPortlets.clear();
User user = req.getUser();
List myNames = layoutMgr.getSubscribedPortlets(req);
List groups = aclService.getGroups(user);
Iterator it = groups.iterator();
PanelBean panel = event.getPanelBean("panel");
PortletRole role = req.getRole();
while (it.hasNext()) {
FrameBean frame = new FrameBean();
DefaultTableModel model = new DefaultTableModel();
PortletGroup g = (PortletGroup)it.next();
TableRowBean tr = new TableRowBean();
tr.setHeader(true);
TableCellBean tc3 = new TableCellBean();
TextBean text3 = new TextBean();
text3.setValue(this.getLocalizedText(req, "SUBSCRIPTION_SUBSCRIBE"));
tc3.addBean(text3);
tr.addBean(tc3);
TableCellBean tc = new TableCellBean();
TextBean text = new TextBean();
text.setValue(portletMgr.getPortletWebApplicationDescription(g.getName()));
tc.addBean(text);
tr.addBean(tc);
tc = new TableCellBean();
text = new TextBean();
text.setValue(this.getLocalizedText(req, "SUBSCRIPTION_DESC"));
tc.addBean(text);
tr.addBean(tc);
model.addTableRowBean(tr);
Collection appColl = portletRegistry.getApplicationPortlets(g.getName());
Iterator appIt = appColl.iterator();
while (appIt.hasNext()) {
ApplicationPortlet app = (ApplicationPortlet)appIt.next();
List concPortlets = app.getConcretePortlets();
Iterator cit = concPortlets.iterator();
while (cit.hasNext()) {
ConcretePortlet conc = (ConcretePortlet)cit.next();
String concID = conc.getConcretePortletID();
PortletRole reqrole = conc.getConcretePortletConfig().getRequiredRole();
log.debug("subscribed to portlet: " + concID + " " + reqrole);
if (role.compare(role, reqrole) >= 0) {
// build an interface
CheckBoxBean cb = new CheckBoxBean(req, "portletsCB");
cb.setValue(concID);
if (myNames.contains(concID)) {
cb.setSelected(true);
}
// don't allow core portlets to be changed
if (g.equals(PortletGroupFactory.GRIDSPHERE_GROUP)) {
gsPortlets.add(concID);
cb.setDisabled(true);
cb.setSelected(true);
}
TableRowBean newtr = new TableRowBean();
TableCellBean newtc = new TableCellBean();
newtc.addBean(cb);
newtr.addBean(newtc);
TableCellBean newtc2 = new TableCellBean();
TextBean tb = new TextBean();
// set 2nd column to portlet display name from concrete portlet
Locale loc = req.getLocale();
// concID = conc.getDisplayName(loc);
tb.setValue(concID);
newtc2.addBean(tb);
newtr.addBean(newtc2);
newtc = new TableCellBean();
TextBean tb2 = new TextBean();
// set 3rd column to portlet description from concrete portlet
// tb2.setValue(conc.getDescription(loc));
newtc.addBean(tb2);
newtr.addBean(newtc);
model.addTableRowBean(newtr);
}
}
}
frame.setTableModel(model);
panel.addBean(frame);
}
setNextState(req, VIEW_JSP);
}
|
diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java
index 6df3d53e5..c7e7e1991 100644
--- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java
+++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java
@@ -1,162 +1,165 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.springframework.util.Assert;
/**
* Abstract base class for JDBC {@link javax.sql.DataSource} implementations
* that operate on a JDBC {@link java.sql.Driver}.
*
* @author Juergen Hoeller
* @since 2.5.5
* @see SimpleDriverDataSource
* @see DriverManagerDataSource
*/
public abstract class AbstractDriverBasedDataSource extends AbstractDataSource {
private String url;
private String username;
private String password;
private Properties connectionProperties;
/**
* Set the JDBC URL to use for connecting through the Driver.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setUrl(String url) {
Assert.hasText(url, "Property 'url' must not be empty");
this.url = url.trim();
}
/**
* Return the JDBC URL to use for connecting through the Driver.
*/
public String getUrl() {
return this.url;
}
/**
* Set the JDBC username to use for connecting through the Driver.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Return the JDBC username to use for connecting through the Driver.
*/
public String getUsername() {
return this.username;
}
/**
* Set the JDBC password to use for connecting through the Driver.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Return the JDBC password to use for connecting through the Driver.
*/
public String getPassword() {
return this.password;
}
/**
* Specify arbitrary connection properties as key/value pairs,
* to be passed to the Driver.
* <p>Can also contain "user" and "password" properties. However,
* any "username" and "password" bean properties specified on this
* DataSource will override the corresponding connection properties.
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
public void setConnectionProperties(Properties connectionProperties) {
this.connectionProperties = connectionProperties;
}
/**
* Return the connection properties to be passed to the Driver, if any.
*/
public Properties getConnectionProperties() {
return this.connectionProperties;
}
/**
* This implementation delegates to {@code getConnectionFromDriver},
* using the default username and password of this DataSource.
* @see #getConnectionFromDriver(String, String)
* @see #setUsername
* @see #setPassword
*/
public Connection getConnection() throws SQLException {
return getConnectionFromDriver(getUsername(), getPassword());
}
/**
* This implementation delegates to {@code getConnectionFromDriver},
* using the given username and password.
* @see #getConnectionFromDriver(String, String)
*/
public Connection getConnection(String username, String password) throws SQLException {
return getConnectionFromDriver(username, password);
}
/**
* Build properties for the Driver, including the given username and password (if any),
* and obtain a corresponding Connection.
* @param username the name of the user
* @param password the password to use
* @return the obtained Connection
* @throws SQLException in case of failure
* @see java.sql.Driver#connect(String, java.util.Properties)
*/
protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
- Properties props = new Properties();
- props.putAll(getConnectionProperties());
+ Properties mergedProps = new Properties();
+ Properties connProps = getConnectionProperties();
+ if (connProps != null) {
+ mergedProps.putAll(connProps);
+ }
if (username != null) {
- props.setProperty("user", username);
+ mergedProps.setProperty("user", username);
}
if (password != null) {
- props.setProperty("password", password);
+ mergedProps.setProperty("password", password);
}
- return getConnectionFromDriver(props);
+ return getConnectionFromDriver(mergedProps);
}
/**
* Obtain a Connection using the given properties.
* <p>Template method to be implemented by subclasses.
* @param props the merged connection properties
* @return the obtained Connection
* @throws SQLException in case of failure
*/
protected abstract Connection getConnectionFromDriver(Properties props) throws SQLException;
}
| false | true | protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
Properties props = new Properties();
props.putAll(getConnectionProperties());
if (username != null) {
props.setProperty("user", username);
}
if (password != null) {
props.setProperty("password", password);
}
return getConnectionFromDriver(props);
}
| protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
Properties mergedProps = new Properties();
Properties connProps = getConnectionProperties();
if (connProps != null) {
mergedProps.putAll(connProps);
}
if (username != null) {
mergedProps.setProperty("user", username);
}
if (password != null) {
mergedProps.setProperty("password", password);
}
return getConnectionFromDriver(mergedProps);
}
|
diff --git a/activejdbc/src/test/java/activejdbc/PostgreSQLStatementProvider.java b/activejdbc/src/test/java/activejdbc/PostgreSQLStatementProvider.java
index 0cdbb465..1389632c 100644
--- a/activejdbc/src/test/java/activejdbc/PostgreSQLStatementProvider.java
+++ b/activejdbc/src/test/java/activejdbc/PostgreSQLStatementProvider.java
@@ -1,160 +1,160 @@
package activejdbc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Igor Polevoy
*/
public class PostgreSQLStatementProvider {
public List<String> getStatements(String table) {
List<String> statements = new ArrayList<String>();
if (table.equals("people")) {
statements = Arrays.asList(
"INSERT INTO people ( name, last_name, dob, graduation_date, created_at, updated_at) VALUES('John', 'Smith', '1934-12-01', '1954-12-01', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Leylah', 'Jonston', '1954-04-03', '1974-04-03', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Muhammad', 'Ali', '1943-01-04', '1963-01-04', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Joe', 'Pesci', '1944-02-23','1964-02-23', now(), now());"
);
} else if (table.equals("accounts")) {
statements = Arrays.asList(
"INSERT INTO accounts VALUES(1, '123', 'checking', 9999.99, 1234.32);"
);
} else if (table.equals("temperatures")) {
statements = Arrays.asList(
"INSERT INTO temperatures VALUES(1, 30);"
);
} else if (table.equals("salaries")) {
statements = Arrays.asList(
"INSERT INTO salaries VALUES(1, 50000.00);"
);
} else if (table.equals("users")) {
statements = Arrays.asList(
"INSERT INTO users (first_name, last_name, email) VALUES('Marilyn', 'Monroe', '[email protected]');",
"INSERT INTO users (first_name, last_name, email) VALUES('John', 'Doe', '[email protected]');"
);
} else if (table.equals("addresses")) {
statements = Arrays.asList(
"INSERT INTO addresses (address1, address2, city, state, zip, user_id) VALUES('123 Pine St.', 'apt 31', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id) VALUES('456 Brook St.', 'apt 21', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('23 Grove St.', 'apt 32', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('143 Madison St.', 'apt 34', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('153 Creek St.', 'apt 35', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('163 Gorge St.', 'apt 36', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('173 Far Side.', 'apt 37', 'Springfield', 'IL', '60606', 2);"
);
} else if (table.equals("legacy_universities")) {
statements = Arrays.asList(
"INSERT INTO legacy_universities VALUES(1, 'DePaul', '123 Pine St.', 'apt 3B', 'Springfield', 'IL', '60606');"
);
} else if (table.equals("libraries")) {
statements = Arrays.asList(
"INSERT INTO libraries (address, city, state ) VALUES('124 Pine Street', 'St. Raphael', 'California');",
"INSERT INTO libraries (address, city, state ) VALUES('345 Burlington Blvd', 'Springfield', 'Il');"
);
} else if (table.equals("books")) {
statements = Arrays.asList(
"INSERT INTO books (title, author, isbn, lib_id ) VALUES('All Quiet on Western Front', 'Eric Remarque', '123', 1);",
"INSERT INTO books (title, author, isbn, lib_id ) VALUES('12 Chairs', 'Ilf, Petrov', '122', 1);"
);
} else if (table.equals("readers")) {
statements = Arrays.asList(
"INSERT INTO readers VALUES(1, 'John', 'Smith', 1);",
"INSERT INTO readers VALUES(2, 'John', 'Doe', 1);",
"INSERT INTO readers VALUES(3, 'Igor', 'Polevoy', 2);"
);
} else if (table.equals("animals")) {
statements = Arrays.asList(
"INSERT INTO animals VALUES(1, 'frog');"
);
} else if (table.equals("patients")) {
statements = Arrays.asList(
"INSERT INTO patients (first_name , last_name ) VALUES('Jim', 'Cary');",
"INSERT INTO patients (first_name , last_name ) VALUES('John', 'Carpenter');"
);
} else if (table.equals("doctors")) {
statements = Arrays.asList(
"INSERT INTO doctors (first_name, last_name, discipline) VALUES('John', 'Doe', 'otholaringology');",
"INSERT INTO doctors (first_name, last_name, discipline) VALUES('Hellen', 'Hunt', 'dentistry');"
);
} else if (table.equals("doctors_patients")) {
statements = Arrays.asList(
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(1, 2);",
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(1, 1);",
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(2, 1);"
);
} else if (table.equals("students")) {
statements = Arrays.asList(
"INSERT INTO students (first_name, last_name, dob) VALUES('Jim', 'Cary', '1965-12-01');",
"INSERT INTO students (first_name, last_name, dob) VALUES('John', 'Carpenter', '1979-12-01');"
);
} else if (table.equals("courses")) {
statements = Arrays.asList(
"INSERT INTO courses VALUES(1, 'Functional programming 101');",
"INSERT INTO courses VALUES(2, 'data structures 415');"
);
} else if (table.equals("registrations")) {
statements = Arrays.asList(
"INSERT INTO registrations VALUES(1, 1, 2);",
"INSERT INTO registrations VALUES(2, 1, 1);",
"INSERT INTO registrations VALUES(3, 2, 1);"
);
} else if (table.equals("items")) {
statements = Arrays.asList(
);
} else if (table.equals("articles")) {
statements = Arrays.asList(
"INSERT INTO articles VALUES(1, 'ActiveJDBC basics', 'this is a test content of the article');",
"INSERT INTO articles VALUES(2, 'ActiveJDBC polymorphic associations', 'Polymorphic associations are...');"
);
} else if (table.equals("posts")) {
statements = Arrays.asList(
"INSERT INTO posts VALUES(1, 'Who gets up early in the morning... is tired all day', 'this is to explain that ...sleeping in is actually really good...');",
"INSERT INTO posts VALUES(2, 'Thou shalt not thread', 'Suns strategy for threading inside J2EE is a bit... insane...');"
);
} else if (table.equals("comments")) {
statements = Arrays.asList();
} else if (table.equals("fruits")) {
statements = Arrays.asList();
} else if (table.equals("vegetables")) {
statements = Arrays.asList();
} else if (table.equals("plants")) {
statements = Arrays.asList();
} else if (table.equals("pages")) {
statements = Arrays.asList();
} else if (table.equals("watermelons")) {
statements = Arrays.asList();
} else if (table.equals("motherboards")) {
statements = Arrays.asList(
- "INSERT INTO motherboards VALUES(1,'motherboardOne');"
+ "INSERT INTO motherboards (description) VALUES('motherboardOne');"
);
} else if (table.equals("keyboards")) {
statements = Arrays.asList(
- "INSERT INTO keyboards VALUES(1,'keyboard-us');"
+ "INSERT INTO keyboards (description) VALUES('keyboard-us');"
);
} else if (table.equals("computers")) {
statements = Arrays.asList(
- "INSERT INTO computers VALUES(1,'ComputerX',1,1);"
+ "INSERT INTO computers (description, mother_id, key_id) VALUES('ComputerX',1,1);"
);
} else {
throw new IllegalArgumentException("no statements for: " + table);
}
ArrayList<String> all = new ArrayList<String>();
all.add("DELETE FROM " + table + ";");
if(table.equals("animals")){
all.add("UPDATE dual SET next_val = SETVAL('animals_animal_id_seq', 1, FALSE);");
}else{
all.add("UPDATE dual SET next_val = SETVAL('" + table + "_id_seq', 1, FALSE);");
}
all.addAll(statements);
return all;
}
}
| false | true | public List<String> getStatements(String table) {
List<String> statements = new ArrayList<String>();
if (table.equals("people")) {
statements = Arrays.asList(
"INSERT INTO people ( name, last_name, dob, graduation_date, created_at, updated_at) VALUES('John', 'Smith', '1934-12-01', '1954-12-01', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Leylah', 'Jonston', '1954-04-03', '1974-04-03', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Muhammad', 'Ali', '1943-01-04', '1963-01-04', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Joe', 'Pesci', '1944-02-23','1964-02-23', now(), now());"
);
} else if (table.equals("accounts")) {
statements = Arrays.asList(
"INSERT INTO accounts VALUES(1, '123', 'checking', 9999.99, 1234.32);"
);
} else if (table.equals("temperatures")) {
statements = Arrays.asList(
"INSERT INTO temperatures VALUES(1, 30);"
);
} else if (table.equals("salaries")) {
statements = Arrays.asList(
"INSERT INTO salaries VALUES(1, 50000.00);"
);
} else if (table.equals("users")) {
statements = Arrays.asList(
"INSERT INTO users (first_name, last_name, email) VALUES('Marilyn', 'Monroe', '[email protected]');",
"INSERT INTO users (first_name, last_name, email) VALUES('John', 'Doe', '[email protected]');"
);
} else if (table.equals("addresses")) {
statements = Arrays.asList(
"INSERT INTO addresses (address1, address2, city, state, zip, user_id) VALUES('123 Pine St.', 'apt 31', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id) VALUES('456 Brook St.', 'apt 21', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('23 Grove St.', 'apt 32', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('143 Madison St.', 'apt 34', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('153 Creek St.', 'apt 35', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('163 Gorge St.', 'apt 36', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('173 Far Side.', 'apt 37', 'Springfield', 'IL', '60606', 2);"
);
} else if (table.equals("legacy_universities")) {
statements = Arrays.asList(
"INSERT INTO legacy_universities VALUES(1, 'DePaul', '123 Pine St.', 'apt 3B', 'Springfield', 'IL', '60606');"
);
} else if (table.equals("libraries")) {
statements = Arrays.asList(
"INSERT INTO libraries (address, city, state ) VALUES('124 Pine Street', 'St. Raphael', 'California');",
"INSERT INTO libraries (address, city, state ) VALUES('345 Burlington Blvd', 'Springfield', 'Il');"
);
} else if (table.equals("books")) {
statements = Arrays.asList(
"INSERT INTO books (title, author, isbn, lib_id ) VALUES('All Quiet on Western Front', 'Eric Remarque', '123', 1);",
"INSERT INTO books (title, author, isbn, lib_id ) VALUES('12 Chairs', 'Ilf, Petrov', '122', 1);"
);
} else if (table.equals("readers")) {
statements = Arrays.asList(
"INSERT INTO readers VALUES(1, 'John', 'Smith', 1);",
"INSERT INTO readers VALUES(2, 'John', 'Doe', 1);",
"INSERT INTO readers VALUES(3, 'Igor', 'Polevoy', 2);"
);
} else if (table.equals("animals")) {
statements = Arrays.asList(
"INSERT INTO animals VALUES(1, 'frog');"
);
} else if (table.equals("patients")) {
statements = Arrays.asList(
"INSERT INTO patients (first_name , last_name ) VALUES('Jim', 'Cary');",
"INSERT INTO patients (first_name , last_name ) VALUES('John', 'Carpenter');"
);
} else if (table.equals("doctors")) {
statements = Arrays.asList(
"INSERT INTO doctors (first_name, last_name, discipline) VALUES('John', 'Doe', 'otholaringology');",
"INSERT INTO doctors (first_name, last_name, discipline) VALUES('Hellen', 'Hunt', 'dentistry');"
);
} else if (table.equals("doctors_patients")) {
statements = Arrays.asList(
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(1, 2);",
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(1, 1);",
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(2, 1);"
);
} else if (table.equals("students")) {
statements = Arrays.asList(
"INSERT INTO students (first_name, last_name, dob) VALUES('Jim', 'Cary', '1965-12-01');",
"INSERT INTO students (first_name, last_name, dob) VALUES('John', 'Carpenter', '1979-12-01');"
);
} else if (table.equals("courses")) {
statements = Arrays.asList(
"INSERT INTO courses VALUES(1, 'Functional programming 101');",
"INSERT INTO courses VALUES(2, 'data structures 415');"
);
} else if (table.equals("registrations")) {
statements = Arrays.asList(
"INSERT INTO registrations VALUES(1, 1, 2);",
"INSERT INTO registrations VALUES(2, 1, 1);",
"INSERT INTO registrations VALUES(3, 2, 1);"
);
} else if (table.equals("items")) {
statements = Arrays.asList(
);
} else if (table.equals("articles")) {
statements = Arrays.asList(
"INSERT INTO articles VALUES(1, 'ActiveJDBC basics', 'this is a test content of the article');",
"INSERT INTO articles VALUES(2, 'ActiveJDBC polymorphic associations', 'Polymorphic associations are...');"
);
} else if (table.equals("posts")) {
statements = Arrays.asList(
"INSERT INTO posts VALUES(1, 'Who gets up early in the morning... is tired all day', 'this is to explain that ...sleeping in is actually really good...');",
"INSERT INTO posts VALUES(2, 'Thou shalt not thread', 'Suns strategy for threading inside J2EE is a bit... insane...');"
);
} else if (table.equals("comments")) {
statements = Arrays.asList();
} else if (table.equals("fruits")) {
statements = Arrays.asList();
} else if (table.equals("vegetables")) {
statements = Arrays.asList();
} else if (table.equals("plants")) {
statements = Arrays.asList();
} else if (table.equals("pages")) {
statements = Arrays.asList();
} else if (table.equals("watermelons")) {
statements = Arrays.asList();
} else if (table.equals("motherboards")) {
statements = Arrays.asList(
"INSERT INTO motherboards VALUES(1,'motherboardOne');"
);
} else if (table.equals("keyboards")) {
statements = Arrays.asList(
"INSERT INTO keyboards VALUES(1,'keyboard-us');"
);
} else if (table.equals("computers")) {
statements = Arrays.asList(
"INSERT INTO computers VALUES(1,'ComputerX',1,1);"
);
} else {
throw new IllegalArgumentException("no statements for: " + table);
}
ArrayList<String> all = new ArrayList<String>();
all.add("DELETE FROM " + table + ";");
if(table.equals("animals")){
all.add("UPDATE dual SET next_val = SETVAL('animals_animal_id_seq', 1, FALSE);");
}else{
all.add("UPDATE dual SET next_val = SETVAL('" + table + "_id_seq', 1, FALSE);");
}
all.addAll(statements);
return all;
}
| public List<String> getStatements(String table) {
List<String> statements = new ArrayList<String>();
if (table.equals("people")) {
statements = Arrays.asList(
"INSERT INTO people ( name, last_name, dob, graduation_date, created_at, updated_at) VALUES('John', 'Smith', '1934-12-01', '1954-12-01', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Leylah', 'Jonston', '1954-04-03', '1974-04-03', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Muhammad', 'Ali', '1943-01-04', '1963-01-04', now(), now());",
"INSERT INTO people (name, last_name, dob, graduation_date, created_at, updated_at) values('Joe', 'Pesci', '1944-02-23','1964-02-23', now(), now());"
);
} else if (table.equals("accounts")) {
statements = Arrays.asList(
"INSERT INTO accounts VALUES(1, '123', 'checking', 9999.99, 1234.32);"
);
} else if (table.equals("temperatures")) {
statements = Arrays.asList(
"INSERT INTO temperatures VALUES(1, 30);"
);
} else if (table.equals("salaries")) {
statements = Arrays.asList(
"INSERT INTO salaries VALUES(1, 50000.00);"
);
} else if (table.equals("users")) {
statements = Arrays.asList(
"INSERT INTO users (first_name, last_name, email) VALUES('Marilyn', 'Monroe', '[email protected]');",
"INSERT INTO users (first_name, last_name, email) VALUES('John', 'Doe', '[email protected]');"
);
} else if (table.equals("addresses")) {
statements = Arrays.asList(
"INSERT INTO addresses (address1, address2, city, state, zip, user_id) VALUES('123 Pine St.', 'apt 31', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id) VALUES('456 Brook St.', 'apt 21', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('23 Grove St.', 'apt 32', 'Springfield', 'IL', '60606', 1);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('143 Madison St.', 'apt 34', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('153 Creek St.', 'apt 35', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('163 Gorge St.', 'apt 36', 'Springfield', 'IL', '60606', 2);",
"INSERT INTO addresses (address1, address2, city, state, zip, user_id ) VALUES('173 Far Side.', 'apt 37', 'Springfield', 'IL', '60606', 2);"
);
} else if (table.equals("legacy_universities")) {
statements = Arrays.asList(
"INSERT INTO legacy_universities VALUES(1, 'DePaul', '123 Pine St.', 'apt 3B', 'Springfield', 'IL', '60606');"
);
} else if (table.equals("libraries")) {
statements = Arrays.asList(
"INSERT INTO libraries (address, city, state ) VALUES('124 Pine Street', 'St. Raphael', 'California');",
"INSERT INTO libraries (address, city, state ) VALUES('345 Burlington Blvd', 'Springfield', 'Il');"
);
} else if (table.equals("books")) {
statements = Arrays.asList(
"INSERT INTO books (title, author, isbn, lib_id ) VALUES('All Quiet on Western Front', 'Eric Remarque', '123', 1);",
"INSERT INTO books (title, author, isbn, lib_id ) VALUES('12 Chairs', 'Ilf, Petrov', '122', 1);"
);
} else if (table.equals("readers")) {
statements = Arrays.asList(
"INSERT INTO readers VALUES(1, 'John', 'Smith', 1);",
"INSERT INTO readers VALUES(2, 'John', 'Doe', 1);",
"INSERT INTO readers VALUES(3, 'Igor', 'Polevoy', 2);"
);
} else if (table.equals("animals")) {
statements = Arrays.asList(
"INSERT INTO animals VALUES(1, 'frog');"
);
} else if (table.equals("patients")) {
statements = Arrays.asList(
"INSERT INTO patients (first_name , last_name ) VALUES('Jim', 'Cary');",
"INSERT INTO patients (first_name , last_name ) VALUES('John', 'Carpenter');"
);
} else if (table.equals("doctors")) {
statements = Arrays.asList(
"INSERT INTO doctors (first_name, last_name, discipline) VALUES('John', 'Doe', 'otholaringology');",
"INSERT INTO doctors (first_name, last_name, discipline) VALUES('Hellen', 'Hunt', 'dentistry');"
);
} else if (table.equals("doctors_patients")) {
statements = Arrays.asList(
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(1, 2);",
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(1, 1);",
"INSERT INTO doctors_patients (doctor_id, patient_id ) VALUES(2, 1);"
);
} else if (table.equals("students")) {
statements = Arrays.asList(
"INSERT INTO students (first_name, last_name, dob) VALUES('Jim', 'Cary', '1965-12-01');",
"INSERT INTO students (first_name, last_name, dob) VALUES('John', 'Carpenter', '1979-12-01');"
);
} else if (table.equals("courses")) {
statements = Arrays.asList(
"INSERT INTO courses VALUES(1, 'Functional programming 101');",
"INSERT INTO courses VALUES(2, 'data structures 415');"
);
} else if (table.equals("registrations")) {
statements = Arrays.asList(
"INSERT INTO registrations VALUES(1, 1, 2);",
"INSERT INTO registrations VALUES(2, 1, 1);",
"INSERT INTO registrations VALUES(3, 2, 1);"
);
} else if (table.equals("items")) {
statements = Arrays.asList(
);
} else if (table.equals("articles")) {
statements = Arrays.asList(
"INSERT INTO articles VALUES(1, 'ActiveJDBC basics', 'this is a test content of the article');",
"INSERT INTO articles VALUES(2, 'ActiveJDBC polymorphic associations', 'Polymorphic associations are...');"
);
} else if (table.equals("posts")) {
statements = Arrays.asList(
"INSERT INTO posts VALUES(1, 'Who gets up early in the morning... is tired all day', 'this is to explain that ...sleeping in is actually really good...');",
"INSERT INTO posts VALUES(2, 'Thou shalt not thread', 'Suns strategy for threading inside J2EE is a bit... insane...');"
);
} else if (table.equals("comments")) {
statements = Arrays.asList();
} else if (table.equals("fruits")) {
statements = Arrays.asList();
} else if (table.equals("vegetables")) {
statements = Arrays.asList();
} else if (table.equals("plants")) {
statements = Arrays.asList();
} else if (table.equals("pages")) {
statements = Arrays.asList();
} else if (table.equals("watermelons")) {
statements = Arrays.asList();
} else if (table.equals("motherboards")) {
statements = Arrays.asList(
"INSERT INTO motherboards (description) VALUES('motherboardOne');"
);
} else if (table.equals("keyboards")) {
statements = Arrays.asList(
"INSERT INTO keyboards (description) VALUES('keyboard-us');"
);
} else if (table.equals("computers")) {
statements = Arrays.asList(
"INSERT INTO computers (description, mother_id, key_id) VALUES('ComputerX',1,1);"
);
} else {
throw new IllegalArgumentException("no statements for: " + table);
}
ArrayList<String> all = new ArrayList<String>();
all.add("DELETE FROM " + table + ";");
if(table.equals("animals")){
all.add("UPDATE dual SET next_val = SETVAL('animals_animal_id_seq', 1, FALSE);");
}else{
all.add("UPDATE dual SET next_val = SETVAL('" + table + "_id_seq', 1, FALSE);");
}
all.addAll(statements);
return all;
}
|
diff --git a/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java b/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java
index 55bd66b8..aec44c8e 100644
--- a/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java
+++ b/src/test/cli/cloudify/InternalUSMPuServiceDownTest.java
@@ -1,179 +1,179 @@
package test.cli.cloudify;
import static org.testng.AssertJUnit.fail;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpStatus;
import org.cloudifysource.dsl.internal.packaging.PackagingException;
import org.cloudifysource.dsl.utils.ServiceUtils;
import org.cloudifysource.usm.USMException;
import org.cloudifysource.usm.shutdown.DefaultProcessKiller;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.machine.Machine;
import org.openspaces.admin.pu.DeploymentStatus;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.ProcessingUnitInstance;
import org.openspaces.admin.pu.events.ProcessingUnitInstanceLifecycleEventListener;
import org.openspaces.pu.service.CustomServiceMonitors;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import test.usm.USMTestUtils;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import framework.utils.LogUtils;
import framework.utils.ProcessingUnitUtils;
import framework.utils.ScriptUtils;
import groovy.util.ConfigObject;
import groovy.util.ConfigSlurper;
public class InternalUSMPuServiceDownTest extends AbstractLocalCloudTest {
ProcessingUnit tomcat;
Long tomcatPId;
Machine machineA;
WebClient client;
private final String TOMCAT_URL = "http://127.0.0.1:8080";
@Override
@BeforeMethod
public void beforeTest() {
super.beforeTest();
client = new WebClient(BrowserVersion.getDefault());
}
@SuppressWarnings("deprecation")
@Test(timeOut = DEFAULT_TEST_TIMEOUT * 2, groups = "1", enabled = true)
public void tomcatServiceDownAndCorruptedTest() throws IOException, InterruptedException, PackagingException {
String serviceDir = ScriptUtils.getBuildPath() + "/recipes/services/tomcat";
String command = "connect " + this.restUrl + ";" + "install-service " + "--verbose -timeout 10 " + serviceDir;
try {
LogUtils.log("installing tomcat service using Cli");
CommandTestUtils.runCommandAndWait(command);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.log("Retrieving tomcat process pid from admin");
tomcat = admin.getProcessingUnits().waitFor(ServiceUtils.getAbsolutePUName("default", "tomcat"), 10, TimeUnit.SECONDS);
assertNotNull(tomcat);
assertTrue("USM Service state is not RUNNING", USMTestUtils.waitForPuRunningState("default.tomcat", 100, TimeUnit.SECONDS, admin));
ProcessingUnitUtils.waitForDeploymentStatus(tomcat, DeploymentStatus.INTACT);
assertTrue(tomcat.getStatus().equals(DeploymentStatus.INTACT));
ProcessingUnitInstance tomcatInstance = tomcat.getInstances()[0];
assertTrue("Tomcat instance is not in RUNNING State", USMTestUtils.waitForPuRunningState("default.tomcat", 60, TimeUnit.SECONDS, admin));
CustomServiceMonitors customServiceDetails = (CustomServiceMonitors) tomcatInstance.getStatistics().getMonitors().get("USM");
GridServiceContainer container = tomcatInstance.getGridServiceContainer();
machineA = container.getMachine();
- tomcatPId = (Long) customServiceDetails.getMonitors().get("Actual Process ID");
+ tomcatPId = (Long) customServiceDetails.getMonitors().get("USM_Actual Process ID");
final CountDownLatch removed = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(2);
LogUtils.log("adding a lifecycle listener to tomcat pu");
ProcessingUnitInstanceLifecycleEventListener eventListener = new ProcessingUnitInstanceLifecycleEventListener() {
@Override
public void processingUnitInstanceRemoved(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been removed due to tomcat failure");
removed.countDown();
}
@Override
public void processingUnitInstanceAdded(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been added");
added.countDown();
}
};
tomcat.addLifecycleListener(eventListener);
String pathToTomcat;
LogUtils.log("deleting catalina.sh/bat from pu folder");
ConfigObject tomcatConfig = new ConfigSlurper().parse(new File(serviceDir, "tomcat.properties").toURI().toURL());
String tomcatVersion = (String) tomcatConfig.get("version");
String catalinaPath = "/work/processing-units/default_tomcat_1/ext/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
String filePath = ScriptUtils.getBuildPath()+ catalinaPath;
if (isWindows()) {
pathToTomcat = filePath + "bat";
}
else {
pathToTomcat = filePath + "sh";
}
File tomcatRun = new File(pathToTomcat);
assertTrue("failed while deleting file: " + tomcatRun, tomcatRun.delete());
LogUtils.log("killing tomcat process : " + tomcatPId);
DefaultProcessKiller dpk = new DefaultProcessKiller();
try {
dpk.killProcess(tomcatPId);
} catch (USMException e) {
AssertFail("failed to kill tomcat process with pid: " + tomcatPId);
}
int responseCode = getResponseCode(TOMCAT_URL);
assertTrue("Tomcat service is still running. Request returned response code: " + responseCode, HttpStatus.SC_NOT_FOUND == responseCode);
LogUtils.log("waiting for tomcat pu instances to decrease");
assertTrue("Tomcat PU instance was not decresed", removed.await(240, TimeUnit.SECONDS));
LogUtils.log("waiting for tomcat pu instances to increase");
added.await(60 * 6, TimeUnit.SECONDS);
assertTrue("ProcessingUnitInstanceAdded event has not been fired", added.getCount() == 0);
LogUtils.log("verifiying tomcat service in running");
assertTomcatPageExists(client);
LogUtils.log("all's well that ends well :)");
}
private boolean isWindows() {
return (System.getenv("windir") != null);
}
private void assertTomcatPageExists(WebClient client) {
HtmlPage page = null;
try {
page = client.getPage("http://" + machineA.getHostAddress() + ":8080");
} catch (IOException e) {
fail(e.getMessage());
}
assertEquals("OK", page.getWebResponse().getStatusMessage());
}
//if service is down, this method will return a 404 not found exception.
private int getResponseCode(String urlString) throws IOException{
URL url = new URL ( urlString );
URLConnection connection = url.openConnection();
try {
connection.connect();
}catch (ConnectException e){
LogUtils.log("The connection to " + urlString + " has failed.");
return HttpStatus.SC_NOT_FOUND;
}
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode();
return code;
}
}
| true | true | public void tomcatServiceDownAndCorruptedTest() throws IOException, InterruptedException, PackagingException {
String serviceDir = ScriptUtils.getBuildPath() + "/recipes/services/tomcat";
String command = "connect " + this.restUrl + ";" + "install-service " + "--verbose -timeout 10 " + serviceDir;
try {
LogUtils.log("installing tomcat service using Cli");
CommandTestUtils.runCommandAndWait(command);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.log("Retrieving tomcat process pid from admin");
tomcat = admin.getProcessingUnits().waitFor(ServiceUtils.getAbsolutePUName("default", "tomcat"), 10, TimeUnit.SECONDS);
assertNotNull(tomcat);
assertTrue("USM Service state is not RUNNING", USMTestUtils.waitForPuRunningState("default.tomcat", 100, TimeUnit.SECONDS, admin));
ProcessingUnitUtils.waitForDeploymentStatus(tomcat, DeploymentStatus.INTACT);
assertTrue(tomcat.getStatus().equals(DeploymentStatus.INTACT));
ProcessingUnitInstance tomcatInstance = tomcat.getInstances()[0];
assertTrue("Tomcat instance is not in RUNNING State", USMTestUtils.waitForPuRunningState("default.tomcat", 60, TimeUnit.SECONDS, admin));
CustomServiceMonitors customServiceDetails = (CustomServiceMonitors) tomcatInstance.getStatistics().getMonitors().get("USM");
GridServiceContainer container = tomcatInstance.getGridServiceContainer();
machineA = container.getMachine();
tomcatPId = (Long) customServiceDetails.getMonitors().get("Actual Process ID");
final CountDownLatch removed = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(2);
LogUtils.log("adding a lifecycle listener to tomcat pu");
ProcessingUnitInstanceLifecycleEventListener eventListener = new ProcessingUnitInstanceLifecycleEventListener() {
@Override
public void processingUnitInstanceRemoved(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been removed due to tomcat failure");
removed.countDown();
}
@Override
public void processingUnitInstanceAdded(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been added");
added.countDown();
}
};
tomcat.addLifecycleListener(eventListener);
String pathToTomcat;
LogUtils.log("deleting catalina.sh/bat from pu folder");
ConfigObject tomcatConfig = new ConfigSlurper().parse(new File(serviceDir, "tomcat.properties").toURI().toURL());
String tomcatVersion = (String) tomcatConfig.get("version");
String catalinaPath = "/work/processing-units/default_tomcat_1/ext/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
String filePath = ScriptUtils.getBuildPath()+ catalinaPath;
if (isWindows()) {
pathToTomcat = filePath + "bat";
}
else {
pathToTomcat = filePath + "sh";
}
File tomcatRun = new File(pathToTomcat);
assertTrue("failed while deleting file: " + tomcatRun, tomcatRun.delete());
LogUtils.log("killing tomcat process : " + tomcatPId);
DefaultProcessKiller dpk = new DefaultProcessKiller();
try {
dpk.killProcess(tomcatPId);
} catch (USMException e) {
AssertFail("failed to kill tomcat process with pid: " + tomcatPId);
}
int responseCode = getResponseCode(TOMCAT_URL);
assertTrue("Tomcat service is still running. Request returned response code: " + responseCode, HttpStatus.SC_NOT_FOUND == responseCode);
LogUtils.log("waiting for tomcat pu instances to decrease");
assertTrue("Tomcat PU instance was not decresed", removed.await(240, TimeUnit.SECONDS));
LogUtils.log("waiting for tomcat pu instances to increase");
added.await(60 * 6, TimeUnit.SECONDS);
assertTrue("ProcessingUnitInstanceAdded event has not been fired", added.getCount() == 0);
LogUtils.log("verifiying tomcat service in running");
assertTomcatPageExists(client);
LogUtils.log("all's well that ends well :)");
}
| public void tomcatServiceDownAndCorruptedTest() throws IOException, InterruptedException, PackagingException {
String serviceDir = ScriptUtils.getBuildPath() + "/recipes/services/tomcat";
String command = "connect " + this.restUrl + ";" + "install-service " + "--verbose -timeout 10 " + serviceDir;
try {
LogUtils.log("installing tomcat service using Cli");
CommandTestUtils.runCommandAndWait(command);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
LogUtils.log("Retrieving tomcat process pid from admin");
tomcat = admin.getProcessingUnits().waitFor(ServiceUtils.getAbsolutePUName("default", "tomcat"), 10, TimeUnit.SECONDS);
assertNotNull(tomcat);
assertTrue("USM Service state is not RUNNING", USMTestUtils.waitForPuRunningState("default.tomcat", 100, TimeUnit.SECONDS, admin));
ProcessingUnitUtils.waitForDeploymentStatus(tomcat, DeploymentStatus.INTACT);
assertTrue(tomcat.getStatus().equals(DeploymentStatus.INTACT));
ProcessingUnitInstance tomcatInstance = tomcat.getInstances()[0];
assertTrue("Tomcat instance is not in RUNNING State", USMTestUtils.waitForPuRunningState("default.tomcat", 60, TimeUnit.SECONDS, admin));
CustomServiceMonitors customServiceDetails = (CustomServiceMonitors) tomcatInstance.getStatistics().getMonitors().get("USM");
GridServiceContainer container = tomcatInstance.getGridServiceContainer();
machineA = container.getMachine();
tomcatPId = (Long) customServiceDetails.getMonitors().get("USM_Actual Process ID");
final CountDownLatch removed = new CountDownLatch(1);
final CountDownLatch added = new CountDownLatch(2);
LogUtils.log("adding a lifecycle listener to tomcat pu");
ProcessingUnitInstanceLifecycleEventListener eventListener = new ProcessingUnitInstanceLifecycleEventListener() {
@Override
public void processingUnitInstanceRemoved(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been removed due to tomcat failure");
removed.countDown();
}
@Override
public void processingUnitInstanceAdded(
ProcessingUnitInstance processingUnitInstance) {
LogUtils.log("USM processing unit instance has been added");
added.countDown();
}
};
tomcat.addLifecycleListener(eventListener);
String pathToTomcat;
LogUtils.log("deleting catalina.sh/bat from pu folder");
ConfigObject tomcatConfig = new ConfigSlurper().parse(new File(serviceDir, "tomcat.properties").toURI().toURL());
String tomcatVersion = (String) tomcatConfig.get("version");
String catalinaPath = "/work/processing-units/default_tomcat_1/ext/apache-tomcat-" + tomcatVersion + "/bin/catalina.";
String filePath = ScriptUtils.getBuildPath()+ catalinaPath;
if (isWindows()) {
pathToTomcat = filePath + "bat";
}
else {
pathToTomcat = filePath + "sh";
}
File tomcatRun = new File(pathToTomcat);
assertTrue("failed while deleting file: " + tomcatRun, tomcatRun.delete());
LogUtils.log("killing tomcat process : " + tomcatPId);
DefaultProcessKiller dpk = new DefaultProcessKiller();
try {
dpk.killProcess(tomcatPId);
} catch (USMException e) {
AssertFail("failed to kill tomcat process with pid: " + tomcatPId);
}
int responseCode = getResponseCode(TOMCAT_URL);
assertTrue("Tomcat service is still running. Request returned response code: " + responseCode, HttpStatus.SC_NOT_FOUND == responseCode);
LogUtils.log("waiting for tomcat pu instances to decrease");
assertTrue("Tomcat PU instance was not decresed", removed.await(240, TimeUnit.SECONDS));
LogUtils.log("waiting for tomcat pu instances to increase");
added.await(60 * 6, TimeUnit.SECONDS);
assertTrue("ProcessingUnitInstanceAdded event has not been fired", added.getCount() == 0);
LogUtils.log("verifiying tomcat service in running");
assertTomcatPageExists(client);
LogUtils.log("all's well that ends well :)");
}
|
diff --git a/src/video_engine/main/test/android_test/src/org/webrtc/videoengineapp/WebRTCDemo.java b/src/video_engine/main/test/android_test/src/org/webrtc/videoengineapp/WebRTCDemo.java
index b5bbc93b6..2d1331c26 100644
--- a/src/video_engine/main/test/android_test/src/org/webrtc/videoengineapp/WebRTCDemo.java
+++ b/src/video_engine/main/test/android_test/src/org/webrtc/videoengineapp/WebRTCDemo.java
@@ -1,996 +1,996 @@
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc.videoengineapp;
import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import org.webrtc.videoengine.ViERenderer;
import android.app.TabActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TabHost.TabSpec;
import android.view.OrientationEventListener;
public class WebRTCDemo extends TabActivity implements IViEAndroidCallback,
View.OnClickListener,
OnItemSelectedListener {
private ViEAndroidJavaAPI ViEAndroidAPI = null;
// remote renderer
private SurfaceView remoteSurfaceView = null;
// local renderer and camera
private SurfaceView svLocal = null;
// channel number
private int channel;
private int cameraId;
private int voiceChannel = -1;
// flags
private boolean viERunning = false;
private boolean voERunning = false;
// debug
private boolean enableTrace = false;
// Constant
private static final String TAG = "WEBRTC";
private static final int RECEIVE_CODEC_FRAMERATE = 15;
private static final int SEND_CODEC_FRAMERATE = 15;
private static final int INIT_BITRATE = 500;
private static final String LOOPBACK_IP = "127.0.0.1";
private int volumeLevel = 204;
private TabHost mTabHost = null;
private TabSpec mTabSpecConfig;
private TabSpec mTabSpecVideo;
private LinearLayout mLlRemoteSurface = null;
private LinearLayout mLlLocalSurface = null;
private Button btStartStopCall;
private Button btSwitchCamera;
// Global Settings
private CheckBox cbVideoSend;
private boolean enableVideoSend = true;
private CheckBox cbVideoReceive;
private boolean enableVideoReceive = true;
private boolean enableVideo = true;
private CheckBox cbVoice;
private boolean enableVoice = true;
private EditText etRemoteIp;
private String remoteIp = "";
private CheckBox cbLoopback;
private boolean loopbackMode = true;
private CheckBox cbStats;
private boolean isStatsOn = true;
private boolean useOpenGLRender = true;
// Video settings
private Spinner spCodecType;
private int codecType = 0;
private Spinner spCodecSize;
private int codecSizeWidth = 0;
private int codecSizeHeight = 0;
private TextView etVRxPort;
private int receivePortVideo = 11111;
private TextView etVTxPort;
private int destinationPortVideo = 11111;
private CheckBox cbEnableNack;
private boolean enableNack = false;
private CheckBox cbEnableVideoRTPDump;
// Audio settings
private Spinner spVoiceCodecType;
private int voiceCodecType = 0;
private TextView etARxPort;
private int receivePortVoice = 11113;
private TextView etATxPort;
private int destinationPortVoice = 11113;
private CheckBox cbEnableSpeaker;
private boolean enableSpeaker = false;
private CheckBox cbEnableAGC;
private boolean enableAGC = false;
private CheckBox cbEnableAECM;
private boolean enableAECM = false;
private CheckBox cbEnableNS;
private boolean enableNS = false;
private CheckBox cbEnableDebugAPM;
private CheckBox cbEnableVoiceRTPDump;
// Stats variables
private int frameRateI;
private int bitRateI;
private int packetLoss;
private int frameRateO;
private int bitRateO;
// Variable for storing variables
private String webrtcName = "/webrtc";
private String webrtcDebugDir = null;
private WakeLock wakeLock;
private boolean usingFrontCamera = true;
private String[] mVideoCodecsStrings = null;
private String[] mVideoCodecsSizeStrings = { "176x144", "320x240",
"352x288", "640x480" };
private String[] mVoiceCodecsStrings = null;
private OrientationEventListener orientationListener;
int currentOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
int currentCameraOrientation = 0;
private StatsView statsView = null;
public int GetCameraOrientation(int cameraOrientation) {
Display display = this.getWindowManager().getDefaultDisplay();
int displatyRotation = display.getRotation();
int degrees = 0;
switch (displatyRotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result=0;
if(cameraOrientation>180) {
result=(cameraOrientation + degrees) % 360;
}
else {
result=(cameraOrientation - degrees+360) % 360;
}
return result;
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int newRotation = GetCameraOrientation(currentCameraOrientation);
if (viERunning){
ViEAndroidAPI.SetRotation(cameraId,newRotation);
}
}
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Set screen orientation
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
PowerManager pm = (PowerManager)this.getSystemService(
Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
setContentView(R.layout.tabhost);
mTabHost = getTabHost();
// Main tab
mTabSpecVideo = mTabHost.newTabSpec("tab_video");
mTabSpecVideo.setIndicator("Main");
mTabSpecVideo.setContent(R.id.tab_video);
mTabHost.addTab(mTabSpecVideo);
// Shared config tab
mTabHost = getTabHost();
mTabSpecConfig = mTabHost.newTabSpec("tab_config");
mTabSpecConfig.setIndicator("Settings");
mTabSpecConfig.setContent(R.id.tab_config);
mTabHost.addTab(mTabSpecConfig);
TabSpec mTabv;
mTabv = mTabHost.newTabSpec("tab_vconfig");
mTabv.setIndicator("Video");
mTabv.setContent(R.id.tab_vconfig);
mTabHost.addTab(mTabv);
TabSpec mTaba;
mTaba = mTabHost.newTabSpec("tab_aconfig");
mTaba.setIndicator("Audio");
mTaba.setContent(R.id.tab_aconfig);
mTabHost.addTab(mTaba);
int childCount = mTabHost.getTabWidget().getChildCount();
for (int i=0; i<childCount; i++)
mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 50;
orientationListener =
new OrientationEventListener(this,SensorManager.SENSOR_DELAY_UI) {
public void onOrientationChanged (int orientation) {
if (orientation != ORIENTATION_UNKNOWN) {
currentOrientation = orientation;
}
}
};
orientationListener.enable ();
// Create a folder named webrtc in /scard for debugging
webrtcDebugDir = Environment.getExternalStorageDirectory().toString() +
webrtcName;
File webrtcDir = new File(webrtcDebugDir);
if (!webrtcDir.exists() && webrtcDir.mkdir() == false) {
Log.v(TAG, "Failed to create " + webrtcDebugDir);
}
else if (!webrtcDir.isDirectory()) {
Log.v(TAG, webrtcDebugDir + " exists but not a folder");
webrtcDebugDir = null;
}
StartMain();
return;
}
private class StatsView extends View{
public StatsView(Context context){
super(context);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint mLoadPaint = new Paint();
mLoadPaint.setAntiAlias(true);
mLoadPaint.setTextSize(16);
mLoadPaint.setARGB(255, 255, 255, 255);
String mLoadText;
mLoadText = "> " + frameRateI + " fps/" + bitRateI + "k bps/ " + packetLoss;
canvas.drawText(mLoadText, 4, 172, mLoadPaint);
mLoadText = "< " + frameRateO + " fps/ " + bitRateO + "k bps";
canvas.drawText(mLoadText, 4, 192, mLoadPaint);
updateDisplay();
}
void updateDisplay() {
invalidate();
}
}
private String GetLocalIpAddress() {
String localIPs = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr =
intf.getInetAddresses();
enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
localIPs +=
inetAddress.getHostAddress().toString() + " ";
// Set the remote ip address the same as
// the local ip address of the last netif
remoteIp = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return localIPs;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (viERunning) {
StopAll();
StartMain();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void StopAll() {
Log.d(TAG, "StopAll");
if (ViEAndroidAPI != null) {
if (voERunning) {
voERunning = false;
StopVoiceEngine();
}
if (viERunning) {
viERunning = false;
ViEAndroidAPI.StopRender(channel);
ViEAndroidAPI.StopReceive(channel);
ViEAndroidAPI.StopSend(channel);
ViEAndroidAPI.RemoveRemoteRenderer(channel);
ViEAndroidAPI.StopCamera(cameraId);
ViEAndroidAPI.Terminate();
mLlRemoteSurface.removeView(remoteSurfaceView);
mLlLocalSurface.removeView(svLocal);
remoteSurfaceView = null;
svLocal = null;
}
}
}
public class SpinnerAdapter extends ArrayAdapter<String> {
private String[] mCodecString = null;
public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
mCodecString = objects;
}
@Override public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
TextView label = (TextView)row.findViewById(R.id.spinner_row);
label.setText(mCodecString[position]);
return row;
}
}
private void StartMain() {
mTabHost.setCurrentTab(0);
mLlRemoteSurface = (LinearLayout) findViewById(R.id.llRemoteView);
mLlLocalSurface = (LinearLayout) findViewById(R.id.llLocalView);
if (null == ViEAndroidAPI)
ViEAndroidAPI = new ViEAndroidJavaAPI(this);
if (0 > SetupVoE() || 0 > ViEAndroidAPI.GetVideoEngine() ||
0 > ViEAndroidAPI.Init(enableTrace) ) {
// Show dialog
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("WebRTC Error");
alertDialog.setMessage("Can not init video engine.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
alertDialog.show();
}
btSwitchCamera = (Button)findViewById(R.id.btSwitchCamera);
btSwitchCamera.setOnClickListener(this);
btStartStopCall = (Button)findViewById(R.id.btStartStopCall);
btStartStopCall.setOnClickListener(this);
findViewById(R.id.btExit).setOnClickListener(this);
// cleaning
remoteSurfaceView = null;
svLocal = null;
// Video codec
mVideoCodecsStrings = ViEAndroidAPI.GetCodecs();
spCodecType = (Spinner)findViewById(R.id.spCodecType);
spCodecType.setOnItemSelectedListener(this);
spCodecType.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVideoCodecsStrings));
spCodecType.setSelection(0);
// Video Codec size
spCodecSize = (Spinner) findViewById(R.id.spCodecSize);
spCodecSize.setOnItemSelectedListener(this);
spCodecSize.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVideoCodecsSizeStrings));
spCodecSize.setSelection(0);
// Voice codec
mVoiceCodecsStrings = ViEAndroidAPI.VoE_GetCodecs();
spVoiceCodecType = (Spinner)findViewById(R.id.spVoiceCodecType);
spVoiceCodecType.setOnItemSelectedListener(this);
spVoiceCodecType.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVoiceCodecsStrings));
spVoiceCodecType.setSelection(0);
- // Find PCMU and use it
- for (int i=0; i<mVoiceCodecsStrings.length; ++i) {
- if (mVoiceCodecsStrings[i].contains("PCMU")) {
+ // Find ISAC and use it
+ for (int i = 0; i < mVoiceCodecsStrings.length; ++i) {
+ if (mVoiceCodecsStrings[i].contains("ISAC")) {
spVoiceCodecType.setSelection(i);
break;
}
}
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group1);
radioGroup.clearCheck();
if (useOpenGLRender == true) {
radioGroup.check(R.id.radio_opengl);
}
else {
radioGroup.check(R.id.radio_surface);
}
etRemoteIp = (EditText) findViewById(R.id.etRemoteIp);
etRemoteIp.setText(remoteIp);
cbLoopback = (CheckBox) findViewById(R.id.cbLoopback);
cbLoopback.setChecked(loopbackMode);
cbStats = (CheckBox) findViewById(R.id.cbStats);
cbStats.setChecked(isStatsOn);
cbVoice = (CheckBox) findViewById(R.id.cbVoice);
cbVoice.setChecked(enableVoice);
cbVideoSend = (CheckBox) findViewById(R.id.cbVideoSend);
cbVideoSend.setChecked(enableVideoSend);
cbVideoReceive = (CheckBox) findViewById(R.id.cbVideoReceive);
cbVideoReceive.setChecked(enableVideoReceive);
etVTxPort = (EditText) findViewById(R.id.etVTxPort);
etVTxPort.setText(Integer.toString(destinationPortVideo));
etVRxPort = (EditText) findViewById(R.id.etVRxPort);
etVRxPort.setText(Integer.toString(receivePortVideo));
etATxPort = (EditText) findViewById(R.id.etATxPort);
etATxPort.setText(Integer.toString(destinationPortVoice));
etARxPort = (EditText) findViewById(R.id.etARxPort);
etARxPort.setText(Integer.toString(receivePortVoice));
cbEnableNack = (CheckBox) findViewById(R.id.cbNack);
cbEnableNack.setChecked(enableNack);
cbEnableSpeaker = (CheckBox) findViewById(R.id.cbSpeaker);
cbEnableSpeaker.setChecked(enableSpeaker);
cbEnableAGC = (CheckBox) findViewById(R.id.cbAutoGainControl);
cbEnableAGC.setChecked(enableAGC);
cbEnableAECM = (CheckBox) findViewById(R.id.cbAECM);
cbEnableAECM.setChecked(enableAECM);
cbEnableNS = (CheckBox) findViewById(R.id.cbNoiseSuppression);
cbEnableNS.setChecked(enableNS);
cbEnableDebugAPM = (CheckBox) findViewById(R.id.cbDebugRecording);
cbEnableDebugAPM.setChecked(false); // Disable APM debugging by default
cbEnableVideoRTPDump = (CheckBox) findViewById(R.id.cbVideoRTPDump);
cbEnableVideoRTPDump.setChecked(false); // Disable Video RTP Dump
cbEnableVoiceRTPDump = (CheckBox) findViewById(R.id.cbVoiceRTPDump);
cbEnableVoiceRTPDump.setChecked(false); // Disable Voice RTP Dump
etRemoteIp.setOnClickListener(this);
cbLoopback.setOnClickListener(this);
cbStats.setOnClickListener(this);
cbEnableNack.setOnClickListener(this);
cbEnableSpeaker.setOnClickListener(this);
cbEnableAECM.setOnClickListener(this);
cbEnableAGC.setOnClickListener(this);
cbEnableNS.setOnClickListener(this);
cbEnableDebugAPM.setOnClickListener(this);
cbEnableVideoRTPDump.setOnClickListener(this);
cbEnableVoiceRTPDump.setOnClickListener(this);
if (loopbackMode) {
remoteIp = LOOPBACK_IP;
etRemoteIp.setText(remoteIp);
}
else {
GetLocalIpAddress();
etRemoteIp.setText(remoteIp);
}
// Read settings to refresh each configuration
ReadSettings();
}
private String GetRemoteIPString() {
return etRemoteIp.getText().toString();
}
private void StartCall() {
int ret = 0;
if (enableVoice) {
StartVoiceEngine();
}
if (enableVideo) {
if (enableVideoSend) {
// camera and preview surface
svLocal = ViERenderer.CreateLocalRenderer(this);
}
channel = ViEAndroidAPI.CreateChannel(voiceChannel);
ret = ViEAndroidAPI.SetLocalReceiver(channel,
receivePortVideo);
ret = ViEAndroidAPI.SetSendDestination(channel,
destinationPortVideo,
GetRemoteIPString());
if (enableVideoReceive) {
if(useOpenGLRender) {
Log.v(TAG, "Create OpenGL Render");
remoteSurfaceView = ViERenderer.CreateRenderer(this, true);
ret = ViEAndroidAPI.AddRemoteRenderer(channel, remoteSurfaceView);
}
else {
Log.v(TAG, "Create SurfaceView Render");
remoteSurfaceView = ViERenderer.CreateRenderer(this, false);
ret = ViEAndroidAPI.AddRemoteRenderer(channel, remoteSurfaceView);
}
ret = ViEAndroidAPI.SetReceiveCodec(channel,
codecType,
INIT_BITRATE,
codecSizeWidth,
codecSizeHeight,
RECEIVE_CODEC_FRAMERATE);
ret = ViEAndroidAPI.StartRender(channel);
ret = ViEAndroidAPI.StartReceive(channel);
}
if (enableVideoSend) {
currentCameraOrientation =
ViEAndroidAPI.GetCameraOrientation(usingFrontCamera?1:0);
ret = ViEAndroidAPI.SetSendCodec(channel, codecType, INIT_BITRATE,
codecSizeWidth, codecSizeHeight, SEND_CODEC_FRAMERATE);
int camId = ViEAndroidAPI.StartCamera(channel, usingFrontCamera?1:0);
if(camId > 0) {
cameraId = camId;
int neededRotation = GetCameraOrientation(currentCameraOrientation);
ViEAndroidAPI.SetRotation(cameraId, neededRotation);
}
else {
ret = camId;
}
ret = ViEAndroidAPI.StartSend(channel);
}
// TODO(leozwang): Add more options besides PLI, currently use pli
// as the default. Also check return value.
ret = ViEAndroidAPI.EnablePLI(channel, true);
ret = ViEAndroidAPI.SetCallback(channel, this);
if (enableVideoSend) {
if (mLlLocalSurface != null)
mLlLocalSurface.addView(svLocal);
}
if (enableVideoReceive) {
if (mLlRemoteSurface != null) {
mLlRemoteSurface.addView(remoteSurfaceView);
}
}
isStatsOn = cbStats.isChecked();
if (isStatsOn) {
AddStatsView();
}
else {
RemoveSatsView();
}
viERunning = true;
}
}
private void StopVoiceEngine() {
// Stop send
if (0 != ViEAndroidAPI.VoE_StopSend(voiceChannel)) {
Log.d(TAG, "VoE stop send failed");
}
// Stop listen
if (0 != ViEAndroidAPI.VoE_StopListen(voiceChannel)) {
Log.d(TAG, "VoE stop listen failed");
}
// Stop playout
if (0 != ViEAndroidAPI.VoE_StopPlayout(voiceChannel)) {
Log.d(TAG, "VoE stop playout failed");
}
if (0 != ViEAndroidAPI.VoE_DeleteChannel(voiceChannel)) {
Log.d(TAG, "VoE delete channel failed");
}
voiceChannel=-1;
// Terminate
if (0 != ViEAndroidAPI.VoE_Terminate()) {
Log.d(TAG, "VoE terminate failed");
}
}
private int SetupVoE() {
// Create VoiceEngine
// Error logging is done in native API wrapper
ViEAndroidAPI.VoE_Create();
// Initialize
if (0 != ViEAndroidAPI.VoE_Init(enableTrace)) {
Log.d(TAG, "VoE init failed");
return -1;
}
// Create channel
voiceChannel = ViEAndroidAPI.VoE_CreateChannel();
if (0 != voiceChannel) {
Log.d(TAG, "VoE create channel failed");
return -1;
}
// Suggest to use the voice call audio stream for hardware volume controls
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
return 0;
}
private int StartVoiceEngine() {
// Set local receiver
if (0 != ViEAndroidAPI.VoE_SetLocalReceiver(voiceChannel,
receivePortVoice)) {
Log.d(TAG, "VoE set local receiver failed");
}
if (0 != ViEAndroidAPI.VoE_StartListen(voiceChannel)) {
Log.d(TAG, "VoE start listen failed");
}
// Route audio
RouteAudio(enableSpeaker);
// set volume to default value
if (0 != ViEAndroidAPI.VoE_SetSpeakerVolume(volumeLevel)) {
Log.d(TAG, "VoE set speaker volume failed");
}
// Start playout
if (0 != ViEAndroidAPI.VoE_StartPlayout(voiceChannel)) {
Log.d(TAG, "VoE start playout failed");
}
if (0 != ViEAndroidAPI.VoE_SetSendDestination(voiceChannel,
destinationPortVoice,
GetRemoteIPString())) {
Log.d(TAG, "VoE set send destination failed");
}
if (0 != ViEAndroidAPI.VoE_SetSendCodec(voiceChannel, voiceCodecType)) {
Log.d(TAG, "VoE set send codec failed");
}
if (0 != ViEAndroidAPI.VoE_SetECStatus(enableAECM)) {
Log.d(TAG, "VoE set EC Status failed");
}
if (0 != ViEAndroidAPI.VoE_SetAGCStatus(enableAGC)) {
Log.d(TAG, "VoE set AGC Status failed");
}
if (0 != ViEAndroidAPI.VoE_SetNSStatus(enableNS)) {
Log.d(TAG, "VoE set NS Status failed");
}
if (0 != ViEAndroidAPI.VoE_StartSend(voiceChannel)) {
Log.d(TAG, "VoE start send failed");
}
voERunning = true;
return 0;
}
private void RouteAudio(boolean enableSpeaker) {
int sdkVersion = Integer.parseInt(android.os.Build.VERSION.SDK);
if (sdkVersion >= 5) {
AudioManager am =
(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(enableSpeaker);
}
else {
if (0 != ViEAndroidAPI.VoE_SetLoudspeakerStatus(enableSpeaker)) {
Log.d(TAG, "VoE set louspeaker status failed");
}
}
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btSwitchCamera:
if (usingFrontCamera ){
btSwitchCamera.setText(R.string.frontCamera);
}
else {
btSwitchCamera.setText(R.string.backCamera);
}
usingFrontCamera = !usingFrontCamera;
if (viERunning) {
currentCameraOrientation =
ViEAndroidAPI.GetCameraOrientation(usingFrontCamera?1:0);
ViEAndroidAPI.StopCamera(cameraId);
mLlLocalSurface.removeView(svLocal);
ViEAndroidAPI.StartCamera(channel,usingFrontCamera?1:0);
mLlLocalSurface.addView(svLocal);
int neededRotation = GetCameraOrientation(currentCameraOrientation);
ViEAndroidAPI.SetRotation(cameraId, neededRotation);
}
break;
case R.id.btStartStopCall:
ReadSettings();
if (viERunning || voERunning) {
StopAll();
wakeLock.release(); // release the wake lock
btStartStopCall.setText(R.string.startCall);
}
else if (enableVoice || enableVideo){
StartCall();
wakeLock.acquire(); // screen stay on during the call
btStartStopCall.setText(R.string.stopCall);
}
break;
case R.id.btExit:
StopAll();
finish();
break;
case R.id.cbLoopback:
loopbackMode = cbLoopback.isChecked();
if (loopbackMode) {
remoteIp = LOOPBACK_IP;
etRemoteIp.setText(LOOPBACK_IP);
}
else {
GetLocalIpAddress();
etRemoteIp.setText(remoteIp);
}
break;
case R.id.etRemoteIp:
remoteIp = etRemoteIp.getText().toString();
break;
case R.id.cbStats:
isStatsOn = cbStats.isChecked();
if (isStatsOn) {
AddStatsView();
}
else {
RemoveSatsView();
}
break;
case R.id.radio_surface:
useOpenGLRender = false;
break;
case R.id.radio_opengl:
useOpenGLRender = true;
break;
case R.id.cbNack:
enableNack = cbEnableNack.isChecked();
if (viERunning) {
ViEAndroidAPI.EnableNACK(channel, enableNack);
}
break;
case R.id.cbSpeaker:
enableSpeaker = cbEnableSpeaker.isChecked();
if (voERunning){
RouteAudio(enableSpeaker);
}
break;
case R.id.cbDebugRecording:
if(voERunning && webrtcDebugDir != null) {
if (cbEnableDebugAPM.isChecked() ) {
ViEAndroidAPI.VoE_StartDebugRecording(
webrtcDebugDir + String.format("/apm_%d.dat",
System.currentTimeMillis()));
}
else {
ViEAndroidAPI.VoE_StopDebugRecording();
}
}
break;
case R.id.cbVoiceRTPDump:
if(voERunning && webrtcDebugDir != null) {
if (cbEnableVoiceRTPDump.isChecked() ) {
ViEAndroidAPI.VoE_StartIncomingRTPDump(channel,
webrtcDebugDir + String.format("/voe_%d.rtp",
System.currentTimeMillis()));
}
else {
ViEAndroidAPI.VoE_StopIncomingRTPDump(channel);
}
}
break;
case R.id.cbVideoRTPDump:
if(viERunning && webrtcDebugDir != null) {
if (cbEnableVideoRTPDump.isChecked() ) {
ViEAndroidAPI.StartIncomingRTPDump(channel,
webrtcDebugDir + String.format("/vie_%d.rtp",
System.currentTimeMillis()));
}
else {
ViEAndroidAPI.StopIncomingRTPDump(channel);
}
}
break;
case R.id.cbAutoGainControl:
enableAGC=cbEnableAGC.isChecked();
if(voERunning) {
ViEAndroidAPI.VoE_SetAGCStatus(enableAGC);
}
break;
case R.id.cbNoiseSuppression:
enableNS=cbEnableNS.isChecked();
if(voERunning) {
ViEAndroidAPI.VoE_SetNSStatus(enableNS);
}
break;
case R.id.cbAECM:
enableAECM = cbEnableAECM.isChecked();
if (voERunning) {
ViEAndroidAPI.VoE_SetECStatus(enableAECM);
}
break;
}
}
private void ReadSettings() {
codecType = spCodecType.getSelectedItemPosition();
voiceCodecType = spVoiceCodecType.getSelectedItemPosition();
String sCodecSize = spCodecSize.getSelectedItem().toString();
String[] aCodecSize = sCodecSize.split("x");
codecSizeWidth = Integer.parseInt(aCodecSize[0]);
codecSizeHeight = Integer.parseInt(aCodecSize[1]);
loopbackMode = cbLoopback.isChecked();
enableVoice = cbVoice.isChecked();
enableVideoSend = cbVideoSend.isChecked();
enableVideoReceive = cbVideoReceive.isChecked();
enableVideo = enableVideoSend || enableVideoReceive;
destinationPortVideo =
Integer.parseInt(etVTxPort.getText().toString());
receivePortVideo =
Integer.parseInt(etVRxPort.getText().toString());
destinationPortVoice =
Integer.parseInt(etATxPort.getText().toString());
receivePortVoice =
Integer.parseInt(etARxPort.getText().toString());
enableNack = cbEnableNack.isChecked();
enableSpeaker = cbEnableSpeaker.isChecked();
enableAGC = cbEnableAGC.isChecked();
enableAECM = cbEnableAECM.isChecked();
enableNS = cbEnableNS.isChecked();
}
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
if ((adapterView == spCodecType || adapterView == spCodecSize) &&
viERunning) {
ReadSettings();
// change the codectype
if (enableVideoReceive) {
if (0 != ViEAndroidAPI.SetReceiveCodec(channel, codecType,
INIT_BITRATE, codecSizeWidth,
codecSizeHeight,
RECEIVE_CODEC_FRAMERATE))
Log.d(TAG, "ViE set receive codec failed");
}
if (enableVideoSend) {
if (0 != ViEAndroidAPI.SetSendCodec(channel, codecType,
INIT_BITRATE, codecSizeWidth, codecSizeHeight,
SEND_CODEC_FRAMERATE))
Log.d(TAG, "ViE set send codec failed");
}
}
else if ((adapterView == spVoiceCodecType) && voERunning) {
// change voice engine codec
ReadSettings();
if (0 != ViEAndroidAPI.VoE_SetSendCodec(voiceChannel, voiceCodecType)) {
Log.d(TAG, "VoE set send codec failed");
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
Log.d(TAG, "No setting selected");
}
public int UpdateStats(int in_frameRateI, int in_bitRateI, int in_packetLoss,
int in_frameRateO, int in_bitRateO) {
frameRateI = in_frameRateI;
bitRateI = in_bitRateI;
packetLoss = in_packetLoss;
frameRateO = in_frameRateO;
bitRateO = in_bitRateO;
return 0;
}
private void AddStatsView() {
if (statsView != null) {
return;
}
statsView = new StatsView(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.TOP;
params.setTitle("Load Average");
mTabHost.addView(statsView, params);
statsView.setBackgroundColor(0);
}
private void RemoveSatsView() {
mTabHost.removeView(statsView);
statsView = null;
}
}
| true | true | private void StartMain() {
mTabHost.setCurrentTab(0);
mLlRemoteSurface = (LinearLayout) findViewById(R.id.llRemoteView);
mLlLocalSurface = (LinearLayout) findViewById(R.id.llLocalView);
if (null == ViEAndroidAPI)
ViEAndroidAPI = new ViEAndroidJavaAPI(this);
if (0 > SetupVoE() || 0 > ViEAndroidAPI.GetVideoEngine() ||
0 > ViEAndroidAPI.Init(enableTrace) ) {
// Show dialog
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("WebRTC Error");
alertDialog.setMessage("Can not init video engine.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
alertDialog.show();
}
btSwitchCamera = (Button)findViewById(R.id.btSwitchCamera);
btSwitchCamera.setOnClickListener(this);
btStartStopCall = (Button)findViewById(R.id.btStartStopCall);
btStartStopCall.setOnClickListener(this);
findViewById(R.id.btExit).setOnClickListener(this);
// cleaning
remoteSurfaceView = null;
svLocal = null;
// Video codec
mVideoCodecsStrings = ViEAndroidAPI.GetCodecs();
spCodecType = (Spinner)findViewById(R.id.spCodecType);
spCodecType.setOnItemSelectedListener(this);
spCodecType.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVideoCodecsStrings));
spCodecType.setSelection(0);
// Video Codec size
spCodecSize = (Spinner) findViewById(R.id.spCodecSize);
spCodecSize.setOnItemSelectedListener(this);
spCodecSize.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVideoCodecsSizeStrings));
spCodecSize.setSelection(0);
// Voice codec
mVoiceCodecsStrings = ViEAndroidAPI.VoE_GetCodecs();
spVoiceCodecType = (Spinner)findViewById(R.id.spVoiceCodecType);
spVoiceCodecType.setOnItemSelectedListener(this);
spVoiceCodecType.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVoiceCodecsStrings));
spVoiceCodecType.setSelection(0);
// Find PCMU and use it
for (int i=0; i<mVoiceCodecsStrings.length; ++i) {
if (mVoiceCodecsStrings[i].contains("PCMU")) {
spVoiceCodecType.setSelection(i);
break;
}
}
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group1);
radioGroup.clearCheck();
if (useOpenGLRender == true) {
radioGroup.check(R.id.radio_opengl);
}
else {
radioGroup.check(R.id.radio_surface);
}
etRemoteIp = (EditText) findViewById(R.id.etRemoteIp);
etRemoteIp.setText(remoteIp);
cbLoopback = (CheckBox) findViewById(R.id.cbLoopback);
cbLoopback.setChecked(loopbackMode);
cbStats = (CheckBox) findViewById(R.id.cbStats);
cbStats.setChecked(isStatsOn);
cbVoice = (CheckBox) findViewById(R.id.cbVoice);
cbVoice.setChecked(enableVoice);
cbVideoSend = (CheckBox) findViewById(R.id.cbVideoSend);
cbVideoSend.setChecked(enableVideoSend);
cbVideoReceive = (CheckBox) findViewById(R.id.cbVideoReceive);
cbVideoReceive.setChecked(enableVideoReceive);
etVTxPort = (EditText) findViewById(R.id.etVTxPort);
etVTxPort.setText(Integer.toString(destinationPortVideo));
etVRxPort = (EditText) findViewById(R.id.etVRxPort);
etVRxPort.setText(Integer.toString(receivePortVideo));
etATxPort = (EditText) findViewById(R.id.etATxPort);
etATxPort.setText(Integer.toString(destinationPortVoice));
etARxPort = (EditText) findViewById(R.id.etARxPort);
etARxPort.setText(Integer.toString(receivePortVoice));
cbEnableNack = (CheckBox) findViewById(R.id.cbNack);
cbEnableNack.setChecked(enableNack);
cbEnableSpeaker = (CheckBox) findViewById(R.id.cbSpeaker);
cbEnableSpeaker.setChecked(enableSpeaker);
cbEnableAGC = (CheckBox) findViewById(R.id.cbAutoGainControl);
cbEnableAGC.setChecked(enableAGC);
cbEnableAECM = (CheckBox) findViewById(R.id.cbAECM);
cbEnableAECM.setChecked(enableAECM);
cbEnableNS = (CheckBox) findViewById(R.id.cbNoiseSuppression);
cbEnableNS.setChecked(enableNS);
cbEnableDebugAPM = (CheckBox) findViewById(R.id.cbDebugRecording);
cbEnableDebugAPM.setChecked(false); // Disable APM debugging by default
cbEnableVideoRTPDump = (CheckBox) findViewById(R.id.cbVideoRTPDump);
cbEnableVideoRTPDump.setChecked(false); // Disable Video RTP Dump
cbEnableVoiceRTPDump = (CheckBox) findViewById(R.id.cbVoiceRTPDump);
cbEnableVoiceRTPDump.setChecked(false); // Disable Voice RTP Dump
etRemoteIp.setOnClickListener(this);
cbLoopback.setOnClickListener(this);
cbStats.setOnClickListener(this);
cbEnableNack.setOnClickListener(this);
cbEnableSpeaker.setOnClickListener(this);
cbEnableAECM.setOnClickListener(this);
cbEnableAGC.setOnClickListener(this);
cbEnableNS.setOnClickListener(this);
cbEnableDebugAPM.setOnClickListener(this);
cbEnableVideoRTPDump.setOnClickListener(this);
cbEnableVoiceRTPDump.setOnClickListener(this);
if (loopbackMode) {
remoteIp = LOOPBACK_IP;
etRemoteIp.setText(remoteIp);
}
else {
GetLocalIpAddress();
etRemoteIp.setText(remoteIp);
}
// Read settings to refresh each configuration
ReadSettings();
}
| private void StartMain() {
mTabHost.setCurrentTab(0);
mLlRemoteSurface = (LinearLayout) findViewById(R.id.llRemoteView);
mLlLocalSurface = (LinearLayout) findViewById(R.id.llLocalView);
if (null == ViEAndroidAPI)
ViEAndroidAPI = new ViEAndroidJavaAPI(this);
if (0 > SetupVoE() || 0 > ViEAndroidAPI.GetVideoEngine() ||
0 > ViEAndroidAPI.Init(enableTrace) ) {
// Show dialog
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("WebRTC Error");
alertDialog.setMessage("Can not init video engine.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
alertDialog.show();
}
btSwitchCamera = (Button)findViewById(R.id.btSwitchCamera);
btSwitchCamera.setOnClickListener(this);
btStartStopCall = (Button)findViewById(R.id.btStartStopCall);
btStartStopCall.setOnClickListener(this);
findViewById(R.id.btExit).setOnClickListener(this);
// cleaning
remoteSurfaceView = null;
svLocal = null;
// Video codec
mVideoCodecsStrings = ViEAndroidAPI.GetCodecs();
spCodecType = (Spinner)findViewById(R.id.spCodecType);
spCodecType.setOnItemSelectedListener(this);
spCodecType.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVideoCodecsStrings));
spCodecType.setSelection(0);
// Video Codec size
spCodecSize = (Spinner) findViewById(R.id.spCodecSize);
spCodecSize.setOnItemSelectedListener(this);
spCodecSize.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVideoCodecsSizeStrings));
spCodecSize.setSelection(0);
// Voice codec
mVoiceCodecsStrings = ViEAndroidAPI.VoE_GetCodecs();
spVoiceCodecType = (Spinner)findViewById(R.id.spVoiceCodecType);
spVoiceCodecType.setOnItemSelectedListener(this);
spVoiceCodecType.setAdapter(new SpinnerAdapter(this,
R.layout.row,
mVoiceCodecsStrings));
spVoiceCodecType.setSelection(0);
// Find ISAC and use it
for (int i = 0; i < mVoiceCodecsStrings.length; ++i) {
if (mVoiceCodecsStrings[i].contains("ISAC")) {
spVoiceCodecType.setSelection(i);
break;
}
}
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group1);
radioGroup.clearCheck();
if (useOpenGLRender == true) {
radioGroup.check(R.id.radio_opengl);
}
else {
radioGroup.check(R.id.radio_surface);
}
etRemoteIp = (EditText) findViewById(R.id.etRemoteIp);
etRemoteIp.setText(remoteIp);
cbLoopback = (CheckBox) findViewById(R.id.cbLoopback);
cbLoopback.setChecked(loopbackMode);
cbStats = (CheckBox) findViewById(R.id.cbStats);
cbStats.setChecked(isStatsOn);
cbVoice = (CheckBox) findViewById(R.id.cbVoice);
cbVoice.setChecked(enableVoice);
cbVideoSend = (CheckBox) findViewById(R.id.cbVideoSend);
cbVideoSend.setChecked(enableVideoSend);
cbVideoReceive = (CheckBox) findViewById(R.id.cbVideoReceive);
cbVideoReceive.setChecked(enableVideoReceive);
etVTxPort = (EditText) findViewById(R.id.etVTxPort);
etVTxPort.setText(Integer.toString(destinationPortVideo));
etVRxPort = (EditText) findViewById(R.id.etVRxPort);
etVRxPort.setText(Integer.toString(receivePortVideo));
etATxPort = (EditText) findViewById(R.id.etATxPort);
etATxPort.setText(Integer.toString(destinationPortVoice));
etARxPort = (EditText) findViewById(R.id.etARxPort);
etARxPort.setText(Integer.toString(receivePortVoice));
cbEnableNack = (CheckBox) findViewById(R.id.cbNack);
cbEnableNack.setChecked(enableNack);
cbEnableSpeaker = (CheckBox) findViewById(R.id.cbSpeaker);
cbEnableSpeaker.setChecked(enableSpeaker);
cbEnableAGC = (CheckBox) findViewById(R.id.cbAutoGainControl);
cbEnableAGC.setChecked(enableAGC);
cbEnableAECM = (CheckBox) findViewById(R.id.cbAECM);
cbEnableAECM.setChecked(enableAECM);
cbEnableNS = (CheckBox) findViewById(R.id.cbNoiseSuppression);
cbEnableNS.setChecked(enableNS);
cbEnableDebugAPM = (CheckBox) findViewById(R.id.cbDebugRecording);
cbEnableDebugAPM.setChecked(false); // Disable APM debugging by default
cbEnableVideoRTPDump = (CheckBox) findViewById(R.id.cbVideoRTPDump);
cbEnableVideoRTPDump.setChecked(false); // Disable Video RTP Dump
cbEnableVoiceRTPDump = (CheckBox) findViewById(R.id.cbVoiceRTPDump);
cbEnableVoiceRTPDump.setChecked(false); // Disable Voice RTP Dump
etRemoteIp.setOnClickListener(this);
cbLoopback.setOnClickListener(this);
cbStats.setOnClickListener(this);
cbEnableNack.setOnClickListener(this);
cbEnableSpeaker.setOnClickListener(this);
cbEnableAECM.setOnClickListener(this);
cbEnableAGC.setOnClickListener(this);
cbEnableNS.setOnClickListener(this);
cbEnableDebugAPM.setOnClickListener(this);
cbEnableVideoRTPDump.setOnClickListener(this);
cbEnableVoiceRTPDump.setOnClickListener(this);
if (loopbackMode) {
remoteIp = LOOPBACK_IP;
etRemoteIp.setText(remoteIp);
}
else {
GetLocalIpAddress();
etRemoteIp.setText(remoteIp);
}
// Read settings to refresh each configuration
ReadSettings();
}
|
diff --git a/src/main/java/com/conventnunnery/plugins/mythicdrops/listeners/IdentifyingListener.java b/src/main/java/com/conventnunnery/plugins/mythicdrops/listeners/IdentifyingListener.java
index 51117268..b66d1b9a 100644
--- a/src/main/java/com/conventnunnery/plugins/mythicdrops/listeners/IdentifyingListener.java
+++ b/src/main/java/com/conventnunnery/plugins/mythicdrops/listeners/IdentifyingListener.java
@@ -1,172 +1,182 @@
/*
* Copyright (c) 2013. ToppleTheNun
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.conventnunnery.plugins.mythicdrops.listeners;
import com.conventnunnery.plugins.mythicdrops.MythicDrops;
import com.conventnunnery.plugins.mythicdrops.events.ItemIdentifiedEvent;
import com.conventnunnery.plugins.mythicdrops.managers.DropManager;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("deprecation")
public class IdentifyingListener implements Listener {
private MythicDrops plugin;
private Map<String, ItemStack> heldIdentify;
public IdentifyingListener(MythicDrops plugin) {
this.plugin = plugin;
heldIdentify = new HashMap<String, ItemStack>();
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (heldIdentify.containsKey(player.getName())) {
heldIdentify.remove(player.getName());
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onRightClick(PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
if (event.getItem() == null) {
return;
}
Player player = event.getPlayer();
ItemStack itemInHand = event.getItem();
String itemType = getPlugin().getItemManager().itemTypeFromMatData(itemInHand.getData());
if (getPlugin().getPluginSettings().getSocketGemMaterials().contains(itemInHand.getData())) {
event.setUseItemInHand(Event.Result.DENY);
}
if (getPlugin().getItemManager().isArmor(itemType) && itemInHand.hasItemMeta()) {
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
if (heldIdentify.containsKey(player.getName())) {
identifyItem(event, player, itemInHand, itemType);
} else {
addHeldIdentify(event, player, itemInHand);
}
}
private void addHeldIdentify(PlayerInteractEvent event, final Player player, ItemStack itemInHand) {
if (itemInHand.getData().getItemType() != Material.ENCHANTED_BOOK || !itemInHand.hasItemMeta()) {
return;
}
ItemMeta im = itemInHand.getItemMeta();
if (!im.hasDisplayName()) {
return;
}
if (!im.getDisplayName().equals(getPlugin().getLanguageManager().getMessage("items.identity-tome" +
".name"))) {
return;
}
getPlugin().getLanguageManager().sendMessage(player, "identify.instructions",
new String[][]{{"%unidentified-name%", getPlugin().getLanguageManager().getMessage("items" +
".unidentified.name")}});
heldIdentify.put(player.getName(), itemInHand);
Bukkit.getScheduler().runTaskLaterAsynchronously(getPlugin(), new Runnable() {
@Override
public void run() {
heldIdentify.remove(player.getName());
}
}, 20L * 30);
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
player.updateInventory();
}
private void identifyItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) {
if (getPlugin().getItemManager().isArmor(itemType) || getPlugin().getItemManager().isTool(itemType)) {
if (!itemInHand.hasItemMeta()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
if (player.getInventory().contains(heldIdentify.get(player.getName()))) {
int indexOfItem = player.getInventory().first(heldIdentify.get(player.getName()));
ItemStack inInventory = player.getInventory().getItem(indexOfItem);
inInventory.setAmount(inInventory.getAmount() - 1);
player.getInventory().setItem(indexOfItem, inInventory);
player.updateInventory();
} else {
getPlugin().getLanguageManager().sendMessage(player, "identify.do-not-have");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
+ if (getPlugin().getTierManager().getTierFromItemStack(itemInHand) != getPlugin().getTierManager()
+ .getUnidentifiedItemTier()) {
+ getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
+ event.setCancelled(true);
+ event.setUseInteractedBlock(Event.Result.DENY);
+ event.setUseItemInHand(Event.Result.DENY);
+ heldIdentify.remove(player.getName());
+ player.updateInventory();
+ return;
+ }
ItemStack iih = getPlugin().getDropManager().constructItemStack(itemInHand.getData(), DropManager
.GenerationReason.IDENTIFYING);
ItemIdentifiedEvent ise = new ItemIdentifiedEvent(player, iih);
Bukkit.getPluginManager().callEvent(ise);
if (ise.isCancelled()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
player.setItemInHand(ise.getItemStack());
getPlugin().getLanguageManager().sendMessage(player, "identify.success");
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
} else {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
}
}
public MythicDrops getPlugin() {
return plugin;
}
}
| true | true | private void identifyItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) {
if (getPlugin().getItemManager().isArmor(itemType) || getPlugin().getItemManager().isTool(itemType)) {
if (!itemInHand.hasItemMeta()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
if (player.getInventory().contains(heldIdentify.get(player.getName()))) {
int indexOfItem = player.getInventory().first(heldIdentify.get(player.getName()));
ItemStack inInventory = player.getInventory().getItem(indexOfItem);
inInventory.setAmount(inInventory.getAmount() - 1);
player.getInventory().setItem(indexOfItem, inInventory);
player.updateInventory();
} else {
getPlugin().getLanguageManager().sendMessage(player, "identify.do-not-have");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
ItemStack iih = getPlugin().getDropManager().constructItemStack(itemInHand.getData(), DropManager
.GenerationReason.IDENTIFYING);
ItemIdentifiedEvent ise = new ItemIdentifiedEvent(player, iih);
Bukkit.getPluginManager().callEvent(ise);
if (ise.isCancelled()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
player.setItemInHand(ise.getItemStack());
getPlugin().getLanguageManager().sendMessage(player, "identify.success");
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
} else {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
}
}
| private void identifyItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) {
if (getPlugin().getItemManager().isArmor(itemType) || getPlugin().getItemManager().isTool(itemType)) {
if (!itemInHand.hasItemMeta()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
if (player.getInventory().contains(heldIdentify.get(player.getName()))) {
int indexOfItem = player.getInventory().first(heldIdentify.get(player.getName()));
ItemStack inInventory = player.getInventory().getItem(indexOfItem);
inInventory.setAmount(inInventory.getAmount() - 1);
player.getInventory().setItem(indexOfItem, inInventory);
player.updateInventory();
} else {
getPlugin().getLanguageManager().sendMessage(player, "identify.do-not-have");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
if (getPlugin().getTierManager().getTierFromItemStack(itemInHand) != getPlugin().getTierManager()
.getUnidentifiedItemTier()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
ItemStack iih = getPlugin().getDropManager().constructItemStack(itemInHand.getData(), DropManager
.GenerationReason.IDENTIFYING);
ItemIdentifiedEvent ise = new ItemIdentifiedEvent(player, iih);
Bukkit.getPluginManager().callEvent(ise);
if (ise.isCancelled()) {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
return;
}
player.setItemInHand(ise.getItemStack());
getPlugin().getLanguageManager().sendMessage(player, "identify.success");
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
} else {
getPlugin().getLanguageManager().sendMessage(player, "identify.cannot-use");
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
heldIdentify.remove(player.getName());
player.updateInventory();
}
}
|
diff --git a/src/test/java/org/silverpeas/file/GestionVariablesTest.java b/src/test/java/org/silverpeas/file/GestionVariablesTest.java
index 07725c3..52fdef1 100644
--- a/src/test/java/org/silverpeas/file/GestionVariablesTest.java
+++ b/src/test/java/org/silverpeas/file/GestionVariablesTest.java
@@ -1,85 +1,85 @@
/*
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection withWriter Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.file;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
/**
*
* @author ehugonnet
*/
public class GestionVariablesTest {
public GestionVariablesTest() {
}
/**
* Test of addVariable method, of class GestionVariables.
*/
@Test
public void testAddVariable() throws IOException {
- String pName = "SILVERPEAS_HOME";
+ String pName = "MY_PATH";
String pValue = "C:/toto";
GestionVariables instance = new GestionVariables(new Properties());
try {
assertThat(instance.getValue(pName), is(not(pValue)));
fail("SILVERPEAS_HOME should not exist");
} catch (IOException ioex) {
}
instance.addVariable(pName, pValue);
assertThat(instance.getValue(pName), is(pValue));
}
/**
* Test of resolveString method, of class GestionVariables.
*/
@Test
public void testResolveString() throws Exception {
GestionVariables instance = new GestionVariables(new Properties());
instance.addVariable("SILVERPEAS_HOME", "/home/bart/silverpeas");
String result = instance.resolveString("${SILVERPEAS_HOME}/data/portlets/config/pcenv.conf");
assertThat(result, is("/home/bart/silverpeas/data/portlets/config/pcenv.conf"));
}
/**
* Test of resolveAndEvalString method, of class GestionVariables.
*/
@Test
public void testResolveAndEvalString() throws Exception {
GestionVariables instance = new GestionVariables(new Properties());
instance.addVariable("SILVERPEAS_HOME", "/home/bart/silverpeas");
String result = instance.resolveAndEvalString(
"${SILVERPEAS_HOME}/data/portlets/config/pcenv.conf");
assertThat(result, is("/home/bart/silverpeas/data/portlets/config/pcenv.conf"));
}
}
| true | true | public void testAddVariable() throws IOException {
String pName = "SILVERPEAS_HOME";
String pValue = "C:/toto";
GestionVariables instance = new GestionVariables(new Properties());
try {
assertThat(instance.getValue(pName), is(not(pValue)));
fail("SILVERPEAS_HOME should not exist");
} catch (IOException ioex) {
}
instance.addVariable(pName, pValue);
assertThat(instance.getValue(pName), is(pValue));
}
| public void testAddVariable() throws IOException {
String pName = "MY_PATH";
String pValue = "C:/toto";
GestionVariables instance = new GestionVariables(new Properties());
try {
assertThat(instance.getValue(pName), is(not(pValue)));
fail("SILVERPEAS_HOME should not exist");
} catch (IOException ioex) {
}
instance.addVariable(pName, pValue);
assertThat(instance.getValue(pName), is(pValue));
}
|
diff --git a/marytts-builder/src/main/java/marytts/tools/newlanguage/LTSTrainer.java b/marytts-builder/src/main/java/marytts/tools/newlanguage/LTSTrainer.java
index 867aa897d..e1298245c 100644
--- a/marytts-builder/src/main/java/marytts/tools/newlanguage/LTSTrainer.java
+++ b/marytts-builder/src/main/java/marytts/tools/newlanguage/LTSTrainer.java
@@ -1,441 +1,441 @@
/**
* Copyright 2000-2009 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package marytts.tools.newlanguage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import marytts.cart.CART;
import marytts.cart.DecisionNode;
import marytts.cart.io.MaryCARTWriter;
import marytts.exceptions.MaryConfigurationException;
import marytts.features.FeatureDefinition;
import marytts.fst.AlignerTrainer;
import marytts.fst.StringPair;
import marytts.modules.phonemiser.Allophone;
import marytts.modules.phonemiser.AllophoneSet;
import marytts.modules.phonemiser.TrainedLTS;
import org.apache.log4j.BasicConfigurator;
import weka.classifiers.trees.j48.BinC45ModelSelection;
import weka.classifiers.trees.j48.C45PruneableClassifierTree;
import weka.classifiers.trees.j48.TreeConverter;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
/**
*
* This class is a generic approach to predict a phone sequence from a
* grapheme sequence.
*
* the normal sequence of steps is:
* 1) initialize the trainer with a phone set and a locale
*
* 2) read in the lexicon, preserve stress if you like
*
* 3) make some alignment iterations (usually 5-10)
*
* 4) train the trees and save them in wagon format in a specified directory
*
* see main method for an example.
*
* Apply the model using TrainedLTS
*
* @author benjaminroth
*
*/
public class LTSTrainer extends AlignerTrainer
{
protected AllophoneSet phSet;
protected int context;
protected boolean convertToLowercase;
protected boolean considerStress;
/**
* Create a new LTSTrainer.
* @param aPhSet the allophone set to use.
* @param convertToLowercase whether to convert all graphemes to lowercase, using the locale of the allophone set.
* @param considerStress indicator if stress is preserved
*/
public LTSTrainer(AllophoneSet aPhSet, boolean convertToLowercase, boolean considerStress, int context) {
super();
this.phSet = aPhSet;
this.convertToLowercase = convertToLowercase;
this.considerStress = considerStress;
this.context = context;
BasicConfigurator.configure();
}
/**
* Train the tree, using binary decision nodes.
* @param minLeafData the minimum number of instances that have to occur in at least two subsets induced by split
* @return
* @throws IOException
*/
public CART trainTree(int minLeafData) throws IOException{
Map<String, List<String[]>> grapheme2align = new HashMap<String, List<String[]>>();
for (String gr : this.graphemeSet){
grapheme2align.put(gr, new ArrayList<String[]>());
}
Set<String> phChains = new HashSet<String>();
// for every alignment pair collect counts
for ( int i = 0; i < this.inSplit.size(); i++ ){
StringPair[] alignment = this.getAlignment(i);
for ( int inNr = 0 ; inNr < alignment.length ; inNr ++ ){
//System.err.println(alignment[inNr]);
// quotation signs needed to represent empty string
String outAlNr = "'" + alignment[inNr].getString2() + "'";
// TODO: don't consider alignments to more than three characters
if (outAlNr.length() > 5)
continue;
phChains.add(outAlNr);
// storing context and target
String[] datapoint = new String[2*context + 2];
for (int ct = 0; ct < 2*context+1; ct++){
int pos = inNr - context +ct;
if (pos >=0 && pos < alignment.length){
datapoint[ct] = alignment[pos].getString1();
} else {
datapoint[ct] = "null";
}
}
// set target
datapoint[2*context+1] = outAlNr;
// add datapoint
grapheme2align.get(alignment[inNr].getString1()).add(datapoint);
}
}
// for conversion need feature definition file
FeatureDefinition fd = this.graphemeFeatureDef(phChains);
int centerGrapheme = fd.getFeatureIndex("att"+(context+1));
List<CART> stl = new ArrayList<CART>(fd.getNumberOfValues(centerGrapheme));
for (String gr : fd.getPossibleValues(centerGrapheme)){
logger.debug(" Training decision tree for: " + gr);
ArrayList<Attribute> attributeDeclarations = new ArrayList<Attribute>();
// attributes with values
for (int att = 1; att <= context*2 + 1; att++){
// ...collect possible values
ArrayList<String> attVals = new ArrayList<String>();
String featureName = "att"+att;
for (String usableGrapheme:fd.getPossibleValues(fd.getFeatureIndex(featureName))){
attVals.add(usableGrapheme);
}
attributeDeclarations.add(new Attribute(featureName, attVals) );
}
List<String[]> datapoints = grapheme2align.get(gr);
// maybe training is faster with targets limited to grapheme
Set<String> graphSpecPh = new HashSet<String>();
for (String[] dp : datapoints){
graphSpecPh.add(dp[dp.length-1]);
}
// targetattribute
// ...collect possible values
ArrayList<String> targetVals = new ArrayList<String>();
for (String phc : graphSpecPh){// todo: use either fd of phChains
targetVals.add(phc);
}
attributeDeclarations.add(new Attribute(TrainedLTS.PREDICTED_STRING_FEATURENAME, targetVals) );
// now, create the dataset adding the datapoints
Instances data = new Instances(gr, attributeDeclarations, 0);
// datapoints
for (String[] point : datapoints){
Instance currInst = new DenseInstance( data.numAttributes() );
currInst.setDataset(data);
for (int i = 0; i < point.length; i++){
currInst.setValue(i, point[i]);
}
data.add(currInst);
}
// Make the last attribute be the class
data.setClassIndex(data.numAttributes() - 1);
// build the tree without using the J48 wrapper class
// standard parameters are:
//binary split selection with minimum x instances at the leaves, tree is pruned, confidenced value, subtree raising, cleanup, don't collapse
C45PruneableClassifierTree decisionTree;
try {
decisionTree = new C45PruneableClassifierTree(new BinC45ModelSelection(minLeafData,data,true),true,0.25f,true,true, false);
decisionTree.buildClassifier(data);
} catch (Exception e) {
- throw new RuntimeException("couldn't train decisiontree using weka: " + e);
+ throw new RuntimeException("couldn't train decisiontree using weka: ", e);
}
CART maryTree = TreeConverter.c45toStringCART(decisionTree, fd,data);
stl.add(maryTree);
}
DecisionNode.ByteDecisionNode rootNode = new DecisionNode.ByteDecisionNode(centerGrapheme, stl.size(), fd);
for (CART st : stl) {
rootNode.addDaughter(st.getRootNode());
}
Properties props = new Properties();
props.setProperty("lowercase", String.valueOf(convertToLowercase));
props.setProperty("stress", String.valueOf(considerStress));
props.setProperty("context", String.valueOf(context));
CART bigTree = new CART(rootNode, fd, props);
return bigTree;
}
/**
*
* Convenience method to save files to graph2phon.wagon and graph2phon.pfeats
* in a specified directory with UTF-8 encoding.
*
* @param tree
* @param saveTreePath
* @throws IOException
*/
public void save(CART tree, String saveTreefile) throws IOException{
MaryCARTWriter mcw = new MaryCARTWriter();
mcw.dumpMaryCART(tree, saveTreefile);
}
private FeatureDefinition graphemeFeatureDef(Set<String> phChains) throws IOException {
String lineBreak = System.getProperty("line.separator");
StringBuilder fdString = new StringBuilder("ByteValuedFeatureProcessors");
fdString.append(lineBreak);
// add attribute features
for (int att = 1; att <= context*2 + 1; att++){
fdString.append("att").append(att);
for (String gr : this.graphemeSet) {
fdString.append(" ").append(gr);
}
fdString.append(lineBreak);
}
fdString.append("ShortValuedFeatureProcessors").append(lineBreak);
// add class features
fdString.append(TrainedLTS.PREDICTED_STRING_FEATURENAME);
for (String ph : phChains){
fdString.append(" ").append(ph);
}
fdString.append(lineBreak);
fdString.append("ContinuousFeatureProcessors").append(lineBreak);
BufferedReader featureReader = new BufferedReader(new StringReader(fdString.toString()));
return new FeatureDefinition(featureReader,false);
}
/**
*
* reads in a lexicon in text format, lines are of the kind:
*
* graphemechain | phonechain | otherinformation
*
* Stress is optionally preserved, marking the first vowel of a stressed
* syllable with "1".
*
* @param lexicon reader with lines of lexicon
* @param splitPattern a regular expression used for identifying the field separator in each line.
* @throws IOException
*/
public void readLexicon(BufferedReader lexicon, String splitPattern) throws IOException{
String line;
while ((line = lexicon.readLine()) != null){
String[] lineParts = line.trim().split(splitPattern);
String graphStr = lineParts[0];
if (convertToLowercase) graphStr = graphStr.toLowerCase(phSet.getLocale());
graphStr = graphStr.replaceAll("['-.]", "");
// remove all secondary stress markers
String phonStr = lineParts[1].replaceAll(",", "");
String[] syllables = phonStr.split("-");
List<String> separatedPhones = new ArrayList<String>();
List<String> separatedGraphemes = new ArrayList<String>();
String currPh;
for (String syl : syllables) {
boolean stress = false;
if (syl.startsWith("'")){
syl = syl.substring(1);
stress = true;
}
for (Allophone ph : phSet.splitIntoAllophones(syl)) {
currPh = ph.name();
if (stress && considerStress && ph.isVowel()) {
currPh += "1";
stress = false;
}
separatedPhones.add(currPh);
}// ... for each allophone
}
for ( int i = 0 ; i < graphStr.length() ; i++ ) {
this.graphemeSet.add(graphStr.substring(i, i+1));
separatedGraphemes.add(graphStr.substring(i, i+1));
}
this.addAlreadySplit(separatedGraphemes, separatedPhones);
}
// Need one entry for the "null" grapheme, which maps to the empty string:
this.addAlreadySplit(new String[]{"null"}, new String[]{""});
}
/**
* reads in a lexicon in text format, lines are of the kind:
*
* graphemechain | phonechain | otherinformation
*
* Stress is optionally preserved, marking the first vowel of a stressed
* syllable with "1".
*
* @param lexicon
* @throws IOException
*/
public void readLexicon(HashMap<String, String> lexicon) {
Iterator<String> it = lexicon.keySet().iterator();
while (it.hasNext()){
String graphStr = it.next();
// remove all secondary stress markers
String phonStr = lexicon.get(graphStr).replaceAll(",", "");
if (convertToLowercase) graphStr = graphStr.toLowerCase(phSet.getLocale());
graphStr = graphStr.replaceAll("['-.]", "");
String[] syllables = phonStr.split("-");
List<String> separatedPhones = new ArrayList<String>();
List<String> separatedGraphemes = new ArrayList<String>();
String currPh;
for (String syl : syllables) {
boolean stress = false;
if (syl.startsWith("'")){
syl = syl.substring(1);
stress = true;
}
for (Allophone ph : phSet.splitIntoAllophones(syl)) {
currPh = ph.name();
if (stress && considerStress && ph.isVowel()) {
currPh += "1";
stress = false;
}
separatedPhones.add(currPh);
}// ... for each allophone
}
for ( int i = 0 ; i < graphStr.length() ; i++ ) {
this.graphemeSet.add(graphStr.substring(i, i+1));
separatedGraphemes.add(graphStr.substring(i, i+1));
}
this.addAlreadySplit(separatedGraphemes, separatedPhones);
}
// Need one entry for the "null" grapheme, which maps to the empty string:
this.addAlreadySplit(new String[]{"null"}, new String[]{""});
}
public static void main(String[] args) throws IOException, MaryConfigurationException {
String phFileLoc = "/Users/benjaminroth/Desktop/mary/english/phone-list-engba.xml";
// initialize trainer
LTSTrainer tp = new LTSTrainer(AllophoneSet.getAllophoneSet(phFileLoc), true, true, 2);
BufferedReader lexReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"/Users/benjaminroth/Desktop/mary/english/sampa-lexicon.txt"),"ISO-8859-1"));
// read lexicon for training
tp.readLexicon(lexReader, "\\\\");
// make some alignment iterations
for ( int i = 0 ; i < 5 ; i++ ){
System.out.println("iteration " + i);
tp.alignIteration();
}
CART st = tp.trainTree(100);
tp.save(st, "/Users/benjaminroth/Desktop/mary/english/trees/");
}
}
| true | true | public CART trainTree(int minLeafData) throws IOException{
Map<String, List<String[]>> grapheme2align = new HashMap<String, List<String[]>>();
for (String gr : this.graphemeSet){
grapheme2align.put(gr, new ArrayList<String[]>());
}
Set<String> phChains = new HashSet<String>();
// for every alignment pair collect counts
for ( int i = 0; i < this.inSplit.size(); i++ ){
StringPair[] alignment = this.getAlignment(i);
for ( int inNr = 0 ; inNr < alignment.length ; inNr ++ ){
//System.err.println(alignment[inNr]);
// quotation signs needed to represent empty string
String outAlNr = "'" + alignment[inNr].getString2() + "'";
// TODO: don't consider alignments to more than three characters
if (outAlNr.length() > 5)
continue;
phChains.add(outAlNr);
// storing context and target
String[] datapoint = new String[2*context + 2];
for (int ct = 0; ct < 2*context+1; ct++){
int pos = inNr - context +ct;
if (pos >=0 && pos < alignment.length){
datapoint[ct] = alignment[pos].getString1();
} else {
datapoint[ct] = "null";
}
}
// set target
datapoint[2*context+1] = outAlNr;
// add datapoint
grapheme2align.get(alignment[inNr].getString1()).add(datapoint);
}
}
// for conversion need feature definition file
FeatureDefinition fd = this.graphemeFeatureDef(phChains);
int centerGrapheme = fd.getFeatureIndex("att"+(context+1));
List<CART> stl = new ArrayList<CART>(fd.getNumberOfValues(centerGrapheme));
for (String gr : fd.getPossibleValues(centerGrapheme)){
logger.debug(" Training decision tree for: " + gr);
ArrayList<Attribute> attributeDeclarations = new ArrayList<Attribute>();
// attributes with values
for (int att = 1; att <= context*2 + 1; att++){
// ...collect possible values
ArrayList<String> attVals = new ArrayList<String>();
String featureName = "att"+att;
for (String usableGrapheme:fd.getPossibleValues(fd.getFeatureIndex(featureName))){
attVals.add(usableGrapheme);
}
attributeDeclarations.add(new Attribute(featureName, attVals) );
}
List<String[]> datapoints = grapheme2align.get(gr);
// maybe training is faster with targets limited to grapheme
Set<String> graphSpecPh = new HashSet<String>();
for (String[] dp : datapoints){
graphSpecPh.add(dp[dp.length-1]);
}
// targetattribute
// ...collect possible values
ArrayList<String> targetVals = new ArrayList<String>();
for (String phc : graphSpecPh){// todo: use either fd of phChains
targetVals.add(phc);
}
attributeDeclarations.add(new Attribute(TrainedLTS.PREDICTED_STRING_FEATURENAME, targetVals) );
// now, create the dataset adding the datapoints
Instances data = new Instances(gr, attributeDeclarations, 0);
// datapoints
for (String[] point : datapoints){
Instance currInst = new DenseInstance( data.numAttributes() );
currInst.setDataset(data);
for (int i = 0; i < point.length; i++){
currInst.setValue(i, point[i]);
}
data.add(currInst);
}
// Make the last attribute be the class
data.setClassIndex(data.numAttributes() - 1);
// build the tree without using the J48 wrapper class
// standard parameters are:
//binary split selection with minimum x instances at the leaves, tree is pruned, confidenced value, subtree raising, cleanup, don't collapse
C45PruneableClassifierTree decisionTree;
try {
decisionTree = new C45PruneableClassifierTree(new BinC45ModelSelection(minLeafData,data,true),true,0.25f,true,true, false);
decisionTree.buildClassifier(data);
} catch (Exception e) {
throw new RuntimeException("couldn't train decisiontree using weka: " + e);
}
CART maryTree = TreeConverter.c45toStringCART(decisionTree, fd,data);
stl.add(maryTree);
}
DecisionNode.ByteDecisionNode rootNode = new DecisionNode.ByteDecisionNode(centerGrapheme, stl.size(), fd);
for (CART st : stl) {
rootNode.addDaughter(st.getRootNode());
}
Properties props = new Properties();
props.setProperty("lowercase", String.valueOf(convertToLowercase));
props.setProperty("stress", String.valueOf(considerStress));
props.setProperty("context", String.valueOf(context));
CART bigTree = new CART(rootNode, fd, props);
return bigTree;
}
| public CART trainTree(int minLeafData) throws IOException{
Map<String, List<String[]>> grapheme2align = new HashMap<String, List<String[]>>();
for (String gr : this.graphemeSet){
grapheme2align.put(gr, new ArrayList<String[]>());
}
Set<String> phChains = new HashSet<String>();
// for every alignment pair collect counts
for ( int i = 0; i < this.inSplit.size(); i++ ){
StringPair[] alignment = this.getAlignment(i);
for ( int inNr = 0 ; inNr < alignment.length ; inNr ++ ){
//System.err.println(alignment[inNr]);
// quotation signs needed to represent empty string
String outAlNr = "'" + alignment[inNr].getString2() + "'";
// TODO: don't consider alignments to more than three characters
if (outAlNr.length() > 5)
continue;
phChains.add(outAlNr);
// storing context and target
String[] datapoint = new String[2*context + 2];
for (int ct = 0; ct < 2*context+1; ct++){
int pos = inNr - context +ct;
if (pos >=0 && pos < alignment.length){
datapoint[ct] = alignment[pos].getString1();
} else {
datapoint[ct] = "null";
}
}
// set target
datapoint[2*context+1] = outAlNr;
// add datapoint
grapheme2align.get(alignment[inNr].getString1()).add(datapoint);
}
}
// for conversion need feature definition file
FeatureDefinition fd = this.graphemeFeatureDef(phChains);
int centerGrapheme = fd.getFeatureIndex("att"+(context+1));
List<CART> stl = new ArrayList<CART>(fd.getNumberOfValues(centerGrapheme));
for (String gr : fd.getPossibleValues(centerGrapheme)){
logger.debug(" Training decision tree for: " + gr);
ArrayList<Attribute> attributeDeclarations = new ArrayList<Attribute>();
// attributes with values
for (int att = 1; att <= context*2 + 1; att++){
// ...collect possible values
ArrayList<String> attVals = new ArrayList<String>();
String featureName = "att"+att;
for (String usableGrapheme:fd.getPossibleValues(fd.getFeatureIndex(featureName))){
attVals.add(usableGrapheme);
}
attributeDeclarations.add(new Attribute(featureName, attVals) );
}
List<String[]> datapoints = grapheme2align.get(gr);
// maybe training is faster with targets limited to grapheme
Set<String> graphSpecPh = new HashSet<String>();
for (String[] dp : datapoints){
graphSpecPh.add(dp[dp.length-1]);
}
// targetattribute
// ...collect possible values
ArrayList<String> targetVals = new ArrayList<String>();
for (String phc : graphSpecPh){// todo: use either fd of phChains
targetVals.add(phc);
}
attributeDeclarations.add(new Attribute(TrainedLTS.PREDICTED_STRING_FEATURENAME, targetVals) );
// now, create the dataset adding the datapoints
Instances data = new Instances(gr, attributeDeclarations, 0);
// datapoints
for (String[] point : datapoints){
Instance currInst = new DenseInstance( data.numAttributes() );
currInst.setDataset(data);
for (int i = 0; i < point.length; i++){
currInst.setValue(i, point[i]);
}
data.add(currInst);
}
// Make the last attribute be the class
data.setClassIndex(data.numAttributes() - 1);
// build the tree without using the J48 wrapper class
// standard parameters are:
//binary split selection with minimum x instances at the leaves, tree is pruned, confidenced value, subtree raising, cleanup, don't collapse
C45PruneableClassifierTree decisionTree;
try {
decisionTree = new C45PruneableClassifierTree(new BinC45ModelSelection(minLeafData,data,true),true,0.25f,true,true, false);
decisionTree.buildClassifier(data);
} catch (Exception e) {
throw new RuntimeException("couldn't train decisiontree using weka: ", e);
}
CART maryTree = TreeConverter.c45toStringCART(decisionTree, fd,data);
stl.add(maryTree);
}
DecisionNode.ByteDecisionNode rootNode = new DecisionNode.ByteDecisionNode(centerGrapheme, stl.size(), fd);
for (CART st : stl) {
rootNode.addDaughter(st.getRootNode());
}
Properties props = new Properties();
props.setProperty("lowercase", String.valueOf(convertToLowercase));
props.setProperty("stress", String.valueOf(considerStress));
props.setProperty("context", String.valueOf(context));
CART bigTree = new CART(rootNode, fd, props);
return bigTree;
}
|
diff --git a/org.caleydo.view.enroute/src/org/caleydo/view/enroute/path/node/MultiMappingAttributeRenderer.java b/org.caleydo.view.enroute/src/org/caleydo/view/enroute/path/node/MultiMappingAttributeRenderer.java
index b1d68a830..5031e1550 100644
--- a/org.caleydo.view.enroute/src/org/caleydo/view/enroute/path/node/MultiMappingAttributeRenderer.java
+++ b/org.caleydo.view.enroute/src/org/caleydo/view/enroute/path/node/MultiMappingAttributeRenderer.java
@@ -1,57 +1,57 @@
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.enroute.path.node;
import gleem.linalg.Vec3f;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import org.caleydo.core.view.opengl.canvas.AGLView;
import org.caleydo.view.enroute.path.APathwayPathRenderer;
/**
* @author Christian
*
*/
public class MultiMappingAttributeRenderer extends ANodeAttributeRenderer {
private static final int GLYPH_SIZE = 8;
/**
* @param view
* @param node
* @param pathwayPathRenderer
*/
public MultiMappingAttributeRenderer(AGLView view, ANode node, APathwayPathRenderer pathwayPathRenderer) {
super(view, node, pathwayPathRenderer);
}
@Override
public void render(GL2 gl) {
Vec3f nodePos = node.getPosition();
float nodeHeight = node.getHeight();
float nodeWidth = node.getWidth();
- float size = pixelGLConverter.getGLHeightForGLWidth(GLYPH_SIZE);
+ float size = pixelGLConverter.getGLHeightForPixelHeight(GLYPH_SIZE);
gl.glColor4f(0.3f, 0.3f, 0.3f, 1f);
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex3f(nodePos.x() - nodeWidth / 2.0f, nodePos.y() + nodeHeight / 2.0f, nodePos.z() + 0.1f);
gl.glVertex3f(nodePos.x() - (nodeWidth / 2.0f) + size, nodePos.y() + nodeHeight / 2.0f, nodePos.z() + 0.1f);
gl.glVertex3f(nodePos.x() - nodeWidth / 2.0f, nodePos.y() + nodeHeight / 2.0f - size,
nodePos.z() + 0.1f);
gl.glEnd();
}
@Override
protected void registerPickingListeners() {
}
@Override
public void unregisterPickingListeners() {
}
}
| true | true | public void render(GL2 gl) {
Vec3f nodePos = node.getPosition();
float nodeHeight = node.getHeight();
float nodeWidth = node.getWidth();
float size = pixelGLConverter.getGLHeightForGLWidth(GLYPH_SIZE);
gl.glColor4f(0.3f, 0.3f, 0.3f, 1f);
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex3f(nodePos.x() - nodeWidth / 2.0f, nodePos.y() + nodeHeight / 2.0f, nodePos.z() + 0.1f);
gl.glVertex3f(nodePos.x() - (nodeWidth / 2.0f) + size, nodePos.y() + nodeHeight / 2.0f, nodePos.z() + 0.1f);
gl.glVertex3f(nodePos.x() - nodeWidth / 2.0f, nodePos.y() + nodeHeight / 2.0f - size,
nodePos.z() + 0.1f);
gl.glEnd();
}
| public void render(GL2 gl) {
Vec3f nodePos = node.getPosition();
float nodeHeight = node.getHeight();
float nodeWidth = node.getWidth();
float size = pixelGLConverter.getGLHeightForPixelHeight(GLYPH_SIZE);
gl.glColor4f(0.3f, 0.3f, 0.3f, 1f);
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex3f(nodePos.x() - nodeWidth / 2.0f, nodePos.y() + nodeHeight / 2.0f, nodePos.z() + 0.1f);
gl.glVertex3f(nodePos.x() - (nodeWidth / 2.0f) + size, nodePos.y() + nodeHeight / 2.0f, nodePos.z() + 0.1f);
gl.glVertex3f(nodePos.x() - nodeWidth / 2.0f, nodePos.y() + nodeHeight / 2.0f - size,
nodePos.z() + 0.1f);
gl.glEnd();
}
|
diff --git a/gitools-core/src/main/java/org/gitools/persistence/text/ModuleMapText2CPersistence.java b/gitools-core/src/main/java/org/gitools/persistence/text/ModuleMapText2CPersistence.java
index 22a6c178..68805834 100644
--- a/gitools-core/src/main/java/org/gitools/persistence/text/ModuleMapText2CPersistence.java
+++ b/gitools-core/src/main/java/org/gitools/persistence/text/ModuleMapText2CPersistence.java
@@ -1,229 +1,233 @@
/*
* Copyright 2010 Universitat Pompeu Fabra.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.
*/
package org.gitools.persistence.text;
import edu.upf.bg.progressmonitor.IProgressMonitor;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.csv.CSVParser;
import org.gitools.model.ModuleMap;
import org.gitools.persistence.PersistenceException;
import org.gitools.persistence.PersistenceUtils;
import org.gitools.utils.CSVStrategies;
/** Read/Write modules from a two columns tabulated file,
* first column for item and second for module. */
public class ModuleMapText2CPersistence
extends ModuleMapPersistence<ModuleMap>{
@Override
public ModuleMap read(File file, IProgressMonitor monitor) throws PersistenceException {
// map between the item names and its index
Map<String, Integer> itemNameToRowMapping = new TreeMap<String, Integer>();
if (isItemNamesFilterEnabled()) {
String[] itemNames = getItemNames();
- for (int i = 0; i < itemNames.length; i++)
- itemNameToRowMapping.put(itemNames[i], i);
- }
+ for (int i = 0; i < itemNames.length; i++) {
+ if (itemNameToRowMapping.containsKey(itemNames[i]))
+ throw new PersistenceException("Modules not mappable to heatmap due to duplicated row: " + itemNames[i]);
+ else
+ itemNameToRowMapping.put(itemNames[i], i);
+ }
+ }
// map between modules and item indices
final Map<String, Set<Integer>> moduleItemsMap =
new HashMap<String, Set<Integer>>();
// read mappings
try {
monitor.begin("Reading modules ...", 1);
Reader reader = PersistenceUtils.openReader(file);
CSVParser parser = new CSVParser(reader, CSVStrategies.TSV);
readModuleMappings(parser, isItemNamesFilterEnabled(),
itemNameToRowMapping, moduleItemsMap);
monitor.end();
}
catch (Exception ex) {
throw new PersistenceException(ex);
}
monitor.begin("Filtering modules ...", 1);
int minSize = getMinSize();
int maxSize = getMaxSize();
// create array of item names
//monitor.debug("isItemNamesFilterEnabled() = " + isItemNamesFilterEnabled());
//monitor.debug("itemNameToRowMapping.size() = " + itemNameToRowMapping.size());
String[] itemNames = new String[itemNameToRowMapping.size()];
for (Map.Entry<String, Integer> entry : itemNameToRowMapping.entrySet()) {
//monitor.debug(entry.getKey() + " --> " + entry.getValue());
itemNames[entry.getValue()] = entry.getKey();
}
// mask of used items
BitSet used = new BitSet(itemNames.length);
// remappend indices
int lastIndex = 0;
int[] indexMap = new int[itemNames.length];
// filter modules by size and identify which items are indexed
List<String> moduleNames = new ArrayList<String>();
List<int[]> modulesItemIndices = new ArrayList<int[]>();
Iterator<Entry<String, Set<Integer>>> it =
moduleItemsMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Set<Integer>> entry = it.next();
Set<Integer> indices = entry.getValue();
if (indices.size() >= minSize && indices.size() <= maxSize) {
moduleNames.add(entry.getKey());
int[] remapedIndices = new int[indices.size()];
Iterator<Integer> iit = indices.iterator();
for (int i = 0; i < indices.size(); i++) {
int index = iit.next();
if (!used.get(index)) {
used.set(index);
indexMap[index] = lastIndex++;
}
remapedIndices[i] = indexMap[index];
}
modulesItemIndices.add(remapedIndices);
}
else
it.remove();
}
// reorder item names according with remaped indices
String[] finalItemNames = new String[lastIndex];
for (int i = 0; i < itemNames.length; i++)
if (used.get(i))
finalItemNames[indexMap[i]] = itemNames[i];
monitor.end();
ModuleMap mmap = new ModuleMap();
mmap.setItemNames(finalItemNames);
mmap.setModuleNames(moduleNames.toArray(new String[moduleNames.size()]));
mmap.setAllItemIndices(modulesItemIndices.toArray(new int[modulesItemIndices.size()][]));
return mmap;
}
protected void readModuleMappings(
CSVParser parser,
boolean filterRows,
Map<String, Integer> itemNameToRowMapping,
Map<String, Set<Integer>> moduleItemsMap)
throws PersistenceException {
try {
String[] fields;
while ((fields = parser.getLine()) != null) {
if (fields.length < 2)
throw new PersistenceException(
"At least 2 columns expected at "
+ parser.getLineNumber()
+ "(item name and group name).");
String itemName = fields[0];
String groupName = fields[1];
Integer itemIndex = itemNameToRowMapping.get(itemName);
if (itemIndex == null && !filterRows) {
itemIndex = itemNameToRowMapping.size();
itemNameToRowMapping.put(itemName, itemIndex);
}
if (itemIndex != null) {
Set<Integer> itemIndices = moduleItemsMap.get(groupName);
if (itemIndices == null) {
itemIndices = new TreeSet<Integer>();
moduleItemsMap.put(groupName, itemIndices);
}
itemIndices.add(itemIndex);
}
}
}
catch (IOException e) {
throw new PersistenceException(e);
}
}
@Override
public void write(File file, ModuleMap moduleMap, IProgressMonitor monitor) throws PersistenceException {
final String[] moduleNames = moduleMap.getModuleNames();
int numModules = moduleNames.length;
monitor.begin("Saving modules...", numModules);
try {
Writer writer = PersistenceUtils.openWriter(file);
final PrintWriter pw = new PrintWriter(writer);
final String[] itemNames = moduleMap.getItemNames();
final int[][] indices = moduleMap.getAllItemIndices();
for (int i = 0; i < numModules; i++) {
for (int index : indices[i]) {
pw.print(itemNames[index]);
pw.print('\t');
pw.print(moduleNames[i]);
pw.print('\n');
}
monitor.worked(1);
}
pw.close();
monitor.end();
}
catch (Exception e) {
throw new PersistenceException(e);
}
}
}
| true | true | public ModuleMap read(File file, IProgressMonitor monitor) throws PersistenceException {
// map between the item names and its index
Map<String, Integer> itemNameToRowMapping = new TreeMap<String, Integer>();
if (isItemNamesFilterEnabled()) {
String[] itemNames = getItemNames();
for (int i = 0; i < itemNames.length; i++)
itemNameToRowMapping.put(itemNames[i], i);
}
// map between modules and item indices
final Map<String, Set<Integer>> moduleItemsMap =
new HashMap<String, Set<Integer>>();
// read mappings
try {
monitor.begin("Reading modules ...", 1);
Reader reader = PersistenceUtils.openReader(file);
CSVParser parser = new CSVParser(reader, CSVStrategies.TSV);
readModuleMappings(parser, isItemNamesFilterEnabled(),
itemNameToRowMapping, moduleItemsMap);
monitor.end();
}
catch (Exception ex) {
throw new PersistenceException(ex);
}
monitor.begin("Filtering modules ...", 1);
int minSize = getMinSize();
int maxSize = getMaxSize();
// create array of item names
//monitor.debug("isItemNamesFilterEnabled() = " + isItemNamesFilterEnabled());
//monitor.debug("itemNameToRowMapping.size() = " + itemNameToRowMapping.size());
String[] itemNames = new String[itemNameToRowMapping.size()];
for (Map.Entry<String, Integer> entry : itemNameToRowMapping.entrySet()) {
//monitor.debug(entry.getKey() + " --> " + entry.getValue());
itemNames[entry.getValue()] = entry.getKey();
}
// mask of used items
BitSet used = new BitSet(itemNames.length);
// remappend indices
int lastIndex = 0;
int[] indexMap = new int[itemNames.length];
// filter modules by size and identify which items are indexed
List<String> moduleNames = new ArrayList<String>();
List<int[]> modulesItemIndices = new ArrayList<int[]>();
Iterator<Entry<String, Set<Integer>>> it =
moduleItemsMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Set<Integer>> entry = it.next();
Set<Integer> indices = entry.getValue();
if (indices.size() >= minSize && indices.size() <= maxSize) {
moduleNames.add(entry.getKey());
int[] remapedIndices = new int[indices.size()];
Iterator<Integer> iit = indices.iterator();
for (int i = 0; i < indices.size(); i++) {
int index = iit.next();
if (!used.get(index)) {
used.set(index);
indexMap[index] = lastIndex++;
}
remapedIndices[i] = indexMap[index];
}
modulesItemIndices.add(remapedIndices);
}
else
it.remove();
}
// reorder item names according with remaped indices
String[] finalItemNames = new String[lastIndex];
for (int i = 0; i < itemNames.length; i++)
if (used.get(i))
finalItemNames[indexMap[i]] = itemNames[i];
monitor.end();
ModuleMap mmap = new ModuleMap();
mmap.setItemNames(finalItemNames);
mmap.setModuleNames(moduleNames.toArray(new String[moduleNames.size()]));
mmap.setAllItemIndices(modulesItemIndices.toArray(new int[modulesItemIndices.size()][]));
return mmap;
}
| public ModuleMap read(File file, IProgressMonitor monitor) throws PersistenceException {
// map between the item names and its index
Map<String, Integer> itemNameToRowMapping = new TreeMap<String, Integer>();
if (isItemNamesFilterEnabled()) {
String[] itemNames = getItemNames();
for (int i = 0; i < itemNames.length; i++) {
if (itemNameToRowMapping.containsKey(itemNames[i]))
throw new PersistenceException("Modules not mappable to heatmap due to duplicated row: " + itemNames[i]);
else
itemNameToRowMapping.put(itemNames[i], i);
}
}
// map between modules and item indices
final Map<String, Set<Integer>> moduleItemsMap =
new HashMap<String, Set<Integer>>();
// read mappings
try {
monitor.begin("Reading modules ...", 1);
Reader reader = PersistenceUtils.openReader(file);
CSVParser parser = new CSVParser(reader, CSVStrategies.TSV);
readModuleMappings(parser, isItemNamesFilterEnabled(),
itemNameToRowMapping, moduleItemsMap);
monitor.end();
}
catch (Exception ex) {
throw new PersistenceException(ex);
}
monitor.begin("Filtering modules ...", 1);
int minSize = getMinSize();
int maxSize = getMaxSize();
// create array of item names
//monitor.debug("isItemNamesFilterEnabled() = " + isItemNamesFilterEnabled());
//monitor.debug("itemNameToRowMapping.size() = " + itemNameToRowMapping.size());
String[] itemNames = new String[itemNameToRowMapping.size()];
for (Map.Entry<String, Integer> entry : itemNameToRowMapping.entrySet()) {
//monitor.debug(entry.getKey() + " --> " + entry.getValue());
itemNames[entry.getValue()] = entry.getKey();
}
// mask of used items
BitSet used = new BitSet(itemNames.length);
// remappend indices
int lastIndex = 0;
int[] indexMap = new int[itemNames.length];
// filter modules by size and identify which items are indexed
List<String> moduleNames = new ArrayList<String>();
List<int[]> modulesItemIndices = new ArrayList<int[]>();
Iterator<Entry<String, Set<Integer>>> it =
moduleItemsMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Set<Integer>> entry = it.next();
Set<Integer> indices = entry.getValue();
if (indices.size() >= minSize && indices.size() <= maxSize) {
moduleNames.add(entry.getKey());
int[] remapedIndices = new int[indices.size()];
Iterator<Integer> iit = indices.iterator();
for (int i = 0; i < indices.size(); i++) {
int index = iit.next();
if (!used.get(index)) {
used.set(index);
indexMap[index] = lastIndex++;
}
remapedIndices[i] = indexMap[index];
}
modulesItemIndices.add(remapedIndices);
}
else
it.remove();
}
// reorder item names according with remaped indices
String[] finalItemNames = new String[lastIndex];
for (int i = 0; i < itemNames.length; i++)
if (used.get(i))
finalItemNames[indexMap[i]] = itemNames[i];
monitor.end();
ModuleMap mmap = new ModuleMap();
mmap.setItemNames(finalItemNames);
mmap.setModuleNames(moduleNames.toArray(new String[moduleNames.size()]));
mmap.setAllItemIndices(modulesItemIndices.toArray(new int[modulesItemIndices.size()][]));
return mmap;
}
|
diff --git a/src/org/eclipse/jface/viewers/ColumnViewerToolTipSupport.java b/src/org/eclipse/jface/viewers/ColumnViewerToolTipSupport.java
index 5a3ffd73..cb4adb56 100644
--- a/src/org/eclipse/jface/viewers/ColumnViewerToolTipSupport.java
+++ b/src/org/eclipse/jface/viewers/ColumnViewerToolTipSupport.java
@@ -1,164 +1,165 @@
/*******************************************************************************
* Copyright (c) 2006, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Tom Schindl <[email protected]> - initial API and implementation
* Fredy Dobler <[email protected]> - bug 159600
*******************************************************************************/
package org.eclipse.jface.viewers;
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.window.DefaultToolTip;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Event;
/**
* The ColumnViewerTooltipSupport is the class that provides tooltips for ColumnViewers.
*
* @since 3.3
*
*/
public class ColumnViewerToolTipSupport extends DefaultToolTip {
private ColumnViewer viewer;
private static final String LABEL_PROVIDER_KEY = Policy.JFACE
+ "_LABEL_PROVIDER"; //$NON-NLS-1$
private static final String ELEMENT_KEY = Policy.JFACE + "_ELEMENT_KEY"; //$NON-NLS-1$
private static final int DEFAULT_SHIFT_X = 10;
private static final int DEFAULT_SHIFT_Y = 0;
/**
* Enable ToolTip support for the viewer by creating an instance from this
* class. To get all necessary informations this support class consults the
* {@link CellLabelProvider}.
*
* @param viewer
* the viewer the support is attached to
* @param style style passed to control tooltip behaviour
*
* @param manualActivation
* <code>true</code> if the activation is done manually using
* {@link #show(Point)}
*/
protected ColumnViewerToolTipSupport(ColumnViewer viewer, int style, boolean manualActivation ) {
super(viewer.getControl(),style,manualActivation);
this.viewer = viewer;
}
/**
* Enable ToolTip support for the viewer by creating an instance from this
* class. To get all necessary informations this support class consults the
* {@link CellLabelProvider}.
*
* @param viewer
* the viewer the support is attached to
*/
public static void enableFor(ColumnViewer viewer) {
new ColumnViewerToolTipSupport(viewer,ToolTip.NO_RECREATE,false);
}
/**
* Enable ToolTip support for the viewer by creating an instance from this
* class. To get all necessary informations this support class consults the
* {@link CellLabelProvider}.
*
* @param viewer
* the viewer the support is attached to
* @param style style passed to control tooltip behaviour
*
* @see ToolTip#RECREATE
* @see ToolTip#NO_RECREATE
*/
public static void enableFor(ColumnViewer viewer, int style) {
new ColumnViewerToolTipSupport(viewer,style,false);
}
protected Object getToolTipArea(Event event) {
return viewer.getCell(new Point(event.x,event.y));
}
protected final boolean shouldCreateToolTip(Event event) {
if( ! super.shouldCreateToolTip(event) ) {
return false;
}
boolean rv = false;
ViewerRow row = viewer.getViewerRow(new Point(event.x, event.y));
viewer.getControl().setToolTipText(""); //$NON-NLS-1$
Point point = new Point(event.x, event.y);
if (row != null) {
Object element = row.getItem().getData();
ViewerColumn viewPart = viewer.getViewerColumn(row
.getColumnIndex(point));
if (viewPart == null) {
return false;
}
CellLabelProvider labelProvider = viewPart.getLabelProvider();
if (labelProvider.useNativeToolTip(element)) {
String text = labelProvider.getToolTipText(element);
if (text != null) {
viewer.getControl().setToolTipText(text);
}
rv = false;
} else {
setPopupDelay(labelProvider.getToolTipDisplayDelayTime(element));
setHideDelay(labelProvider.getToolTipTimeDisplayed(element));
Point shift = labelProvider.getToolTipShift(element);
if (shift == null) {
setShift(new Point(DEFAULT_SHIFT_X, DEFAULT_SHIFT_Y));
} else {
setShift(new Point(shift.x, shift.y));
}
setData(LABEL_PROVIDER_KEY, labelProvider);
setData(ELEMENT_KEY, element);
- rv = true;
+ // Check if at least one of the values is set
+ rv = getText(event) != null || getImage(event) != null;
updateData();
}
}
return rv;
}
private void updateData() {
CellLabelProvider labelProvider = (CellLabelProvider) getData(LABEL_PROVIDER_KEY);
Object element = getData(ELEMENT_KEY);
setText(labelProvider.getToolTipText(element));
setStyle(labelProvider.getToolTipStyle(element));
setForegroundColor(labelProvider.getToolTipForegroundColor(element));
setBackgroundColor(labelProvider.getToolTipBackgroundColor(element));
setFont(labelProvider.getToolTipFont(element));
setImage(labelProvider.getToolTipImage(element));
}
protected void afterHideToolTip(Event event) {
if (event != null && event.widget != viewer.getControl()) {
if (event.type == SWT.MouseDown) {
viewer.setSelection(new StructuredSelection());
} else {
viewer.getControl().setFocus();
}
}
}
}
| true | true | protected final boolean shouldCreateToolTip(Event event) {
if( ! super.shouldCreateToolTip(event) ) {
return false;
}
boolean rv = false;
ViewerRow row = viewer.getViewerRow(new Point(event.x, event.y));
viewer.getControl().setToolTipText(""); //$NON-NLS-1$
Point point = new Point(event.x, event.y);
if (row != null) {
Object element = row.getItem().getData();
ViewerColumn viewPart = viewer.getViewerColumn(row
.getColumnIndex(point));
if (viewPart == null) {
return false;
}
CellLabelProvider labelProvider = viewPart.getLabelProvider();
if (labelProvider.useNativeToolTip(element)) {
String text = labelProvider.getToolTipText(element);
if (text != null) {
viewer.getControl().setToolTipText(text);
}
rv = false;
} else {
setPopupDelay(labelProvider.getToolTipDisplayDelayTime(element));
setHideDelay(labelProvider.getToolTipTimeDisplayed(element));
Point shift = labelProvider.getToolTipShift(element);
if (shift == null) {
setShift(new Point(DEFAULT_SHIFT_X, DEFAULT_SHIFT_Y));
} else {
setShift(new Point(shift.x, shift.y));
}
setData(LABEL_PROVIDER_KEY, labelProvider);
setData(ELEMENT_KEY, element);
rv = true;
updateData();
}
}
return rv;
}
| protected final boolean shouldCreateToolTip(Event event) {
if( ! super.shouldCreateToolTip(event) ) {
return false;
}
boolean rv = false;
ViewerRow row = viewer.getViewerRow(new Point(event.x, event.y));
viewer.getControl().setToolTipText(""); //$NON-NLS-1$
Point point = new Point(event.x, event.y);
if (row != null) {
Object element = row.getItem().getData();
ViewerColumn viewPart = viewer.getViewerColumn(row
.getColumnIndex(point));
if (viewPart == null) {
return false;
}
CellLabelProvider labelProvider = viewPart.getLabelProvider();
if (labelProvider.useNativeToolTip(element)) {
String text = labelProvider.getToolTipText(element);
if (text != null) {
viewer.getControl().setToolTipText(text);
}
rv = false;
} else {
setPopupDelay(labelProvider.getToolTipDisplayDelayTime(element));
setHideDelay(labelProvider.getToolTipTimeDisplayed(element));
Point shift = labelProvider.getToolTipShift(element);
if (shift == null) {
setShift(new Point(DEFAULT_SHIFT_X, DEFAULT_SHIFT_Y));
} else {
setShift(new Point(shift.x, shift.y));
}
setData(LABEL_PROVIDER_KEY, labelProvider);
setData(ELEMENT_KEY, element);
// Check if at least one of the values is set
rv = getText(event) != null || getImage(event) != null;
updateData();
}
}
return rv;
}
|
diff --git a/trunk/src/java/org/apache/commons/dbcp/BasicDataSourceFactory.java b/trunk/src/java/org/apache/commons/dbcp/BasicDataSourceFactory.java
index 646b750..5a9c859 100644
--- a/trunk/src/java/org/apache/commons/dbcp/BasicDataSourceFactory.java
+++ b/trunk/src/java/org/apache/commons/dbcp/BasicDataSourceFactory.java
@@ -1,363 +1,363 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.dbcp;
import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Collections;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource;
/**
* <p>JNDI object factory that creates an instance of
* <code>BasicDataSource</code> that has been configured based on the
* <code>RefAddr</code> values of the specified <code>Reference</code>,
* which must match the names and data types of the
* <code>BasicDataSource</code> bean properties.</p>
*
* @author Craig R. McClanahan
* @author Dirk Verbeeck
* @version $Revision$ $Date$
*/
public class BasicDataSourceFactory implements ObjectFactory {
private final static String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
private final static String PROP_DEFAULTREADONLY = "defaultReadOnly";
private final static String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
private final static String PROP_DEFAULTCATALOG = "defaultCatalog";
private final static String PROP_DRIVERCLASSNAME = "driverClassName";
private final static String PROP_MAXACTIVE = "maxActive";
private final static String PROP_MAXIDLE = "maxIdle";
private final static String PROP_MINIDLE = "minIdle";
private final static String PROP_INITIALSIZE = "initialSize";
private final static String PROP_MAXWAIT = "maxWait";
private final static String PROP_TESTONBORROW = "testOnBorrow";
private final static String PROP_TESTONRETURN = "testOnReturn";
private final static String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
private final static String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
private final static String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
private final static String PROP_TESTWHILEIDLE = "testWhileIdle";
private final static String PROP_PASSWORD = "password";
private final static String PROP_URL = "url";
private final static String PROP_USERNAME = "username";
private final static String PROP_VALIDATIONQUERY = "validationQuery";
/**
* The property name for initConnectionSqls.
* The associated value String must be of the form [query;]*
* @since 1.3
*/
private final static String PROP_INITCONNECTIONSQLS = "initConnectionSqls";
private final static String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
private final static String PROP_REMOVEABANDONED = "removeAbandoned";
private final static String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
private final static String PROP_LOGABANDONED = "logAbandoned";
private final static String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
private final static String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
private final static String PROP_CONNECTIONPROPERTIES = "connectionProperties";
private final static String[] ALL_PROPERTIES = {
PROP_DEFAULTAUTOCOMMIT,
PROP_DEFAULTREADONLY,
PROP_DEFAULTTRANSACTIONISOLATION,
PROP_DEFAULTCATALOG,
PROP_DRIVERCLASSNAME,
PROP_MAXACTIVE,
PROP_MAXIDLE,
PROP_MINIDLE,
PROP_INITIALSIZE,
PROP_MAXWAIT,
PROP_TESTONBORROW,
PROP_TESTONRETURN,
PROP_TIMEBETWEENEVICTIONRUNSMILLIS,
PROP_NUMTESTSPEREVICTIONRUN,
PROP_MINEVICTABLEIDLETIMEMILLIS,
PROP_TESTWHILEIDLE,
PROP_PASSWORD,
PROP_URL,
PROP_USERNAME,
PROP_VALIDATIONQUERY,
PROP_INITCONNECTIONSQLS,
PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED,
PROP_REMOVEABANDONED,
PROP_REMOVEABANDONEDTIMEOUT,
PROP_LOGABANDONED,
PROP_POOLPREPAREDSTATEMENTS,
PROP_MAXOPENPREPAREDSTATEMENTS,
PROP_CONNECTIONPROPERTIES
};
// -------------------------------------------------- ObjectFactory Methods
/**
* <p>Create and return a new <code>BasicDataSource</code> instance. If no
* instance can be created, return <code>null</code> instead.</p>
*
* @param obj The possibly null object containing location or
* reference information that can be used in creating an object
* @param name The name of this object relative to <code>nameCtx</code>
* @param nameCtx The context relative to which the <code>name</code>
* parameter is specified, or <code>null</code> if <code>name</code>
* is relative to the default initial context
* @param environment The possibly null environment that is used in
* creating this object
*
* @exception Exception if an exception occurs creating the instance
*/
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable environment)
throws Exception {
// We only know how to deal with <code>javax.naming.Reference</code>s
// that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference)) {
return null;
}
Reference ref = (Reference) obj;
if (!"javax.sql.DataSource".equals(ref.getClassName())) {
return null;
}
Properties properties = new Properties();
for (int i = 0 ; i < ALL_PROPERTIES.length ; i++) {
String propertyName = ALL_PROPERTIES[i];
RefAddr ra = ref.get(propertyName);
if (ra != null) {
String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue);
}
}
return createDataSource(properties);
}
/**
* Creates and configures a {@link BasicDataSource} instance based on the
* given properties.
*
* @param properties the datasource configuration properties
* @throws Exception if an error occurs creating the data source
*/
public static DataSource createDataSource(Properties properties) throws Exception {
BasicDataSource dataSource = new BasicDataSource();
String value = null;
value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
}
else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
}
else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
}
else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
}
else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
}
else {
try {
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation: " + value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
}
}
dataSource.setDefaultTransactionIsolation(level);
}
value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
dataSource.setDefaultCatalog(value);
}
value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
}
value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
dataSource.setMaxActive(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
dataSource.setMaxIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
dataSource.setMinIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
dataSource.setInitialSize(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
dataSource.setMaxWait(Long.parseLong(value));
}
value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
}
value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
}
value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
}
value = properties.getProperty(PROP_URL);
if (value != null) {
dataSource.setUrl(value);
}
value = properties.getProperty(PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
}
value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
dataSource.setValidationQuery(value);
}
value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONED);
if (value != null) {
dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
if (value != null) {
dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_LOGABANDONED);
if (value != null) {
dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITCONNECTIONSQLS);
if (value != null) {
StringTokenizer tokenizer = new StringTokenizer(value, ";");
dataSource.setConnectionInitSqls(Collections.list(tokenizer));
}
value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
Enumeration e = p.propertyNames();
while (e.hasMoreElements()) {
String propertyName = (String) e.nextElement();
dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
}
}
// DBCP-215
// Trick to make sure that initialSize connections are created
- if (dataSource.initialSize > 0) {
+ if (dataSource.getInitialSize() > 0) {
dataSource.getLogWriter();
}
// Return the configured DataSource instance
return dataSource;
}
/**
* <p>Parse properties from the string. Format of the string must be [propertyName=property;]*<p>
* @param propText
* @return Properties
* @throws Exception
*/
static private Properties getProperties(String propText) throws Exception {
Properties p = new Properties();
if (propText != null) {
p.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes()));
}
return p;
}
}
| true | true | public static DataSource createDataSource(Properties properties) throws Exception {
BasicDataSource dataSource = new BasicDataSource();
String value = null;
value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
}
else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
}
else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
}
else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
}
else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
}
else {
try {
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation: " + value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
}
}
dataSource.setDefaultTransactionIsolation(level);
}
value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
dataSource.setDefaultCatalog(value);
}
value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
}
value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
dataSource.setMaxActive(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
dataSource.setMaxIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
dataSource.setMinIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
dataSource.setInitialSize(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
dataSource.setMaxWait(Long.parseLong(value));
}
value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
}
value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
}
value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
}
value = properties.getProperty(PROP_URL);
if (value != null) {
dataSource.setUrl(value);
}
value = properties.getProperty(PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
}
value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
dataSource.setValidationQuery(value);
}
value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONED);
if (value != null) {
dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
if (value != null) {
dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_LOGABANDONED);
if (value != null) {
dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITCONNECTIONSQLS);
if (value != null) {
StringTokenizer tokenizer = new StringTokenizer(value, ";");
dataSource.setConnectionInitSqls(Collections.list(tokenizer));
}
value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
Enumeration e = p.propertyNames();
while (e.hasMoreElements()) {
String propertyName = (String) e.nextElement();
dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
}
}
// DBCP-215
// Trick to make sure that initialSize connections are created
if (dataSource.initialSize > 0) {
dataSource.getLogWriter();
}
// Return the configured DataSource instance
return dataSource;
}
| public static DataSource createDataSource(Properties properties) throws Exception {
BasicDataSource dataSource = new BasicDataSource();
String value = null;
value = properties.getProperty(PROP_DEFAULTAUTOCOMMIT);
if (value != null) {
dataSource.setDefaultAutoCommit(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_DEFAULTREADONLY);
if (value != null) {
dataSource.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_DEFAULTTRANSACTIONISOLATION);
if (value != null) {
int level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
if ("NONE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_NONE;
}
else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_COMMITTED;
}
else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_READ_UNCOMMITTED;
}
else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_REPEATABLE_READ;
}
else if ("SERIALIZABLE".equalsIgnoreCase(value)) {
level = Connection.TRANSACTION_SERIALIZABLE;
}
else {
try {
level = Integer.parseInt(value);
} catch (NumberFormatException e) {
System.err.println("Could not parse defaultTransactionIsolation: " + value);
System.err.println("WARNING: defaultTransactionIsolation not set");
System.err.println("using default value of database driver");
level = PoolableConnectionFactory.UNKNOWN_TRANSACTIONISOLATION;
}
}
dataSource.setDefaultTransactionIsolation(level);
}
value = properties.getProperty(PROP_DEFAULTCATALOG);
if (value != null) {
dataSource.setDefaultCatalog(value);
}
value = properties.getProperty(PROP_DRIVERCLASSNAME);
if (value != null) {
dataSource.setDriverClassName(value);
}
value = properties.getProperty(PROP_MAXACTIVE);
if (value != null) {
dataSource.setMaxActive(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXIDLE);
if (value != null) {
dataSource.setMaxIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINIDLE);
if (value != null) {
dataSource.setMinIdle(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITIALSIZE);
if (value != null) {
dataSource.setInitialSize(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MAXWAIT);
if (value != null) {
dataSource.setMaxWait(Long.parseLong(value));
}
value = properties.getProperty(PROP_TESTONBORROW);
if (value != null) {
dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TESTONRETURN);
if (value != null) {
dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_TIMEBETWEENEVICTIONRUNSMILLIS);
if (value != null) {
dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
}
value = properties.getProperty(PROP_NUMTESTSPEREVICTIONRUN);
if (value != null) {
dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
}
value = properties.getProperty(PROP_MINEVICTABLEIDLETIMEMILLIS);
if (value != null) {
dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
}
value = properties.getProperty(PROP_TESTWHILEIDLE);
if (value != null) {
dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_PASSWORD);
if (value != null) {
dataSource.setPassword(value);
}
value = properties.getProperty(PROP_URL);
if (value != null) {
dataSource.setUrl(value);
}
value = properties.getProperty(PROP_USERNAME);
if (value != null) {
dataSource.setUsername(value);
}
value = properties.getProperty(PROP_VALIDATIONQUERY);
if (value != null) {
dataSource.setValidationQuery(value);
}
value = properties.getProperty(PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED);
if (value != null) {
dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONED);
if (value != null) {
dataSource.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_REMOVEABANDONEDTIMEOUT);
if (value != null) {
dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
}
value = properties.getProperty(PROP_LOGABANDONED);
if (value != null) {
dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_POOLPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setPoolPreparedStatements(Boolean.valueOf(value).booleanValue());
}
value = properties.getProperty(PROP_MAXOPENPREPAREDSTATEMENTS);
if (value != null) {
dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
}
value = properties.getProperty(PROP_INITCONNECTIONSQLS);
if (value != null) {
StringTokenizer tokenizer = new StringTokenizer(value, ";");
dataSource.setConnectionInitSqls(Collections.list(tokenizer));
}
value = properties.getProperty(PROP_CONNECTIONPROPERTIES);
if (value != null) {
Properties p = getProperties(value);
Enumeration e = p.propertyNames();
while (e.hasMoreElements()) {
String propertyName = (String) e.nextElement();
dataSource.addConnectionProperty(propertyName, p.getProperty(propertyName));
}
}
// DBCP-215
// Trick to make sure that initialSize connections are created
if (dataSource.getInitialSize() > 0) {
dataSource.getLogWriter();
}
// Return the configured DataSource instance
return dataSource;
}
|
diff --git a/buildhealth.analysers/src/org/pescuma/buildhealth/analyser/diskusage/DiskUsageAnalyser.java b/buildhealth.analysers/src/org/pescuma/buildhealth/analyser/diskusage/DiskUsageAnalyser.java
index 050daca..39880ee 100644
--- a/buildhealth.analysers/src/org/pescuma/buildhealth/analyser/diskusage/DiskUsageAnalyser.java
+++ b/buildhealth.analysers/src/org/pescuma/buildhealth/analyser/diskusage/DiskUsageAnalyser.java
@@ -1,169 +1,169 @@
package org.pescuma.buildhealth.analyser.diskusage;
import static java.util.Arrays.*;
import static org.pescuma.buildhealth.analyser.NumbersFormater.*;
import static org.pescuma.buildhealth.core.BuildHealth.ReportFlags.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import org.kohsuke.MetaInfServices;
import org.pescuma.buildhealth.analyser.BuildHealthAnalyser;
import org.pescuma.buildhealth.analyser.utils.SimpleTree;
import org.pescuma.buildhealth.core.BuildData;
import org.pescuma.buildhealth.core.BuildData.Line;
import org.pescuma.buildhealth.core.BuildStatus;
import org.pescuma.buildhealth.core.Report;
import org.pescuma.buildhealth.core.prefs.BuildHealthPreference;
import org.pescuma.buildhealth.prefs.Preferences;
import com.google.common.base.Function;
/**
* Expect the lines to be:
*
* <pre>
* Disk usage,tag (optional),folder or file name (optional)
* </pre>
*
* All values are in bytes
*
* Example:
*
* <pre>
* 10 | Disk usage
* 1024 | Disk usage,Executable
* 1024 | Disk usage,Executable,/tmp/X
* </pre>
*/
@MetaInfServices
public class DiskUsageAnalyser implements BuildHealthAnalyser {
public static final int COLUMN_TAG = 1;
public static final int COLUMN_PATH = 2;
@Override
public String getName() {
return "Disk usage";
}
@Override
public int getPriority() {
return 600;
}
@Override
public List<BuildHealthPreference> getPreferences() {
List<BuildHealthPreference> result = new ArrayList<BuildHealthPreference>();
result.add(new BuildHealthPreference("If file tags should be used in the full report tree", "true",
"diskUsage", "reportWithTags"));
return Collections.unmodifiableList(result);
}
@Override
public List<Report> computeReport(BuildData data, Preferences prefs, int opts) {
data = data.filter("Disk usage");
if (data.isEmpty())
return Collections.emptyList();
prefs = prefs.child("diskUsage");
boolean summaryOnly = (opts & SummaryOnly) != 0;
if (summaryOnly) {
double total = data.sum();
return asList(new Report(BuildStatus.Good, getName(), formatBytes(total)));
}
boolean useTags = prefs.get("reportWithTags", true);
if (useTags && !hasTags(data))
useTags = false;
SimpleTree<Stats> tree = buildTree(data, useTags);
propagateToParents(tree);
return asList(toReport(tree.getRoot(), getName()));
}
private boolean hasTags(BuildData data) {
Collection<String> tags = data.getDistinct(COLUMN_TAG);
return tags.size() > 1 || !tags.iterator().next().isEmpty();
}
private SimpleTree<Stats> buildTree(BuildData data, boolean useTags) {
SimpleTree<Stats> tree = new SimpleTree<Stats>(new Function<String[], Stats>() {
@Override
public Stats apply(String[] name) {
return new Stats();
}
});
for (Line line : data.getLines()) {
SimpleTree<Stats>.Node node = tree.getRoot();
if (useTags) {
String tag = line.getColumn(COLUMN_TAG);
if (tag.isEmpty())
tag = "No tag";
node = node.getChild(tag);
}
- String[] path = line.getColumn(COLUMN_PATH).split("(?<=[\\\\\\\\/])");
+ String[] path = line.getColumn(COLUMN_PATH).split("(?<=[\\\\/])");
for (String p : path)
if (!p.isEmpty())
node = node.getChild(p);
node.getData().total += line.getValue();
}
return tree;
}
private void propagateToParents(SimpleTree<Stats> tree) {
tree.visit(new SimpleTree.Visitor<Stats>() {
Deque<Stats> parents = new ArrayDeque<Stats>();
@Override
public void preVisitNode(SimpleTree<Stats>.Node node) {
parents.push(node.getData());
}
@Override
public void posVisitNode(SimpleTree<Stats>.Node node) {
parents.pop();
Stats stats = node.getData();
if (!parents.isEmpty())
parents.peekFirst().add(stats);
}
});
}
private Report toReport(SimpleTree<Stats>.Node node, String name) {
List<Report> children = new ArrayList<Report>();
for (SimpleTree<Stats>.Node child : node.getChildren())
children.add(toReport(child, child.getName()));
Stats stats = node.getData();
return new Report(BuildStatus.Good, name, formatBytes(stats.total), children);
}
private static class Stats {
double total;
void add(Stats stats) {
total += stats.total;
}
}
}
| true | true | private SimpleTree<Stats> buildTree(BuildData data, boolean useTags) {
SimpleTree<Stats> tree = new SimpleTree<Stats>(new Function<String[], Stats>() {
@Override
public Stats apply(String[] name) {
return new Stats();
}
});
for (Line line : data.getLines()) {
SimpleTree<Stats>.Node node = tree.getRoot();
if (useTags) {
String tag = line.getColumn(COLUMN_TAG);
if (tag.isEmpty())
tag = "No tag";
node = node.getChild(tag);
}
String[] path = line.getColumn(COLUMN_PATH).split("(?<=[\\\\\\\\/])");
for (String p : path)
if (!p.isEmpty())
node = node.getChild(p);
node.getData().total += line.getValue();
}
return tree;
}
| private SimpleTree<Stats> buildTree(BuildData data, boolean useTags) {
SimpleTree<Stats> tree = new SimpleTree<Stats>(new Function<String[], Stats>() {
@Override
public Stats apply(String[] name) {
return new Stats();
}
});
for (Line line : data.getLines()) {
SimpleTree<Stats>.Node node = tree.getRoot();
if (useTags) {
String tag = line.getColumn(COLUMN_TAG);
if (tag.isEmpty())
tag = "No tag";
node = node.getChild(tag);
}
String[] path = line.getColumn(COLUMN_PATH).split("(?<=[\\\\/])");
for (String p : path)
if (!p.isEmpty())
node = node.getChild(p);
node.getData().total += line.getValue();
}
return tree;
}
|
diff --git a/src/master/src/org/drftpd/vfs/DirectoryHandle.java b/src/master/src/org/drftpd/vfs/DirectoryHandle.java
index 888fa76f..ab0173ca 100644
--- a/src/master/src/org/drftpd/vfs/DirectoryHandle.java
+++ b/src/master/src/org/drftpd/vfs/DirectoryHandle.java
@@ -1,980 +1,987 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* DrFTPD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.vfs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.drftpd.GlobalContext;
import org.drftpd.exceptions.FileExistsException;
import org.drftpd.io.PermissionDeniedException;
import org.drftpd.master.RemoteSlave;
import org.drftpd.slave.LightRemoteInode;
import org.drftpd.usermanager.User;
/**
* @author zubov
* @version $Id$
*/
public class DirectoryHandle extends InodeHandle implements
DirectoryHandleInterface {
public DirectoryHandle(String path) {
super(path);
}
/**
* @param reason
* @throws FileNotFoundException if this Directory does not exist
*/
public void abortAllTransfers(String reason) throws FileNotFoundException {
for (FileHandle file : getFilesUnchecked()) {
try {
file.abortTransfers(reason);
} catch (FileNotFoundException e) {
}
}
}
/**
* Returns a DirectoryHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public DirectoryHandle getNonExistentDirectoryHandle(String name) {
if (name.startsWith(VirtualFileSystem.separator)) {
// absolute path, easy to handle
return new DirectoryHandle(name);
}
// path must be relative
return new DirectoryHandle(getPath() + VirtualFileSystem.separator + name);
}
/**
* Returns a LinkHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public LinkHandle getNonExistentLinkHandle(String name) {
return new LinkHandle(getPath() + VirtualFileSystem.separator + name);
}
/**
* @see org.drftpd.vfs.InodleHandle#getInode()
*/
@Override
public VirtualFileSystemDirectory getInode()
throws FileNotFoundException {
VirtualFileSystemInode inode = super.getInode();
if (inode instanceof VirtualFileSystemDirectory) {
return (VirtualFileSystemDirectory) inode;
}
throw new ClassCastException(
"DirectoryHandle object pointing to Inode:" + inode);
}
/**
* @return all InodeHandles inside this dir.
* @throws FileNotFoundException
*/
public Set<InodeHandle> getInodeHandles(User user) throws FileNotFoundException {
Set<InodeHandle> inodes = getInodeHandlesUnchecked();
for (Iterator<InodeHandle> iter = inodes.iterator(); iter.hasNext();) {
InodeHandle inode = iter.next();
try {
checkHiddenPath(inode, user);
} catch (FileNotFoundException e) {
// file is hidden or a race just happened.
iter.remove();
}
}
return inodes;
}
/**
* @return all InodeHandles inside this dir.
* @throws FileNotFoundException
*/
public Set<InodeHandle> getInodeHandlesUnchecked() throws FileNotFoundException {
return getInode().getInodes();
}
public ArrayList<FileHandle> getAllFilesRecursiveUnchecked() {
ArrayList<FileHandle> files = new ArrayList<FileHandle>();
try {
for (InodeHandle inode : getInodeHandlesUnchecked()) {
if (inode.isFile()) {
files.add((FileHandle) inode);
} else if (inode.isDirectory()) {
files.addAll(((DirectoryHandle)inode).getAllFilesRecursiveUnchecked());
}
}
} catch (FileNotFoundException e) {
// oh well, we just won't have any files to add
}
return files;
}
/**
* This method *does* check for hidden paths.
* @return a set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getFiles(User user) throws FileNotFoundException {
return getFilesUnchecked(getInodeHandles(user));
}
/**
* This method *does* check for hidden paths.
* @return a sorted set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getSortedFiles(User user) throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandles(user));
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getFilesUnchecked(sortedInodes);
}
/**
* This method does not check for hidden paths.
* @return a set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getFilesUnchecked() throws FileNotFoundException {
return getFilesUnchecked(getInodeHandlesUnchecked());
}
/**
* This method does not check for hidden paths.
* @return a sorted set containing only the files of this dir.
* (no links or directories included.)
* @throws FileNotFoundException
*/
public Set<FileHandle> getSortedFilesUnchecked() throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getFilesUnchecked(sortedInodes);
}
private Set<FileHandle> getFilesUnchecked(Collection<InodeHandle> inodes) throws FileNotFoundException {
Set<FileHandle> set = new LinkedHashSet<FileHandle>();
for (InodeHandle handle : getInode().getInodes()) {
if (handle instanceof FileHandle) {
set.add((FileHandle) handle);
}
}
return set;
}
/**.
* This method *does* check for hiddens paths.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getDirectories(User user) throws FileNotFoundException {
return getDirectoriesUnchecked(getInodeHandles(user));
}
/**.
* This method *does* check for hiddens paths.
* @return a sorted set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getSortedDirectories(User user) throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandles(user));
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getDirectoriesUnchecked(sortedInodes);
}
/**
* This method does not check for hiddens paths.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getDirectoriesUnchecked() throws FileNotFoundException {
return getDirectoriesUnchecked(getInodeHandlesUnchecked());
}
/**
* This method does not check for hiddens paths.
* @return a sorted set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
public Set<DirectoryHandle> getSortedDirectoriesUnchecked() throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getDirectoriesUnchecked(sortedInodes);
}
/**
* This method iterates through the given Collection, removing non-Directory objects.
* @return a set containing only the directories of this dir. (no links or files included.)
* @throws FileNotFoundException
*/
private Set<DirectoryHandle> getDirectoriesUnchecked(Collection<InodeHandle> inodes)
throws FileNotFoundException {
Set<DirectoryHandle> set = new LinkedHashSet<DirectoryHandle>();
for (InodeHandle handle : inodes) {
if (handle instanceof DirectoryHandle) {
set.add((DirectoryHandle) handle);
}
}
return set;
}
/**
* This method *does* check for hiddens paths.
* @return a set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getLinks(User user) throws FileNotFoundException {
return getLinksUnchecked(getInodeHandles(user));
}
/**
* This method *does* check for hiddens paths.
* @return a sorted set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getSortedLinks(User user) throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandles(user));
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getLinksUnchecked(sortedInodes);
}
/**
* This method does not check for hiddens paths.
* @return a set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getLinksUnchecked() throws FileNotFoundException {
return getLinksUnchecked(getInodeHandlesUnchecked());
}
/**
* This method does not check for hiddens paths.
* @return a sorted set containing only the links of this dir.
* (no directories or files included.)
* @throws FileNotFoundException
*/
public Set<LinkHandle> getSortedLinksUnchecked() throws FileNotFoundException {
ArrayList<InodeHandle> sortedInodes = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
Collections.sort(sortedInodes,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
return getLinksUnchecked(sortedInodes);
}
private Set<LinkHandle> getLinksUnchecked(Collection<InodeHandle> inodes) {
Set<LinkHandle> set = new LinkedHashSet<LinkHandle>();
for (Iterator<InodeHandle> iter = inodes.iterator(); iter
.hasNext();) {
InodeHandle handle = iter.next();
if (handle instanceof LinkHandle) {
set.add((LinkHandle) handle);
}
}
return set;
}
/**
* @return true if the dir has offline files.
* @throws FileNotFoundException
*/
public boolean hasOfflineFiles() throws FileNotFoundException {
return getOfflineFiles().size() != 0;
}
/**
* @return a set containing only the offline files of this dir.
* @throws FileNotFoundException
*/
private Set<FileHandle> getOfflineFiles() throws FileNotFoundException {
Set<FileHandle> allFiles = getFilesUnchecked();
Set<FileHandle> offlineFiles = new LinkedHashSet<FileHandle>(allFiles.size());
for (FileHandle file : allFiles) {
if (!file.isAvailable())
offlineFiles.add(file);
}
return offlineFiles;
}
/**
* @param name
* @throws FileNotFoundException
*/
public InodeHandle getInodeHandle(String name, User user) throws FileNotFoundException {
InodeHandle inode = getInodeHandleUnchecked(name);
checkHiddenPath(inode, user);
return inode;
}
public InodeHandle getInodeHandleUnchecked(String name) throws FileNotFoundException {
VirtualFileSystemInode inode = getInode().getInodeByName(name);
if (inode.isDirectory()) {
return new DirectoryHandle(inode.getPath());
} else if (inode.isFile()) {
return new FileHandle(inode.getPath());
} else if (inode.isLink()) {
return new LinkHandle(inode.getPath());
}
throw new IllegalStateException(
"Not a directory, file, or link -- punt");
}
public DirectoryHandle getDirectory(String name, User user)
throws FileNotFoundException, ObjectNotValidException {
DirectoryHandle dir = getDirectoryUnchecked(name);
checkHiddenPath(dir, user);
return dir;
}
public DirectoryHandle getDirectoryUnchecked(String name)
throws FileNotFoundException, ObjectNotValidException {
if (name.equals(VirtualFileSystem.separator)) {
return new DirectoryHandle("/");
}
logger.debug("getDirectory(" + name + ")");
if (name.equals("..")) {
return getParent();
} else if (name.startsWith("../")) {
// strip off the ../
return getParent().getDirectoryUnchecked(name.substring(3));
} else if (name.equals(".")) {
return this;
} else if (name.startsWith("./")) {
return getDirectoryUnchecked(name.substring(2));
}
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isDirectory()) {
return (DirectoryHandle) handle;
}
if (handle.isLink()) {
return ((LinkHandle) handle).getTargetDirectoryUnchecked();
}
throw new ObjectNotValidException(name + " is not a directory");
}
public FileHandle getFile(String name, User user) throws FileNotFoundException, ObjectNotValidException {
FileHandle file = getFileUnchecked(name);
checkHiddenPath(file.getParent(), user);
return file;
}
public FileHandle getFileUnchecked(String name) throws FileNotFoundException,
ObjectNotValidException {
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isFile()) {
return (FileHandle) handle;
} else if (handle.isLink()) {
LinkHandle link = (LinkHandle) handle;
return link.getTargetFileUnchecked();
}
throw new ObjectNotValidException(name + " is not a file");
}
public LinkHandle getLink(String name, User user) throws FileNotFoundException,
ObjectNotValidException {
LinkHandle link = getLinkUnchecked(name);
checkHiddenPath(link.getTargetInode(user), user);
return link;
}
public LinkHandle getLinkUnchecked(String name) throws FileNotFoundException,
ObjectNotValidException {
InodeHandle handle = getInodeHandleUnchecked(name);
if (handle.isLink()) {
return (LinkHandle) handle;
}
throw new ObjectNotValidException(name + " is not a link");
}
private void createRemergedFile(LightRemoteInode lrf, RemoteSlave rslave,
boolean collision) throws IOException {
String name = lrf.getName();
if (collision) {
name = lrf.getName() + ".collision." + rslave.getName();
rslave.simpleRename(getPath() + lrf.getPath(), getPath(), name);
}
FileHandle newFile = createFileUnchecked(name, "drftpd", "drftpd",
rslave, lrf.lastModified(), true, lrf.length());
//newFile.setCheckSum(rslave.getCheckSumForPath(newFile.getPath()));
// TODO Implement a Checksum queue on remerge
newFile.setCheckSum(0);
}
public void remerge(List<LightRemoteInode> files, RemoteSlave rslave, long lastModified)
throws IOException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
// create directory for merging
getParent().createDirectoryRecursive(getName(), true);
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
try {
// Update the last modified on the dir, this allows us to get a correct
// timestamp on higher level dirs created recursively when remerging a
// lower level. Additionally if the same dir exists on multiple slaves it
// ensures we use the latest timestamp for the dir from all slaves in the
// VFS
compareAndUpdateLastModified(lastModified);
} catch (FileNotFoundException e) {
// Not sure this should be able to happen, for now log an error
logger.error("Directory not found but was there a second ago!",e);
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source.getName()
+ " from slave " + rslave.getName() +
" isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
- // add the file
- createRemergedFile(source, rslave, false);
+ if (source.isFile()) {
+ // add the file
+ createRemergedFile(source, rslave, false);
+ } else {
+ throw new IOException(
+ source.getName()
+ + " from slave " + rslave.getName() +
+ " isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
+ }
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/
if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collision, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
/**
* Shortcut to create "owner-less" directories.
* @param name
* @return the created directory
* @throws FileExistsException
* @throws FileNotFoundException
*/
public DirectoryHandle createDirectorySystem(String name) throws FileExistsException, FileNotFoundException {
return createDirectorySystem(name, false);
}
/**
* Shortcut to create "owner-less" directories.
* @param name
* @param placeHolderLastModified
* @return the created directory
* @throws FileExistsException
* @throws FileNotFoundException
*/
protected DirectoryHandle createDirectorySystem(String name, boolean placeHolderLastModified)
throws FileExistsException, FileNotFoundException {
return createDirectoryUnchecked(name, "drftpd", "drftpd", placeHolderLastModified);
}
/**
* Given a DirectoryHandle, it makes sure that this directory and all of its parent(s) exist
* @param name
* @throws FileExistsException
* @throws FileNotFoundException
*/
public void createDirectoryRecursive(String name)
throws FileExistsException, FileNotFoundException {
createDirectoryRecursive(name, false);
}
/**
* Given a DirectoryHandle, it makes sure that this directory and all of its parent(s) exist
* @param name
* @param placeHolderLastModified
* @throws FileExistsException
* @throws FileNotFoundException
*/
public void createDirectoryRecursive(String name, boolean placeHolderLastModified)
throws FileExistsException, FileNotFoundException {
DirectoryHandle dir = null;
try {
dir = createDirectorySystem(name, placeHolderLastModified);
} catch (FileNotFoundException e) {
getParent().createDirectoryRecursive(getName(), placeHolderLastModified);
} catch (FileExistsException e) {
throw new FileExistsException("Object already exists -- "
+ getPath() + VirtualFileSystem.separator + name);
}
if (dir == null) {
dir = createDirectorySystem(name, placeHolderLastModified);
}
logger.debug("Created directory " + dir);
}
/**
* Creates a Directory object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For a checked way of creating dirs {@link #createFile(User, String, RemoteSlave)};
* @param name
* @param user
* @param group
* @return the created directory.
* @throws FileNotFoundException
* @throws FileExistsException
*/
public DirectoryHandle createDirectoryUnchecked(String name, String user,
String group) throws FileExistsException, FileNotFoundException {
return createDirectoryUnchecked(name, user, group, false);
}
/**
* Creates a Directory object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For a checked way of creating dirs {@link #createFile(User, String, RemoteSlave)};
* @param name
* @param user
* @param group
* @param placeHolderLastModified
* @return the created directory.
* @throws FileNotFoundException
* @throws FileExistsException
*/
protected DirectoryHandle createDirectoryUnchecked(String name, String user,
String group, boolean placeHolderLastModified) throws FileExistsException, FileNotFoundException {
getInode().createDirectory(name, user, group, placeHolderLastModified);
try {
return getDirectoryUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
/**
* Attempts to create a Directory in the FileSystem with this directory as parent.
* @see For an unchecked way of creating dirs: {@link #createDirectoryUnchecked(String, String, String)}
* @param user
* @param name
* @return the created directory.
* @throws PermissionDeniedException if the given user is not allowed to create dirs.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public DirectoryHandle createDirectory(User user, String name)
throws PermissionDeniedException, FileExistsException, FileNotFoundException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
DirectoryHandle newDir = getNonExistentDirectoryHandle(name);
checkHiddenPath(newDir, user);
if (!getVFSPermissions().checkPathPermission("makedir", user, newDir)) {
throw new PermissionDeniedException("You are not allowed to create a directory at "+ newDir.getParent());
}
return createDirectoryUnchecked(name, user.getName(), user.getGroup());
}
/**
* Creates a File object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For unchecked creating of files {@link #createFileUnchecked(String, String, String, RemoteSlave)}
* @param name
* @param user
* @param group
* @param initialSlave
* @return the created file.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public FileHandle createFileUnchecked(String name, String user, String group,
RemoteSlave initialSlave) throws FileExistsException,
FileNotFoundException {
return createFileUnchecked(name, user, group, initialSlave, 0L, false, 0L);
}
/**
* Creates a File object in the FileSystem with this directory as its parent.<br>
* This method does not check for permissions, so be careful while using it.<br>
* @see For unchecked creating of files {@link #createFileUnchecked(String, String, String, RemoteSlave)}
* @param name
* @param user
* @param group
* @param initialSlave
* @param lastModified
* @param setLastModified
* @param size
* @return the created file.
* @throws FileExistsException
* @throws FileNotFoundException
*/
protected FileHandle createFileUnchecked(String name, String user, String group,
RemoteSlave initialSlave, long lastModified, boolean setLastModified, long size) throws FileExistsException,
FileNotFoundException {
getInode().createFile(name, user, group, initialSlave.getName(), lastModified, setLastModified, size);
try {
return getFileUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
/**
* Attempts to create a File in the FileSystem having this directory as parent.
* @param user
* @param name
* @param initialSlave
* @return
* @throws PermissionDeniedException if the user is not allowed to create a file in this dir.
* @throws FileExistsException
* @throws FileNotFoundException
*/
public FileHandle createFile(User user, String name, RemoteSlave initialSlave)
throws PermissionDeniedException, FileExistsException, FileNotFoundException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
checkHiddenPath(this, user);
if (!getVFSPermissions().checkPathPermission("upload", user, getNonExistentFileHandle(name))) {
throw new PermissionDeniedException("You are not allowed to upload to "+ getParent());
}
return createFileUnchecked(name, user.getName(), user.getGroup(), initialSlave);
}
/**
* Creates a Link object in the FileSystem with this directory as its parent
*/
public LinkHandle createLinkUnchecked(String name, String target, String user,
String group) throws FileExistsException, FileNotFoundException {
getInode().createLink(name, target, user, group);
try {
return getLinkUnchecked(name);
} catch (FileNotFoundException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
} catch (ObjectNotValidException e) {
throw new RuntimeException("Something really funky happened, we just created it", e);
}
}
public LinkHandle createLink(User user, String name, String target)
throws FileExistsException, FileNotFoundException, PermissionDeniedException {
if (user == null) {
throw new PermissionDeniedException("User cannot be null");
}
// check if this dir is hidden.
checkHiddenPath(this, user);
InodeHandle inode = getInodeHandle(target, user);
// check if the target is hidden
checkHiddenPath(inode, user);
if (inode.isLink()) {
throw new PermissionDeniedException("Impossible to point a link to a link");
}
return createLinkUnchecked(name, target, user.getName(), user.getGroup());
}
public boolean isRoot() {
return equals(GlobalContext.getGlobalContext().getRoot());
}
/**
* For use during PRET
* Returns a FileHandle for a possibly non-existant directory in this path
* No verification to its existence is made
* @param name
* @return
*/
public FileHandle getNonExistentFileHandle(String argument) {
if (argument.startsWith(VirtualFileSystem.separator)) {
// absolute path, easy to handle
return new FileHandle(argument);
}
// path must be relative
return new FileHandle(getPath() + VirtualFileSystem.separator
+ argument);
}
public void removeSlave(RemoteSlave rslave) throws FileNotFoundException {
boolean empty = isEmptyUnchecked();
for (InodeHandle inode : getInodeHandlesUnchecked()) {
inode.removeSlave(rslave);
}
if (!empty && isEmptyUnchecked()) { // if it wasn't empty before, but is now, delete it
deleteUnchecked();
}
}
public boolean isEmptyUnchecked() throws FileNotFoundException {
return getInodeHandlesUnchecked().size() == 0;
}
public boolean isEmpty(User user) throws FileNotFoundException, PermissionDeniedException {
// let's fetch the list of existent files inside this dir
// if the dir does not exist, FileNotFoundException is thrown
// if the dir exists the operation continues smoothly.
getInode();
try {
checkHiddenPath(this, user);
} catch (FileNotFoundException e) {
// either a race condition happened or the dir is hidden
// cuz we just checked and the dir was here.
throw new PermissionDeniedException("Unable to check if the directory is empty.");
}
return isEmptyUnchecked();
}
@Override
public boolean isDirectory() {
return true;
}
@Override
public boolean isFile() {
return false;
}
@Override
public boolean isLink() {
return false;
}
@Override
public void deleteUnchecked() throws FileNotFoundException {
abortAllTransfers("Directory " + getPath() + " is being deleted");
GlobalContext.getGlobalContext().getSlaveManager().deleteOnAllSlaves(this);
super.deleteUnchecked();
}
public long validateSizeRecursive() throws FileNotFoundException {
Set<InodeHandle> inodes = getInodeHandlesUnchecked();
long newSize = 0;
long oldSize = getSize();
for (InodeHandle inode : inodes) {
if (inode.isDirectory()) {
((DirectoryHandle) inode).validateSizeRecursive();
}
newSize += inode.getSize();
}
getInode().setSize(newSize);
return oldSize - newSize;
}
protected void compareAndUpdateLastModified(long lastModified) throws FileNotFoundException {
getInode().compareAndUpdateLastModified(lastModified);
}
}
| true | true | public void remerge(List<LightRemoteInode> files, RemoteSlave rslave, long lastModified)
throws IOException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
// create directory for merging
getParent().createDirectoryRecursive(getName(), true);
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
try {
// Update the last modified on the dir, this allows us to get a correct
// timestamp on higher level dirs created recursively when remerging a
// lower level. Additionally if the same dir exists on multiple slaves it
// ensures we use the latest timestamp for the dir from all slaves in the
// VFS
compareAndUpdateLastModified(lastModified);
} catch (FileNotFoundException e) {
// Not sure this should be able to happen, for now log an error
logger.error("Directory not found but was there a second ago!",e);
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source.getName()
+ " from slave " + rslave.getName() +
" isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
// add the file
createRemergedFile(source, rslave, false);
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/
if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collision, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
| public void remerge(List<LightRemoteInode> files, RemoteSlave rslave, long lastModified)
throws IOException {
Iterator<LightRemoteInode> sourceIter = files.iterator();
// source comes pre-sorted from the slave
List<InodeHandle> destinationList = null;
try {
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
} catch (FileNotFoundException e) {
// create directory for merging
getParent().createDirectoryRecursive(getName(), true);
// lets try this again, this time, if it doesn't work, we throw an
// IOException up the chain
destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked());
}
try {
// Update the last modified on the dir, this allows us to get a correct
// timestamp on higher level dirs created recursively when remerging a
// lower level. Additionally if the same dir exists on multiple slaves it
// ensures we use the latest timestamp for the dir from all slaves in the
// VFS
compareAndUpdateLastModified(lastModified);
} catch (FileNotFoundException e) {
// Not sure this should be able to happen, for now log an error
logger.error("Directory not found but was there a second ago!",e);
}
Collections.sort(destinationList,
VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR);
Iterator<InodeHandle> destinationIter = destinationList.iterator();
LightRemoteInode source = null;
InodeHandle destination = null;
if (sourceIter.hasNext()) {
source = sourceIter.next();
}
if (destinationIter.hasNext()) {
destination = destinationIter.next();
}
while (true) {
/*logger.debug("loop, [destination="
+ (destination == null ? "null" : destination.getName())
+ "][source="
+ (source == null ? "null" : source.getName()) + "]");
*/
// source & destination are set at the "next to process" one OR are
// null and at the end of that list
// case1 : source list is out, remove slave from all remaining
// files/directories
if (source == null) {
while (destination != null) {
// can removeSlave()'s from all types of Inodes, no type
// checking needed
destination.removeSlave(rslave);
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
}
// all done, both lists are empty
return;
}
// case2: destination list is out, add files
if (destination == null) {
while (source != null) {
if (source.isFile()) {
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source.getName()
+ " from slave " + rslave.getName() +
" isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
// all done, both lists are empty
return;
}
// both source and destination are non-null
// we don't know which one is first alphabetically
int compare = source.getName().compareToIgnoreCase(
destination.getName());
// compare is < 0, source comes before destination
// compare is > 0, source comes after destination
// compare is == 0, they have the same name
if (compare < 0) {
if (source.isFile()) {
// add the file
createRemergedFile(source, rslave, false);
} else {
throw new IOException(
source.getName()
+ " from slave " + rslave.getName() +
" isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process");
}
// advance one runner
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
} else if (compare > 0) {
// remove the slave
destination.removeSlave(rslave);
// advance one runner
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
} else if (compare == 0) {
if (destination.isLink()) {
// this is bad, links don't exist on slaves
// name collision
if (source.isFile()) {
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
// set crc now?
} else { // source.isDirectory()
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a link on the master");
}
} else if (source.isFile() && destination.isFile()) {
// both files
FileHandle destinationFile = (FileHandle) destination;
/* long sourceCRC = rslave.getCheckSumForPath(getPath()
+ VirtualFileSystem.separator + source.getName());
long destinationCRC;
try {
destinationCRC = destinationFile.getCheckSum();
} catch (NoAvailableSlaveException e) {
destinationCRC = 0L;
}
*/
if (source.length() != destinationFile.getSize()) {
// || (sourceCRC != destinationCRC && destinationCRC != 0L)) {
// handle collision
Set<RemoteSlave> rslaves = destinationFile.getSlaves();
if (rslaves.contains(rslave) && rslaves.size() == 1) {
// size of the file has changed, but since this is the only slave with the file, just change the size
destinationFile.setSize(source.length());
} else {
if (rslaves.contains(rslave)) {
// the master thought the slave had the file, it's not the same size anymore, remove it
destinationFile.removeSlave(rslave);
}
createRemergedFile(source, rslave, true);
logger.warn("In remerging " + rslave.getName()
+ ", a file on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
}
} else {
destinationFile.addSlave(rslave);
}
} else if (source.isDirectory() && destination.isDirectory()) {
// this is good, do nothing other than take up this case
} else {
// we have a directory/name collision, let's find which one
// :)
if (source.isDirectory()) { // & destination.isFile()
// we don't care about directories on the slaves, let's
// just skip it
logger.warn("In remerging " + rslave.getName()
+ ", a directory on the slave (" + getPath()
+ VirtualFileSystem.separator
+ source.getName()
+ ") collided with a file on the master");
} else {
// source.isFile() && destination.isDirectory()
// handle collision
createRemergedFile(source, rslave, true);
// set crc now?
}
}
// advance both runners, they were equal
if (destinationIter.hasNext()) {
destination = destinationIter.next();
} else {
destination = null;
}
if (sourceIter.hasNext()) {
source = sourceIter.next();
} else {
source = null;
}
}
}
}
|
diff --git a/src/Client/Contact.java b/src/Client/Contact.java
index 77fb0d31..4e6f8578 100644
--- a/src/Client/Contact.java
+++ b/src/Client/Contact.java
@@ -1,905 +1,897 @@
/*
* Contact.java
*
* Created on 6.01.2005, 19:16
* Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package Client;
//#ifndef WMUC
import Conference.MucContact;
//#endif
import Fonts.FontCache;
//#ifdef CLIENTS_ICONS
//# import images.ClientsIcons;
//#endif
//#if HISTORY
//# import History.HistoryAppend;
//#endif
import javax.microedition.lcdui.Graphics;
import ui.ImageList;
//#ifdef PEP
//# import images.MoodIcons;
//# import PEP.Moods;
//#endif
import images.RosterIcons;
import Colors.ColorTheme;
import Messages.MessageItem;
import VCard.VCard;
import ui.IconTextElement;
import com.alsutton.jabber.datablocks.Presence;
import java.util.Enumeration;
import java.util.Vector;
import locale.SR;
public class Contact extends IconTextElement {
//#if USE_ROTATOR
//# private int isnew = 0;
//#
//# public void setNewContact() {
//# this.isnew = 8;
//# }
//#endif
//#ifdef PEP
//# public int pepMood = -1;
//# public String pepMoodName = null;
//# public String pepMoodText = null;
//#ifdef PEP_TUNE
//# public boolean pepTune;
//# public String pepTuneText = null;
//#endif
//#ifdef PEP_ACTIVITY
//# public String activity = null;
//#endif
//#ifdef PEP_LOCATION
//# public String location = null;
//#endif
//#endif
public final static short ORIGIN_ROSTER = 0;
public final static short ORIGIN_ROSTERRES = 1;
public final static short ORIGIN_CLONE = 2;
public final static short ORIGIN_PRESENCE = 3;
public final static short ORIGIN_GROUPCHAT = 4;
//#ifndef WMUC
public final static short ORIGIN_GC_MEMBER = 5;
public final static short ORIGIN_GC_MYSELF = 6;
//#endif
public String nick;
public Jid jid;
public String bareJid; // for roster/subscription manipulating
public int status;
public int priority;
public Group group;
public int transport;
public boolean autoresponded = false;
public boolean moveToLatest = false;
public String presence;
public String statusString;
public boolean acceptComposing;
public boolean showComposing = false;
public short deliveryType;
public short incomingState = INC_NONE;
public final static short INC_NONE = 0;
public final static short INC_APPEARING = 1;
public final static short INC_VIEWING = 2;
protected short key0;
protected String key1;
public byte origin;
public String subscr;
public int offline_type = Presence.PRESENCE_UNKNOWN;
public boolean ask_subscribe;
public final Vector msgs;
public int activeMessage = -1;
private int newMsgCnt = 0;
private int newHighLitedMsgCnt = 0;
public int unreadType;
public int lastUnread;
public int mark = -1;
public String msgSuspended;
public String lastSendedMessage;
public VCard vcard;
//#ifdef CLIENTS_ICONS
//# public int client = -1;
//# public String clientName = null;
//#endif
//#ifdef LOGROTATE
//# public boolean redraw = false;
//#endif
public String j2j;
public String lang;
public String version;
//#ifdef FILE_TRANSFER
//# public boolean fileQuery;
//#endif
//#ifdef HISTORY
//#ifdef LAST_MESSAGES
//# private boolean loaded;
//#endif
//#endif
StaticData sd = StaticData.getInstance();
//private Font secondFont; //Issue 88
//private int secondFontHeight;
private int fontHeight;
int ilHeight;
int maxImgHeight;
private boolean smiles = false;
ContactMessageList cml = null;
protected Contact() {
super(RosterIcons.getInstance());
cf = Config.getInstance();
//#ifdef SMILES
//# smiles = cf.smiles;
//#endif
msgs = new Vector();
key1 = "";
ilHeight = il.getHeight();
maxImgHeight = ilHeight;
//secondFont=FontCache.getFont(false, FontCache.baloon);
//secondFontHeight=secondFont.getHeight();
fontHeight = getFont().getHeight();
}
public Contact(final String Nick, final String sJid, final int Status, String subscr) {
this();
nick = Nick;
jid = new Jid(sJid);
status = Status;
bareJid = sJid;
this.subscr = subscr;
setSortKey((Nick == null) ? sJid : Nick);
//calculating transport
transport = RosterIcons.getInstance().getTransportIndex(jid.getTransport());
}
public Contact clone(Jid newjid, final int status) {
Contact clone = new Contact();
clone.group = group;
clone.jid = newjid;
clone.nick = nick;
clone.key1 = key1;
clone.subscr = subscr;
clone.offline_type = offline_type;
clone.origin = ORIGIN_CLONE;
clone.status = status;
clone.transport = RosterIcons.getInstance().getTransportIndex(newjid.getTransport()); //<<<<
//#ifdef PEP
//# clone.pepMood = pepMood;
//# clone.pepMoodName = pepMoodName;
//# clone.pepMoodText = pepMoodText;
//#ifdef PEP_TUNE
//# clone.pepTune = pepTune;
//# clone.pepTuneText = pepTuneText;
//#endif
//#ifdef PEP_ACTIVITY
//# clone.activity = activity;
//#endif
//#ifdef PEP_LOCATION
//# clone.location = location;
//#endif
//#
//#endif
clone.bareJid = bareJid;
return clone;
}
public int getColor() {
//#if USE_ROTATOR
//# if (isnew > 0) {
//# isnew--;
//# return (isnew % 2 == 0) ? 0xFF0000 : 0x0000FF;
//# }
//#endif
if (j2j != null) {
return ColorTheme.getColor(ColorTheme.CONTACT_J2J);
}
return getMainColor();
}
public int getMainColor() {
switch (status) {
case Presence.PRESENCE_CHAT:
return ColorTheme.getColor(ColorTheme.CONTACT_CHAT);
case Presence.PRESENCE_AWAY:
return ColorTheme.getColor(ColorTheme.CONTACT_AWAY);
case Presence.PRESENCE_XA:
return ColorTheme.getColor(ColorTheme.CONTACT_XA);
case Presence.PRESENCE_DND:
return ColorTheme.getColor(ColorTheme.CONTACT_DND);
}
return ColorTheme.getColor(ColorTheme.CONTACT_DEFAULT);
}
public boolean haveChatMessages() {
for (Enumeration e = msgs.elements(); e.hasMoreElements();) {
Msg msg = ((MessageItem) e.nextElement()).msg;
if (msg.messageType == Msg.MESSAGE_TYPE_IN || msg.messageType == Msg.MESSAGE_TYPE_OUT || msg.messageType == Msg.MESSAGE_TYPE_AUTH) {
return true;
}
}
return false;
}
public int getNewMsgsCount() {
if (msgs.isEmpty()) {
return 0;
}
/* if (newMsgCnt > 0) {
return newMsgCnt;
}*/
int nm = 0;
if (getGroupType() != Groups.TYPE_IGNORE) {
unreadType = Msg.MESSAGE_TYPE_IN;
for (Enumeration e = msgs.elements(); e.hasMoreElements();) {
Msg m = ((MessageItem) e.nextElement()).msg;
if (m.unread) {
nm++;
if (m.messageType == Msg.MESSAGE_TYPE_AUTH) {
unreadType = m.messageType;
}
}
}
}
return newMsgCnt = nm;
}
public int getNewHighliteMsgsCount() {
if (newHighLitedMsgCnt > 0) {
return newHighLitedMsgCnt;
}
int nm = 0;
if (getGroupType() != Groups.TYPE_IGNORE) {
for (Enumeration e = msgs.elements(); e.hasMoreElements();) {
Msg m = ((MessageItem) e.nextElement()).msg;
if (m.unread && m.highlite) {
nm++;
}
}
}
return newHighLitedMsgCnt = nm;
}
public boolean active() {
if (msgSuspended != null) {
return true;
}
return (activeMessage > -1);
}
public void resetNewMsgCnt() {
newMsgCnt = 0;
newHighLitedMsgCnt = 0;
}
public void setIncoming(int state) {
if (!cf.IQNotify && state == INC_VIEWING) {
return;
}
short i = 0;
switch (state) {
case INC_APPEARING:
i = RosterIcons.ICON_APPEARING_INDEX;
break;
case INC_VIEWING:
i = RosterIcons.ICON_VIEWING_INDEX;
break;
}
incomingState = i;
}
public int compare(IconTextElement right) {
Contact c = (Contact) right;
int cmp;
if ((cmp = key0 - c.key0) != 0) {
return cmp;
}
if ((cmp = status - c.status) != 0) {
return cmp;
}
if ((cmp = key1.compareTo(c.key1)) != 0) {
return cmp;
}
if ((cmp = c.priority - priority) != 0) {
return cmp;
}
return c.transport - transport;
}
public void addMessage(Msg m) {
boolean last_replace = false;
if (origin == ORIGIN_GROUPCHAT) {
if (!m.body.startsWith("/me ")) {
if (cf.showNickNames && !m.isPresence() && m.messageType != Msg.MESSAGE_TYPE_SUBJ && m.messageType != Msg.MESSAGE_TYPE_SYSTEM) {
StringBuffer who = new StringBuffer();
- Msg.appendNick(who, m.from);
- if (!cf.hideTimestamps) {
- who.append(" (").append(m.getTime()).append(")");
- }
- who.append(":");
+ Msg.appendNick(who, m.from + ((cf.hideTimestamps) ? ":" : " ("+m.getTime() + ")" + ":"));
if (m.subject != null) {
who.append("\n").append(m.subject);
}
m.subject = who.toString();
}
}
if (m.body.startsWith("/me ")) {
StringBuffer b = new StringBuffer();
Msg.appendNick(b, m.from);
b.insert(0, '*');
b.append(m.body.substring(3));
m.body = b.toString();
b = null;
}
status = Presence.PRESENCE_ONLINE;
//#ifdef LOGROTATE
//# redraw = deleteOldMessages();
//#endif
}
if (origin != ORIGIN_GROUPCHAT) {
if (msgs.size() > 0 && m.isPresence()) {
Object item = msgs.lastElement();
if (item != null) {
if (((MessageItem) item).msg.isPresence()) {
last_replace = true;
}
}
} else {
if (!m.body.startsWith("/me ")) {
if (cf.showNickNames && !m.isPresence()) {
StringBuffer who = new StringBuffer();
- Msg.appendNick(who, m.messageType == Msg.MESSAGE_TYPE_OUT ? sd.account.getNickName() : getName());
- if (!cf.hideTimestamps) {
- who.append(" (").append(m.getTime()).append(")");
- }
- who.append(":");
+ Msg.appendNick(who, m.messageType == Msg.MESSAGE_TYPE_OUT ? sd.account.getNickName() + ((cf.hideTimestamps) ? ":" : " (" + m.getTime() + ")" + ":") : getName() + ((cf.hideTimestamps) ? ":" : " ("+m.getTime() + ")" + ":"));
if (m.subject != null) {
who.append("\n").append(m.subject);
}
m.subject = who.toString();
}
} else { // if (m.body.startsWith("/me "))
StringBuffer b = new StringBuffer();
Msg.appendNick(b, (m.messageType == Msg.MESSAGE_TYPE_OUT) ? sd.account.getNickName() : getName());
b.insert(0, '*');
b.append(m.body.substring(3));
m.body = b.toString();
b = null;
}
}
} else {
status = Presence.PRESENCE_ONLINE;
//#ifdef LOGROTATE
//# redraw = deleteOldMessages();
//#endif
}
//#if HISTORY
//# if (!m.history) {
//# if (!cf.msgPath.equals("") && !jid.isTransport() && group.type != Groups.TYPE_SEARCH_RESULT) {
//# boolean allowLog = false;
//# switch (m.messageType) {
//# case Msg.MESSAGE_TYPE_PRESENCE:
//# if (origin >= ORIGIN_GROUPCHAT) {
//# if (cf.msgLogConfPresence) {
//# allowLog = true;
//# }
//# } else if (cf.msgLogPresence) {
//# allowLog = true;
//# }
//# break;
//# case Msg.MESSAGE_TYPE_HISTORY:
//# break;
//# default:
//# if (origin >= ORIGIN_GROUPCHAT && cf.msgLogConf) {
//# allowLog = true;
//# }
//# if (origin < ORIGIN_GROUPCHAT && cf.msgLog) {
//# allowLog = true;
//# }
//# }
//#
//#ifndef WMUC
//# if (origin != ORIGIN_GROUPCHAT && this instanceof MucContact) {
//# allowLog = false;
//# }
//#endif
//#
//# if (allowLog) {
//# HistoryAppend.getInstance().addMessage(m, bareJid);
//# }
//# }
//# }
//#endif
if (last_replace) {
msgs.setElementAt(new MessageItem(m, smiles), msgs.size() - 1);
return;
}
if (m.messageType != Msg.MESSAGE_TYPE_HISTORY && m.messageType != Msg.MESSAGE_TYPE_PRESENCE) {
activeMessage = msgs.size();
}
msgs.addElement(new MessageItem(m, smiles));
if (m.unread || m.messageType == Msg.MESSAGE_TYPE_OUT) {
lastUnread = msgs.size();
if (m.messageType > unreadType) {
unreadType = m.messageType;
}
if (newMsgCnt >= 0) {
newMsgCnt++;
}
if (m.highlite) {
if (newHighLitedMsgCnt >= 0) {
newHighLitedMsgCnt++;
}
}
}
}
public int getFontIndex() {
if (cf.showResources) {
return (cf.useBoldFont && status < 5) ? 1 : 0;
}
return active() ? 1 : 0;
}
public final String getName() {
return (nick == null) ? bareJid : nick;
}
public final Jid getJid() {
return jid;
}
public String getResource() {
return jid.resource;
}
public String getNickJid() {
if (nick == null) {
return bareJid;
}
return nick + " <" + bareJid + ">";
}
public final void purge() {
msgs.removeAllElements();
lastSendedMessage = null;
activeMessage = -1; //drop activeMessage num
resetNewMsgCnt();
clearVCard();
}
public final void clearVCard() {
try {
if (vcard != null) {
vcard.clearVCard();
vcard = null;
}
} catch (Exception e) {
}
}
//#ifdef LOGROTATE
//# public final boolean deleteOldMessages() {
//# int limit = cf.msglistLimit;
//# if (msgs.size() < limit) {
//# return false;
//# }
//#
//# int trash = msgs.size() - limit;
//# for (int i = 0; i < trash; i++) {
//# msgs.removeElementAt(0);
//# }
//#
//# return true;
//# }
//#endif
public final void setSortKey(String sortKey) {
key1 = (sortKey == null) ? "" : sortKey.toLowerCase();
}
public String getTipString() {
int nm = getNewMsgsCount();
if (nm != 0) {
return String.valueOf(nm);
}
StringBuffer mess = new StringBuffer();
//#ifndef WMUC
boolean isMucContact = (this instanceof MucContact);
if (isMucContact) {
MucContact mucContact = (MucContact) this;
if (mucContact.origin != Contact.ORIGIN_GROUPCHAT) {
mess.append((mucContact.realJid == null) ? "" : "jid: " + mucContact.realJid + "\n");
if (mucContact.affiliationCode > MucContact.AFFILIATION_NONE) {
mess.append(MucContact.getAffiliationLocale(mucContact.affiliationCode));
}
if (!(mucContact.roleCode == MucContact.ROLE_PARTICIPANT && mucContact.affiliationCode == MucContact.AFFILIATION_MEMBER)) {
if (mucContact.affiliationCode > MucContact.AFFILIATION_NONE) {
mess.append(SR.MS_AND);
}
mess.append(MucContact.getRoleLocale(mucContact.roleCode));
}
}
} else {
//#endif
mess.append("jid: ").append(bareJid).append(jid.resource).append("\n").append(SR.MS_SUBSCRIPTION).append(": ").append(subscr);
//#ifdef PEP
//# if (hasMood()) {
//# mess.append("\n").append(SR.MS_USERMOOD).append(": ").append(getMoodString());
//# }
//#ifdef PEP_ACTIVITY
//# if (hasActivity()) {
//# mess.append("\n").append(SR.MS_USERACTIVITY).append(": ").append(activity);
//# }
//#endif
//#ifdef PEP_LOCATION
//# if (hasLocation()) {
//# mess.append("\n").append(SR.MS_USERLOCATION).append(": ").append(location);
//# }
//#endif
//#
//#ifdef PEP_TUNE
//# if (pepTune) {
//# mess.append("\n").append(SR.MS_USERTUNE);
//# if (!pepTuneText.equals("")) {
//# mess.append(": ").append(pepTuneText);
//# }
//# }
//#endif
//#endif
//#ifndef WMUC
}
//#endif
if (origin != Contact.ORIGIN_GROUPCHAT) {
mess.append((j2j != null) ? "\nJ2J: " + j2j : "");
//#ifdef CLIENTS_ICONS
//# if (client > -1) {
//# mess.append("\n").append(SR.MS_USE).append(": ").append(clientName);
//# }
//#endif
if (version != null) {
mess.append("\n").append(SR.MS_VERSION).append(": ").append(version);
}
if (lang != null) {
mess.append("\n").append(SR.MS_LANGUAGE).append(": ").append(lang);
}
}
if (statusString != null) {
if (origin != Contact.ORIGIN_GROUPCHAT) {
mess.append("\n").append(SR.MS_STATUS).append(": ");
}
mess.append(statusString);
if (priority != 0) {
mess.append(" [").append(priority).append("]");
}
}
return mess.toString();
}
public int getGroupType() {
if (group == null) {
return 0;
}
return group.type;
}
public void setStatus(int status) {
setIncoming(0);
this.status = status;
if (status >= Presence.PRESENCE_OFFLINE) {
acceptComposing = false;
}
}
void markDelivered(String id) {
if (id == null) {
return;
}
for (Enumeration e = msgs.elements(); e.hasMoreElements();) {
Msg m = ((MessageItem) e.nextElement()).msg;
if (m.id != null) {
if (m.id.equals(id)) {
m.delivered = true;
}
}
}
}
//#ifdef HISTORY
//#ifdef LAST_MESSAGES
//# public boolean isHistoryLoaded() {
//# return loaded;
//# }
//#
//# public void setHistoryLoaded(boolean state) {
//# loaded = state;
//# }
//#endif
//#endif
public int getVWidth() {
String str = (!cf.rosterStatus) ? getFirstString() : (getFirstLength() > getSecondLength()) ? getFirstString() : getSecondString();
int wft = getFont().stringWidth(str);
return wft + il.getWidth() + 4;
}
public String toString() {
return getFirstString();
}
public int getSecondLength() {
if (getSecondString() == null) {
return 0;
}
if (getSecondString().length() == 0) {
return 0;
}
return FontCache.getFont(false, FontCache.baloon).stringWidth(getSecondString());
}
public int getFirstLength() {
if (getFirstString() == null) {
return 0;
}
if (getFirstString().length() == 0) {
return 0;
}
return getFont().stringWidth(getFirstString());
}
public String getFirstString() {
if (!cf.showResources) {
return (nick == null) ? jid.bareJid : nick;
}
if (origin > ORIGIN_GROUPCHAT) {
return nick;
}
if (origin == ORIGIN_GROUPCHAT) {
return getJid().toString();
}
return (nick == null) ? getJid().toString() : nick + jid.resource;
}
public String getSecondString() {
if (cf.rosterStatus) {
if (statusString != null) {
return statusString;
}
//#if PEP
//# return getMoodString();
//#endif
}
return null;
}
public int getImageIndex() {
if (showComposing == true) {
return RosterIcons.ICON_COMPOSING_INDEX;
}
int st = (status == Presence.PRESENCE_OFFLINE) ? offline_type : status;
if (st < 8) {
st += transport;
}
return st;
}
public int getSecImageIndex() {
if (getNewMsgsCount() > 0) {
return (unreadType == Msg.MESSAGE_TYPE_AUTH) ? RosterIcons.ICON_AUTHRQ_INDEX : RosterIcons.ICON_MESSAGE_INDEX;
}
if (incomingState > 0) {
return incomingState;
}
return -1;
}
//#ifdef PEP
//# public String getMoodString() {
//# StringBuffer mood = null;
//# if (hasMood()) {
//# mood = new StringBuffer(pepMoodName);
//# if (pepMoodText != null) {
//# if (pepMoodText.length() > 0) {
//# mood.append("(").append(pepMoodText).append(")");
//# }
//# }
//# }
//# return (mood != null) ? mood.toString() : null;
//# }
//#endif
public int getVHeight() {
int itemVHeight = Math.max(maxImgHeight, fontHeight);
if (getSecondString() != null) {
itemVHeight += FontCache.getFont(false, FontCache.baloon).getHeight() - 3;
}
return Math.max(itemVHeight, cf.minItemHeight);
}
public void drawItem(Graphics g, int ofs, boolean sel) {
int w = g.getClipWidth();
int h = getVHeight();
int xo = g.getClipX();
int yo = g.getClipY();
int offset = xo + 4;
int imgH = (h - ilHeight) >> 1;
if (getImageIndex() > -1) {
offset += ilHeight;
il.drawImage(g, getImageIndex(), xo + 2, imgH);
}
//#ifdef CLIENTS_ICONS
//# if (hasClientIcon()) {
//# ImageList clients = ClientsIcons.getInstance();
//# int clientImgSize = clients.getWidth();
//# w -= clientImgSize;
//# clients.drawImage(g, client, w, (h - clientImgSize) / 2);
//# if (maxImgHeight < clientImgSize) {
//# maxImgHeight = clientImgSize;
//# }
//# }
//#endif
//#ifdef PEP
//# if (hasMood()) {
//# ImageList moods = MoodIcons.getInstance();
//# int moodImgSize = moods.getWidth();
//# w -= moodImgSize;
//# moods.drawImage(g, pepMood, w, (h - moodImgSize) / 2);
//# if (maxImgHeight < moodImgSize) {
//# maxImgHeight = moodImgSize;
//# }
//# }
//#ifdef PEP_TUNE
//# if (pepTune) {
//# w -= ilHeight;
//# il.drawImage(g, RosterIcons.ICON_PROFILE_INDEX + 1, w, imgH);
//# }
//#ifdef PEP_ACTIVITY
//# if (hasActivity()) {
//# w -= ilHeight;
//# il.drawImage(g, RosterIcons.ICON_PROFILE_INDEX, w, imgH);
//# }
//#endif
//#ifdef PEP_LOCATION
//# if (hasLocation()) {
//# w -= ilHeight;
//# il.drawImage(g, RosterIcons.ICON_PROGRESS_INDEX, w, imgH);
//# }
//#endif
//#
//#endif
//#endif
/*
if (vcard!=null) {
w-=ilHeight;
il.drawImage(g, RosterIcons.ICON_SEARCH_INDEX, w,imgH);
}
*/
//#ifdef FILE_TRANSFER
//# if (fileQuery) {
//# w -= ilHeight;
//# il.drawImage(g, RosterIcons.ICON_PROGRESS_INDEX, w, imgH);
//# }
//#endif
if (getSecImageIndex() > -1) {
w -= ilHeight;
il.drawImage(g, getSecImageIndex(), w, imgH);
}
int thisOfs = 0;
g.setClip(offset, yo, w - offset, h);
thisOfs = (getFirstLength() > w) ? -ofs + offset : offset;
if ((thisOfs + getFirstLength()) < 0) {
thisOfs = offset;
}
g.setFont(getFont());
int thisYOfs = 0;
if (getSecondString() == null) {
thisYOfs = (h - getFont().getHeight()) >> 1;
}
FontCache.drawString(g, getFirstString(), thisOfs, thisYOfs, Graphics.TOP | Graphics.LEFT);
if (getSecondString() != null) {
int y = getFont().getHeight() - 3;
thisOfs = (getSecondLength() > w) ? -ofs + offset : offset;
g.setFont(FontCache.getFont(false, FontCache.baloon));
g.setColor(ColorTheme.getColor(ColorTheme.SECOND_LINE));
FontCache.drawString(g, getSecondString(), thisOfs, y, Graphics.TOP | Graphics.LEFT);
}
g.setClip(xo, yo, w, h);
}
//#ifdef CLIENTS_ICONS
//# boolean hasClientIcon() {
//# return (client > -1);
//# }
//#endif
//#ifdef PEP
//# boolean hasMood() {
//# return (pepMood > -1 && pepMood < Moods.getInstance().getCount());
//# }
//#ifdef PEP_ACTIVITY
//#
//# boolean hasActivity() {
//# if (activity != null) {
//# if (activity.length() > 0) {
//# return true;
//# }
//# }
//# return false;
//# }
//#endif
//#ifdef PEP_LOCATION
//#
//# boolean hasLocation() {
//# return (location != null);
//# }
//#endif
//#endif
public ContactMessageList getMsgList() {
if (cml == null) {
cml = new ContactMessageList(this);
} else {
if (newMsgCnt > 0 && cml.on_end) cml.moveToUnread();
cml.show();
}
return cml;
}
}
| false | true | public void addMessage(Msg m) {
boolean last_replace = false;
if (origin == ORIGIN_GROUPCHAT) {
if (!m.body.startsWith("/me ")) {
if (cf.showNickNames && !m.isPresence() && m.messageType != Msg.MESSAGE_TYPE_SUBJ && m.messageType != Msg.MESSAGE_TYPE_SYSTEM) {
StringBuffer who = new StringBuffer();
Msg.appendNick(who, m.from);
if (!cf.hideTimestamps) {
who.append(" (").append(m.getTime()).append(")");
}
who.append(":");
if (m.subject != null) {
who.append("\n").append(m.subject);
}
m.subject = who.toString();
}
}
if (m.body.startsWith("/me ")) {
StringBuffer b = new StringBuffer();
Msg.appendNick(b, m.from);
b.insert(0, '*');
b.append(m.body.substring(3));
m.body = b.toString();
b = null;
}
status = Presence.PRESENCE_ONLINE;
//#ifdef LOGROTATE
//# redraw = deleteOldMessages();
//#endif
}
if (origin != ORIGIN_GROUPCHAT) {
if (msgs.size() > 0 && m.isPresence()) {
Object item = msgs.lastElement();
if (item != null) {
if (((MessageItem) item).msg.isPresence()) {
last_replace = true;
}
}
} else {
if (!m.body.startsWith("/me ")) {
if (cf.showNickNames && !m.isPresence()) {
StringBuffer who = new StringBuffer();
Msg.appendNick(who, m.messageType == Msg.MESSAGE_TYPE_OUT ? sd.account.getNickName() : getName());
if (!cf.hideTimestamps) {
who.append(" (").append(m.getTime()).append(")");
}
who.append(":");
if (m.subject != null) {
who.append("\n").append(m.subject);
}
m.subject = who.toString();
}
} else { // if (m.body.startsWith("/me "))
StringBuffer b = new StringBuffer();
Msg.appendNick(b, (m.messageType == Msg.MESSAGE_TYPE_OUT) ? sd.account.getNickName() : getName());
b.insert(0, '*');
b.append(m.body.substring(3));
m.body = b.toString();
b = null;
}
}
} else {
status = Presence.PRESENCE_ONLINE;
//#ifdef LOGROTATE
//# redraw = deleteOldMessages();
//#endif
}
//#if HISTORY
//# if (!m.history) {
//# if (!cf.msgPath.equals("") && !jid.isTransport() && group.type != Groups.TYPE_SEARCH_RESULT) {
//# boolean allowLog = false;
//# switch (m.messageType) {
//# case Msg.MESSAGE_TYPE_PRESENCE:
//# if (origin >= ORIGIN_GROUPCHAT) {
//# if (cf.msgLogConfPresence) {
//# allowLog = true;
//# }
//# } else if (cf.msgLogPresence) {
//# allowLog = true;
//# }
//# break;
//# case Msg.MESSAGE_TYPE_HISTORY:
//# break;
//# default:
//# if (origin >= ORIGIN_GROUPCHAT && cf.msgLogConf) {
//# allowLog = true;
//# }
//# if (origin < ORIGIN_GROUPCHAT && cf.msgLog) {
//# allowLog = true;
//# }
//# }
//#
//#ifndef WMUC
//# if (origin != ORIGIN_GROUPCHAT && this instanceof MucContact) {
//# allowLog = false;
//# }
//#endif
//#
//# if (allowLog) {
//# HistoryAppend.getInstance().addMessage(m, bareJid);
//# }
//# }
//# }
//#endif
if (last_replace) {
msgs.setElementAt(new MessageItem(m, smiles), msgs.size() - 1);
return;
}
if (m.messageType != Msg.MESSAGE_TYPE_HISTORY && m.messageType != Msg.MESSAGE_TYPE_PRESENCE) {
activeMessage = msgs.size();
}
msgs.addElement(new MessageItem(m, smiles));
if (m.unread || m.messageType == Msg.MESSAGE_TYPE_OUT) {
lastUnread = msgs.size();
if (m.messageType > unreadType) {
unreadType = m.messageType;
}
if (newMsgCnt >= 0) {
newMsgCnt++;
}
if (m.highlite) {
if (newHighLitedMsgCnt >= 0) {
newHighLitedMsgCnt++;
}
}
}
}
| public void addMessage(Msg m) {
boolean last_replace = false;
if (origin == ORIGIN_GROUPCHAT) {
if (!m.body.startsWith("/me ")) {
if (cf.showNickNames && !m.isPresence() && m.messageType != Msg.MESSAGE_TYPE_SUBJ && m.messageType != Msg.MESSAGE_TYPE_SYSTEM) {
StringBuffer who = new StringBuffer();
Msg.appendNick(who, m.from + ((cf.hideTimestamps) ? ":" : " ("+m.getTime() + ")" + ":"));
if (m.subject != null) {
who.append("\n").append(m.subject);
}
m.subject = who.toString();
}
}
if (m.body.startsWith("/me ")) {
StringBuffer b = new StringBuffer();
Msg.appendNick(b, m.from);
b.insert(0, '*');
b.append(m.body.substring(3));
m.body = b.toString();
b = null;
}
status = Presence.PRESENCE_ONLINE;
//#ifdef LOGROTATE
//# redraw = deleteOldMessages();
//#endif
}
if (origin != ORIGIN_GROUPCHAT) {
if (msgs.size() > 0 && m.isPresence()) {
Object item = msgs.lastElement();
if (item != null) {
if (((MessageItem) item).msg.isPresence()) {
last_replace = true;
}
}
} else {
if (!m.body.startsWith("/me ")) {
if (cf.showNickNames && !m.isPresence()) {
StringBuffer who = new StringBuffer();
Msg.appendNick(who, m.messageType == Msg.MESSAGE_TYPE_OUT ? sd.account.getNickName() + ((cf.hideTimestamps) ? ":" : " (" + m.getTime() + ")" + ":") : getName() + ((cf.hideTimestamps) ? ":" : " ("+m.getTime() + ")" + ":"));
if (m.subject != null) {
who.append("\n").append(m.subject);
}
m.subject = who.toString();
}
} else { // if (m.body.startsWith("/me "))
StringBuffer b = new StringBuffer();
Msg.appendNick(b, (m.messageType == Msg.MESSAGE_TYPE_OUT) ? sd.account.getNickName() : getName());
b.insert(0, '*');
b.append(m.body.substring(3));
m.body = b.toString();
b = null;
}
}
} else {
status = Presence.PRESENCE_ONLINE;
//#ifdef LOGROTATE
//# redraw = deleteOldMessages();
//#endif
}
//#if HISTORY
//# if (!m.history) {
//# if (!cf.msgPath.equals("") && !jid.isTransport() && group.type != Groups.TYPE_SEARCH_RESULT) {
//# boolean allowLog = false;
//# switch (m.messageType) {
//# case Msg.MESSAGE_TYPE_PRESENCE:
//# if (origin >= ORIGIN_GROUPCHAT) {
//# if (cf.msgLogConfPresence) {
//# allowLog = true;
//# }
//# } else if (cf.msgLogPresence) {
//# allowLog = true;
//# }
//# break;
//# case Msg.MESSAGE_TYPE_HISTORY:
//# break;
//# default:
//# if (origin >= ORIGIN_GROUPCHAT && cf.msgLogConf) {
//# allowLog = true;
//# }
//# if (origin < ORIGIN_GROUPCHAT && cf.msgLog) {
//# allowLog = true;
//# }
//# }
//#
//#ifndef WMUC
//# if (origin != ORIGIN_GROUPCHAT && this instanceof MucContact) {
//# allowLog = false;
//# }
//#endif
//#
//# if (allowLog) {
//# HistoryAppend.getInstance().addMessage(m, bareJid);
//# }
//# }
//# }
//#endif
if (last_replace) {
msgs.setElementAt(new MessageItem(m, smiles), msgs.size() - 1);
return;
}
if (m.messageType != Msg.MESSAGE_TYPE_HISTORY && m.messageType != Msg.MESSAGE_TYPE_PRESENCE) {
activeMessage = msgs.size();
}
msgs.addElement(new MessageItem(m, smiles));
if (m.unread || m.messageType == Msg.MESSAGE_TYPE_OUT) {
lastUnread = msgs.size();
if (m.messageType > unreadType) {
unreadType = m.messageType;
}
if (newMsgCnt >= 0) {
newMsgCnt++;
}
if (m.highlite) {
if (newHighLitedMsgCnt >= 0) {
newHighLitedMsgCnt++;
}
}
}
}
|
diff --git a/cyklotron-core/src/main/java/net/cyklotron/cms/documents/DocumentTool.java b/cyklotron-core/src/main/java/net/cyklotron/cms/documents/DocumentTool.java
index cca6850ee..0aafec2db 100644
--- a/cyklotron-core/src/main/java/net/cyklotron/cms/documents/DocumentTool.java
+++ b/cyklotron-core/src/main/java/net/cyklotron/cms/documents/DocumentTool.java
@@ -1,195 +1,195 @@
package net.cyklotron.cms.documents;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.dom4j.Document;
import org.objectledge.html.HTMLException;
import org.objectledge.pipeline.ProcessingException;
import net.cyklotron.cms.documents.internal.DocumentRenderingHelper;
/**
* Tool for displaying documents contents in velocity templates.
*
* @author <a href="mailto:[email protected]">Damian Gajda</a>
* @version $Id: DocumentTool.java,v 1.3 2006-05-08 12:29:08 pablo Exp $
*/
public class DocumentTool
{
// state variables ////////////////////////////////////////////////////////
/** document data for document which owns this tool. */
private DocumentRenderingHelper docRenderer;
/** owner document's current page */
private int currentPage;
/** currently used encoding. */
private String encoding;
// cache variables ////////////////////////////////////////////////////////
/** cache for concatenated content prepared for current request */
private String encodedContent;
/** cache for xpath expressions executed on content DOM */
private HashMap contentData = new HashMap();
/** cache for xpath expressions executed on metadata DOM */
private HashMap metaData = new HashMap();
// initialisation ///////////////////////////////////////////////////////
public DocumentTool(DocumentRenderingHelper docRenderer,
int currentPage, String encoding)
throws ProcessingException
{
// state variables
this.docRenderer = docRenderer;
this.currentPage = currentPage;
this.encoding = encoding;
}
// public interface ///////////////////////////////////////////////////////
public DocumentNodeResource getDocument()
{
return docRenderer.getDocument();
}
// content /////////////////////////////////////////////////////////////////////////////////////
public String getTitle()
throws HTMLException
{
return docRenderer.getDocument().getTitle();
}
public String getAbstract()
throws HTMLException
{
return docRenderer.getDocument().getAbstract();
}
public String getContent()
throws HTMLException, DocumentException
{
if(encodedContent == null)
{
encodedContent = docRenderer.getContent();
}
return encodedContent;
}
public int getNumPages()
{
return docRenderer.getNumPages();
}
public int getCurrentPage()
{
return currentPage;
}
public String getPageContent()
throws HTMLException, DocumentException
{
return getPageContent(currentPage);
}
public String getPageContent(int page)
throws HTMLException, DocumentException
{
return docRenderer.getPageContent(page);
}
/**
* Returns the value of selected data from <code>content</code> attribute.
*
* @return selected value from the <code>content</code> attribute.
*/
public List getContentNodes(String xPathExpression)
throws DocumentException
{
List nodes = (List)contentData.get(xPathExpression);
if(nodes == null)
{
Document dom = docRenderer.getContentDom();
if(dom == null)
{
nodes = new ArrayList();
}
else
{
nodes = dom.selectNodes(xPathExpression);
}
contentData.put(xPathExpression, nodes);
}
return nodes;
}
// meta ////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns a list of keywords from document's <code>keywords</code> attribute.
*
* @return the list of keywords.
*/
public List getKeywords()
{
return docRenderer.getKeywords();
}
/**
* Returns the value of selected data from <code>meta</code> attribute.
*
* @return selected value from the <code>meta</code> attribute.
*/
public List getMetaNodes(String xPathExpression)
throws HTMLException
{
// rewrite for cyklotron 2.13
- if("/meta/organisation".equals(xPathExpression))
+ if("/meta/organisation".equals(xPathExpression.toLowerCase()))
{
xPathExpression = "/meta/organizations/organization";
List nodes = (List)metaData.get(xPathExpression);
if(nodes == null)
{
Document metaDom = docRenderer.getMetaDom();
if(metaDom == null)
{
nodes = new ArrayList();
}
else
{
nodes = metaDom.selectNodes(xPathExpression);
}
metaData.put(xPathExpression, nodes);
}
if(nodes == null)
{
nodes = Arrays.asList(nodes.get(0));
}
return nodes;
}
else
{
List nodes = (List)metaData.get(xPathExpression);
if(nodes == null)
{
Document metaDom = docRenderer.getMetaDom();
if(metaDom == null)
{
nodes = new ArrayList();
}
else
{
nodes = metaDom.selectNodes(xPathExpression);
}
metaData.put(xPathExpression, nodes);
}
return nodes;
}
}
}
| true | true | public List getMetaNodes(String xPathExpression)
throws HTMLException
{
// rewrite for cyklotron 2.13
if("/meta/organisation".equals(xPathExpression))
{
xPathExpression = "/meta/organizations/organization";
List nodes = (List)metaData.get(xPathExpression);
if(nodes == null)
{
Document metaDom = docRenderer.getMetaDom();
if(metaDom == null)
{
nodes = new ArrayList();
}
else
{
nodes = metaDom.selectNodes(xPathExpression);
}
metaData.put(xPathExpression, nodes);
}
if(nodes == null)
{
nodes = Arrays.asList(nodes.get(0));
}
return nodes;
}
else
{
List nodes = (List)metaData.get(xPathExpression);
if(nodes == null)
{
Document metaDom = docRenderer.getMetaDom();
if(metaDom == null)
{
nodes = new ArrayList();
}
else
{
nodes = metaDom.selectNodes(xPathExpression);
}
metaData.put(xPathExpression, nodes);
}
return nodes;
}
}
| public List getMetaNodes(String xPathExpression)
throws HTMLException
{
// rewrite for cyklotron 2.13
if("/meta/organisation".equals(xPathExpression.toLowerCase()))
{
xPathExpression = "/meta/organizations/organization";
List nodes = (List)metaData.get(xPathExpression);
if(nodes == null)
{
Document metaDom = docRenderer.getMetaDom();
if(metaDom == null)
{
nodes = new ArrayList();
}
else
{
nodes = metaDom.selectNodes(xPathExpression);
}
metaData.put(xPathExpression, nodes);
}
if(nodes == null)
{
nodes = Arrays.asList(nodes.get(0));
}
return nodes;
}
else
{
List nodes = (List)metaData.get(xPathExpression);
if(nodes == null)
{
Document metaDom = docRenderer.getMetaDom();
if(metaDom == null)
{
nodes = new ArrayList();
}
else
{
nodes = metaDom.selectNodes(xPathExpression);
}
metaData.put(xPathExpression, nodes);
}
return nodes;
}
}
|
diff --git a/src/gnu/prolog/vm/buildins/misc/Predicate_member.java b/src/gnu/prolog/vm/buildins/misc/Predicate_member.java
index 1c4dd1d..4bf899d 100644
--- a/src/gnu/prolog/vm/buildins/misc/Predicate_member.java
+++ b/src/gnu/prolog/vm/buildins/misc/Predicate_member.java
@@ -1,160 +1,160 @@
/* GNU Prolog for Java
* Copyright (C) 1997-1999 Constantine Plotnikov
* Copyright (C) 2009 Michiel Hendriks
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA. The text ol license can be also found
* at http://www.gnu.org/copyleft/lgpl.html
*/
package gnu.prolog.vm.buildins.misc;
import gnu.prolog.term.AtomTerm;
import gnu.prolog.term.CompoundTerm;
import gnu.prolog.term.Term;
import gnu.prolog.term.VariableTerm;
import gnu.prolog.vm.BacktrackInfo;
import gnu.prolog.vm.Environment;
import gnu.prolog.vm.Interpreter;
import gnu.prolog.vm.PrologCode;
import gnu.prolog.vm.PrologException;
/**
* Does:
*
* <pre>
* member(X, [X|_]).
* member(X, [_|Y]):-member(X,Y).
* </pre>
*
* But without recursion
*
* @author Michiel Hendriks
*/
public class Predicate_member implements PrologCode
{
protected class MemberBacktrackInfo extends BacktrackInfo
{
protected Term item;
protected Term list;
protected boolean listExpand;
protected Term listDest;
protected int startUndoPosition;
protected MemberBacktrackInfo()
{
super(-1, -1);
}
}
public Predicate_member()
{}
/*
* (non-Javadoc)
*
* @see gnu.prolog.vm.PrologCode#execute(gnu.prolog.vm.Interpreter, boolean,
* gnu.prolog.term.Term[])
*/
public int execute(Interpreter interpreter, boolean backtrackMode, Term[] args) throws PrologException
{
if (backtrackMode)
{
MemberBacktrackInfo bi = (MemberBacktrackInfo) interpreter.popBacktrackInfo();
interpreter.undo(bi.startUndoPosition);
return nextSolution(interpreter, bi);
}
else
{
MemberBacktrackInfo bi = new MemberBacktrackInfo();
bi.startUndoPosition = interpreter.getUndoPosition();
bi.item = args[0];
if (args[1] instanceof VariableTerm)
{
bi.list = new VariableTerm();
bi.listExpand = true;
bi.listDest = args[1];
}
else
{
bi.list = args[1];
}
return nextSolution(interpreter, bi);
}
}
/*
* member(1,N) -> N = [1|_] -> N = [_,1|_] -> N = [_,_,1|_]
*/
/**
* @param interpreter
* @param bi
* @return
* @throws PrologException
*/
protected int nextSolution(Interpreter interpreter, MemberBacktrackInfo bi) throws PrologException
{
while (!AtomTerm.emptyList.equals(bi.list))
{
if (bi.listExpand)
{
Term tmp = CompoundTerm.getList(bi.item, bi.list);
interpreter.unify(bi.listDest, tmp);
bi.item = new VariableTerm();
bi.list = tmp;
}
Term head = ((CompoundTerm) bi.list).args[0].dereference();
- if (bi.listExpand)
+ if (!bi.listExpand)
{
bi.list = ((CompoundTerm) bi.list).args[1].dereference();
}
- if (interpreter.unify(bi.item, head) == FAIL)
- {
- interpreter.undo(bi.startUndoPosition);
- continue;
- }
if (bi.list instanceof VariableTerm)
{
bi.listDest = bi.list;
bi.list = new VariableTerm();
bi.listExpand = true;
}
else if (!CompoundTerm.isListPair(bi.list) && !AtomTerm.emptyList.equals(bi.list))
{
return FAIL;
}
+ if (interpreter.unify(bi.item, head) == FAIL)
+ {
+ interpreter.undo(bi.startUndoPosition);
+ continue;
+ }
interpreter.pushBacktrackInfo(bi);
return SUCCESS;
}
return FAIL;
}
/*
* (non-Javadoc)
*
* @see gnu.prolog.vm.PrologCode#install(gnu.prolog.vm.Environment)
*/
public void install(Environment env)
{}
/*
* (non-Javadoc)
*
* @see gnu.prolog.vm.PrologCode#uninstall(gnu.prolog.vm.Environment)
*/
public void uninstall(Environment env)
{}
}
| false | true | protected int nextSolution(Interpreter interpreter, MemberBacktrackInfo bi) throws PrologException
{
while (!AtomTerm.emptyList.equals(bi.list))
{
if (bi.listExpand)
{
Term tmp = CompoundTerm.getList(bi.item, bi.list);
interpreter.unify(bi.listDest, tmp);
bi.item = new VariableTerm();
bi.list = tmp;
}
Term head = ((CompoundTerm) bi.list).args[0].dereference();
if (bi.listExpand)
{
bi.list = ((CompoundTerm) bi.list).args[1].dereference();
}
if (interpreter.unify(bi.item, head) == FAIL)
{
interpreter.undo(bi.startUndoPosition);
continue;
}
if (bi.list instanceof VariableTerm)
{
bi.listDest = bi.list;
bi.list = new VariableTerm();
bi.listExpand = true;
}
else if (!CompoundTerm.isListPair(bi.list) && !AtomTerm.emptyList.equals(bi.list))
{
return FAIL;
}
interpreter.pushBacktrackInfo(bi);
return SUCCESS;
}
return FAIL;
}
| protected int nextSolution(Interpreter interpreter, MemberBacktrackInfo bi) throws PrologException
{
while (!AtomTerm.emptyList.equals(bi.list))
{
if (bi.listExpand)
{
Term tmp = CompoundTerm.getList(bi.item, bi.list);
interpreter.unify(bi.listDest, tmp);
bi.item = new VariableTerm();
bi.list = tmp;
}
Term head = ((CompoundTerm) bi.list).args[0].dereference();
if (!bi.listExpand)
{
bi.list = ((CompoundTerm) bi.list).args[1].dereference();
}
if (bi.list instanceof VariableTerm)
{
bi.listDest = bi.list;
bi.list = new VariableTerm();
bi.listExpand = true;
}
else if (!CompoundTerm.isListPair(bi.list) && !AtomTerm.emptyList.equals(bi.list))
{
return FAIL;
}
if (interpreter.unify(bi.item, head) == FAIL)
{
interpreter.undo(bi.startUndoPosition);
continue;
}
interpreter.pushBacktrackInfo(bi);
return SUCCESS;
}
return FAIL;
}
|
diff --git a/paprocci/java/src/org/ow2/proactive/compatibleone/scheduler/SchedulerClient.java b/paprocci/java/src/org/ow2/proactive/compatibleone/scheduler/SchedulerClient.java
index bbc6f584..69929fdc 100644
--- a/paprocci/java/src/org/ow2/proactive/compatibleone/scheduler/SchedulerClient.java
+++ b/paprocci/java/src/org/ow2/proactive/compatibleone/scheduler/SchedulerClient.java
@@ -1,421 +1,421 @@
/* -------------------------------------------------------------------- */
/* ACCORDS PLATFORM */
/* (C) 2012 by Oasis (INRIA Sophia Antipolis) and ActiveEon teams. */
/* -------------------------------------------------------------------- */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------- */
package org.ow2.proactive.compatibleone.scheduler;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.ow2.proactive.compatibleone.exchangeobjects.NodeInfo;
import org.ow2.proactive.compatibleone.exchangeobjects.NodePublicInfo;
import org.ow2.proactive.compatibleone.misc.CONodeState;
import org.ow2.proactive.compatibleone.misc.Misc;
import org.ow2.proactive.compatibleone.misc.Signal;
import org.ow2.proactive.compatibleone.rm.NodeId;
import org.ow2.proactive.compatibleone.rm.ResourceManagerClient;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface;
import org.ow2.proactive.scheduler.common.SchedulerConnection;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobPriority;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.task.Log4JTaskLogs;
import org.ow2.proactive.scheduler.common.task.NativeTask;
import org.ow2.proactive.scheduler.common.task.ParallelEnvironment;
import org.ow2.proactive.scheduler.common.task.TaskState;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingService;
import org.ow2.proactive.scheduler.job.JobIdImpl;
import org.ow2.proactive.scripting.SelectionScript;
import org.ow2.proactive.topology.descriptor.TopologyDescriptor;
import org.ow2.proactive.authentication.crypto.CredData;
import org.ow2.proactive.authentication.crypto.Credentials;
public class SchedulerClient {
public static final String JOBNAME = "COApplication";
private static String schedulerurl_backup;
private static String username_backup;
private static String password_backup;
protected static Logger logger = // Logger.
Logger.getLogger(SchedulerClient.class.getName());
private String pendingJobId; // Tells if after any operation there is a pending job (useful when
// there is a timeout, and one job must be killed).
private Scheduler scheduler;
public static void setUpInitiParameters(
String schedulerurl,
String username,
String password){
schedulerurl_backup = schedulerurl;
username_backup = username;
password_backup = password;
}
public static SchedulerClient getInstance() throws Exception{
logger.info("Initializing instance of Scheduler...");
return new SchedulerClient(schedulerurl_backup, username_backup, password_backup);
}
/**
* Constructor.
* @param schedulerurl
* @param rmurl
* @param username
* @param password
* @throws Exception */
private SchedulerClient(
String schedulerurl,
String username,
String password) throws Exception{
this.pendingJobId = null;
//logger.info("HARDCODED");
//int a = 3; if (a>2){return;}
scheduler = initializeSchedulerProxy(schedulerurl, username, password);
}
/**
* Get the proxy of the Scheduler. */
private Scheduler initializeSchedulerProxy(String schedulerurl, String username, String password) throws Exception {
logger.info("Joining the scheduler at '" + schedulerurl + "'...");
SchedulerAuthenticationInterface auth = SchedulerConnection.join(schedulerurl);
logger.info("Done.");
logger.info("Logging in...");
Credentials cred = Credentials.createCredentials(
new CredData(username, password), auth.getPublicKey());
Scheduler schedulerStub = auth.login(cred);
logger.info("Done.");
return schedulerStub;
}
/**
* Method to create a job with one task, which runs a specific application (i.e. COSACS of
* CompatibleOne) and later returns the information of that node.
* @param stopsignal signal to listen to to know if the job submission attempt is no longer needed.
* @param nodeselectioncriteria criteria to select the node (it must be a Selection Script of ProActive).
* @param applicationpath path of the application to be run in the node.
* @param applicationargs arguments to pass to the application.
* @param appworkingdir working directory for the application.
* @param nodetoken special token that allow the usage of some privileged nodes.
* @param nonodes number of nodes needed by this application.
* @return information about the node in which the application runs.
* @throws Exception if something goes wrong. */
public String acquireApplicationInNode(
Signal stopsignal,
SelectionScript nodeselectioncriteria,
String applicationpath,
String applicationargs[],
String appworkingdir,
String nodetoken,
Integer nonodes) throws Exception {
//logger.info("HARDCODED");
//int a = 3; if (a>2){ return "{\"id\":\"12385\",\"adminPass\":\"passWord\",\"status\":\"RUNNING\",\"hostname\":\"cper-PC\",\"privateip\":\"138.96.126.112\",\"publicip\":\"138.96.126.112\",\"nodeurl\":\"pamr://6131/xps1\",\"owner\":\"mjost\"}"; }
logger.info("Creating job and tasks...");
NativeTask primaryTask = new NativeTask();
logger.info("Using application path: '"+applicationpath+"'...");
logger.info("Using application args: '"+applicationargs+"'...");
for (String arg:applicationargs){
logger.info(" - '"+arg+"'");
}
logger.info("Using app. working dir: '"+appworkingdir+"'...");
primaryTask.setWorkingDir(appworkingdir);
primaryTask.setCommandLine(Misc.getStringArray(applicationpath, applicationargs));
primaryTask.setName(applicationpath);
logger.info("Using selection script: '"+nodeselectioncriteria.getScript()+"'...");
primaryTask.addSelectionScript(nodeselectioncriteria);
if (nonodes != null && nonodes > 1){
logger.info("Using topology made of " + nonodes + " nodes...");
TopologyDescriptor topologyDescriptor = TopologyDescriptor.SINGLE_HOST;
ParallelEnvironment parallelEnvironment = new ParallelEnvironment(nonodes, topologyDescriptor);
primaryTask.setParallelEnvironment(parallelEnvironment);
}else{
logger.info("Only one node required, no topology needed.");
}
if (nodetoken != null){
logger.info("Using node token: '"+nodetoken+"'...");
primaryTask.addGenericInformation("NS_AUTH", nodetoken);
}
TaskFlowJob taskFlowJob = new TaskFlowJob();
taskFlowJob.setName(JOBNAME);
taskFlowJob.setPriority(JobPriority.NORMAL);
taskFlowJob.addTask(primaryTask);
logger.info("Submitting job...");
JobId jobId = scheduler.submit(taskFlowJob);
pendingJobId = jobId.toString();
logger.info("Submitted the job (JobId " + jobId + ")");
JobState jobstate = null;
while(true){
jobstate = scheduler.getJobState(jobId);
if (jobstate.getStatus().equals(JobStatus.PENDING)){ // It is still pending... We need to wait...
logger.info("Waiting for the pending job...");
if (stopsignal.getValue()==true){
logger.info("Waited too much for the job to execute, trying to remove it...");
removeJobAlone(jobId);
logger.info("Removed the job " + jobId);
throw new Exception("Obliged to stop, removed the job " + jobId + ". ");
}
Thread.sleep(3000);
}else{ // Not pending anymore, so it went through execution but it's not sure that it's running, so
// the correct execution must be checked.
if (!jobstate.getStatus().equals(JobStatus.RUNNING)){ // Not running? There is a problem then...
JobResult jr = scheduler.getJobResult(jobId);
logger.warn("The job is not running (it is " + jobstate.getStatus().name() + "), so something went wrong.");
String output =
"Stdout: '" + jr.getResult(applicationpath).getOutput().getStdoutLogs(false) + "'." +
"Stderr: '" + jr.getResult(applicationpath).getOutput().getStderrLogs(false) + "'.";
logger.warn(output);
throw new Exception("The job is not running as expected (status=" + jobstate.getStatus().name() + "): " + output);
}
logger.info("Job not pending anymore!!!");
break;
}
}
// Getting information about the tasks/application and its host node.
- ArrayList<TaskState> tasks = jobstate.getTasks();
+ ArrayList<TaskState> tasks = scheduler.getJobState(jobId).getTasks();
int taskssize = tasks.size();
if (taskssize != 1){
logger.warn("The amount of tasks is supposed to be 1, but it is: " + taskssize);
throw new Exception("Incorrect amount of tasks: " + taskssize);
}
// There is only one task for the submitted job.
- while(jobstate.getTasks().get(0).getExecutionHostName() == null){
+ while(scheduler.getJobState(jobId).getTasks().get(0).getExecutionHostName() == null){
logger.warn("The host name where the task is being executed had a null name... Waiting...");
Thread.sleep(200);
}
- String runninghostname = jobstate.getTasks().get(0).getExecutionHostName();
+ String runninghostname = scheduler.getJobState(jobId).getTasks().get(0).getExecutionHostName();
logger.info("Execution host name: " + runninghostname);
String runningnode = runninghostname.substring(runninghostname.indexOf("(")).replace("(", "").replace(")","");
logger.info("Execution node: " + runningnode);
TaskStatus status = tasks.get(0).getStatus();
logger.info("Execution status: " + status);
ResourceManagerClient rm = ResourceManagerClient.getInstance();
NodePublicInfo nodePublicInfo = rm.getCompleteNodePublicInfo(runningnode, null);
rm.disconnect();
logger.info("IP address detected: " + nodePublicInfo.getIpAddress());
// Return a json formatted object with all information needed.
NodeInfo ret = new NodeInfo(
jobId.toString(),
"passWord",
new CONodeState(status),
nodePublicInfo.getHostname(),
nodePublicInfo.getIpAddress(),
nodePublicInfo.getIpAddress(),
nodePublicInfo.getNodeURL(),
nodePublicInfo.getOwner());
if (stopsignal.getValue()==true){
logger.info("Job executed but too late...");
removeJobAlone(jobId);
logger.info("Removed the job " + jobId);
throw new Exception("Job " + jobId + " executed but too late...");
}
return ret.toString();
}
/**
* Best effort to remove a job.
* @param jobId of the job to remove.
* @throws Exception if something goes wrong.
*/
public void removeJobAlone(final JobId jobId) throws Exception{
logger.info("Trying to FINAL release node whose related id is: " + jobId);
Callable<String> callable = new Callable<String>(){
@Override
public String call() throws Exception {
SchedulerClient scheduler = SchedulerClient.getInstance();
String result = scheduler.releaseNode(jobId.toString());
logger.info("Released the node: " + jobId + ", result: " + result);
scheduler.disconnect();
return result;
}
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(callable); // We ask to execute the callable.
String res = null;
try{
res = future.get(Integer.MAX_VALUE, TimeUnit.SECONDS);
}catch(Exception e){
logger.error("Error: ", e);
}
}
/**
* Maps a given node with a running job.
* @return a hashtable containing the mapping.
* @throws Exception if something fails. */
public Hashtable<NodeId, String> mapNodesWithJobs() throws Exception {
Hashtable<NodeId, String> ret = new Hashtable<NodeId, String>();
logger.info("Mapping nodes with jobs...");
Vector<JobState> jobs = scheduler.getState().getRunningJobs();
for(JobState job: jobs){
if (job.getName().equals(JOBNAME)){
ArrayList<TaskState> tasks = job.getTasks();
int taskssize = tasks.size();
if (taskssize != 1){
logger.warn("The amount of tasks is supposed to be 1, but it is: " + taskssize);
throw new Exception("Incorrect amount of tasks: " + taskssize);
}
// There is only one task for the submitted job.
String runninghostname = tasks.get(0).getExecutionHostName();
String runningnode = runninghostname.substring(runninghostname.indexOf("(")).replace("(", "").replace(")","");
logger.info(" - Node: " + runningnode + " mapped with job " + job.getId().toString());
ret.put(new NodeId(runningnode), job.getId().toString());
}
}
return ret;
}
/**
* Method to get a snapshot of the output of a given job.
* The output used is stdout.
* @param jobId job to observe.
* @return the result of the operation.
* @throws Exception if something fails. */
public String acquireOutput(String jobId) throws Exception {
LogForwardingService lfsPA = new LogForwardingService(
"org.ow2.proactive.scheduler.common.util.logforwarder.providers.ProActiveBasedForwardingProvider");
lfsPA.initialize();
Logger l1 = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + jobId);
l1.setAdditivity(false);
l1.removeAllAppenders();
AppenderTester test1 = new AppenderTester();
l1.addAppender(test1);
scheduler.listenJobLogs(jobId, lfsPA.getAppenderProvider());
while (true) {
try {
logger.info("Waiting... ");
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
return "{}";
}
public class AppenderTester extends AppenderSkeleton {
protected Logger logger = // Logger.
Logger.getLogger(AppenderTester.class.getName());
@Override
protected void append(LoggingEvent loggingevent) {
logger.info(">> " + loggingevent.getMessage());
}
@Override
public void close() {
super.closed = true;
}
@Override
public boolean requiresLayout() {
return false;
}
}
/**
* Release the node (by killing the application/task that it runs).
* @param uuid of the node/task/application/job.
* @return the result of the operation.
* @throws Exception if something fails. */
public String releaseNode(String uuid) throws Exception {
logger.info("Getting scheduler proxy...");
JobId jobId = JobIdImpl.makeJobId(uuid);
this.killJob(jobId);
return "{}";
}
/**
* Kill the job from the Scheduler.
* @param jobId the ID of the job.
* @exception Exception if something fails. */
private void killJob(JobId jobId) throws Exception{
boolean killed = scheduler.killJob(jobId);
if (killed == false){
logger.warn("Error while trying to kill job " + jobId + " (returned=false).");
throw new Exception("Can't kill job " + jobId + ".");
}else{
logger.info("Job " + jobId + " killed successfully.");
}
}
/**
* Kill the pending job from the Scheduler.
* @exception Exception if something fails. */
public void releasePotentialNode(){
if (this.pendingJobId != null){
logger.warn("There is a pending job (" + pendingJobId + "). Trying to kill it...");
try{
this.releaseNode(pendingJobId);
}catch(Exception r){
logger.warn("Error while killing the job " + pendingJobId + ": " + r.getMessage());
}
this.pendingJobId = null;
}
}
/**
* Disconnect this scheduler stub.
**/
public void disconnect(){
try{
scheduler.disconnect();
}catch(Exception e){
logger.warn("Error while trying to disconnect...", e);
}
}
}
| false | true | public String acquireApplicationInNode(
Signal stopsignal,
SelectionScript nodeselectioncriteria,
String applicationpath,
String applicationargs[],
String appworkingdir,
String nodetoken,
Integer nonodes) throws Exception {
//logger.info("HARDCODED");
//int a = 3; if (a>2){ return "{\"id\":\"12385\",\"adminPass\":\"passWord\",\"status\":\"RUNNING\",\"hostname\":\"cper-PC\",\"privateip\":\"138.96.126.112\",\"publicip\":\"138.96.126.112\",\"nodeurl\":\"pamr://6131/xps1\",\"owner\":\"mjost\"}"; }
logger.info("Creating job and tasks...");
NativeTask primaryTask = new NativeTask();
logger.info("Using application path: '"+applicationpath+"'...");
logger.info("Using application args: '"+applicationargs+"'...");
for (String arg:applicationargs){
logger.info(" - '"+arg+"'");
}
logger.info("Using app. working dir: '"+appworkingdir+"'...");
primaryTask.setWorkingDir(appworkingdir);
primaryTask.setCommandLine(Misc.getStringArray(applicationpath, applicationargs));
primaryTask.setName(applicationpath);
logger.info("Using selection script: '"+nodeselectioncriteria.getScript()+"'...");
primaryTask.addSelectionScript(nodeselectioncriteria);
if (nonodes != null && nonodes > 1){
logger.info("Using topology made of " + nonodes + " nodes...");
TopologyDescriptor topologyDescriptor = TopologyDescriptor.SINGLE_HOST;
ParallelEnvironment parallelEnvironment = new ParallelEnvironment(nonodes, topologyDescriptor);
primaryTask.setParallelEnvironment(parallelEnvironment);
}else{
logger.info("Only one node required, no topology needed.");
}
if (nodetoken != null){
logger.info("Using node token: '"+nodetoken+"'...");
primaryTask.addGenericInformation("NS_AUTH", nodetoken);
}
TaskFlowJob taskFlowJob = new TaskFlowJob();
taskFlowJob.setName(JOBNAME);
taskFlowJob.setPriority(JobPriority.NORMAL);
taskFlowJob.addTask(primaryTask);
logger.info("Submitting job...");
JobId jobId = scheduler.submit(taskFlowJob);
pendingJobId = jobId.toString();
logger.info("Submitted the job (JobId " + jobId + ")");
JobState jobstate = null;
while(true){
jobstate = scheduler.getJobState(jobId);
if (jobstate.getStatus().equals(JobStatus.PENDING)){ // It is still pending... We need to wait...
logger.info("Waiting for the pending job...");
if (stopsignal.getValue()==true){
logger.info("Waited too much for the job to execute, trying to remove it...");
removeJobAlone(jobId);
logger.info("Removed the job " + jobId);
throw new Exception("Obliged to stop, removed the job " + jobId + ". ");
}
Thread.sleep(3000);
}else{ // Not pending anymore, so it went through execution but it's not sure that it's running, so
// the correct execution must be checked.
if (!jobstate.getStatus().equals(JobStatus.RUNNING)){ // Not running? There is a problem then...
JobResult jr = scheduler.getJobResult(jobId);
logger.warn("The job is not running (it is " + jobstate.getStatus().name() + "), so something went wrong.");
String output =
"Stdout: '" + jr.getResult(applicationpath).getOutput().getStdoutLogs(false) + "'." +
"Stderr: '" + jr.getResult(applicationpath).getOutput().getStderrLogs(false) + "'.";
logger.warn(output);
throw new Exception("The job is not running as expected (status=" + jobstate.getStatus().name() + "): " + output);
}
logger.info("Job not pending anymore!!!");
break;
}
}
// Getting information about the tasks/application and its host node.
ArrayList<TaskState> tasks = jobstate.getTasks();
int taskssize = tasks.size();
if (taskssize != 1){
logger.warn("The amount of tasks is supposed to be 1, but it is: " + taskssize);
throw new Exception("Incorrect amount of tasks: " + taskssize);
}
// There is only one task for the submitted job.
while(jobstate.getTasks().get(0).getExecutionHostName() == null){
logger.warn("The host name where the task is being executed had a null name... Waiting...");
Thread.sleep(200);
}
String runninghostname = jobstate.getTasks().get(0).getExecutionHostName();
logger.info("Execution host name: " + runninghostname);
String runningnode = runninghostname.substring(runninghostname.indexOf("(")).replace("(", "").replace(")","");
logger.info("Execution node: " + runningnode);
TaskStatus status = tasks.get(0).getStatus();
logger.info("Execution status: " + status);
ResourceManagerClient rm = ResourceManagerClient.getInstance();
NodePublicInfo nodePublicInfo = rm.getCompleteNodePublicInfo(runningnode, null);
rm.disconnect();
logger.info("IP address detected: " + nodePublicInfo.getIpAddress());
// Return a json formatted object with all information needed.
NodeInfo ret = new NodeInfo(
jobId.toString(),
"passWord",
new CONodeState(status),
nodePublicInfo.getHostname(),
nodePublicInfo.getIpAddress(),
nodePublicInfo.getIpAddress(),
nodePublicInfo.getNodeURL(),
nodePublicInfo.getOwner());
if (stopsignal.getValue()==true){
logger.info("Job executed but too late...");
removeJobAlone(jobId);
logger.info("Removed the job " + jobId);
throw new Exception("Job " + jobId + " executed but too late...");
}
return ret.toString();
}
| public String acquireApplicationInNode(
Signal stopsignal,
SelectionScript nodeselectioncriteria,
String applicationpath,
String applicationargs[],
String appworkingdir,
String nodetoken,
Integer nonodes) throws Exception {
//logger.info("HARDCODED");
//int a = 3; if (a>2){ return "{\"id\":\"12385\",\"adminPass\":\"passWord\",\"status\":\"RUNNING\",\"hostname\":\"cper-PC\",\"privateip\":\"138.96.126.112\",\"publicip\":\"138.96.126.112\",\"nodeurl\":\"pamr://6131/xps1\",\"owner\":\"mjost\"}"; }
logger.info("Creating job and tasks...");
NativeTask primaryTask = new NativeTask();
logger.info("Using application path: '"+applicationpath+"'...");
logger.info("Using application args: '"+applicationargs+"'...");
for (String arg:applicationargs){
logger.info(" - '"+arg+"'");
}
logger.info("Using app. working dir: '"+appworkingdir+"'...");
primaryTask.setWorkingDir(appworkingdir);
primaryTask.setCommandLine(Misc.getStringArray(applicationpath, applicationargs));
primaryTask.setName(applicationpath);
logger.info("Using selection script: '"+nodeselectioncriteria.getScript()+"'...");
primaryTask.addSelectionScript(nodeselectioncriteria);
if (nonodes != null && nonodes > 1){
logger.info("Using topology made of " + nonodes + " nodes...");
TopologyDescriptor topologyDescriptor = TopologyDescriptor.SINGLE_HOST;
ParallelEnvironment parallelEnvironment = new ParallelEnvironment(nonodes, topologyDescriptor);
primaryTask.setParallelEnvironment(parallelEnvironment);
}else{
logger.info("Only one node required, no topology needed.");
}
if (nodetoken != null){
logger.info("Using node token: '"+nodetoken+"'...");
primaryTask.addGenericInformation("NS_AUTH", nodetoken);
}
TaskFlowJob taskFlowJob = new TaskFlowJob();
taskFlowJob.setName(JOBNAME);
taskFlowJob.setPriority(JobPriority.NORMAL);
taskFlowJob.addTask(primaryTask);
logger.info("Submitting job...");
JobId jobId = scheduler.submit(taskFlowJob);
pendingJobId = jobId.toString();
logger.info("Submitted the job (JobId " + jobId + ")");
JobState jobstate = null;
while(true){
jobstate = scheduler.getJobState(jobId);
if (jobstate.getStatus().equals(JobStatus.PENDING)){ // It is still pending... We need to wait...
logger.info("Waiting for the pending job...");
if (stopsignal.getValue()==true){
logger.info("Waited too much for the job to execute, trying to remove it...");
removeJobAlone(jobId);
logger.info("Removed the job " + jobId);
throw new Exception("Obliged to stop, removed the job " + jobId + ". ");
}
Thread.sleep(3000);
}else{ // Not pending anymore, so it went through execution but it's not sure that it's running, so
// the correct execution must be checked.
if (!jobstate.getStatus().equals(JobStatus.RUNNING)){ // Not running? There is a problem then...
JobResult jr = scheduler.getJobResult(jobId);
logger.warn("The job is not running (it is " + jobstate.getStatus().name() + "), so something went wrong.");
String output =
"Stdout: '" + jr.getResult(applicationpath).getOutput().getStdoutLogs(false) + "'." +
"Stderr: '" + jr.getResult(applicationpath).getOutput().getStderrLogs(false) + "'.";
logger.warn(output);
throw new Exception("The job is not running as expected (status=" + jobstate.getStatus().name() + "): " + output);
}
logger.info("Job not pending anymore!!!");
break;
}
}
// Getting information about the tasks/application and its host node.
ArrayList<TaskState> tasks = scheduler.getJobState(jobId).getTasks();
int taskssize = tasks.size();
if (taskssize != 1){
logger.warn("The amount of tasks is supposed to be 1, but it is: " + taskssize);
throw new Exception("Incorrect amount of tasks: " + taskssize);
}
// There is only one task for the submitted job.
while(scheduler.getJobState(jobId).getTasks().get(0).getExecutionHostName() == null){
logger.warn("The host name where the task is being executed had a null name... Waiting...");
Thread.sleep(200);
}
String runninghostname = scheduler.getJobState(jobId).getTasks().get(0).getExecutionHostName();
logger.info("Execution host name: " + runninghostname);
String runningnode = runninghostname.substring(runninghostname.indexOf("(")).replace("(", "").replace(")","");
logger.info("Execution node: " + runningnode);
TaskStatus status = tasks.get(0).getStatus();
logger.info("Execution status: " + status);
ResourceManagerClient rm = ResourceManagerClient.getInstance();
NodePublicInfo nodePublicInfo = rm.getCompleteNodePublicInfo(runningnode, null);
rm.disconnect();
logger.info("IP address detected: " + nodePublicInfo.getIpAddress());
// Return a json formatted object with all information needed.
NodeInfo ret = new NodeInfo(
jobId.toString(),
"passWord",
new CONodeState(status),
nodePublicInfo.getHostname(),
nodePublicInfo.getIpAddress(),
nodePublicInfo.getIpAddress(),
nodePublicInfo.getNodeURL(),
nodePublicInfo.getOwner());
if (stopsignal.getValue()==true){
logger.info("Job executed but too late...");
removeJobAlone(jobId);
logger.info("Removed the job " + jobId);
throw new Exception("Job " + jobId + " executed but too late...");
}
return ret.toString();
}
|
diff --git a/test/uk/org/ponder/test/dateutil/TestDateTransit.java b/test/uk/org/ponder/test/dateutil/TestDateTransit.java
index 9e4ca11..676a9aa 100644
--- a/test/uk/org/ponder/test/dateutil/TestDateTransit.java
+++ b/test/uk/org/ponder/test/dateutil/TestDateTransit.java
@@ -1,40 +1,40 @@
/*
* Created on 5 Apr 2007
*/
package uk.org.ponder.test.dateutil;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import uk.org.ponder.dateutil.StandardFieldDateTransit;
import uk.org.ponder.util.UniversalRuntimeException;
import junit.framework.TestCase;
public class TestDateTransit extends TestCase {
public void testTZTransit() {
StandardFieldDateTransit transit = new StandardFieldDateTransit();
TimeZone offtz = TimeZone.getTimeZone("BST");
transit.setTimeZone(offtz);
transit.init();
Calendar cal = new GregorianCalendar();
cal.set(2007, 4, 5, 1, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date caltime = cal.getTime();
- caltime.setTimeZone(offtz);
+ //caltime.setTimeZone(offtz);
transit.setDate(cal.getTime());
String tz8601 = transit.getISO8601TZ();
assertEquals(tz8601, "2007-05-05T01:00:00.000+0100");
// Test that transit correctly ignores any timezone strewn in by a
// client-side knowlessman
tz8601 = tz8601.substring(0, 23) + "+0200";
try {
transit.setISO8601TZ(tz8601);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e, "Error parsing date " + tz8601);
}
assertEquals(transit.getDate(), cal.getTime());
}
}
| true | true | public void testTZTransit() {
StandardFieldDateTransit transit = new StandardFieldDateTransit();
TimeZone offtz = TimeZone.getTimeZone("BST");
transit.setTimeZone(offtz);
transit.init();
Calendar cal = new GregorianCalendar();
cal.set(2007, 4, 5, 1, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date caltime = cal.getTime();
caltime.setTimeZone(offtz);
transit.setDate(cal.getTime());
String tz8601 = transit.getISO8601TZ();
assertEquals(tz8601, "2007-05-05T01:00:00.000+0100");
// Test that transit correctly ignores any timezone strewn in by a
// client-side knowlessman
tz8601 = tz8601.substring(0, 23) + "+0200";
try {
transit.setISO8601TZ(tz8601);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e, "Error parsing date " + tz8601);
}
assertEquals(transit.getDate(), cal.getTime());
}
| public void testTZTransit() {
StandardFieldDateTransit transit = new StandardFieldDateTransit();
TimeZone offtz = TimeZone.getTimeZone("BST");
transit.setTimeZone(offtz);
transit.init();
Calendar cal = new GregorianCalendar();
cal.set(2007, 4, 5, 1, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date caltime = cal.getTime();
//caltime.setTimeZone(offtz);
transit.setDate(cal.getTime());
String tz8601 = transit.getISO8601TZ();
assertEquals(tz8601, "2007-05-05T01:00:00.000+0100");
// Test that transit correctly ignores any timezone strewn in by a
// client-side knowlessman
tz8601 = tz8601.substring(0, 23) + "+0200";
try {
transit.setISO8601TZ(tz8601);
}
catch (Exception e) {
throw UniversalRuntimeException.accumulate(e, "Error parsing date " + tz8601);
}
assertEquals(transit.getDate(), cal.getTime());
}
|
diff --git a/utgb-core/src/main/java/org/utgenome/format/fastq/FastqToBAM.java b/utgb-core/src/main/java/org/utgenome/format/fastq/FastqToBAM.java
index c7a8e916..24b631cd 100755
--- a/utgb-core/src/main/java/org/utgenome/format/fastq/FastqToBAM.java
+++ b/utgb-core/src/main/java/org/utgenome/format/fastq/FastqToBAM.java
@@ -1,200 +1,200 @@
/*--------------------------------------------------------------------------
* Copyright 2010 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-core Project
//
// FastqToBAM.java
// Since: Jul 5, 2010
//
//--------------------------------------
package org.utgenome.format.fastq;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.zip.GZIPInputStream;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileWriter;
import net.sf.samtools.SAMFileWriterFactory;
import net.sf.samtools.SAMReadGroupRecord;
import net.sf.samtools.SAMRecord;
import org.utgenome.UTGBErrorCode;
import org.utgenome.UTGBException;
import org.xerial.util.log.Logger;
import org.xerial.util.opt.Argument;
import org.xerial.util.opt.Option;
import org.xerial.util.opt.OptionParser;
import org.xerial.util.opt.OptionParserException;
/**
* Converting Illumina's FASTQ read data (single or paired-end) into BAM format, which can be used BLOAD's GATK
* pipeline.
*
* This code is migrated from
*
* @author leo
*
*/
public class FastqToBAM {
private static Logger _logger = Logger.getLogger(FastqToBAM.class);
@Option(longName = "readGroup", description = "read group name")
private String readGroupName;
@Option(longName = "sample", description = "sample name")
private String sampleName;
@Option(longName = "prefix", description = "prefix of the read")
private String readPrefix;
@Argument(index = 0, name = "input fastq (.fastq, .fastq.gz)", required = true)
private File input1;
@Argument(index = 1, name = "input fastq (.fastq, .fastq.gz, when paried-end read)")
private File input2;
@Option(symbol = "o", longName = "output", description = "output file name (.sam or .bam)")
private File outputFile;
public static int execute(String[] args) throws Exception {
FastqToBAM main = new FastqToBAM();
OptionParser parser = new OptionParser(main);
try {
parser.parse(args);
main.convert();
}
catch (OptionParserException e) {
_logger.error(e);
return 1;
}
return 0;
}
public int convert() throws UTGBException, IOException {
if (input1 == null) {
throw new UTGBException(UTGBErrorCode.MISSING_OPTION, "missing fastq file");
}
Reader in1;
if (input1.getName().endsWith(".gz")) {
in1 = new InputStreamReader(new GZIPInputStream(new FileInputStream(input1)));
}
else
in1 = new FileReader(input1);
Reader in2 = null;
if (input2 != null) {
if (input2.getName().endsWith(".gz"))
in2 = new InputStreamReader(new GZIPInputStream(new FileInputStream(input2)));
else
in2 = new FileReader(input2);
}
return convert(new BufferedReader(in1), in2 == null ? null : new BufferedReader(in2));
}
public int convert(Reader input1, Reader input2) throws UTGBException, IOException {
FastqReader end1 = new FastqReader(input1);
FastqReader end2 = (input2 == null) ? null : new FastqReader(input2);
SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord(readGroupName);
SAMFileHeader samHeader = new SAMFileHeader();
if (readGroupName != null) {
samHeader.addReadGroup(readGroupRecord);
}
readGroupRecord.setSample(sampleName);
samHeader.setSortOrder(SAMFileHeader.SortOrder.queryname);
if (outputFile == null)
throw new UTGBException(UTGBErrorCode.MISSING_OPTION, "no output file is specified by -o option");
SAMFileWriter sfw = (new SAMFileWriterFactory()).makeSAMOrBAMWriter(samHeader, false, outputFile);
int readsSeen = 0;
try {
for (FastqRead fqr1, fqr2 = null; (fqr1 = end1.next()) != null && (end2 == null || (fqr2 = end2.next()) != null);) {
String fqr1Name = fqr1.seqname;
SAMRecord sr1 = new SAMRecord(samHeader);
sr1.setReadName(readPrefix != null ? (readPrefix + ":" + fqr1Name) : fqr1Name);
sr1.setReadString(fqr1.seq);
sr1.setBaseQualityString(fqr1.qual);
sr1.setReadUnmappedFlag(true);
sr1.setReadPairedFlag(false);
sr1.setAttribute("RG", readGroupName);
SAMRecord sr2 = null;
// paired-end read
if (fqr2 != null) {
sr1.setReadPairedFlag(true);
sr1.setFirstOfPairFlag(true);
sr1.setSecondOfPairFlag(false);
sr1.setMateUnmappedFlag(true);
String fqr2Name = fqr2.seqname;
sr2 = new SAMRecord(samHeader);
sr2.setReadName(readPrefix != null ? (readPrefix + ":" + fqr2Name) : fqr2Name);
sr2.setReadString(fqr2.seq);
sr2.setBaseQualityString(fqr2.qual);
sr2.setReadUnmappedFlag(true);
sr2.setReadPairedFlag(true);
sr2.setAttribute("RG", readGroupName);
sr2.setFirstOfPairFlag(false);
sr2.setSecondOfPairFlag(true);
sr2.setMateUnmappedFlag(true);
}
sfw.addAlignment(sr1);
if (fqr2 != null) {
sfw.addAlignment(sr2);
}
readsSeen++;
if (readsSeen > 0 && (readsSeen % 100000) == 0) {
_logger.info(String.format("%d (paired) reads has been processed.", readsSeen));
}
}
}
- catch (IllegalArgumentException e) {
- _logger.error(String.format("error found in read (%d) : %s", readsSeen, e.getMessage()));
- throw e;
+ catch (Exception e) {
+ _logger.error(String.format("error found when reading %d-th read: %s", readsSeen, e.getMessage()));
+ throw UTGBException.convert(e);
}
finally {
if (end1 != null)
end1.close();
if (end2 != null)
end2.close();
if (sfw != null)
sfw.close();
}
return readsSeen;
}
}
| true | true | public int convert(Reader input1, Reader input2) throws UTGBException, IOException {
FastqReader end1 = new FastqReader(input1);
FastqReader end2 = (input2 == null) ? null : new FastqReader(input2);
SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord(readGroupName);
SAMFileHeader samHeader = new SAMFileHeader();
if (readGroupName != null) {
samHeader.addReadGroup(readGroupRecord);
}
readGroupRecord.setSample(sampleName);
samHeader.setSortOrder(SAMFileHeader.SortOrder.queryname);
if (outputFile == null)
throw new UTGBException(UTGBErrorCode.MISSING_OPTION, "no output file is specified by -o option");
SAMFileWriter sfw = (new SAMFileWriterFactory()).makeSAMOrBAMWriter(samHeader, false, outputFile);
int readsSeen = 0;
try {
for (FastqRead fqr1, fqr2 = null; (fqr1 = end1.next()) != null && (end2 == null || (fqr2 = end2.next()) != null);) {
String fqr1Name = fqr1.seqname;
SAMRecord sr1 = new SAMRecord(samHeader);
sr1.setReadName(readPrefix != null ? (readPrefix + ":" + fqr1Name) : fqr1Name);
sr1.setReadString(fqr1.seq);
sr1.setBaseQualityString(fqr1.qual);
sr1.setReadUnmappedFlag(true);
sr1.setReadPairedFlag(false);
sr1.setAttribute("RG", readGroupName);
SAMRecord sr2 = null;
// paired-end read
if (fqr2 != null) {
sr1.setReadPairedFlag(true);
sr1.setFirstOfPairFlag(true);
sr1.setSecondOfPairFlag(false);
sr1.setMateUnmappedFlag(true);
String fqr2Name = fqr2.seqname;
sr2 = new SAMRecord(samHeader);
sr2.setReadName(readPrefix != null ? (readPrefix + ":" + fqr2Name) : fqr2Name);
sr2.setReadString(fqr2.seq);
sr2.setBaseQualityString(fqr2.qual);
sr2.setReadUnmappedFlag(true);
sr2.setReadPairedFlag(true);
sr2.setAttribute("RG", readGroupName);
sr2.setFirstOfPairFlag(false);
sr2.setSecondOfPairFlag(true);
sr2.setMateUnmappedFlag(true);
}
sfw.addAlignment(sr1);
if (fqr2 != null) {
sfw.addAlignment(sr2);
}
readsSeen++;
if (readsSeen > 0 && (readsSeen % 100000) == 0) {
_logger.info(String.format("%d (paired) reads has been processed.", readsSeen));
}
}
}
catch (IllegalArgumentException e) {
_logger.error(String.format("error found in read (%d) : %s", readsSeen, e.getMessage()));
throw e;
}
finally {
if (end1 != null)
end1.close();
if (end2 != null)
end2.close();
if (sfw != null)
sfw.close();
}
return readsSeen;
}
| public int convert(Reader input1, Reader input2) throws UTGBException, IOException {
FastqReader end1 = new FastqReader(input1);
FastqReader end2 = (input2 == null) ? null : new FastqReader(input2);
SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord(readGroupName);
SAMFileHeader samHeader = new SAMFileHeader();
if (readGroupName != null) {
samHeader.addReadGroup(readGroupRecord);
}
readGroupRecord.setSample(sampleName);
samHeader.setSortOrder(SAMFileHeader.SortOrder.queryname);
if (outputFile == null)
throw new UTGBException(UTGBErrorCode.MISSING_OPTION, "no output file is specified by -o option");
SAMFileWriter sfw = (new SAMFileWriterFactory()).makeSAMOrBAMWriter(samHeader, false, outputFile);
int readsSeen = 0;
try {
for (FastqRead fqr1, fqr2 = null; (fqr1 = end1.next()) != null && (end2 == null || (fqr2 = end2.next()) != null);) {
String fqr1Name = fqr1.seqname;
SAMRecord sr1 = new SAMRecord(samHeader);
sr1.setReadName(readPrefix != null ? (readPrefix + ":" + fqr1Name) : fqr1Name);
sr1.setReadString(fqr1.seq);
sr1.setBaseQualityString(fqr1.qual);
sr1.setReadUnmappedFlag(true);
sr1.setReadPairedFlag(false);
sr1.setAttribute("RG", readGroupName);
SAMRecord sr2 = null;
// paired-end read
if (fqr2 != null) {
sr1.setReadPairedFlag(true);
sr1.setFirstOfPairFlag(true);
sr1.setSecondOfPairFlag(false);
sr1.setMateUnmappedFlag(true);
String fqr2Name = fqr2.seqname;
sr2 = new SAMRecord(samHeader);
sr2.setReadName(readPrefix != null ? (readPrefix + ":" + fqr2Name) : fqr2Name);
sr2.setReadString(fqr2.seq);
sr2.setBaseQualityString(fqr2.qual);
sr2.setReadUnmappedFlag(true);
sr2.setReadPairedFlag(true);
sr2.setAttribute("RG", readGroupName);
sr2.setFirstOfPairFlag(false);
sr2.setSecondOfPairFlag(true);
sr2.setMateUnmappedFlag(true);
}
sfw.addAlignment(sr1);
if (fqr2 != null) {
sfw.addAlignment(sr2);
}
readsSeen++;
if (readsSeen > 0 && (readsSeen % 100000) == 0) {
_logger.info(String.format("%d (paired) reads has been processed.", readsSeen));
}
}
}
catch (Exception e) {
_logger.error(String.format("error found when reading %d-th read: %s", readsSeen, e.getMessage()));
throw UTGBException.convert(e);
}
finally {
if (end1 != null)
end1.close();
if (end2 != null)
end2.close();
if (sfw != null)
sfw.close();
}
return readsSeen;
}
|
diff --git a/src/com/dmdirc/updater/Update.java b/src/com/dmdirc/updater/Update.java
index 3487cefe5..2eb217fa2 100644
--- a/src/com/dmdirc/updater/Update.java
+++ b/src/com/dmdirc/updater/Update.java
@@ -1,221 +1,221 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.updater;
import com.dmdirc.Main;
import com.dmdirc.interfaces.UpdateListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.util.DownloadListener;
import com.dmdirc.util.Downloader;
import com.dmdirc.util.WeakList;
import java.util.List;
/**
* Represents a single available update for some component.
*
* @author chris
*/
public final class Update implements DownloadListener {
/** Update component. */
private final UpdateComponent component;
/** Remote version name. */
private final String versionName;
/** Update url. */
private final String url;
/** The progress of the current stage. */
private float progress;
/** A list of registered update listeners. */
private final List<UpdateListener> listeners
= new WeakList<UpdateListener>();
/** Our current status. */
private UpdateStatus status = UpdateStatus.PENDING;
/**
* Creates a new instance of Update, with details from the specified line.
*
* @param updateInfo An update information line from the update server
*/
public Update(final String updateInfo) {
// outofdate client STABLE 20071007 0.5.1 file
final String[] parts = updateInfo.split(" ");
if (parts.length == 6) {
component = UpdateChecker.findComponent(parts[1]);
versionName = parts[4];
url = parts[5];
} else {
component = null;
versionName = null;
url = null;
Logger.appError(ErrorLevel.LOW,
"Invalid update line received from server: ",
new UnsupportedOperationException("line: " + updateInfo));
}
}
/**
* Retrieves the component that this update is for.
*
* @return The component of this update
*/
public UpdateComponent getComponent() {
return component;
}
/**
* Returns the remote version of the component that's available.
*
* @return The remote version number
*/
public String getRemoteVersion() {
return versionName;
}
/**
* Returns the URL where the new update may be downloaded.
*
* @return The URL of the update
*/
public String getUrl() {
return url;
}
/**
* Retrieves the status of this update.
*
* @return This update's status
*/
public UpdateStatus getStatus() {
return status;
}
/**
* Sets the status of this update, and notifies all listeners of the change.
*
* @param newStatus This update's new status
*/
protected void setStatus(final UpdateStatus newStatus) {
status = newStatus;
progress = 0;
for (UpdateListener listener : listeners) {
listener.updateStatusChange(this, status);
}
}
/**
* Removes the specified update listener.
*
* @param o The update listener to remove
*/
public void removeUpdateListener(final Object o) {
listeners.remove(o);
}
/**
* Adds the specified update listener.
*
* @param e The update listener to add
*/
public void addUpdateListener(final UpdateListener e) {
listeners.add(e);
}
/**
* Makes this update download and install itself.
*/
public void doUpdate() {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String path = Main.getConfigDir() + "update.tmp."
+ Math.round(Math.random() * 1000);
setStatus(UpdateStatus.DOWNLOADING);
try {
Downloader.downloadPage(getUrl(), path, Update.this);
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
- Logger.appError(ErrorLevel.MEDIUM,
- "Error when updating component " + component, ex);
+ Logger.appError(ErrorLevel.MEDIUM, "Error when updating component "
+ + component.getName(), ex);
return;
}
setStatus(UpdateStatus.INSTALLING);
try {
final boolean restart = getComponent().doInstall(path);
if (restart) {
setStatus(UpdateStatus.RESTART_NEEDED);
UpdateChecker.removeComponent(getComponent().getName());
} else {
setStatus(UpdateStatus.INSTALLED);
}
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component, ex);
}
}
}, "Update thread").start();
}
/** {@inheritDoc} */
@Override
public void downloadProgress(final float percent) {
progress = percent;
for (UpdateListener listener : listeners) {
listener.updateProgressChange(this, percent);
}
}
/**
* Retrieves the current progress of the current state of this update.
*
* @return The percentage of the current stage that has been completed
*/
public float getProgress() {
return progress;
}
/** {@inheritDoc} */
@Override
public void setIndeterminate(boolean indeterminate) {
//TODO
}
}
| true | true | public void doUpdate() {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String path = Main.getConfigDir() + "update.tmp."
+ Math.round(Math.random() * 1000);
setStatus(UpdateStatus.DOWNLOADING);
try {
Downloader.downloadPage(getUrl(), path, Update.this);
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component, ex);
return;
}
setStatus(UpdateStatus.INSTALLING);
try {
final boolean restart = getComponent().doInstall(path);
if (restart) {
setStatus(UpdateStatus.RESTART_NEEDED);
UpdateChecker.removeComponent(getComponent().getName());
} else {
setStatus(UpdateStatus.INSTALLED);
}
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component, ex);
}
}
}, "Update thread").start();
}
| public void doUpdate() {
new Thread(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
final String path = Main.getConfigDir() + "update.tmp."
+ Math.round(Math.random() * 1000);
setStatus(UpdateStatus.DOWNLOADING);
try {
Downloader.downloadPage(getUrl(), path, Update.this);
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM, "Error when updating component "
+ component.getName(), ex);
return;
}
setStatus(UpdateStatus.INSTALLING);
try {
final boolean restart = getComponent().doInstall(path);
if (restart) {
setStatus(UpdateStatus.RESTART_NEEDED);
UpdateChecker.removeComponent(getComponent().getName());
} else {
setStatus(UpdateStatus.INSTALLED);
}
} catch (Throwable ex) {
setStatus(UpdateStatus.ERROR);
Logger.appError(ErrorLevel.MEDIUM,
"Error when updating component " + component, ex);
}
}
}, "Update thread").start();
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java
index 479a5efa3..dfeac0c4f 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/query/change/ChangeData.java
@@ -1,189 +1,187 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.query.change;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.PatchLineComment;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gerrit.reviewdb.PatchSetApproval;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.reviewdb.TrackingId;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.patch.PatchList;
import com.google.gerrit.server.patch.PatchListCache;
import com.google.gerrit.server.patch.PatchListEntry;
import com.google.gwtorm.client.OrmException;
import com.google.inject.Provider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class ChangeData {
private final Change.Id legacyId;
private Change change;
private Collection<PatchSet> patches;
private Collection<PatchSetApproval> approvals;
private Collection<PatchSetApproval> currentApprovals;
private Collection<String> currentFiles;
private Collection<PatchLineComment> comments;
private Collection<TrackingId> trackingIds;
private CurrentUser visibleTo;
public ChangeData(final Change.Id id) {
legacyId = id;
}
public ChangeData(final Change c) {
legacyId = c.getId();
change = c;
}
public void setCurrentFilePaths(Collection<String> filePaths) {
currentFiles = filePaths;
}
public Collection<String> currentFilePaths(Provider<ReviewDb> db,
PatchListCache cache) throws OrmException {
if (currentFiles == null) {
Change c = change(db);
if (c == null) {
return null;
}
PatchSet ps = currentPatchSet(db);
if (ps == null) {
return null;
}
PatchList p = cache.get(c, ps);
List<String> r = new ArrayList<String>(p.getPatches().size());
for (PatchListEntry e : p.getPatches()) {
switch (e.getChangeType()) {
case ADDED:
case MODIFIED:
+ case DELETED:
case COPIED:
r.add(e.getNewName());
break;
- case DELETED:
- r.add(e.getOldName());
- break;
case RENAMED:
r.add(e.getOldName());
r.add(e.getNewName());
break;
}
}
currentFiles = r;
}
return currentFiles;
}
public Change.Id getId() {
return legacyId;
}
public Change getChange() {
return change;
}
public boolean hasChange() {
return change != null;
}
boolean fastIsVisibleTo(CurrentUser user) {
return visibleTo == user;
}
void cacheVisibleTo(CurrentUser user) {
visibleTo = user;
}
public Change change(Provider<ReviewDb> db) throws OrmException {
if (change == null) {
change = db.get().changes().get(legacyId);
}
return change;
}
public PatchSet currentPatchSet(Provider<ReviewDb> db) throws OrmException {
Change c = change(db);
if (c == null) {
return null;
}
for (PatchSet p : patches(db)) {
if (p.getId().equals(c.currentPatchSetId())) {
return p;
}
}
return null;
}
public Collection<PatchSetApproval> currentApprovals(Provider<ReviewDb> db)
throws OrmException {
if (currentApprovals == null) {
Change c = change(db);
if (c == null) {
currentApprovals = Collections.emptyList();
} else {
currentApprovals = approvalsFor(db, c.currentPatchSetId());
}
}
return currentApprovals;
}
public Collection<PatchSetApproval> approvalsFor(Provider<ReviewDb> db,
PatchSet.Id psId) throws OrmException {
List<PatchSetApproval> r = new ArrayList<PatchSetApproval>();
for (PatchSetApproval p : approvals(db)) {
if (p.getPatchSetId().equals(psId)) {
r.add(p);
}
}
return r;
}
public Collection<PatchSet> patches(Provider<ReviewDb> db)
throws OrmException {
if (patches == null) {
patches = db.get().patchSets().byChange(legacyId).toList();
}
return patches;
}
public Collection<PatchSetApproval> approvals(Provider<ReviewDb> db)
throws OrmException {
if (approvals == null) {
approvals = db.get().patchSetApprovals().byChange(legacyId).toList();
}
return approvals;
}
public Collection<PatchLineComment> comments(Provider<ReviewDb> db)
throws OrmException {
if (comments == null) {
comments = db.get().patchComments().byChange(legacyId).toList();
}
return comments;
}
public Collection<TrackingId> trackingIds(Provider<ReviewDb> db)
throws OrmException {
if (trackingIds == null) {
trackingIds = db.get().trackingIds().byChange(legacyId).toList();
}
return trackingIds;
}
}
| false | true | public Collection<String> currentFilePaths(Provider<ReviewDb> db,
PatchListCache cache) throws OrmException {
if (currentFiles == null) {
Change c = change(db);
if (c == null) {
return null;
}
PatchSet ps = currentPatchSet(db);
if (ps == null) {
return null;
}
PatchList p = cache.get(c, ps);
List<String> r = new ArrayList<String>(p.getPatches().size());
for (PatchListEntry e : p.getPatches()) {
switch (e.getChangeType()) {
case ADDED:
case MODIFIED:
case COPIED:
r.add(e.getNewName());
break;
case DELETED:
r.add(e.getOldName());
break;
case RENAMED:
r.add(e.getOldName());
r.add(e.getNewName());
break;
}
}
currentFiles = r;
}
return currentFiles;
}
| public Collection<String> currentFilePaths(Provider<ReviewDb> db,
PatchListCache cache) throws OrmException {
if (currentFiles == null) {
Change c = change(db);
if (c == null) {
return null;
}
PatchSet ps = currentPatchSet(db);
if (ps == null) {
return null;
}
PatchList p = cache.get(c, ps);
List<String> r = new ArrayList<String>(p.getPatches().size());
for (PatchListEntry e : p.getPatches()) {
switch (e.getChangeType()) {
case ADDED:
case MODIFIED:
case DELETED:
case COPIED:
r.add(e.getNewName());
break;
case RENAMED:
r.add(e.getOldName());
r.add(e.getNewName());
break;
}
}
currentFiles = r;
}
return currentFiles;
}
|
diff --git a/src/com/teamblobby/studybeacon/APIClient.java b/src/com/teamblobby/studybeacon/APIClient.java
index 6501eeb..24080b6 100644
--- a/src/com/teamblobby/studybeacon/APIClient.java
+++ b/src/com/teamblobby/studybeacon/APIClient.java
@@ -1,116 +1,116 @@
package com.teamblobby.studybeacon;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.loopj.android.http.*;
import com.teamblobby.studybeacon.datastructures.Beacon;
import org.json.*;
public class APIClient {
public static final String TAG = "APIClient";
public static final String BASE_URL = "http://leostein.scripts.mit.edu/StudyBeacon/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
////////////////////////////////
// Interface to doing a query.
public final static String QUERY_URL = "query.py";
// These strings are for the format of the query
public final static String COURSE_STR = "course";
public final static String LAT_MIN_STR = "LatE6Min";
public final static String LAT_MAX_STR = "LatE6Max";
public final static String LON_MIN_STR = "LonE6Min";
public final static String LON_MAX_STR = "LonE6Max";
// These strings are for the format of the response
public final static String LAT_STR = "LatE6";
public final static String LON_STR = "LonE6";
public final static String DETAILS_STR = "Details";
public final static String CONTACT_STR = "Contact";
public final static String COUNT_STR = "count";
public final static String CREATED_STR = "Created";
public final static String EXPIRES_STR = "Expires";
public static void query(int LatE6Min, int LatE6Max, int LonE6Min, int LonE6Max, String courses[],
final SBAPIHandler handler)
//throws JSONException
{
RequestParams params = new RequestParams();
params.put(LAT_MIN_STR,Integer.toString(LatE6Min));
params.put(LAT_MAX_STR,Integer.toString(LatE6Max));
params.put(LON_MIN_STR,Integer.toString(LonE6Min));
params.put(LON_MAX_STR,Integer.toString(LonE6Max));
// TODO This does not make multiple entries for multiple courses!
for (String course : courses)
params.put(COURSE_STR, course);
Log.d(TAG,"Query string " + params.toString());
get(QUERY_URL, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray response) {
// the response should be an array of objects
ArrayList<Beacon> beacons = new ArrayList<Beacon>();
try {
for(int i =0; i < response.length(); i++) {
JSONObject bObj = response.getJSONObject(i);
GeoPoint point = new GeoPoint(bObj.getInt(LAT_STR), bObj.getInt(LON_STR));
// TODO Check that this parsing works
DateFormat df = DateFormat.getDateInstance();
Date created = df.parse(bObj.getString(CREATED_STR));
Date expires = df.parse(bObj.getString(EXPIRES_STR));
beacons.add(new Beacon(bObj.getString(COURSE_STR), point, bObj.getInt(COUNT_STR),
bObj.getString(DETAILS_STR), bObj.getString(CONTACT_STR),
created, expires));
}
// Call the handler's function (This is not within the UI thread? is this bad?)
handler.onQuery(beacons);
}
catch (Exception e) {
// TODO do something here??
- Log.d(TAG,e.getMessage());
+ Log.e(TAG,e.getMessage());
}
}
});
}
}
| true | true | public static void query(int LatE6Min, int LatE6Max, int LonE6Min, int LonE6Max, String courses[],
final SBAPIHandler handler)
//throws JSONException
{
RequestParams params = new RequestParams();
params.put(LAT_MIN_STR,Integer.toString(LatE6Min));
params.put(LAT_MAX_STR,Integer.toString(LatE6Max));
params.put(LON_MIN_STR,Integer.toString(LonE6Min));
params.put(LON_MAX_STR,Integer.toString(LonE6Max));
// TODO This does not make multiple entries for multiple courses!
for (String course : courses)
params.put(COURSE_STR, course);
Log.d(TAG,"Query string " + params.toString());
get(QUERY_URL, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray response) {
// the response should be an array of objects
ArrayList<Beacon> beacons = new ArrayList<Beacon>();
try {
for(int i =0; i < response.length(); i++) {
JSONObject bObj = response.getJSONObject(i);
GeoPoint point = new GeoPoint(bObj.getInt(LAT_STR), bObj.getInt(LON_STR));
// TODO Check that this parsing works
DateFormat df = DateFormat.getDateInstance();
Date created = df.parse(bObj.getString(CREATED_STR));
Date expires = df.parse(bObj.getString(EXPIRES_STR));
beacons.add(new Beacon(bObj.getString(COURSE_STR), point, bObj.getInt(COUNT_STR),
bObj.getString(DETAILS_STR), bObj.getString(CONTACT_STR),
created, expires));
}
// Call the handler's function (This is not within the UI thread? is this bad?)
handler.onQuery(beacons);
}
catch (Exception e) {
// TODO do something here??
Log.d(TAG,e.getMessage());
}
}
});
}
| public static void query(int LatE6Min, int LatE6Max, int LonE6Min, int LonE6Max, String courses[],
final SBAPIHandler handler)
//throws JSONException
{
RequestParams params = new RequestParams();
params.put(LAT_MIN_STR,Integer.toString(LatE6Min));
params.put(LAT_MAX_STR,Integer.toString(LatE6Max));
params.put(LON_MIN_STR,Integer.toString(LonE6Min));
params.put(LON_MAX_STR,Integer.toString(LonE6Max));
// TODO This does not make multiple entries for multiple courses!
for (String course : courses)
params.put(COURSE_STR, course);
Log.d(TAG,"Query string " + params.toString());
get(QUERY_URL, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray response) {
// the response should be an array of objects
ArrayList<Beacon> beacons = new ArrayList<Beacon>();
try {
for(int i =0; i < response.length(); i++) {
JSONObject bObj = response.getJSONObject(i);
GeoPoint point = new GeoPoint(bObj.getInt(LAT_STR), bObj.getInt(LON_STR));
// TODO Check that this parsing works
DateFormat df = DateFormat.getDateInstance();
Date created = df.parse(bObj.getString(CREATED_STR));
Date expires = df.parse(bObj.getString(EXPIRES_STR));
beacons.add(new Beacon(bObj.getString(COURSE_STR), point, bObj.getInt(COUNT_STR),
bObj.getString(DETAILS_STR), bObj.getString(CONTACT_STR),
created, expires));
}
// Call the handler's function (This is not within the UI thread? is this bad?)
handler.onQuery(beacons);
}
catch (Exception e) {
// TODO do something here??
Log.e(TAG,e.getMessage());
}
}
});
}
|
diff --git a/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/index/solr/SearchRequest.java b/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/index/solr/SearchRequest.java
index 88ccfde92..acabe6bde 100644
--- a/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/index/solr/SearchRequest.java
+++ b/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/index/solr/SearchRequest.java
@@ -1,665 +1,671 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.contentrepository.impl.index.solr;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.ALTERNATE_VERSION;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.CONTENT_EXTERNAL_REPRESENTATION;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.CONTENT_FILENAME;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.CONTENT_MIMETYPE;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.CONTENT_SOURCE;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.CREATED;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.CREATED_BY;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.FULLTEXT;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.ID;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.MODIFIED;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.MODIFIED_BY;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PAGELET_CONTENTS;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PAGELET_PROPERTIES;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PAGELET_TYPE;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PAGELET_TYPE_COMPOSER;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PAGELET_TYPE_COMPOSER_POSITION;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PATH;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PATH_PREFIX;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PUBLISHED_BY;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.PUBLISHED_FROM;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.RESOURCE_ID;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.SCORE;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.SERIES;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.STATIONARY;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.SUBJECT;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.TEMPLATE;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.TITLE_BOOST;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.TITLE_LOCALIZED;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.TYPE;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrSchema.VERSION;
import static ch.entwine.weblounge.contentrepository.impl.index.solr.SolrUtils.clean;
import ch.entwine.weblounge.common.content.ResourceMetadata;
import ch.entwine.weblounge.common.content.SearchQuery;
import ch.entwine.weblounge.common.content.SearchResult;
import ch.entwine.weblounge.common.content.SearchResultItem;
import ch.entwine.weblounge.common.content.page.Pagelet;
import ch.entwine.weblounge.common.content.page.PageletURI;
import ch.entwine.weblounge.common.impl.content.ResourceMetadataImpl;
import ch.entwine.weblounge.common.impl.content.SearchQueryImpl;
import ch.entwine.weblounge.common.impl.content.SearchResultImpl;
import ch.entwine.weblounge.common.security.User;
import ch.entwine.weblounge.common.site.Site;
import ch.entwine.weblounge.contentrepository.ResourceSerializer;
import ch.entwine.weblounge.contentrepository.ResourceSerializerFactory;
import ch.entwine.weblounge.contentrepository.impl.index.SearchIndex;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Class implementing <code>LookupRequester</code> to provide connection to solr
* indexing facility.
*/
public class SearchRequest {
/** Logging facility */
private static Logger logger = LoggerFactory.getLogger(SearchRequest.class);
/** The connection to the solr database */
private Solr solr = null;
/**
* Creates a new requester for solr that will be using the given connection
* object to query the search index.
*
* @param connection
* the solr connection
*/
public SearchRequest(Solr connection) {
if (connection == null)
throw new IllegalStateException("Unable to run queries on null connection");
this.solr = connection;
}
/**
* Executes a search operation using the given query and returns the result
* range as specified by the parameters <code>offset</code> and
* <code>limit</code>.
*
* @param query
* the search query
* @return the search result
* @throws SolrServerException
* if executing the search operation fails
*/
public SearchResult getByQuery(SearchQuery query) throws SolrServerException {
Site site = query.getSite();
// Build the solr query string
StringBuilder solrQuery = new StringBuilder();
// Resource id
if (query.getIdentifier().length > 0) {
and(solrQuery, RESOURCE_ID, query.getIdentifier(), true, true);
}
// Version / Preferred version
if (query.getPreferredVersion() >= 0) {
andNot(solrQuery, ALTERNATE_VERSION, Long.toString(query.getPreferredVersion()), false, false);
} else if (query.getVersion() >= 0) {
and(solrQuery, VERSION, Long.toString(query.getVersion()), false, false);
}
// Path
if (query.getPath() != null) {
and(solrQuery, PATH, query.getPath(), true, true);
}
if (query.getPathPrefix() != null) {
and(solrQuery, PATH_PREFIX, query.getPathPrefix(), true, true);
}
// Type
if (query.getTypes().length > 0) {
and(solrQuery, TYPE, query.getTypes(), true, true);
}
// Without type
if (query.getWithoutTypes().length > 0) {
andNot(solrQuery, TYPE, query.getWithoutTypes(), true, true);
}
// Subjects (OR)
if (query.getSubjects().length > 0) {
and(solrQuery, SUBJECT, query.getSubjects(), true, true);
}
// Subjects (AND)
if (query.getANDSubjects().length > 0) {
for (String subject : query.getANDSubjects()) {
and(solrQuery, SUBJECT, subject, true, true);
}
}
// Series
if (query.getSeries().length > 0) {
and(solrQuery, SERIES, query.getSeries(), true, true);
}
// Template
if (query.getTemplate() != null) {
and(solrQuery, TEMPLATE, query.getTemplate(), true, true);
}
// Stationary
if (query.isStationary()) {
and(solrQuery, STATIONARY, Boolean.TRUE.toString(), false, false);
}
// Creator
if (query.getCreator() != null) {
and(solrQuery, CREATED_BY, SolrUtils.serializeUserId(query.getCreator()), true, true);
}
// Creation date
if (query.getCreationDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, CREATED, SolrUtils.serializeDateRange(query.getCreationDate(), query.getCreationDateEnd()), false, false);
else
and(solrQuery, CREATED, SolrUtils.selectDay(query.getCreationDate()), false, false);
}
// Modifier
if (query.getModifier() != null) {
and(solrQuery, MODIFIED_BY, SolrUtils.serializeUserId(query.getModifier()), true, true);
}
// Modification date
if (query.getModificationDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, MODIFIED, SolrUtils.serializeDateRange(query.getModificationDate(), query.getModificationDateEnd()), false, false);
else
and(solrQuery, MODIFIED, SolrUtils.selectDay(query.getModificationDate()), false, false);
}
// Without Modification
if (query.getWithoutModification()) {
andEmpty(solrQuery, MODIFIED);
}
// Publisher
if (query.getPublisher() != null) {
and(solrQuery, PUBLISHED_BY, SolrUtils.serializeUserId(query.getPublisher()), true, true);
}
// Publication date
if (query.getPublishingDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, PUBLISHED_FROM, SolrUtils.serializeDateRange(query.getPublishingDate(), query.getPublishingDateEnd()), false, false);
else
and(solrQuery, PUBLISHED_FROM, SolrUtils.selectDay(query.getPublishingDate()), false, false);
}
// Without Publication
if (query.getWithoutPublication()) {
andEmpty(solrQuery, PUBLISHED_FROM);
}
// Lock owner
if (query.getLockOwner() != null) {
User user = query.getLockOwner();
if (SearchQueryImpl.ANY_USER.equals(user.getLogin()))
andNotEmpty(solrQuery, SolrSchema.LOCKED_BY);
else
and(solrQuery, SolrSchema.LOCKED_BY, SolrUtils.serializeUserId(user), true, true);
}
// Pagelet elements
for (Map.Entry<String, String> entry : query.getElements().entrySet()) {
// TODO: Language?
solrQuery.append(" ").append(PAGELET_CONTENTS).append(":");
solrQuery.append("\"").append(entry.getKey()).append(":=\"");
for (String contentValue : StringUtils.split(entry.getValue())) {
solrQuery.append(" \"").append(SolrUtils.clean(contentValue)).append("\"");
}
}
// Pagelet properties
for (Map.Entry<String, String> entry : query.getProperties().entrySet()) {
StringBuffer searchTerm = new StringBuffer();
searchTerm.append(entry.getKey());
searchTerm.append(":=").append(entry.getValue());
and(solrQuery, PAGELET_PROPERTIES, searchTerm.toString(), true, true);
}
// Pagelet types
for (Pagelet pagelet : query.getPagelets()) {
StringBuffer searchTerm = new StringBuffer();
searchTerm.append(pagelet.getModule()).append("/").append(pagelet.getIdentifier());
// Are we looking for the pagelet in a certain composer or position?
PageletURI uri = pagelet.getURI();
if (uri != null && (StringUtils.isNotBlank(uri.getComposer()) || uri.getPosition() >= 0)) {
if (StringUtils.isNotBlank(uri.getComposer())) {
String field = MessageFormat.format(PAGELET_TYPE_COMPOSER, uri.getComposer());
and(solrQuery, field, searchTerm.toString(), true, true);
}
if (uri.getPosition() >= 0) {
String field = MessageFormat.format(PAGELET_TYPE_COMPOSER_POSITION, uri.getPosition());
and(solrQuery, field, searchTerm.toString(), true, true);
}
} else {
and(solrQuery, PAGELET_TYPE, searchTerm.toString(), true, true);
}
}
// Content filenames
if (query.getFilename() != null) {
and(solrQuery, CONTENT_FILENAME, query.getFilename(), true, true);
}
// Content source
if (query.getSource() != null) {
and(solrQuery, CONTENT_SOURCE, query.getSource(), true, true);
}
// Content external location
if (query.getExternalLocation() != null) {
and(solrQuery, CONTENT_EXTERNAL_REPRESENTATION, query.getExternalLocation().toExternalForm(), true, true);
}
// Content mime types
if (query.getMimetype() != null) {
and(solrQuery, CONTENT_MIMETYPE, query.getMimetype(), true, true);
}
// Fulltext
if (query.getText() != null) {
// TODO: Wildcard searches are not yet working. Retry when switching
// over to Solr 4
// if (query.isWildcardSearch()) {
// and(solrQuery, FULLTEXT, clean(query.getText()) + "*", false, false);
// } else {
// and(solrQuery, FULLTEXT, query.getText(), true, true);
// }
for (String s : StringUtils.split(query.getText())) {
and(solrQuery, FULLTEXT, s, true, true);
}
}
if (solrQuery.length() == 0)
solrQuery.append("*:*");
// Hide the root entry
andNot(solrQuery, ID, Long.toString(SearchIndex.ROOT_ID), true, true);
logger.debug("Solr query is {}", solrQuery.toString());
// Prepare the solr query
SolrQuery q = new SolrQuery(solrQuery.toString());
q.setStart(query.getOffset() > 0 ? query.getOffset() : 0);
q.setRows(query.getLimit() > 0 ? query.getLimit() : Integer.MAX_VALUE);
// Filter query
if (query.getFilter() != null) {
q.addFilterQuery(clean(query.getFilter().toLowerCase()));
}
// Define the fields that should be returned by the query
List<String> fields = new ArrayList<String>();
fields.add("*");
// Order by publishing date
if (!SearchQuery.Order.None.equals(query.getPublishingDateSortOrder())) {
switch (query.getPublishingDateSortOrder()) {
case Ascending:
q.addSortField(PUBLISHED_FROM, ORDER.asc);
break;
case Descending:
q.addSortField(PUBLISHED_FROM, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by modification date
else if (!SearchQuery.Order.None.equals(query.getModificationDateSortOrder())) {
switch (query.getModificationDateSortOrder()) {
case Ascending:
q.addSortField(MODIFIED, ORDER.asc);
break;
case Descending:
q.addSortField(MODIFIED, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by creation date
else if (!SearchQuery.Order.None.equals(query.getCreationDateSortOrder())) {
switch (query.getCreationDateSortOrder()) {
case Ascending:
q.addSortField(CREATED, ORDER.asc);
break;
case Descending:
q.addSortField(CREATED, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by score
else {
q.setSortField(SCORE, SolrQuery.ORDER.desc);
q.setIncludeScore(true);
fields.add("score");
}
// Add the fields to return
q.setFields(StringUtils.join(fields, " "));
// Execute the query and try to get hold of a query response
QueryResponse solrResponse = null;
try {
solrResponse = solr.request(q);
} catch (Throwable t) {
throw new SolrServerException(t);
}
// Create and configure the query result
long hits = solrResponse.getResults().getNumFound();
long size = solrResponse.getResults().size();
SearchResultImpl result = new SearchResultImpl(query, hits, size);
result.setSearchTime(solrResponse.getQTime());
// Walk through response and create new items with title, creator, etc:
for (SolrDocument doc : solrResponse.getResults()) {
// Get the resource serializer
String type = (String) doc.getFirstValue(TYPE);
ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(type);
if (serializer == null) {
logger.warn("Skipping search result due to missing serializer of type {}", type);
continue;
}
// Wrap the search result metadata
List<ResourceMetadata<?>> metadata = new ArrayList<ResourceMetadata<?>>(doc.size());
for (Map.Entry<String, Object> entry : doc.entrySet()) {
String name = entry.getKey();
ResourceMetadata<Object> m = new ResourceMetadataImpl<Object>(name);
// TODO: Add values with more care (localized, correct type etc.)
if (entry.getValue() instanceof List) {
for (Object v : ((List<?>) entry.getValue())) {
m.addValue(v);
}
} else {
m.addValue(entry.getValue());
}
metadata.add(m);
}
// Get the score for this item
float score = fields.contains("score") ? (Float) doc.getFieldValue(SCORE) : 0.0f;
// Have the serializer in charge create a type-specific search result item
- SearchResultItem item = serializer.toSearchResultItem(site, score, metadata);
+ SearchResultItem item;
+ try {
+ item = serializer.toSearchResultItem(site, score, metadata);
+ } catch (Throwable t) {
+ logger.warn("Error during search result serialization: '{}'. Skipping this search result.", t.getMessage());
+ continue;
+ }
result.addResultItem(item);
}
return result;
}
/**
* Encodes field name and value as part of the AND clause of a solr query:
* <tt>AND fieldName : fieldValue</tt>.
*
* @param buf
* the <code>StringBuilder</code> to append to
* @param fieldName
* the field name
* @param fieldValue
* the field value
* @param quote
* <code>true</code> to put the field values in quotes
* @param clean
* <code>true</code> to escape solr special characters in the field
* value
* @return the encoded query part
*/
private StringBuilder and(StringBuilder buf, String fieldName,
String fieldValue, boolean quote, boolean clean) {
if (buf.length() > 0)
buf.append(" AND ");
buf.append(StringUtils.trim(fieldName));
buf.append(":");
if (quote)
buf.append("\"");
if (clean)
buf.append(StringUtils.trim(clean(fieldValue)));
else
buf.append(StringUtils.trim(fieldValue));
if (quote)
buf.append("\"");
return buf;
}
/**
* Encodes field name and values as part of a solr query:
* <tt>AND (fieldName : fieldValue[0] OR fieldName : fieldValue[1] ...)</tt>.
*
* @param buf
* the <code>StringBuilder</code> to append to
* @param fieldName
* the field name
* @param fieldValues
* the field value
* @param quote
* <code>true</code> to put the field values in quotes
* @param clean
* <code>true</code> to escape solr special characters in the field
* value
* @return the encoded query part
*/
private StringBuilder and(StringBuilder buf, String fieldName,
String[] fieldValues, boolean quote, boolean clean) {
if (buf.length() > 0)
buf.append(" AND ");
buf.append(fieldName);
buf.append(":(");
boolean first = true;
for (String value : fieldValues) {
if (!first)
buf.append(" OR ");
if (quote)
buf.append("\"");
if (clean)
buf.append(StringUtils.trim(clean(value)));
else
buf.append(StringUtils.trim(value));
if (quote)
buf.append("\"");
first = false;
}
buf.append(")");
return buf;
}
/**
* Encodes field name and value as part of the AND clause of a solr query:
* <tt>AND -fieldName : fieldValue</tt>.
*
* @param buf
* the <code>StringBuilder</code> to append to
* @param fieldName
* the field name
* @param fieldValue
* the field value
* @param quote
* <code>true</code> to put the field values in quotes
* @param clean
* <code>true</code> to escape solr special characters in the field
* value
* @return the encoded query part
*/
private StringBuilder andNot(StringBuilder buf, String fieldName,
String fieldValue, boolean quote, boolean clean) {
if (buf.length() > 0)
buf.append(" AND ");
buf.append("-"); // notice the minus sign
buf.append(StringUtils.trim(fieldName));
buf.append(":");
if (quote)
buf.append("\"");
if (clean)
buf.append(StringUtils.trim(clean(fieldValue)));
else
buf.append(StringUtils.trim(fieldValue));
if (quote)
buf.append("\"");
return buf;
}
/**
* Encodes field name and values as part of a solr query:
* <tt>AND -(fieldName : fieldValue[0] OR fieldName : fieldValue[1] ...)</tt>.
*
* @param buf
* the <code>StringBuilder</code> to append to
* @param fieldName
* the field name
* @param fieldValues
* the field value
* @param quote
* <code>true</code> to put the field values in quotes
* @param clean
* <code>true</code> to escape solr special characters in the field
* value
* @return the encoded query part
*/
private StringBuilder andNot(StringBuilder buf, String fieldName,
String[] fieldValues, boolean quote, boolean clean) {
if (buf.length() > 0)
buf.append(" AND ");
buf.append("-"); // notice the minus sign
buf.append(StringUtils.trim(fieldName));
buf.append(":(");
boolean first = true;
for (String value : fieldValues) {
if (!first)
buf.append(" OR ");
if (quote)
buf.append("\"");
if (clean)
buf.append(StringUtils.trim(clean(value)));
else
buf.append(StringUtils.trim(value));
if (quote)
buf.append("\"");
first = false;
}
buf.append(")");
return buf;
}
/**
* Encodes the field name as part of the AND clause of a solr query:
* <tt>AND -fieldName : [* TO *]</tt>.
*
* @param buf
* the <code>StringBuilder</code> to append to
* @param fieldName
* the field name
* @return the encoded query part
*/
private StringBuilder andEmpty(StringBuilder buf, String fieldName) {
if (buf.length() > 0)
buf.append(" AND ");
buf.append("-"); // notice the minus sign
buf.append(StringUtils.trim(fieldName));
buf.append(":[* TO *]");
return buf;
}
/**
* Encodes the field name as part of the AND clause of a solr query:
* <tt>AND fieldName : ["" TO *]</tt>.
*
* @param buf
* the <code>StringBuilder</code> to append to
* @param fieldName
* the field name
* @return the encoded query part
*/
private StringBuilder andNotEmpty(StringBuilder buf, String fieldName) {
if (buf.length() > 0)
buf.append(" AND "); // notice the minus sign
buf.append(StringUtils.trim(fieldName));
buf.append(":[* TO *]");
return buf;
}
/**
* Modifies the query such that certain fields are being boosted (meaning they
* gain some weight).
*
* @param query
* The user query.
* @return The boosted query
*/
public StringBuffer boost(String query) {
String uq = SolrUtils.clean(query);
StringBuffer sb = new StringBuffer();
sb.append("(");
sb.append(TITLE_LOCALIZED);
sb.append(":(");
sb.append(uq);
sb.append(")^");
sb.append(TITLE_BOOST);
sb.append(" ");
sb.append(FULLTEXT);
sb.append(":(");
sb.append(uq);
sb.append(") ");
sb.append(")");
return sb;
}
}
| true | true | public SearchResult getByQuery(SearchQuery query) throws SolrServerException {
Site site = query.getSite();
// Build the solr query string
StringBuilder solrQuery = new StringBuilder();
// Resource id
if (query.getIdentifier().length > 0) {
and(solrQuery, RESOURCE_ID, query.getIdentifier(), true, true);
}
// Version / Preferred version
if (query.getPreferredVersion() >= 0) {
andNot(solrQuery, ALTERNATE_VERSION, Long.toString(query.getPreferredVersion()), false, false);
} else if (query.getVersion() >= 0) {
and(solrQuery, VERSION, Long.toString(query.getVersion()), false, false);
}
// Path
if (query.getPath() != null) {
and(solrQuery, PATH, query.getPath(), true, true);
}
if (query.getPathPrefix() != null) {
and(solrQuery, PATH_PREFIX, query.getPathPrefix(), true, true);
}
// Type
if (query.getTypes().length > 0) {
and(solrQuery, TYPE, query.getTypes(), true, true);
}
// Without type
if (query.getWithoutTypes().length > 0) {
andNot(solrQuery, TYPE, query.getWithoutTypes(), true, true);
}
// Subjects (OR)
if (query.getSubjects().length > 0) {
and(solrQuery, SUBJECT, query.getSubjects(), true, true);
}
// Subjects (AND)
if (query.getANDSubjects().length > 0) {
for (String subject : query.getANDSubjects()) {
and(solrQuery, SUBJECT, subject, true, true);
}
}
// Series
if (query.getSeries().length > 0) {
and(solrQuery, SERIES, query.getSeries(), true, true);
}
// Template
if (query.getTemplate() != null) {
and(solrQuery, TEMPLATE, query.getTemplate(), true, true);
}
// Stationary
if (query.isStationary()) {
and(solrQuery, STATIONARY, Boolean.TRUE.toString(), false, false);
}
// Creator
if (query.getCreator() != null) {
and(solrQuery, CREATED_BY, SolrUtils.serializeUserId(query.getCreator()), true, true);
}
// Creation date
if (query.getCreationDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, CREATED, SolrUtils.serializeDateRange(query.getCreationDate(), query.getCreationDateEnd()), false, false);
else
and(solrQuery, CREATED, SolrUtils.selectDay(query.getCreationDate()), false, false);
}
// Modifier
if (query.getModifier() != null) {
and(solrQuery, MODIFIED_BY, SolrUtils.serializeUserId(query.getModifier()), true, true);
}
// Modification date
if (query.getModificationDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, MODIFIED, SolrUtils.serializeDateRange(query.getModificationDate(), query.getModificationDateEnd()), false, false);
else
and(solrQuery, MODIFIED, SolrUtils.selectDay(query.getModificationDate()), false, false);
}
// Without Modification
if (query.getWithoutModification()) {
andEmpty(solrQuery, MODIFIED);
}
// Publisher
if (query.getPublisher() != null) {
and(solrQuery, PUBLISHED_BY, SolrUtils.serializeUserId(query.getPublisher()), true, true);
}
// Publication date
if (query.getPublishingDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, PUBLISHED_FROM, SolrUtils.serializeDateRange(query.getPublishingDate(), query.getPublishingDateEnd()), false, false);
else
and(solrQuery, PUBLISHED_FROM, SolrUtils.selectDay(query.getPublishingDate()), false, false);
}
// Without Publication
if (query.getWithoutPublication()) {
andEmpty(solrQuery, PUBLISHED_FROM);
}
// Lock owner
if (query.getLockOwner() != null) {
User user = query.getLockOwner();
if (SearchQueryImpl.ANY_USER.equals(user.getLogin()))
andNotEmpty(solrQuery, SolrSchema.LOCKED_BY);
else
and(solrQuery, SolrSchema.LOCKED_BY, SolrUtils.serializeUserId(user), true, true);
}
// Pagelet elements
for (Map.Entry<String, String> entry : query.getElements().entrySet()) {
// TODO: Language?
solrQuery.append(" ").append(PAGELET_CONTENTS).append(":");
solrQuery.append("\"").append(entry.getKey()).append(":=\"");
for (String contentValue : StringUtils.split(entry.getValue())) {
solrQuery.append(" \"").append(SolrUtils.clean(contentValue)).append("\"");
}
}
// Pagelet properties
for (Map.Entry<String, String> entry : query.getProperties().entrySet()) {
StringBuffer searchTerm = new StringBuffer();
searchTerm.append(entry.getKey());
searchTerm.append(":=").append(entry.getValue());
and(solrQuery, PAGELET_PROPERTIES, searchTerm.toString(), true, true);
}
// Pagelet types
for (Pagelet pagelet : query.getPagelets()) {
StringBuffer searchTerm = new StringBuffer();
searchTerm.append(pagelet.getModule()).append("/").append(pagelet.getIdentifier());
// Are we looking for the pagelet in a certain composer or position?
PageletURI uri = pagelet.getURI();
if (uri != null && (StringUtils.isNotBlank(uri.getComposer()) || uri.getPosition() >= 0)) {
if (StringUtils.isNotBlank(uri.getComposer())) {
String field = MessageFormat.format(PAGELET_TYPE_COMPOSER, uri.getComposer());
and(solrQuery, field, searchTerm.toString(), true, true);
}
if (uri.getPosition() >= 0) {
String field = MessageFormat.format(PAGELET_TYPE_COMPOSER_POSITION, uri.getPosition());
and(solrQuery, field, searchTerm.toString(), true, true);
}
} else {
and(solrQuery, PAGELET_TYPE, searchTerm.toString(), true, true);
}
}
// Content filenames
if (query.getFilename() != null) {
and(solrQuery, CONTENT_FILENAME, query.getFilename(), true, true);
}
// Content source
if (query.getSource() != null) {
and(solrQuery, CONTENT_SOURCE, query.getSource(), true, true);
}
// Content external location
if (query.getExternalLocation() != null) {
and(solrQuery, CONTENT_EXTERNAL_REPRESENTATION, query.getExternalLocation().toExternalForm(), true, true);
}
// Content mime types
if (query.getMimetype() != null) {
and(solrQuery, CONTENT_MIMETYPE, query.getMimetype(), true, true);
}
// Fulltext
if (query.getText() != null) {
// TODO: Wildcard searches are not yet working. Retry when switching
// over to Solr 4
// if (query.isWildcardSearch()) {
// and(solrQuery, FULLTEXT, clean(query.getText()) + "*", false, false);
// } else {
// and(solrQuery, FULLTEXT, query.getText(), true, true);
// }
for (String s : StringUtils.split(query.getText())) {
and(solrQuery, FULLTEXT, s, true, true);
}
}
if (solrQuery.length() == 0)
solrQuery.append("*:*");
// Hide the root entry
andNot(solrQuery, ID, Long.toString(SearchIndex.ROOT_ID), true, true);
logger.debug("Solr query is {}", solrQuery.toString());
// Prepare the solr query
SolrQuery q = new SolrQuery(solrQuery.toString());
q.setStart(query.getOffset() > 0 ? query.getOffset() : 0);
q.setRows(query.getLimit() > 0 ? query.getLimit() : Integer.MAX_VALUE);
// Filter query
if (query.getFilter() != null) {
q.addFilterQuery(clean(query.getFilter().toLowerCase()));
}
// Define the fields that should be returned by the query
List<String> fields = new ArrayList<String>();
fields.add("*");
// Order by publishing date
if (!SearchQuery.Order.None.equals(query.getPublishingDateSortOrder())) {
switch (query.getPublishingDateSortOrder()) {
case Ascending:
q.addSortField(PUBLISHED_FROM, ORDER.asc);
break;
case Descending:
q.addSortField(PUBLISHED_FROM, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by modification date
else if (!SearchQuery.Order.None.equals(query.getModificationDateSortOrder())) {
switch (query.getModificationDateSortOrder()) {
case Ascending:
q.addSortField(MODIFIED, ORDER.asc);
break;
case Descending:
q.addSortField(MODIFIED, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by creation date
else if (!SearchQuery.Order.None.equals(query.getCreationDateSortOrder())) {
switch (query.getCreationDateSortOrder()) {
case Ascending:
q.addSortField(CREATED, ORDER.asc);
break;
case Descending:
q.addSortField(CREATED, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by score
else {
q.setSortField(SCORE, SolrQuery.ORDER.desc);
q.setIncludeScore(true);
fields.add("score");
}
// Add the fields to return
q.setFields(StringUtils.join(fields, " "));
// Execute the query and try to get hold of a query response
QueryResponse solrResponse = null;
try {
solrResponse = solr.request(q);
} catch (Throwable t) {
throw new SolrServerException(t);
}
// Create and configure the query result
long hits = solrResponse.getResults().getNumFound();
long size = solrResponse.getResults().size();
SearchResultImpl result = new SearchResultImpl(query, hits, size);
result.setSearchTime(solrResponse.getQTime());
// Walk through response and create new items with title, creator, etc:
for (SolrDocument doc : solrResponse.getResults()) {
// Get the resource serializer
String type = (String) doc.getFirstValue(TYPE);
ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(type);
if (serializer == null) {
logger.warn("Skipping search result due to missing serializer of type {}", type);
continue;
}
// Wrap the search result metadata
List<ResourceMetadata<?>> metadata = new ArrayList<ResourceMetadata<?>>(doc.size());
for (Map.Entry<String, Object> entry : doc.entrySet()) {
String name = entry.getKey();
ResourceMetadata<Object> m = new ResourceMetadataImpl<Object>(name);
// TODO: Add values with more care (localized, correct type etc.)
if (entry.getValue() instanceof List) {
for (Object v : ((List<?>) entry.getValue())) {
m.addValue(v);
}
} else {
m.addValue(entry.getValue());
}
metadata.add(m);
}
// Get the score for this item
float score = fields.contains("score") ? (Float) doc.getFieldValue(SCORE) : 0.0f;
// Have the serializer in charge create a type-specific search result item
SearchResultItem item = serializer.toSearchResultItem(site, score, metadata);
result.addResultItem(item);
}
return result;
}
| public SearchResult getByQuery(SearchQuery query) throws SolrServerException {
Site site = query.getSite();
// Build the solr query string
StringBuilder solrQuery = new StringBuilder();
// Resource id
if (query.getIdentifier().length > 0) {
and(solrQuery, RESOURCE_ID, query.getIdentifier(), true, true);
}
// Version / Preferred version
if (query.getPreferredVersion() >= 0) {
andNot(solrQuery, ALTERNATE_VERSION, Long.toString(query.getPreferredVersion()), false, false);
} else if (query.getVersion() >= 0) {
and(solrQuery, VERSION, Long.toString(query.getVersion()), false, false);
}
// Path
if (query.getPath() != null) {
and(solrQuery, PATH, query.getPath(), true, true);
}
if (query.getPathPrefix() != null) {
and(solrQuery, PATH_PREFIX, query.getPathPrefix(), true, true);
}
// Type
if (query.getTypes().length > 0) {
and(solrQuery, TYPE, query.getTypes(), true, true);
}
// Without type
if (query.getWithoutTypes().length > 0) {
andNot(solrQuery, TYPE, query.getWithoutTypes(), true, true);
}
// Subjects (OR)
if (query.getSubjects().length > 0) {
and(solrQuery, SUBJECT, query.getSubjects(), true, true);
}
// Subjects (AND)
if (query.getANDSubjects().length > 0) {
for (String subject : query.getANDSubjects()) {
and(solrQuery, SUBJECT, subject, true, true);
}
}
// Series
if (query.getSeries().length > 0) {
and(solrQuery, SERIES, query.getSeries(), true, true);
}
// Template
if (query.getTemplate() != null) {
and(solrQuery, TEMPLATE, query.getTemplate(), true, true);
}
// Stationary
if (query.isStationary()) {
and(solrQuery, STATIONARY, Boolean.TRUE.toString(), false, false);
}
// Creator
if (query.getCreator() != null) {
and(solrQuery, CREATED_BY, SolrUtils.serializeUserId(query.getCreator()), true, true);
}
// Creation date
if (query.getCreationDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, CREATED, SolrUtils.serializeDateRange(query.getCreationDate(), query.getCreationDateEnd()), false, false);
else
and(solrQuery, CREATED, SolrUtils.selectDay(query.getCreationDate()), false, false);
}
// Modifier
if (query.getModifier() != null) {
and(solrQuery, MODIFIED_BY, SolrUtils.serializeUserId(query.getModifier()), true, true);
}
// Modification date
if (query.getModificationDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, MODIFIED, SolrUtils.serializeDateRange(query.getModificationDate(), query.getModificationDateEnd()), false, false);
else
and(solrQuery, MODIFIED, SolrUtils.selectDay(query.getModificationDate()), false, false);
}
// Without Modification
if (query.getWithoutModification()) {
andEmpty(solrQuery, MODIFIED);
}
// Publisher
if (query.getPublisher() != null) {
and(solrQuery, PUBLISHED_BY, SolrUtils.serializeUserId(query.getPublisher()), true, true);
}
// Publication date
if (query.getPublishingDate() != null) {
if (query.getCreationDateEnd() != null)
and(solrQuery, PUBLISHED_FROM, SolrUtils.serializeDateRange(query.getPublishingDate(), query.getPublishingDateEnd()), false, false);
else
and(solrQuery, PUBLISHED_FROM, SolrUtils.selectDay(query.getPublishingDate()), false, false);
}
// Without Publication
if (query.getWithoutPublication()) {
andEmpty(solrQuery, PUBLISHED_FROM);
}
// Lock owner
if (query.getLockOwner() != null) {
User user = query.getLockOwner();
if (SearchQueryImpl.ANY_USER.equals(user.getLogin()))
andNotEmpty(solrQuery, SolrSchema.LOCKED_BY);
else
and(solrQuery, SolrSchema.LOCKED_BY, SolrUtils.serializeUserId(user), true, true);
}
// Pagelet elements
for (Map.Entry<String, String> entry : query.getElements().entrySet()) {
// TODO: Language?
solrQuery.append(" ").append(PAGELET_CONTENTS).append(":");
solrQuery.append("\"").append(entry.getKey()).append(":=\"");
for (String contentValue : StringUtils.split(entry.getValue())) {
solrQuery.append(" \"").append(SolrUtils.clean(contentValue)).append("\"");
}
}
// Pagelet properties
for (Map.Entry<String, String> entry : query.getProperties().entrySet()) {
StringBuffer searchTerm = new StringBuffer();
searchTerm.append(entry.getKey());
searchTerm.append(":=").append(entry.getValue());
and(solrQuery, PAGELET_PROPERTIES, searchTerm.toString(), true, true);
}
// Pagelet types
for (Pagelet pagelet : query.getPagelets()) {
StringBuffer searchTerm = new StringBuffer();
searchTerm.append(pagelet.getModule()).append("/").append(pagelet.getIdentifier());
// Are we looking for the pagelet in a certain composer or position?
PageletURI uri = pagelet.getURI();
if (uri != null && (StringUtils.isNotBlank(uri.getComposer()) || uri.getPosition() >= 0)) {
if (StringUtils.isNotBlank(uri.getComposer())) {
String field = MessageFormat.format(PAGELET_TYPE_COMPOSER, uri.getComposer());
and(solrQuery, field, searchTerm.toString(), true, true);
}
if (uri.getPosition() >= 0) {
String field = MessageFormat.format(PAGELET_TYPE_COMPOSER_POSITION, uri.getPosition());
and(solrQuery, field, searchTerm.toString(), true, true);
}
} else {
and(solrQuery, PAGELET_TYPE, searchTerm.toString(), true, true);
}
}
// Content filenames
if (query.getFilename() != null) {
and(solrQuery, CONTENT_FILENAME, query.getFilename(), true, true);
}
// Content source
if (query.getSource() != null) {
and(solrQuery, CONTENT_SOURCE, query.getSource(), true, true);
}
// Content external location
if (query.getExternalLocation() != null) {
and(solrQuery, CONTENT_EXTERNAL_REPRESENTATION, query.getExternalLocation().toExternalForm(), true, true);
}
// Content mime types
if (query.getMimetype() != null) {
and(solrQuery, CONTENT_MIMETYPE, query.getMimetype(), true, true);
}
// Fulltext
if (query.getText() != null) {
// TODO: Wildcard searches are not yet working. Retry when switching
// over to Solr 4
// if (query.isWildcardSearch()) {
// and(solrQuery, FULLTEXT, clean(query.getText()) + "*", false, false);
// } else {
// and(solrQuery, FULLTEXT, query.getText(), true, true);
// }
for (String s : StringUtils.split(query.getText())) {
and(solrQuery, FULLTEXT, s, true, true);
}
}
if (solrQuery.length() == 0)
solrQuery.append("*:*");
// Hide the root entry
andNot(solrQuery, ID, Long.toString(SearchIndex.ROOT_ID), true, true);
logger.debug("Solr query is {}", solrQuery.toString());
// Prepare the solr query
SolrQuery q = new SolrQuery(solrQuery.toString());
q.setStart(query.getOffset() > 0 ? query.getOffset() : 0);
q.setRows(query.getLimit() > 0 ? query.getLimit() : Integer.MAX_VALUE);
// Filter query
if (query.getFilter() != null) {
q.addFilterQuery(clean(query.getFilter().toLowerCase()));
}
// Define the fields that should be returned by the query
List<String> fields = new ArrayList<String>();
fields.add("*");
// Order by publishing date
if (!SearchQuery.Order.None.equals(query.getPublishingDateSortOrder())) {
switch (query.getPublishingDateSortOrder()) {
case Ascending:
q.addSortField(PUBLISHED_FROM, ORDER.asc);
break;
case Descending:
q.addSortField(PUBLISHED_FROM, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by modification date
else if (!SearchQuery.Order.None.equals(query.getModificationDateSortOrder())) {
switch (query.getModificationDateSortOrder()) {
case Ascending:
q.addSortField(MODIFIED, ORDER.asc);
break;
case Descending:
q.addSortField(MODIFIED, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by creation date
else if (!SearchQuery.Order.None.equals(query.getCreationDateSortOrder())) {
switch (query.getCreationDateSortOrder()) {
case Ascending:
q.addSortField(CREATED, ORDER.asc);
break;
case Descending:
q.addSortField(CREATED, ORDER.desc);
break;
case None:
default:
break;
}
}
// Order by score
else {
q.setSortField(SCORE, SolrQuery.ORDER.desc);
q.setIncludeScore(true);
fields.add("score");
}
// Add the fields to return
q.setFields(StringUtils.join(fields, " "));
// Execute the query and try to get hold of a query response
QueryResponse solrResponse = null;
try {
solrResponse = solr.request(q);
} catch (Throwable t) {
throw new SolrServerException(t);
}
// Create and configure the query result
long hits = solrResponse.getResults().getNumFound();
long size = solrResponse.getResults().size();
SearchResultImpl result = new SearchResultImpl(query, hits, size);
result.setSearchTime(solrResponse.getQTime());
// Walk through response and create new items with title, creator, etc:
for (SolrDocument doc : solrResponse.getResults()) {
// Get the resource serializer
String type = (String) doc.getFirstValue(TYPE);
ResourceSerializer<?, ?> serializer = ResourceSerializerFactory.getSerializerByType(type);
if (serializer == null) {
logger.warn("Skipping search result due to missing serializer of type {}", type);
continue;
}
// Wrap the search result metadata
List<ResourceMetadata<?>> metadata = new ArrayList<ResourceMetadata<?>>(doc.size());
for (Map.Entry<String, Object> entry : doc.entrySet()) {
String name = entry.getKey();
ResourceMetadata<Object> m = new ResourceMetadataImpl<Object>(name);
// TODO: Add values with more care (localized, correct type etc.)
if (entry.getValue() instanceof List) {
for (Object v : ((List<?>) entry.getValue())) {
m.addValue(v);
}
} else {
m.addValue(entry.getValue());
}
metadata.add(m);
}
// Get the score for this item
float score = fields.contains("score") ? (Float) doc.getFieldValue(SCORE) : 0.0f;
// Have the serializer in charge create a type-specific search result item
SearchResultItem item;
try {
item = serializer.toSearchResultItem(site, score, metadata);
} catch (Throwable t) {
logger.warn("Error during search result serialization: '{}'. Skipping this search result.", t.getMessage());
continue;
}
result.addResultItem(item);
}
return result;
}
|
diff --git a/tests/frontend/org/voltdb/regressionsuites/TestCRUDSuite.java b/tests/frontend/org/voltdb/regressionsuites/TestCRUDSuite.java
index 61e7c59bd..524b892e7 100644
--- a/tests/frontend/org/voltdb/regressionsuites/TestCRUDSuite.java
+++ b/tests/frontend/org/voltdb/regressionsuites/TestCRUDSuite.java
@@ -1,150 +1,150 @@
package org.voltdb.regressionsuites;
import java.io.IOException;
import org.voltdb.*;
import org.voltdb.client.*;
import org.voltdb.compiler.VoltProjectBuilder;
public class TestCRUDSuite extends RegressionSuite {
static final Class<?>[] PROCEDURES = {};
public TestCRUDSuite(String name) {
super(name);
}
public void testPartitionedPkPartitionCol() throws Exception
{
final Client client = this.getClient();
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.insert", i, Integer.toHexString(i));
assertTrue(resp.getStatus() == ClientResponse.SUCCESS);
assertTrue(resp.getResults()[0].asScalarLong() == 1);
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.select", i);
assertTrue(resp.getStatus() == ClientResponse.SUCCESS);
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
assertTrue(vt.getLong(0) == i);
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.update", i, "STR" + Integer.toHexString(i), i);
assertTrue(resp.getStatus() == ClientResponse.SUCCESS);
assertTrue(resp.getResults()[0].asScalarLong() == 1);
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.select", i);
assertTrue(resp.getStatus() == ClientResponse.SUCCESS);
VoltTable vt = resp.getResults()[0];
assertTrue(vt.advanceRow());
assertTrue(vt.getString(1).equals("STR" + Integer.toHexString(i)));
}
for (int i=0; i < 10; i++) {
ClientResponse resp = client.callProcedure("P1.delete", i);
assertTrue(resp.getStatus() == ClientResponse.SUCCESS);
assertTrue(resp.getResults()[0].asScalarLong() == 1);
}
ClientResponse resp = client.callProcedure("CountP1");
assertTrue(resp.getStatus() == ClientResponse.SUCCESS);
assertTrue(resp.getResults()[0].asScalarLong() == 0);
}
public void testPartitionedPkWithoutPartitionCol() throws Exception
{
Client client = getClient();
try {
client.callProcedure("P2.insert", 0, "ABC");
} catch (ProcCallException e) {
assertTrue(e.getMessage().contains("was not found"));
return;
}
fail();
}
public void testPartitionedPkWithoutPartitionCol2() throws Exception
{
Client client = getClient();
try {
client.callProcedure("P3.insert", 0, "ABC");
} catch (ProcCallException e) {
assertTrue(e.getMessage().contains("was not found"));
return;
}
fail();
}
public void testReplicatedTable() throws Exception
{
Client client = getClient();
try {
client.callProcedure("R1.insert", 0, "ABC");
} catch (ProcCallException e) {
assertTrue(e.getMessage().contains("was not found"));
return;
}
fail();
}
static public junit.framework.Test suite() {
VoltServerConfig config = null;
final MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestCRUDSuite.class);
final VoltProjectBuilder project = new VoltProjectBuilder();
// necessary because at least one procedure is required
project.addStmtProcedure("CountP1", "select count(*) from p1;");
try {
// a table that should generate procedures
project.addLiteralSchema(
"CREATE TABLE p1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
project.addPartitionInfo("p1", "a1");
// a partitioned table that should not generate procedures (no pkey)
project.addLiteralSchema(
"CREATE TABLE p2(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p2_tree_idx ON p2(a1);"
);
project.addPartitionInfo("p2", "a1");
// a partitioned table that should not generate procedures (pkey not partition key)
project.addLiteralSchema(
"CREATE TABLE p3(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p3_tree_idx ON p3(a1);"
);
- project.addPartitionInfo("p2", "a2");
+ project.addPartitionInfo("p3", "a2");
// a replicated table (should not generate procedures).
project.addLiteralSchema(
"CREATE TABLE r1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
} catch (IOException error) {
fail(error.getMessage());
}
// JNI
config = new LocalSingleProcessServer("sqltypes-onesite.jar", 1, BackendTarget.NATIVE_EE_JNI);
boolean t1 = config.compile(project);
assertTrue(t1);
builder.addServerConfig(config);
// CLUSTER
config = new LocalCluster("sqltypes-cluster.jar", 2, 2, 1, BackendTarget.NATIVE_EE_JNI);
boolean t2 = config.compile(project);
assertTrue(t2);
builder.addServerConfig(config);
return builder;
}
}
| true | true | static public junit.framework.Test suite() {
VoltServerConfig config = null;
final MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestCRUDSuite.class);
final VoltProjectBuilder project = new VoltProjectBuilder();
// necessary because at least one procedure is required
project.addStmtProcedure("CountP1", "select count(*) from p1;");
try {
// a table that should generate procedures
project.addLiteralSchema(
"CREATE TABLE p1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
project.addPartitionInfo("p1", "a1");
// a partitioned table that should not generate procedures (no pkey)
project.addLiteralSchema(
"CREATE TABLE p2(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p2_tree_idx ON p2(a1);"
);
project.addPartitionInfo("p2", "a1");
// a partitioned table that should not generate procedures (pkey not partition key)
project.addLiteralSchema(
"CREATE TABLE p3(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p3_tree_idx ON p3(a1);"
);
project.addPartitionInfo("p2", "a2");
// a replicated table (should not generate procedures).
project.addLiteralSchema(
"CREATE TABLE r1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
} catch (IOException error) {
fail(error.getMessage());
}
// JNI
config = new LocalSingleProcessServer("sqltypes-onesite.jar", 1, BackendTarget.NATIVE_EE_JNI);
boolean t1 = config.compile(project);
assertTrue(t1);
builder.addServerConfig(config);
// CLUSTER
config = new LocalCluster("sqltypes-cluster.jar", 2, 2, 1, BackendTarget.NATIVE_EE_JNI);
boolean t2 = config.compile(project);
assertTrue(t2);
builder.addServerConfig(config);
return builder;
}
| static public junit.framework.Test suite() {
VoltServerConfig config = null;
final MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestCRUDSuite.class);
final VoltProjectBuilder project = new VoltProjectBuilder();
// necessary because at least one procedure is required
project.addStmtProcedure("CountP1", "select count(*) from p1;");
try {
// a table that should generate procedures
project.addLiteralSchema(
"CREATE TABLE p1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
project.addPartitionInfo("p1", "a1");
// a partitioned table that should not generate procedures (no pkey)
project.addLiteralSchema(
"CREATE TABLE p2(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p2_tree_idx ON p2(a1);"
);
project.addPartitionInfo("p2", "a1");
// a partitioned table that should not generate procedures (pkey not partition key)
project.addLiteralSchema(
"CREATE TABLE p3(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL); " +
"CREATE UNIQUE INDEX p3_tree_idx ON p3(a1);"
);
project.addPartitionInfo("p3", "a2");
// a replicated table (should not generate procedures).
project.addLiteralSchema(
"CREATE TABLE r1(a1 INTEGER NOT NULL, a2 VARCHAR(10) NOT NULL, PRIMARY KEY (a1));"
);
} catch (IOException error) {
fail(error.getMessage());
}
// JNI
config = new LocalSingleProcessServer("sqltypes-onesite.jar", 1, BackendTarget.NATIVE_EE_JNI);
boolean t1 = config.compile(project);
assertTrue(t1);
builder.addServerConfig(config);
// CLUSTER
config = new LocalCluster("sqltypes-cluster.jar", 2, 2, 1, BackendTarget.NATIVE_EE_JNI);
boolean t2 = config.compile(project);
assertTrue(t2);
builder.addServerConfig(config);
return builder;
}
|
diff --git a/src/main/java/net/madz/download/engine/DownloadSegmentWorker.java b/src/main/java/net/madz/download/engine/DownloadSegmentWorker.java
index f32d000..02449e7 100644
--- a/src/main/java/net/madz/download/engine/DownloadSegmentWorker.java
+++ b/src/main/java/net/madz/download/engine/DownloadSegmentWorker.java
@@ -1,80 +1,82 @@
package net.madz.download.engine;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import net.madz.download.LogUtils;
import net.madz.download.service.metadata.DownloadTask;
import net.madz.download.service.metadata.MetaManager;
import net.madz.download.service.metadata.Segment;
public final class DownloadSegmentWorker implements Runnable {
private final DownloadTask task;
private final Segment segment;
private volatile boolean pauseFlag;
private IDownloadProcess process;
private File dataFile;
private File metadataFile;
public DownloadSegmentWorker(IDownloadProcess process, DownloadTask task, Segment segment, File dataFile, File metadataFile) {
this.process = process;
this.task = task;
this.segment = segment;
this.dataFile = dataFile;
this.metadataFile = metadataFile;
}
@Override
public void run() {
URL url = task.getUrl();
HttpURLConnection openConnection = null;
InputStream inputStream = null;
RandomAccessFile randomAccessDataFile = null;
byte[] buf = new byte[8096];
int size = 0;
try {
openConnection = (HttpURLConnection) url.openConnection();
openConnection.setRequestProperty("RANGE", "bytes=" + segment.getStartBytes() + "-" + segment.getEndBytes());
openConnection.connect();
inputStream = openConnection.getInputStream();
randomAccessDataFile = new RandomAccessFile(dataFile, "rw");
long off = segment.getStartBytes();
while ( ( !isPauseFlag() ) && ( size = inputStream.read(buf) ) != -1 ) {
randomAccessDataFile.seek(off);
randomAccessDataFile.write(buf, 0, size);
synchronized (process) {
if ( !isPauseFlag() ) {
process.receive(size);
}
}
off += size;
MetaManager.updateSegmentDownloadProgress(metadataFile, segment.getId(), off);
}
} catch (IOException ignored) {
LogUtils.error(DownloadSegmentWorker.class, ignored);
} finally {
openConnection.disconnect();
try {
- inputStream.close();
+ if ( null != inputStream) {
+ inputStream.close();
+ }
randomAccessDataFile.close();
} catch (IOException ignored) {
LogUtils.error(DownloadSegmentWorker.class, ignored);
}
}
}
public synchronized boolean isPauseFlag() {
return pauseFlag;
}
public synchronized void setPauseFlag(boolean pauseFlag) {
this.pauseFlag = pauseFlag;
}
}
| true | true | public void run() {
URL url = task.getUrl();
HttpURLConnection openConnection = null;
InputStream inputStream = null;
RandomAccessFile randomAccessDataFile = null;
byte[] buf = new byte[8096];
int size = 0;
try {
openConnection = (HttpURLConnection) url.openConnection();
openConnection.setRequestProperty("RANGE", "bytes=" + segment.getStartBytes() + "-" + segment.getEndBytes());
openConnection.connect();
inputStream = openConnection.getInputStream();
randomAccessDataFile = new RandomAccessFile(dataFile, "rw");
long off = segment.getStartBytes();
while ( ( !isPauseFlag() ) && ( size = inputStream.read(buf) ) != -1 ) {
randomAccessDataFile.seek(off);
randomAccessDataFile.write(buf, 0, size);
synchronized (process) {
if ( !isPauseFlag() ) {
process.receive(size);
}
}
off += size;
MetaManager.updateSegmentDownloadProgress(metadataFile, segment.getId(), off);
}
} catch (IOException ignored) {
LogUtils.error(DownloadSegmentWorker.class, ignored);
} finally {
openConnection.disconnect();
try {
inputStream.close();
randomAccessDataFile.close();
} catch (IOException ignored) {
LogUtils.error(DownloadSegmentWorker.class, ignored);
}
}
}
| public void run() {
URL url = task.getUrl();
HttpURLConnection openConnection = null;
InputStream inputStream = null;
RandomAccessFile randomAccessDataFile = null;
byte[] buf = new byte[8096];
int size = 0;
try {
openConnection = (HttpURLConnection) url.openConnection();
openConnection.setRequestProperty("RANGE", "bytes=" + segment.getStartBytes() + "-" + segment.getEndBytes());
openConnection.connect();
inputStream = openConnection.getInputStream();
randomAccessDataFile = new RandomAccessFile(dataFile, "rw");
long off = segment.getStartBytes();
while ( ( !isPauseFlag() ) && ( size = inputStream.read(buf) ) != -1 ) {
randomAccessDataFile.seek(off);
randomAccessDataFile.write(buf, 0, size);
synchronized (process) {
if ( !isPauseFlag() ) {
process.receive(size);
}
}
off += size;
MetaManager.updateSegmentDownloadProgress(metadataFile, segment.getId(), off);
}
} catch (IOException ignored) {
LogUtils.error(DownloadSegmentWorker.class, ignored);
} finally {
openConnection.disconnect();
try {
if ( null != inputStream) {
inputStream.close();
}
randomAccessDataFile.close();
} catch (IOException ignored) {
LogUtils.error(DownloadSegmentWorker.class, ignored);
}
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java
index 35669da9a..5def8e0dd 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleDatePicker.java
@@ -1,225 +1,228 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.DatePicker;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.DateRange;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
/**
* @author Rob Elves
*/
public class ScheduleDatePicker extends Composite {
private Text scheduledDateText;
private Button pickButton;
private final List<SelectionListener> pickerListeners = new LinkedList<SelectionListener>();
private final String initialText = DatePicker.LABEL_CHOOSE;
private final List<IRepositoryElement> tasks;
private final ScheduleTaskMenuContributor contributor;
private DateRange scheduledDate;
private final boolean isFloating = false;
private ImageHyperlink clearControl;
public ScheduleDatePicker(Composite parent, AbstractTask task, int style) {
super(parent, style);
if (task != null) {
if (task.getScheduledForDate() != null) {
this.scheduledDate = task.getScheduledForDate();
}
}
initialize((style & SWT.FLAT) > 0 ? SWT.FLAT : 0);
contributor = new ScheduleTaskMenuContributor() {
@Override
protected DateRange getScheduledForDate(AbstractTask singleTaskSelection) {
return ScheduleDatePicker.this.scheduledDate;
}
@Override
protected void setScheduledDate(DateRange dateRange) {
if (dateRange != null) {
scheduledDate = dateRange;
} else {
scheduledDate = null;
}
updateDateText();
notifyPickerListeners();
}
};
tasks = new ArrayList<IRepositoryElement>();
tasks.add(task);
}
private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
- gridLayout.horizontalSpacing = 3;
+ gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
scheduledDateText = new Text(this, style);
scheduledDateText.setEditable(false);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.widthHint = SWT.FILL;
dateTextGridData.verticalIndent = 0;
scheduledDateText.setLayoutData(dateTextGridData);
scheduledDateText.setText(initialText);
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.ScheduleDatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
setScheduledDate(null);
for (IRepositoryElement task : tasks) {
if (task instanceof AbstractTask) {
// XXX why is this set here?
((AbstractTask) task).setReminded(false);
}
}
notifyPickerListeners();
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
- clearControl.setLayoutData(new GridData());
+ GridData clearButtonGridData = new GridData();
+ clearButtonGridData.horizontalIndent = 3;
+ clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
+ pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
MenuManager menuManager = contributor.getSubMenuManager(tasks);
Menu menu = menuManager.createContextMenu(pickButton);
pickButton.setMenu(menu);
menu.setVisible(true);
Point location = pickButton.toDisplay(pickButton.getLocation());
Rectangle bounds = pickButton.getBounds();
menu.setLocation(location.x - pickButton.getBounds().x, location.y + bounds.height + 2);
}
});
updateDateText();
pack();
}
private void updateClearControlVisibility() {
if (clearControl != null && clearControl.getLayoutData() instanceof GridData) {
GridData gd = (GridData) clearControl.getLayoutData();
gd.exclude = scheduledDate == null;
clearControl.getParent().layout();
}
}
public void addPickerSelectionListener(SelectionListener listener) {
pickerListeners.add(listener);
}
@Override
public void setForeground(Color color) {
pickButton.setForeground(color);
scheduledDateText.setForeground(color);
super.setForeground(color);
}
@Override
public void setBackground(Color backgroundColor) {
pickButton.setBackground(backgroundColor);
scheduledDateText.setBackground(backgroundColor);
super.setBackground(backgroundColor);
}
private void notifyPickerListeners() {
for (SelectionListener listener : pickerListeners) {
listener.widgetSelected(null);
}
}
private void updateDateText() {
if (scheduledDate != null) {
scheduledDateText.setText(scheduledDate.toString());
} else {
scheduledDateText.setEnabled(false);
scheduledDateText.setText(DatePicker.LABEL_CHOOSE);
scheduledDateText.setEnabled(true);
}
updateClearControlVisibility();
}
@Override
public void setEnabled(boolean enabled) {
scheduledDateText.setEnabled(enabled);
pickButton.setEnabled(enabled);
clearControl.setEnabled(enabled);
super.setEnabled(enabled);
}
public DateRange getScheduledDate() {
return scheduledDate;
}
public void setScheduledDate(DateRange date) {
scheduledDate = date;
updateDateText();
}
public boolean isFloatingDate() {
return isFloating;
}
}
| false | true | private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 3;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
scheduledDateText = new Text(this, style);
scheduledDateText.setEditable(false);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.widthHint = SWT.FILL;
dateTextGridData.verticalIndent = 0;
scheduledDateText.setLayoutData(dateTextGridData);
scheduledDateText.setText(initialText);
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.ScheduleDatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
setScheduledDate(null);
for (IRepositoryElement task : tasks) {
if (task instanceof AbstractTask) {
// XXX why is this set here?
((AbstractTask) task).setReminded(false);
}
}
notifyPickerListeners();
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
clearControl.setLayoutData(new GridData());
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
MenuManager menuManager = contributor.getSubMenuManager(tasks);
Menu menu = menuManager.createContextMenu(pickButton);
pickButton.setMenu(menu);
menu.setVisible(true);
Point location = pickButton.toDisplay(pickButton.getLocation());
Rectangle bounds = pickButton.getBounds();
menu.setLocation(location.x - pickButton.getBounds().x, location.y + bounds.height + 2);
}
});
updateDateText();
pack();
}
| private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
scheduledDateText = new Text(this, style);
scheduledDateText.setEditable(false);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.widthHint = SWT.FILL;
dateTextGridData.verticalIndent = 0;
scheduledDateText.setLayoutData(dateTextGridData);
scheduledDateText.setText(initialText);
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.ScheduleDatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
setScheduledDate(null);
for (IRepositoryElement task : tasks) {
if (task instanceof AbstractTask) {
// XXX why is this set here?
((AbstractTask) task).setReminded(false);
}
}
notifyPickerListeners();
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
MenuManager menuManager = contributor.getSubMenuManager(tasks);
Menu menu = menuManager.createContextMenu(pickButton);
pickButton.setMenu(menu);
menu.setVisible(true);
Point location = pickButton.toDisplay(pickButton.getLocation());
Rectangle bounds = pickButton.getBounds();
menu.setLocation(location.x - pickButton.getBounds().x, location.y + bounds.height + 2);
}
});
updateDateText();
pack();
}
|
diff --git a/loci/visbio/ClassManager.java b/loci/visbio/ClassManager.java
index 4edb403..84dfbb9 100644
--- a/loci/visbio/ClassManager.java
+++ b/loci/visbio/ClassManager.java
@@ -1,101 +1,101 @@
//
// ClassManager.java
//
/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2004 Curtis Rueden.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.visbio;
import java.io.*;
import java.util.Vector;
/**
* ClassManager is the manager for preloading classes
* to speed VisBio response time later on.
*/
public class ClassManager extends LogicManager {
// -- Fields --
/** List of classes to preload. */
protected Vector preloadClasses;
// -- Constructor --
/** Constructs a class manager. */
public ClassManager(VisBioFrame bio) {
super(bio);
// extract classes to preload from data file
preloadClasses = new Vector();
try {
BufferedReader fin = new BufferedReader(new FileReader("classes.txt"));
while (true) {
String line = fin.readLine();
if (line == null) break; // eof
preloadClasses.add(line);
}
fin.close();
}
catch (IOException exc) { } // ignore data file I/O errors
}
// -- LogicManager API methods --
/** Called to notify the logic manager of a VisBio event. */
public void doEvent(VisBioEvent evt) {
int eventType = evt.getEventType();
if (eventType == VisBioEvent.LOGIC_ADDED) {
LogicManager lm = (LogicManager) evt.getSource();
if (lm == this) doGUI();
}
}
/** Gets the number of tasks required to initialize this logic manager. */
public int getTasks() { return preloadClasses.size(); }
// -- Helper methods --
/** Adds system-related GUI components to VisBio. */
private void doGUI() {
// preload a bunch of classes
int size = preloadClasses.size();
String pkg = "";
for (int i=0; i<size; i++) {
String className = (String) preloadClasses.elementAt(i);
int dot = className.lastIndexOf(".");
String prefix = className.substring(0, dot);
if (!prefix.equals(pkg)) {
pkg = prefix;
bio.setSplashStatus("Loading " + pkg);
}
else bio.setSplashStatus(null);
// preload class, ignoring errors
try { Class.forName(className); }
- catch (ClassNotFoundException exc) { }
+ catch (Exception exc) { }
}
if (VisBioFrame.DEBUG) System.out.println("DONE PRELOADING CLASSES");
}
}
| true | true | private void doGUI() {
// preload a bunch of classes
int size = preloadClasses.size();
String pkg = "";
for (int i=0; i<size; i++) {
String className = (String) preloadClasses.elementAt(i);
int dot = className.lastIndexOf(".");
String prefix = className.substring(0, dot);
if (!prefix.equals(pkg)) {
pkg = prefix;
bio.setSplashStatus("Loading " + pkg);
}
else bio.setSplashStatus(null);
// preload class, ignoring errors
try { Class.forName(className); }
catch (ClassNotFoundException exc) { }
}
if (VisBioFrame.DEBUG) System.out.println("DONE PRELOADING CLASSES");
}
| private void doGUI() {
// preload a bunch of classes
int size = preloadClasses.size();
String pkg = "";
for (int i=0; i<size; i++) {
String className = (String) preloadClasses.elementAt(i);
int dot = className.lastIndexOf(".");
String prefix = className.substring(0, dot);
if (!prefix.equals(pkg)) {
pkg = prefix;
bio.setSplashStatus("Loading " + pkg);
}
else bio.setSplashStatus(null);
// preload class, ignoring errors
try { Class.forName(className); }
catch (Exception exc) { }
}
if (VisBioFrame.DEBUG) System.out.println("DONE PRELOADING CLASSES");
}
|
diff --git a/source/RMG/jing/rxnSys/ReactionModelGenerator.java b/source/RMG/jing/rxnSys/ReactionModelGenerator.java
index 413d931e..abeff723 100644
--- a/source/RMG/jing/rxnSys/ReactionModelGenerator.java
+++ b/source/RMG/jing/rxnSys/ReactionModelGenerator.java
@@ -1,4420 +1,4421 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.rxnSys;
import java.io.*;
import jing.rxnSys.ReactionSystem;
import jing.rxn.*;
import jing.chem.*;
import java.util.*;
import jing.mathTool.UncertainDouble;
import jing.param.*;
import jing.chemUtil.*;
import jing.chemParser.*;
//## package jing::rxnSys
//----------------------------------------------------------------------------
// jing\rxnSys\ReactionModelGenerator.java
//----------------------------------------------------------------------------
//## class ReactionModelGenerator
public class ReactionModelGenerator {
protected LinkedList timeStep; //## attribute timeStep
protected ReactionModel reactionModel; //gmagoon 9/24/07
protected String workingDirectory; //## attribute workingDirectory
// protected ReactionSystem reactionSystem;
protected LinkedList reactionSystemList; //10/24/07 gmagoon: changed from reactionSystem to reactionSystemList
protected int paraInfor;//svp
protected boolean error;//svp
protected boolean sensitivity;//svp
protected LinkedList species;//svp
// protected InitialStatus initialStatus;//svp
protected LinkedList initialStatusList; //10/23/07 gmagoon: changed from initialStatus to initialStatusList
protected double rtol;//svp
protected static double atol;
protected PrimaryReactionLibrary primaryReactionLibrary;//9/24/07 gmagoon
protected ReactionModelEnlarger reactionModelEnlarger;//9/24/07 gmagoon
protected LinkedHashSet speciesSeed;//9/24/07 gmagoon;
protected ReactionGenerator reactionGenerator;//9/24/07 gmagoon
protected LibraryReactionGenerator lrg;// = new LibraryReactionGenerator();//9/24/07 gmagoon: moved from ReactionSystem.java;10/4/07 gmagoon: postponed initialization of lrg til later
//10/23/07 gmagoon: added additional variables
protected LinkedList tempList;
protected LinkedList presList;
protected LinkedList validList;//10/24/07 gmagoon: added
//10/25/07 gmagoon: moved variables from modelGeneration()
protected LinkedList initList = new LinkedList();
protected LinkedList beginList = new LinkedList();
protected LinkedList endList = new LinkedList();
protected LinkedList lastTList = new LinkedList();
protected LinkedList currentTList = new LinkedList();
protected LinkedList lastPList = new LinkedList();
protected LinkedList currentPList = new LinkedList();
protected LinkedList conditionChangedList = new LinkedList();
protected LinkedList reactionChangedList = new LinkedList();
protected int numConversions;//5/6/08 gmagoon: moved from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
protected String equationOfState;
// 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file
// This temperature is used to select the "best" kinetics from the rxn library
protected static Temperature temp4BestKinetics;
// This is the new "PrimaryReactionLibrary"
protected SeedMechanism seedMechanism;
protected PrimaryThermoLibrary primaryThermoLibrary;
protected boolean restart = false;
protected boolean readrestart = false;
protected boolean writerestart = false;
protected LinkedHashSet restartCoreSpcs = new LinkedHashSet();
protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet();
protected LinkedHashSet restartCoreRxns = new LinkedHashSet();
protected LinkedHashSet restartEdgeRxns = new LinkedHashSet();
// Constructors
private HashSet specs = new HashSet();
//public static native long getCpuTime();
//static {System.loadLibrary("cpuTime");}
//## operation ReactionModelGenerator()
public ReactionModelGenerator() {
//#[ operation ReactionModelGenerator()
workingDirectory = System.getProperty("RMG.workingDirectory");
//#]
}
//## operation initializeReactionSystem()
//10/24/07 gmagoon: changed name to initializeReactionSystems
public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
//PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below
setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader);
}
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
// int numPTLs = 0;
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// String[] tempString = line.split("Name: ");
// String name = tempString[tempString.length-1].trim();
// line = ChemParser.readMeaningfulLine(reader);
// tempString = line.split("Location: ");
// String path = tempString[tempString.length-1].trim();
// if (numPTLs==0) {
// setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
// ++numPTLs;
// }
// else {
// getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
// ++numPTLs;
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (numPTLs == 0) setPrimaryThermoLibrary(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String t = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
// Global.temperature = new Temperature(t,unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PressureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String p = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
//Global.pressure = new Pressure(p, unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// // add reading curved pressure function here
// pressureModel = new CurvedPM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
speciesnum ++;
+ if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.exit(0);
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("InertGas:")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader);
}
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence flag
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pressuredependence:")) {
setPressureDependenceType(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String pDepType = st.nextToken();
// if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
// pDepType.toLowerCase().equals("reservoirstate") ||
// pDepType.toLowerCase().equals("chemdis")) {
//
// reactionModelEnlarger = new RateBasedPDepRME();
// PDepNetwork.generateNetworks = true;
//
// if (pDepType.toLowerCase().equals("reservoirstate")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
// if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
// System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// }
// else if (pDepType.toLowerCase().equals("modifiedstrongcollision")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
// if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
// System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// }
// else if (pDepType.toLowerCase().equals("chemdis")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
// if (SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
// System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsEstimator = " + pDepType);
// }
//
// // Set temperatures and pressures to use in PDep kinetics estimation
// Temperature[] temperatures = new Temperature[8];
// temperatures[0] = new Temperature(300, "K");
// temperatures[1] = new Temperature(400, "K");
// temperatures[2] = new Temperature(600, "K");
// temperatures[3] = new Temperature(900, "K");
// temperatures[4] = new Temperature(1200, "K");
// temperatures[5] = new Temperature(1500, "K");
// temperatures[6] = new Temperature(1800, "K");
// temperatures[7] = new Temperature(2100, "K");
// FastMasterEqn.setTemperatures(temperatures);
// PDepRateConstant.setTemperatures(temperatures);
// ChebyshevPolynomials.setTlow(temperatures[0]);
// ChebyshevPolynomials.setTup(temperatures[7]);
//
// Pressure[] pressures = new Pressure[5];
// pressures[0] = new Pressure(0.01, "bar");
// pressures[1] = new Pressure(0.1, "bar");
// pressures[2] = new Pressure(1, "bar");
// pressures[3] = new Pressure(10, "bar");
// pressures[4] = new Pressure(100, "bar");
// FastMasterEqn.setPressures(pressures);
// PDepRateConstant.setPressures(pressures);
// ChebyshevPolynomials.setPlow(pressures[0]);
// ChebyshevPolynomials.setPup(pressures[4]);
//
// }
// else if (pDepType.toLowerCase().equals("off")) {
// // No pressure dependence
// reactionModelEnlarger = new RateBasedRME();
// PDepNetwork.generateNetworks = false;
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
// pressure dependence flag
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
line = setPDepKineticsModel(line,reader);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String pDepKinType = st.nextToken();
// if (pDepKinType.toLowerCase().equals("chebyshev") ||
// pDepKinType.toLowerCase().equals("pdeparrhenius") ||
// pDepKinType.toLowerCase().equals("rate")) {
//
// if (pDepKinType.toLowerCase().equals("chebyshev")) {
// PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("TRange")) {
// st = new StringTokenizer(line);
// String temp = st.nextToken(); // Should be "TRange:"
// String TUNITS = ChemParser.removeBrace(st.nextToken());
// double tLow = Double.parseDouble(st.nextToken());
// Temperature TMIN = new Temperature(tLow,TUNITS);
// ChebyshevPolynomials.setTlow(TMIN);
// double tHigh = Double.parseDouble(st.nextToken());
// if (tHigh <= tLow) {
// System.err.println("Tmax is less than or equal to Tmin");
// System.exit(0);
// }
// Temperature TMAX = new Temperature(tHigh,TUNITS);
// ChebyshevPolynomials.setTup(TMAX);
// int tResolution = Integer.parseInt(st.nextToken());
// int tbasisFuncs = Integer.parseInt(st.nextToken());
// if (tbasisFuncs > tResolution) {
// System.err.println("The number of basis functions cannot exceed the number of grid points");
// System.exit(0);
// }
// FastMasterEqn.setNumTBasisFuncs(tbasisFuncs);
// line = ChemParser.readMeaningfulLine(reader);
// String PUNITS = "";
// Pressure PMIN = new Pressure();
// Pressure PMAX = new Pressure();
// int pResolution = 0;
// int pbasisFuncs = 0;
// if (line.startsWith("PRange")) {
// st = new StringTokenizer(line);
// temp = st.nextToken(); // Should be "PRange:"
// PUNITS = ChemParser.removeBrace(st.nextToken());
// double pLow = Double.parseDouble(st.nextToken());
// PMIN = new Pressure(pLow,PUNITS);
// ChebyshevPolynomials.setPlow(PMIN);
// double pHigh = Double.parseDouble(st.nextToken());
// if (pHigh <= pLow) {
// System.err.println("Pmax is less than or equal to Pmin");
// System.exit(0);
// }
// PMAX = new Pressure(pHigh,PUNITS);
// ChebyshevPolynomials.setPup(PMAX);
// pResolution = Integer.parseInt(st.nextToken());
// pbasisFuncs = Integer.parseInt(st.nextToken());
// if (pbasisFuncs > pResolution) {
// System.err.println("The number of basis functions cannot exceed the number of grid points");
// System.exit(0);
// }
// FastMasterEqn.setNumPBasisFuncs(pbasisFuncs);
// }
// else {
// System.err.println("RMG cannot locate PRange field for Chebyshev polynomials.");
// System.exit(0);
// }
//
// // Set temperatures and pressures to use in PDep kinetics estimation
// Temperature[] temperatures = new Temperature[tResolution];
// for (int i=0; i<temperatures.length; i++) {
// double tempValueTilda = Math.cos((2*(i+1)-1)*Math.PI/(2*temperatures.length));
// double tempValue = 2 / (tempValueTilda * ((1/TMAX.getK()) - (1/TMIN.getK())) + (1/TMIN.getK()) + (1/TMAX.getK()));
// temperatures[temperatures.length-i-1] = new Temperature(tempValue,TUNITS);
// }
// FastMasterEqn.setTemperatures(temperatures);
// PDepRateConstant.setTemperatures(temperatures);
//
// Pressure[] pressures = new Pressure[pResolution];
// for (int j=0; j<pressures.length; j++) {
// double pressValueTilda = Math.cos((2*(j+1)-1)*Math.PI/(2*pressures.length));
// double pressValue = Math.pow(10,(pressValueTilda*(Math.log10(PMAX.getBar())-Math.log10(PMIN.getBar()))+Math.log10(PMIN.getBar())+Math.log10(PMAX.getBar()))/2);
// pressures[pressures.length-j-1] = new Pressure(pressValue,PUNITS);
// }
// FastMasterEqn.setPressures(pressures);
// PDepRateConstant.setPressures(pressures);
// line = ChemParser.readMeaningfulLine(reader);
// }
// }
// else if (pDepKinType.toLowerCase().equals("pdeparrhenius")) {
// //PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
// /*
// * Updated by MRH on 10Feb2010
// * Allow user to specify # of T's/P's solved for in fame &
// * # of PLOG's to report
// */
// PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("TRange")) {
// st = new StringTokenizer(line);
// String temp = st.nextToken(); // Should be "TRange:"
// String TUNITS = ChemParser.removeBrace(st.nextToken());
// int numT = Integer.parseInt(st.nextToken());
// Temperature[] listOfTs = new Temperature[numT];
// int counter = 0;
// while (st.hasMoreTokens()) {
// listOfTs[counter] = new Temperature(Double.parseDouble(st.nextToken()),TUNITS);
// ++counter;
// }
// if (counter != numT) {
// System.out.println("Warning in TRange field of PressureDependence:\n" +
// "The stated number of temperatures is: " + numT +
// "but the length of the temperature list is: " + counter);
// }
//
// line = ChemParser.readMeaningfulLine(reader);
// String PUNITS = "";
// if (line.startsWith("PRange")) {
// st = new StringTokenizer(line);
// temp = st.nextToken(); // Should be "PRange:"
// PUNITS = ChemParser.removeBrace(st.nextToken());
// int numP = Integer.parseInt(st.nextToken());
// Pressure[] listOfPs = new Pressure[numP];
// counter = 0;
// while (st.hasMoreTokens()) {
// listOfPs[counter] = new Pressure(Double.parseDouble(st.nextToken()),PUNITS);
// ++counter;
// }
// if (counter != numP) {
// System.out.println("Warning in PRange field of PressureDependence:\n" +
// "The stated number of pressures is: " + numT +
// "but the length of the pressure list is: " + counter);
// }
// FastMasterEqn.setTemperatures(listOfTs);
// PDepRateConstant.setTemperatures(listOfTs);
// FastMasterEqn.setPressures(listOfPs);
// PDepRateConstant.setPressures(listOfPs);
// PDepArrheniusKinetics.setNumPressures(numP);
// PDepArrheniusKinetics.setPressures(listOfPs);
// }
// else {
// System.err.println("RMG cannot locate PRange field for PDepArrhenius.");
// System.exit(0);
// }
//
// line = ChemParser.readMeaningfulLine(reader);
// }
// }
// // 6Jul2009-MRH:
// // RATE mode reports p-dep rxn kinetics as: A 0.0 0.0
// // where A is k(T,P) evaluated at the single temperature
// // and pressure given in the condition.txt file
// else if (pDepKinType.toLowerCase().equals("rate"))
// PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
//
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PDepKinetics = " + pDepKinType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PDepKinetics flag!");
}
// include species (optional)
if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
!PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
double tolerance;
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
// read in atol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!");
// read in reaction model enlarger
/* Read in the Primary Reaction Library
* MRH 12-Jun-2009
*
* I've made minor changes to this piece of code. In particular, I've
* eliminated the on/off flag. The user can specify as many PRLs,
* including none, as they like.
*/
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PrimaryReactionLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Reaction Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePRL
*/
readAndMakePRL(reader);
// // GJB modified to allow multiple primary reaction libraries
// int Ilib = 0;
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// String[] tempString = line.split("Name: ");
// String name = tempString[tempString.length-1].trim();
// line = ChemParser.readMeaningfulLine(reader);
// tempString = line.split("Location: ");
// String path = tempString[tempString.length-1].trim();
// if (Ilib==0) {
// //primaryReactionLibrary = new PrimaryReactionLibrary(name, path);
// setPrimaryReactionLibrary(new PrimaryReactionLibrary(name, path));//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
// Ilib++;
// }
// else {
// //primaryReactionLibrary.appendPrimaryReactionLibrary(name,path);
// getPrimaryReactionLibrary().appendPrimaryReactionLibrary(name,path);//10/14/07 gmagoon: changed to use getPrimaryReactionLibrary; check to make sure this is valid
// Ilib++;//just in case anybody wants to track how many are processed
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
// // System.out.println("Primary Reaction Libraries in use: " +getPrimaryReactionLibrary().getName());//10/14/07 gmagoon: changed to use getPrimaryReactionLibrary
// if (Ilib==0) {
// //primaryReactionLibrary = null;
// setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary; check to make sure this is valid
// }
// else System.out.println("Primary Reaction Libraries in use: " + getPrimaryReactionLibrary().getName());
} else throw new InvalidSymbolException("condition.txt: can't find PrimaryReactionLibrary!");
/*
* Added by MRH 12-Jun-2009
*
* The SeedMechanism acts almost exactly as the old
* PrimaryReactionLibrary did. Whatever is in the SeedMechanism
* will be placed in the core at the beginning of the simulation.
* The user can specify as many seed mechanisms as they like, with
* the priority (in the case of duplicates) given to the first
* instance. There is no on/off flag.
*/
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SeedMechanism:")) {
int numMechs = 0;
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("GenerateReactions: ");
String generateStr = tempString[tempString.length-1].trim();
boolean generate = true;
if (generateStr.equalsIgnoreCase("yes") ||
generateStr.equalsIgnoreCase("on") ||
generateStr.equalsIgnoreCase("true")){
generate = true;
System.out.println("Will generate cross-reactions between species in seed mechanism " + name);
} else if(generateStr.equalsIgnoreCase("no") ||
generateStr.equalsIgnoreCase("off") ||
generateStr.equalsIgnoreCase("false")) {
generate = false;
System.out.println("Will NOT initially generate cross-reactions between species in seed mechanism "+ name);
System.out.println("This may have unintended consequences");
}
else {
System.err.println("Input file invalid");
System.err.println("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name);
System.exit(0);
}
if (numMechs==0) {
setSeedMechanism(new SeedMechanism(name, path, generate));
++numMechs;
}
else {
getSeedMechanism().appendSeedMechanism(name, path, generate);
++numMechs;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (numMechs != 0) System.out.println("Seed Mechanisms in use: " + getSeedMechanism().getName());
else setSeedMechanism(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate SeedMechanism field");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ChemkinUnits")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Verbose:")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken();
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
ArrheniusKinetics.setVerbose(false);
} else if (OnOff.equals("on")) {
ArrheniusKinetics.setVerbose(true);
}
line = ChemParser.readMeaningfulLine(reader);
}
/*
* MRH 3MAR2010:
* Adding user option regarding chemkin file
*
* New field: If user would like the empty SMILES string
* printed with each species in the thermochemistry portion
* of the generated chem.inp file
*/
if (line.toUpperCase().startsWith("SMILES")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "SMILES:"
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
Chemkin.setSMILES(false);
} else if (OnOff.equals("on")) {
Chemkin.setSMILES(true);
/*
* MRH 9MAR2010:
* MRH decided not to generate an InChI for every new species
* during an RMG simulation (especially since it is not used
* for anything). Instead, they will only be generated in the
* post-processing, if the user asked for InChIs.
*/
//Species.useInChI = true;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("A")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "A:"
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
ArrheniusKinetics.setAUnits(units);
else {
System.err.println("Units for A were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units A field.");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Ea")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "Ea:"
String units = st.nextToken();
if (units.equals("kcal/mol") || units.equals("cal/mol") ||
units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins"))
ArrheniusKinetics.setEaUnits(units);
else {
System.err.println("Units for Ea were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units Ea field.");
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate ChemkinUnits field.");
in.close();
//11/6/07 gmagoon: initializing temperatureArray and pressureArray before libraryReactionGenerator is initialized (initialization calls PDepNetwork and performs initializekLeak); UPDATE: moved after initialStatusList initialization (in case primaryReactionLibrary calls the similar pdep functions
// LinkedList temperatureArray = new LinkedList();
// LinkedList pressureArray = new LinkedList();
// Iterator iterIS = initialStatusList.iterator();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// InitialStatus is = (InitialStatus)iterIS.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));
// pressureArray.add(pm.getPressure(is.getTime()));
// }
// }
// PDepNetwork.setTemperatureArray(temperatureArray);
// PDepNetwork.setPressureArray(pressureArray);
//10/4/07 gmagoon: moved to modelGeneration()
//ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator
// setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added
/*
* MRH 12-Jun-2009
* A TemplateReactionGenerator now requires a Temperature be passed to it.
* This allows RMG to determine the "best" kinetic parameters to use
* in the mechanism generation. For now, I choose to pass the first
* temperature in the list of temperatures. RMG only outputs one mechanism,
* even for multiple temperature/pressure systems, so we can only have one
* set of kinetics.
*/
Temperature t = new Temperature(300,"K");
for (Iterator iter = tempList.iterator(); iter.hasNext();) {
TemperatureModel tm = (TemperatureModel)iter.next();
t = tm.getTemperature(new ReactionTime(0,"sec"));
setTemp4BestKinetics(t);
break;
}
setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary reaction library files!"
lrg = new LibraryReactionGenerator();//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator
//10/24/07 gmagoon: updated to use multiple reactionSystem variables
reactionSystemList = new LinkedList();
// LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
// LinkedList pressureArray = new LinkedList();//10/30/07 gmagoon: same for pressure;//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time; 11/1-2/07 restored;11/6/07 gmagoon: moved before initialization of lrg;
Iterator iter3 = initialStatusList.iterator();
Iterator iter4 = dynamicSimulatorList.iterator();
int i = 0;//10/30/07 gmagoon: added
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
//InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop"
//DynamicSimulator ds = (DynamicSimulator)iter4.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop""
DynamicSimulator ds = (DynamicSimulator)iter4.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg;
// pressureArray.add(pm.getPressure(is.getTime()));//10/30/07 gmagoon: added//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time;11/1-2/07 restored with .getTemperature(is.getTime()) added;11/6/07 gmagoon: moved before initialization of lrg;
//11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT
//UPDATE: actually, I don't think this deep copy was necessary; original case with FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester()) is probably OK; (in any case, this didn't do completetly deep copy (references to speciesConversion element in LinkedList were the same);
// TerminationTester termTestCopy;
// if (finishController.getTerminationTester() instanceof ConversionTT){
// ConversionTT termTest = (ConversionTT)finishController.getTerminationTester();
// LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone());
// termTestCopy = new ConversionTT(spcCopy);
// }
// else{
// termTestCopy = finishController.getTerminationTester();
// }
FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable"
// FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester());
reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryReactionLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState));
i++;//10/30/07 gmagoon: added
System.out.println("Created reaction system "+i+"\n");
}
}
// PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
// PDepNetwork.setPressureArray(pressureArray);//10/30/07 gmagoon: same for pressure;//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time; 11/1-2/07 restored; 11/6/07 gmagoon: moved before initialization of lrg;
}
catch (IOException e) {
System.err.println("Error in read in reaction system initialization file!");
throw new IOException("Reaction System Initialization: " + e.getMessage());
}
}
public void setReactionModel(ReactionModel p_ReactionModel) {
reactionModel = p_ReactionModel;
}
public void modelGeneration() {
//long begin_t = System.currentTimeMillis();
try{
ChemGraph.readForbiddenStructure();
setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel
// setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems
// setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem
// initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
initializeReactionSystems();
}
catch (IOException e) {
System.err.println(e.getMessage());
System.exit(0);
}
catch (InvalidSymbolException e) {
System.err.println(e.getMessage());
System.exit(0);
}
//10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called
validList = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
validList.add(false);
}
initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
//10/24/07 gmagoon: changed to use reactionSystemList
// LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class
// LinkedList beginList = new LinkedList();
// LinkedList endList = new LinkedList();
// LinkedList lastTList = new LinkedList();
// LinkedList currentTList = new LinkedList();
// LinkedList lastPList = new LinkedList();
// LinkedList currentPList = new LinkedList();
// LinkedList conditionChangedList = new LinkedList();
// LinkedList reactionChangedList = new LinkedList();
//5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester)
boolean intermediateSteps = true;
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (timeStep == null){
intermediateSteps = false;
}
}
else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length
intermediateSteps=false;
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
rs.initializePDepNetwork();
}
ReactionTime init = rs.getInitialReactionTime();
initList.add(init);
ReactionTime begin = init;
beginList.add(begin);
ReactionTime end;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
end = (ReactionTime)timeStep.get(0);
}
else{
end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime;
}
//end = (ReactionTime)timeStep.get(0);
endList.add(end);
}
else{
end = new ReactionTime(1e6,"sec");
endList.add(end);
}
// int iterationNumber = 1;
lastTList.add(rs.getTemperature(init));
currentTList.add(rs.getTemperature(init));
lastPList.add(rs.getPressure(init));
currentPList.add(rs.getPressure(init));
conditionChangedList.add(false);
reactionChangedList.add(false);//10/31/07 gmagoon: added
//Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus());
}
int iterationNumber = 1;
LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated
//validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel
//10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively
boolean allTerminated = true;
boolean allValid = true;
// IF RESTART IS TURNED ON
// Update the systemSnapshot for each ReactionSystem in the reactionSystemList
if (readrestart) {
for (Integer i=0; i<reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
InitialStatus is = rs.getInitialStatus();
putRestartSpeciesInInitialStatus(is,i);
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1));
Chemkin.writeChemkinInputFile(rs);//11/9/07 gmagoon:****temporarily commenting out: there is a NullPointerException in Reaction.toChemkinString when called from writeChemkinPdepReactions; occurs with pre-modified version of RMG as well; //11/12/07 gmagoon: restored; ****this appears to be source of non-Pdep bug
boolean terminated = rs.isReactionTerminated();
terminatedList.add(terminated);
if(!terminated)
allTerminated = false;
boolean valid = rs.isModelValid();
//validList.add(valid);
validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel
if(!valid)
allValid = false;
reactionChangedList.set(i,false);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
//System.exit(0);
System.out.println("The model core has " + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
System.out.println("The model edge has " + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + " species.");
StringBuilder print_info = Global.diagnosticInfo;
print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n");
print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac");
print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n");
double solverMin = 0;
double vTester = 0;
/*if (!restart){
writeRestartFile();
writeCoreReactions();
writeAllReactions();
}*/
//System.exit(0);
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
System.out.println("Species dictionary size: "+dictionary.size());
//boolean reactionChanged = false;//10/24/07 gmagoon: I don't know if this is even required, but I will change to use reactionChangedList (I put analogous line of code for list in above for loop); update: yes, it is required; I had been thinking of conditionChangedList
double tAtInitialization = Global.tAtInitialization;
//10/24/07: changed to use allTerminated and allValid
// step 2: iteratively grow reaction system
while (!allTerminated || !allValid) {
while (!allValid) {
//writeCoreSpecies();
double pt = System.currentTimeMillis();
// ENLARGE THE MODEL!!! (this is where the good stuff happens)
enlargeReactionModel();//10/24/07 gmagoon: need to adjust this function
double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60;
//PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet());
//10/24/07 gmagoon: changed to use reactionSystemList
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.initializePDepNetwork();
}
//reactionSystem.initializePDepNetwork();
}
pt = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.resetSystemSnapshot();
}
//reactionSystem.resetSystemSnapshot();
double resetSystem = (System.currentTimeMillis() - pt)/1000/60;
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
//reactionChanged = true;
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i,true);
// begin = init;
beginList.set(i, (ReactionTime)initList.get(i));
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
endList.set(i,(ReactionTime)timeStep.get(0));
}
else{
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
}
// endList.set(i, (ReactionTime)timeStep.get(0));
//end = (ReactionTime)timeStep.get(0);
}
else
endList.set(i, new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
// iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
}
iterationNumber = 1;
double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1));
//end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(rs);//10/25/07 gmagoon: ***I don't know if this will still work with multiple reaction systems: may want to modify to only write one chemkin input file for all reaction systems //11/9/07 gmagoon:****temporarily commenting out; cf. previous comment; //11/12/07 gmagoon: restored; ****this appears to be source of non-Pdep bug
//Chemkin.writeChemkinInputFile(reactionSystem);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
double chemkint = (System.currentTimeMillis()-startTime)/1000/60;
if (writerestart) {
writeCoreSpecies();
writeCoreReactions();
writeEdgeSpecies();
writeEdgeReactions();
if (PDepNetwork.generateNetworks == true) writePDepNetworks();
}
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(1);
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getName() + " is:");
System.out.println(conv);
}
System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis()-tAtInitialization)/1000/60) + " minutes.");
System.out.println("The model edge has " + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + " species.");
//10/24/07 gmagoon: note: all reaction systems should use the same core, but I will display for each reactionSystem for testing purposes:
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
if (rs.getDynamicSimulator() instanceof JDASPK){
JDASPK solver = (JDASPK)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
}
else{
JDASSL solver = (JDASSL)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
}
}
// if (reactionSystem.getDynamicSimulator() instanceof JDASPK){
// JDASPK solver = (JDASPK)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
//}
//else{
// JDASSL solver = (JDASSL)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
//}
startTime = System.currentTimeMillis();
double mU = memoryUsed();
double gc = (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: updating to use reactionSystemList
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
if(!valid)
allValid = false;
validList.set(i,valid);
//valid = reactionSystem.isModelValid();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
writeDiagnosticInfo();
writeEnlargerInfo();
double restart2 = (System.currentTimeMillis()-startTime)/1000/60;
int allSpecies, allReactions;
allSpecies = SpeciesDictionary.getInstance().size();
print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n");
}
//5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps
double startTime = System.currentTimeMillis();
if(intermediateSteps){
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i, false);
//reactionChanged = false;
Temperature currentT = (Temperature)currentTList.get(i);
Pressure currentP = (Pressure)currentPList.get(i);
lastTList.set(i,(Temperature)currentT.clone()) ;
lastPList.set(i,(Pressure)currentP.clone());
//lastT = (Temperature)currentT.clone();
//lastP = (Pressure)currentP.clone();
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));//10/24/07 gmagoon: ****I think this should actually be at end? (it shouldn't matter for isothermal/isobaric case)
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);//10/24/07 gmagoon: ****I think this should actually be at end? (it shouldn't matter for isothermal/isobaric case)
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time);
// begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber < timeStep.size()){
endList.set(i,(ReactionTime)timeStep.get(iterationNumber));
//end = (ReactionTime)timeStep.get(iterationNumber);
}
else
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else
endList.set(i,new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
}
iterationNumber++;
startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps
//double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1));
// end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
validList.set(i,valid);
if(!valid)
allValid = false;
}
}//5/6/08 gmagoon: end of block for intermediateSteps
allTerminated = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean terminated = rs.isReactionTerminated();
terminatedList.set(i,terminated);
if(!terminated){
allTerminated = false;
System.out.println("Reaction System "+(i+1)+" has not reached its termination criterion");
if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) {
System.out.println("although it seems to be valid (complete), so it was not interrupted for being invalid.");
System.out.println("This probably means there was an error with the ODE solver, and we risk entering an endless loop.");
System.out.println("Stopping.");
throw new Error();
}
}
}
// //10/24/07 gmagoon: changed to use reactionSystemList
// allTerminated = true;
// allValid = true;
// for (Integer i = 0; i<reactionSystemList.size();i++) {
// ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
// boolean terminated = rs.isReactionTerminated();
// terminatedList.set(i,terminated);
// if(!terminated)
// allTerminated = false;
// boolean valid = rs.isModelValid();
// validList.set(i,valid);
// if(!valid)
// allValid = false;
// }
// //terminated = reactionSystem.isReactionTerminated();
// //valid = reactionSystem.isModelValid();
//10/24/07 gmagoon: changed to use reactionSystemList, allValid
if (allValid) {
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this reaction time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(1);
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getName() + " is:");
System.out.println(conv);
}
//System.out.println("At this time: " + end.toString());
//Species spe = SpeciesDictionary.getSpeciesFromID(1);
//double conv = reactionSystem.getPresentConversion(spe);
//System.out.print("current conversion = ");
//System.out.println(conv);
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
//runTime.gc();
/* if we're not calling runTime.gc() then don't bother printing this:
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
*/
//10/24/07 gmagoon: note: all reaction systems should use the same core, but I will display for each reactionSystem for testing purposes:
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
if (rs.getDynamicSimulator() instanceof JDASPK){
JDASPK solver = (JDASPK)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
}
else{
JDASSL solver = (JDASSL)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
System.out.println("(although rs.getReactionModel().getReactionNumber() returns "+rs.getReactionModel().getReactionNumber()+")");
}
}
// if (reactionSystem.getDynamicSimulator() instanceof JDASPK){
// JDASPK solver = (JDASPK)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
// }
// else{
// JDASSL solver = (JDASSL)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
// }
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing
}
//System.out.println("Performing model reduction");
if (paraInfor != 0){
System.out.println("Model Generation performed. Now generating sensitivity data.");
//10/24/07 gmagoon: updated to use reactionSystemList
LinkedList dynamicSimulator2List = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
//6/25/08 gmagoon: updated to pass index i
//6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here);
dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i));
//DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus);
((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length);
//dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length);
rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i));
//reactionSystem.setDynamicSimulator(dynamicSimulator2);
int numSteps = rs.systemSnapshot.size() -1;
rs.resetSystemSnapshot();
beginList.set(i, (ReactionTime)initList.get(i));
//begin = init;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else{
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i, end.add(end));
//end = end.add(end);
}
terminatedList.set(i, false);
//terminated = false;
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
rs.solveReactionSystemwithSEN(begin, end, true, false, false);
//reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false);
}
}
//10/24/07 gmagoon: updated to use reactionSystemList (***see previous comment regarding having one Chemkin input file)
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus());//11/9/07 gmagoon: temporarily commenting out; see previous comment; this line may not cause a problem because it is different instance of writeChemkinInputFile, but I am commenting out just in case//11/12/07 gmagoon: restored; ****this appears to be source of non-Pdep bug
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
System.out.println("Model Generation Completed");
return;
}
//9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey
//this is based off of writeChemkinFile in ChemkinInputFile.java
private void writeInChIs(ReactionModel p_reactionModel) {
StringBuilder result=new StringBuilder();
for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) {
Species species = (Species) iter.next();
result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n");
}
String file = "inchiDictionary.txt";
try {
FileWriter fw = new FileWriter(file);
fw.write(result.toString());
fw.close();
}
catch (Exception e) {
System.out.println("Error in writing InChI file inchiDictionary.txt!");
System.out.println(e.getMessage());
System.exit(0);
}
}
//9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java
private void writeDictionary(ReactionModel rm){
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
//Write core species to RMG_Dictionary.txt
String coreSpecies ="";
Iterator iter = cerm.getSpecies();
if (Species.useInChI) {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
} else {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
}
try{
File rmgDictionary = new File("RMG_Dictionary.txt");
FileWriter fw = new FileWriter(rmgDictionary);
fw.write(coreSpecies);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Dictionary.txt");
System.exit(0);
}
}
private void parseRestartFiles() {
parseAllSpecies();
parseCoreSpecies();
parseEdgeSpecies();
parseAllReactions();
parseCoreReactions();
}
private void parseEdgeReactions() {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
//HasMap speciesMap = dictionary.dictionary;
try{
File coreReactions = new File("Restart/edgeReactions.txt");
FileReader fr = new FileReader(coreReactions);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
boolean found = false;
LinkedHashSet reactionSet = new LinkedHashSet();
while (line != null){
Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1);
boolean added = reactionSet.add(reaction);
if (!added){
if (reaction.hasResonanceIsomerAsReactant()){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"reactants", reactionSet);
}
if (reaction.hasResonanceIsomerAsProduct() && !found){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"products", reactionSet);
}
if (!found){
System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added");
System.exit(0);
}
else found = false;
}
//Reaction reverse = reaction.getReverseReaction();
//if (reverse != null) reactionSet.add(reverse);
line = ChemParser.readMeaningfulLine(reader);
}
((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
public void parseCoreReactions() {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
int i=1;
//HasMap speciesMap = dictionary.dictionary;
try{
File coreReactions = new File("Restart/coreReactions.txt");
FileReader fr = new FileReader(coreReactions);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
boolean found = false;
LinkedHashSet reactionSet = new LinkedHashSet();
while (line != null){
Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel));
boolean added = reactionSet.add(reaction);
if (!added){
if (reaction.hasResonanceIsomerAsReactant()){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"reactants", reactionSet);
}
if (reaction.hasResonanceIsomerAsProduct() && !found){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"products", reactionSet);
}
if (!found){
System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
//System.exit(0);
}
else found = false;
}
Reaction reverse = reaction.getReverseReaction();
if (reverse != null) {
reactionSet.add(reverse);
//System.out.println(2 + "\t " + line);
}
//else System.out.println(1 + "\t" + line);
line = ChemParser.readMeaningfulLine(reader);
i=i+1;
}
((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet);
}
catch (IOException e){
System.out.println("Could not read the coreReactions restart file");
System.exit(0);
}
}
private void parseAllReactions() {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
int i=1;
//HasMap speciesMap = dictionary.dictionary;
try{
File allReactions = new File("Restart/allReactions.txt");
FileReader fr = new FileReader(allReactions);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
boolean found = false;
LinkedHashSet reactionSet = new LinkedHashSet();
OuterLoop:
while (line != null){
Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel()));
if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){
boolean added = reactionSet.add(reaction);
if (!added){
found = false;
if (reaction.hasResonanceIsomerAsReactant()){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"reactants", reactionSet);
}
if (reaction.hasResonanceIsomerAsProduct() && !found){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"products", reactionSet);
}
if (!found){
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction reacTemp = (Reaction)iter.next();
if (reacTemp.equals(reaction)){
reactionSet.remove(reacTemp);
reactionSet.add(reaction);
break;
}
}
//System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
//System.exit(0);
}
//else found = false;
}
}
/*Reaction reverse = reaction.getReverseReaction();
if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) {
reactionSet.add(reverse);
//System.out.println(2 + "\t " + line);
}*/
//else System.out.println(1 + "\t" + line);
i=i+1;
line = ChemParser.readMeaningfulLine(reader);
}
((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) {
Structure reactionStructure = p_Reaction.getStructure();
//Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList());
boolean found = false;
if (rOrP.equals("reactants")){
Iterator originalreactants = reactionStructure.getReactants();
HashSet tempHashSet = new HashSet();
while(originalreactants.hasNext()){
tempHashSet.add(originalreactants.next());
}
Iterator reactants = tempHashSet.iterator();
while(reactants.hasNext() && !found){
ChemGraph reactant = (ChemGraph)reactants.next();
if (reactant.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeReactants(reactant);
reactionStructure.addReactants(newChemGraph);
reactant = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
else{
Iterator originalproducts = reactionStructure.getProducts();
HashSet tempHashSet = new HashSet();
while(originalproducts.hasNext()){
tempHashSet.add(originalproducts.next());
}
Iterator products = tempHashSet.iterator();
while(products.hasNext() && !found){
ChemGraph product = (ChemGraph)products.next();
if (product.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeProducts(product);
reactionStructure.addProducts(newChemGraph);
product = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
return found;
}
public void parseCoreSpecies() {
// String restartFileContent ="";
//int speciesCount = 0;
//boolean added;
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File coreSpecies = new File ("Restart/coreSpecies.txt");
FileReader fr = new FileReader(coreSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
//HashSet speciesSet = new HashSet();
// if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway
// //ReactionSystem reactionSystem = new ReactionSystem();
// }
setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
System.out.println("There was no species with ID "+ID +" in the species dictionary");
((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader);
}
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
public static void garbageCollect(){
System.gc();
}
public static long memoryUsed(){
garbageCollect();
Runtime rT = Runtime.getRuntime();
long uM, tM, fM;
tM = rT.totalMemory();
fM = rT.freeMemory();
uM = tM - fM;
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(tM);
System.out.print("Free memory: ");
System.out.println(fM);
return uM;
}
private HashSet readIncludeSpecies(String fileName) {
HashSet speciesSet = new HashSet();
try {
File includeSpecies = new File (fileName);
FileReader fr = new FileReader(includeSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken().trim();
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.exit(0);
}
Species species = Species.make(name,cg);
//speciesSet.put(name, species);
speciesSet.add(species);
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
}
}
catch (IOException e){
System.out.println("Could not read the included species file");
System.exit(0);
}
return speciesSet;
}
public LinkedHashSet parseAllSpecies() {
// String restartFileContent ="";
int speciesCount = 0;
LinkedHashSet speciesSet = new LinkedHashSet();
boolean added;
try{
long initialTime = System.currentTimeMillis();
File coreSpecies = new File ("allSpecies.txt");
BufferedReader reader = new BufferedReader(new FileReader(coreSpecies));
String line = ChemParser.readMeaningfulLine(reader);
int i=0;
while (line!=null) {
i++;
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken().trim();
int ID = getID(name);
name = getName(name);
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.exit(0);
}
Species species;
if (ID == 0)
species = Species.make(name,cg);
else
species = Species.make(name,cg,ID);
speciesSet.add(species);
double flux = 0;
int species_type = 1;
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
}
}
catch (IOException e){
System.out.println("Could not read the allSpecies restart file");
System.exit(0);
}
return speciesSet;
}
private String getName(String name) {
//int id;
String number = "";
int index=0;
if (!name.endsWith(")")) return name;
else {
char [] nameChars = name.toCharArray();
String temp = String.copyValueOf(nameChars);
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') {
index=i;
i=0;
}
else i = i-1;
}
}
number = name.substring(0,index);
return number;
}
private int getID(String name) {
int id;
String number = "";
if (!name.endsWith(")")) return 0;
else {
char [] nameChars = name.toCharArray();
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') i=0;
else{
number = name.charAt(i)+number;
i = i-1;
}
}
}
id = Integer.parseInt(number);
return id;
}
private void parseEdgeSpecies() {
// String restartFileContent ="";
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File edgeSpecies = new File ("Restart/edgeSpecies.txt");
FileReader fr = new FileReader(edgeSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
//HashSet speciesSet = new HashSet();
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
System.out.println("There was no species with ID "+ID +" in the species dictionary");
//reactionSystem.reactionModel = new CoreEdgeReactionModel();
((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader);
}
}
catch (IOException e){
System.out.println("Could not read the edgepecies restart file");
System.exit(0);
}
}
/*private int calculateAllReactionsinReactionTemplate() {
int totalnum = 0;
TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator;
Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate();
while (iter.hasNext()){
ReactionTemplate rt = (ReactionTemplate)iter.next();
totalnum += rt.getNumberOfReactions();
}
return totalnum;
}*/
private void writeEnlargerInfo() {
try {
File diagnosis = new File("enlarger.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.enlargerInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write enlarger file");
System.exit(0);
}
}
private void writeDiagnosticInfo() {
try {
File diagnosis = new File("diagnosis.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.diagnosticInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write diagnosis file");
System.exit(0);
}
}
//10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified
//Is still incomplete.
public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) {
//writeCoreSpecies(p_rs);
//writeCoreReactions(p_rs, p_time);
//writeEdgeSpecies();
//writeAllReactions(p_rs, p_time);
//writeEdgeReactions(p_rs, p_time);
//String restartFileName;
//String restartFileContent="";
/*File restartFile;
try {
restartFileName="Restart.txt";
restartFile = new File(restartFileName);
FileWriter fw = new FileWriter(restartFile);
restartFileContent = restartFileContent+ "TemperatureModel: Constant " + reactionSystem.temperatureModel.getTemperature(reactionSystem.getInitialReactionTime()).getStandard()+ " (K)\n";
restartFileContent = restartFileContent+ "PressureModel: Constant " + reactionSystem.pressureModel.getPressure(reactionSystem.getInitialReactionTime()).getAtm() + " (atm)\n\n";
restartFileContent = restartFileContent+ "InitialStatus: \n";
int speciesCount = 1;
for(Iterator iter=reactionSystem.reactionModel.getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
restartFileContent = restartFileContent + "("+ speciesCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent + species.toStringWithoutH(1) + "\n";
speciesCount = speciesCount + 1;
}
restartFileContent = restartFileContent + "\n\n END \n\nInertGas:\n";
for (Iterator iter=reactionSystem.getPresentStatus().getInertGas(); iter.hasNext();){
String inertName= (String) iter.next();
restartFileContent = restartFileContent + inertName + " " + reactionSystem.getPresentStatus().getInertGas(inertName) + " mol/cm3 \n";
}
restartFileContent = restartFileContent + "END\n";
double tolerance;
if (reactionSystem.reactionModelEnlarger instanceof RateBasedPDepRME){
restartFileContent = restartFileContent + "ReactionModelEnlarger: RateBasedPDepModelEnlarger\n";
restartFileContent = restartFileContent + "FinishController: RateBasedPDepFinishController\n";
}
else {
restartFileContent = restartFileContent + "ReactionModelEnlarger: RateBasedModelEnlarger\n";
restartFileContent = restartFileContent + "FinishController: RateBasedFinishController\n";
}
if (reactionSystem.finishController.terminationTester instanceof ConversionTT){
restartFileContent = restartFileContent + "(1) Goal Conversion: ";
for (Iterator iter = ((ConversionTT)reactionSystem.finishController.terminationTester).getSpeciesGoalConversionSet();iter.hasNext();){
SpeciesConversion sc = (SpeciesConversion) iter.next();
restartFileContent = restartFileContent + sc.getSpecies().getName()+" "+sc.conversion + "\n";
}
}
else {
restartFileContent = restartFileContent + "(1) Goal ReactionTime: "+((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime.toString();
}
restartFileContent = restartFileContent + "Error Tolerance: " +((RateBasedVT) reactionSystem.finishController.validityTester).tolerance + "\n";
fw.write(restartFileContent);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write the restart file");
System.exit(0);
}*/
}
/*Only write the forward reactions in the model core.
The reverse reactions are generated from the forward reactions.*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) {
StringBuilder restartFileContent =new StringBuilder();
int reactionCount = 1;
try{
File coreSpecies = new File ("Restart/edgeReactions.txt");
FileWriter fw = new FileWriter(coreSpecies);
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
//if (reaction.getDirection()==1){
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
reactionCount = reactionCount + 1;
//}
}
//restartFileContent += "\nEND";
fw.write(restartFileContent.toString());
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart edgereactions file");
System.exit(0);
}
}
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) {
StringBuilder restartFileContent = new StringBuilder();
int reactionCount = 1;
try{
File allReactions = new File ("Restart/allReactions.txt");
FileWriter fw = new FileWriter(allReactions);
for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
}
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
//if (reaction.getDirection()==1){
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
}
//restartFileContent += "\nEND";
fw.write(restartFileContent.toString());
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart edgereactions file");
System.exit(0);
}
}
private void writeEdgeSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt"));
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) {
StringBuilder restartFileContent = new StringBuilder();
int reactionCount = 0;
try{
File coreSpecies = new File ("Restart/coreReactions.txt");
FileWriter fw = new FileWriter(coreSpecies);
for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.getDirection()==1){
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
reactionCount = reactionCount + 1;
}
}
//restartFileContent += "\nEND";
fw.write(restartFileContent.toString());
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart corereactions file");
System.exit(0);
}
}
private void writeCoreSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt"));
for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeCoreReactions() {
BufferedWriter bw_rxns = null;
BufferedWriter bw_troe = null;
BufferedWriter bw_lindemann = null;
BufferedWriter bw_thirdbody = null;
try {
bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt"));
bw_troe = new BufferedWriter(new FileWriter("Restart/troeReactions.txt"));
bw_lindemann = new BufferedWriter(new FileWriter("Restart/lindemannReactions.txt"));
bw_thirdbody = new BufferedWriter(new FileWriter("Restart/thirdBodyReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
String AUnits = ArrheniusKinetics.getAUnits();
bw_rxns.write("UnitsOfEa: " + EaUnits);
bw_rxns.newLine();
bw_troe.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_troe.newLine();
bw_lindemann.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_lindemann.newLine();
bw_thirdbody.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions :");
bw_thirdbody.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet allcoreRxns = cerm.core.reaction;
for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
if (reaction instanceof TROEReaction) {
TROEReaction troeRxn = (TROEReaction) reaction;
bw_troe.write(troeRxn.toRestartString(new Temperature(298,"K")));
bw_troe.newLine();
}
else if (reaction instanceof LindemannReaction) {
LindemannReaction lindeRxn = (LindemannReaction) reaction;
bw_lindemann.write(lindeRxn.toRestartString(new Temperature(298,"K")));
bw_lindemann.newLine();
}
else if (reaction instanceof ThirdBodyReaction) {
ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction;
bw_thirdbody.write(tbRxn.toRestartString(new Temperature(298,"K")));
bw_thirdbody.newLine();
}
else {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw_rxns.write(reaction.toRestartString(new Temperature(298,"K")));
bw_rxns.newLine();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw_rxns != null) {
bw_rxns.flush();
bw_rxns.close();
}
if (bw_troe != null) {
bw_troe.flush();
bw_troe.close();
}
if (bw_lindemann != null) {
bw_lindemann.flush();
bw_lindemann.close();
}
if (bw_thirdbody != null) {
bw_thirdbody.flush();
bw_thirdbody.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeEdgeReactions() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet alledgeRxns = cerm.edge.reaction;
for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw.write(reaction.toRestartString(new Temperature(298,"K")));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
//bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K")));
bw.newLine();
} else
System.out.println("Could not determine forward direction for following rxn: " + reaction.toString());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writePDepNetworks() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt"));
int numFameTemps = PDepRateConstant.getTemperatures().length;
int numFamePress = PDepRateConstant.getPressures().length;
int numChebyTemps = ChebyshevPolynomials.getNT();
int numChebyPress = ChebyshevPolynomials.getNP();
int numPlog = PDepArrheniusKinetics.getNumPressures();
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
bw.write("NumberOfFameTemps: " + numFameTemps);
bw.newLine();
bw.write("NumberOfFamePress: " + numFamePress);
bw.newLine();
bw.write("NumberOfChebyTemps: " + numChebyTemps);
bw.newLine();
bw.write("NumberOfChebyPress: " + numChebyPress);
bw.newLine();
bw.write("NumberOfPLogs: " + numPlog);
bw.newLine();
bw.newLine();
LinkedList allNets = PDepNetwork.getNetworks();
int netCounter = 0;
for(Iterator iter=allNets.iterator(); iter.hasNext();){
PDepNetwork pdepnet = (PDepNetwork) iter.next();
++netCounter;
bw.write("PDepNetwork #" + netCounter);
bw.newLine();
// Write netReactionList
LinkedList netRxns = pdepnet.getNetReactions();
bw.write("netReactionList:");
bw.newLine();
for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
// Write nonincludedReactionList
LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions();
bw.write("nonIncludedReactionList:");
bw.newLine();
for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
// Write pathReactionList
LinkedList pathRxns = pdepnet.getPathReactions();
bw.write("pathReactionList:");
bw.newLine();
for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toChemkinString(new Temperature(298,"K")));
bw.newLine();
}
bw.newLine();
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps,
int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) {
StringBuilder sb = new StringBuilder();
// Write the rate coefficients
double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants();
for (int i=0; i<numFameTemps; i++) {
for (int j=0; j<numFamePress; j++) {
sb.append(rateConstants[i][j] + "\t");
}
sb.append("\n");
}
sb.append("\n");
// If chebyshev polynomials are present, write them
if (numChebyTemps != 0) {
ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev();
for (int i=0; i<numChebyTemps; i++) {
for (int j=0; j<numChebyPress; j++) {
sb.append(chebyPolys.getAlpha(i,j) + "\t");
}
sb.append("\n");
}
sb.append("\n");
}
// If plog parameters are present, write them
else if (numPlog != 0) {
PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics();
for (int i=0; i<numPlog; i++) {
double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K"));
sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n");
}
sb.append("\n");
}
return sb.toString();
}
public LinkedList getTimeStep() {
return timeStep;
}
public void setTimeStep(ReactionTime p_timeStep) {
if (timeStep == null)
timeStep = new LinkedList();
timeStep.add(p_timeStep);
}
public String getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(String p_workingDirectory) {
workingDirectory = p_workingDirectory;
}
//svp
public boolean getError(){
return error;
}
//svp
public boolean getSensitivity(){
return sensitivity;
}
public LinkedList getSpeciesList() {
return species;
}
//gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem
// public ReactionSystem getReactionSystem() {
// return reactionSystem;
// }
//11/2/07 gmagoon: adding accessor method for reactionSystemList
public LinkedList getReactionSystemList(){
return reactionSystemList;
}
//added by gmagoon 9/24/07
// public void setReactionSystem(ReactionSystem p_ReactionSystem) {
// reactionSystem = p_ReactionSystem;
// }
//copied from ReactionSystem.java by gmagoon 9/24/07
public ReactionModel getReactionModel() {
return reactionModel;
}
public void readRestartSpecies() {
// Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure)
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")");
Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartCoreSpcs.add(species);
/*int species_type = 1; // reacted species
for (int i=0; i<numRxnSystems; i++) {
SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]);
speciesStatus[i].put(species, ss);
}*/
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Read in edge species
try {
FileReader in = new FileReader("Restart/edgeSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartEdgeSpcs.add(species);
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readRestartReactions() {
// Grab the IDs from the core species
int[] coreSpcsIds = new int[restartCoreSpcs.size()];
int i = 0;
for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) {
Species spcs = (Species)iter.next();
coreSpcsIds[i] = spcs.getID();
++i;
}
// Read in core reactions
try {
FileReader in = new FileReader("Restart/coreReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits);
Iterator rxnIter = restartCoreRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics(),1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
if (r.hasReverseReaction()) r.generateReverseReaction();
restartCoreRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
SeedMechanism.readThirdBodyReactions("Restart/thirdBodyReactions.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
SeedMechanism.readLindemannReactions("Restart/lindemannReactions.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
SeedMechanism.readTroeReactions("Restart/troeReactions.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
restartCoreRxns.addAll(SeedMechanism.reactionSet);
// Read in edge reactions
try {
FileReader in = new FileReader("Restart/edgeReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits);
Iterator rxnIter = restartEdgeRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics(),1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
r.generateReverseReaction();
restartEdgeRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public LinkedHashMap getRestartSpeciesStatus(int i) {
LinkedHashMap speciesStatus = new LinkedHashMap();
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader));
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
double y = 0.0;
double yprime = 0.0;
for (int j=0; j<numRxnSystems; j++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
if (j == i) {
y = Double.parseDouble(st.nextToken());
yprime = Double.parseDouble(st.nextToken());
}
}
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return speciesStatus;
}
public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) {
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error in reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
if (is.getSpeciesStatus(species) == null) {
SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0);
is.putSpeciesStatus(ss);
}
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readPDepNetworks() {
SpeciesDictionary sd = SpeciesDictionary.getInstance();
LinkedList allNetworks = PDepNetwork.getNetworks();
try {
FileReader in = new FileReader("Restart/pdepnetworks.txt");
BufferedReader reader = new BufferedReader(in);
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
String tempString = st.nextToken();
String EaUnits = st.nextToken();
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numFameTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numFamePs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numChebyTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numChebyPs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numPlogs = Integer.parseInt(st.nextToken());
double[][] rateCoefficients = new double[numFameTs][numFamePs];
double[][] chebyPolys = new double[numChebyTs][numChebyPs];
Kinetics[] plogKinetics = new Kinetics[numPlogs];
String line = ChemParser.readMeaningfulLine(reader); // line should be "PDepNetwork #"
while (line != null) {
line = ChemParser.readMeaningfulLine(reader); // line should now be "netReactionList:"
PDepNetwork newNetwork = new PDepNetwork();
LinkedList netRxns = newNetwork.getNetReactions();
LinkedList nonincludeRxns = newNetwork.getNonincludedReactions();
line = ChemParser.readMeaningfulLine(reader); // line is either data or "nonIncludedReactionList"
// If line is "nonincludedreactionlist", we need to skip over this while loop
if (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
while (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\-->");
PDepIsomer Reactants = null;
String reacts = reactsANDprods[0].trim();
if (reacts.contains("+")) {
String[] indivReacts = reacts.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc1,spc2);
} else {
String name = reacts.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc);
}
PDepIsomer Products = null;
String prods = reactsANDprods[1].trim();
if (prods.contains("+")) {
String[] indivProds = prods.split("[+]");
String name = indivProds[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivProds[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc1,spc2);
} else {
String name = prods.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc);
}
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
line = ChemParser.readMeaningfulLine(reader);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
netRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader);
}
}
// This loop ends once line == "nonIncludedReactionList"
line = ChemParser.readMeaningfulLine(reader); // line is either data or "pathReactionList"
if (!line.toLowerCase().startsWith("pathreactionList")) {
while (!line.toLowerCase().startsWith("pathreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\-->");
PDepIsomer Reactants = null;
String reacts = reactsANDprods[0].trim();
if (reacts.contains("+")) {
String[] indivReacts = reacts.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc1,spc2);
} else {
String name = reacts.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc);
}
PDepIsomer Products = null;
String prods = reactsANDprods[1].trim();
if (prods.contains("+")) {
String[] indivProds = prods.split("[+]");
String name = indivProds[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivProds[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc1,spc2);
} else {
String name = prods.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc);
}
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
line = ChemParser.readMeaningfulLine(reader);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
nonincludeRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader);
}
}
// This loop ends once line == "pathReactionList"
line = ChemParser.readMeaningfulLine(reader); // line is either data or "PDepNetwork #_" or null (end of file)
while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) {
st = new StringTokenizer(line);
int direction = Integer.parseInt(st.nextToken());
// First token is the rxn structure: A+B=C+D
// Note: Up to 3 reactants/products allowed
// : Either "=" or "=>" will separate reactants and products
String structure = st.nextToken();
// Separate the reactants from the products
boolean generateReverse = false;
String[] reactsANDprods = structure.split("\\=>");
if (reactsANDprods.length == 1) {
reactsANDprods = structure.split("[=]");
generateReverse = true;
}
sd = SpeciesDictionary.getInstance();
LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]);
LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]);
Structure s = new Structure(r,p);
s.setDirection(direction);
// Next three tokens are the modified Arrhenius parameters
double rxn_A = Double.parseDouble(st.nextToken());
double rxn_n = Double.parseDouble(st.nextToken());
double rxn_E = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
rxn_E = rxn_E / 1000;
else if (EaUnits.equals("J/mol"))
rxn_E = rxn_E / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
rxn_E = rxn_E / 4.184;
else if (EaUnits.equals("Kelvins"))
rxn_E = rxn_E * 1.987;
UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A");
UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A");
UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A");
// The remaining tokens are comments
String comments = "";
while (st.hasMoreTokens()) {
comments += st.nextToken();
}
ArrheniusKinetics k = new ArrheniusKinetics(uA,un,uE,"",1,"",comments);
Reaction pathRxn = new Reaction();
// if (direction == 1)
// pathRxn = Reaction.makeReaction(s,k,generateReverse);
// else
// pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse);
pathRxn = Reaction.makeReaction(s,k,generateReverse);
PDepIsomer Reactants = new PDepIsomer(r);
PDepIsomer Products = new PDepIsomer(p);
PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn);
newNetwork.addReaction(pdeppathrxn);
line = ChemParser.readMeaningfulLine(reader);
}
PDepNetwork.getNetworks().add(newNetwork);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* MRH 14Jan2010
*
* getSpeciesBySPCName
*
* Input: String name - Name of species, normally chemical formula followed
* by "J"s for radicals, and then (#)
* SpeciesDictionary sd
*
* This method was originally written as a complement to the method readPDepNetworks.
* jdmo found a bug with the readrestart option. The bug was that the method was
* attempting to add a null species to the Isomer list. The null species resulted
* from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the
* chemkinName present in the dictionary was SPC(48).
*
*/
public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) {
String[] nameFromNumber = name.split("\\(");
String newName = "SPC(" + nameFromNumber[1];
return sd.getSpeciesFromChemkinName(newName);
}
/**
* MRH 12-Jun-2009
*
* Function initializes the model's core and edge.
* The initial core species always consists of the species contained
* in the condition.txt file. If seed mechanisms exist, those species
* (and the reactions given in the seed mechanism) are also added to
* the core.
* The initial edge species/reactions are determined by reacting the core
* species by one full iteration.
*/
public void initializeCoreEdgeModel() {
LinkedHashSet allInitialCoreSpecies = new LinkedHashSet();
LinkedHashSet allInitialCoreRxns = new LinkedHashSet();
if (readrestart) {
readRestartReactions();
if (PDepNetwork.generateNetworks) readPDepNetworks();
allInitialCoreSpecies.addAll(restartCoreSpcs);
allInitialCoreRxns.addAll(restartCoreRxns);
}
// Add the species from the condition.txt (input) file
allInitialCoreSpecies.addAll(getSpeciesSeed());
// Add the species from the seed mechanisms, if they exist
if (hasSeedMechanisms()) {
allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet());
allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet());
}
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns);
if (readrestart) {
cerm.addUnreactedSpeciesSet(restartEdgeSpcs);
cerm.addUnreactedReactionSet(restartEdgeRxns);
}
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file and the seed mechanisms as the core
if (!readrestart) {
LinkedHashSet reactionSet;
if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
reactionSet = getReactionGenerator().react(allInitialCoreSpecies);
}
else {
reactionSet = new LinkedHashSet();
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec));
}
}
reactionSet.addAll(getLibraryReactionGenerator().react(allInitialCoreSpecies));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
}
//## operation initializeCoreEdgeModelWithPRL()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeModelWithPRL() {
//#[ operation initializeCoreEdgeModelWithPRL()
initializeCoreEdgeModelWithoutPRL();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet primarySpeciesSet = getPrimaryReactionLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary
LinkedHashSet primaryReactionSet = getPrimaryReactionLibrary().getReactionSet();
cerm.addReactedSpeciesSet(primarySpeciesSet);
cerm.addPrimaryReactionSet(primaryReactionSet);
LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet());
if (reactionModelEnlarger instanceof RateBasedRME)
cerm.addReactionSet(newReactions);
else {
Iterator iter = newReactions.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){
cerm.addReaction(r);
}
}
}
return;
//#]
}
//## operation initializeCoreEdgeModelWithoutPRL()
//9/24/07 gmagoon: moved from ReactionSystem.java
protected void initializeCoreEdgeModelWithoutPRL() {
//#[ operation initializeCoreEdgeModelWithoutPRL()
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed()));
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file as the core
LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed());
reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed()));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
//10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement
//10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
//reactionSystem.setReactionModel(getReactionModel());
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
//#]
}
//## operation initializeCoreEdgeReactionModel()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeReactionModel() {
System.out.println("\nInitializing core-edge reaction model");
// setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon:moved from initializeReactionSystem; later moved to modelGeneration()
//#[ operation initializeCoreEdgeReactionModel()
// if (hasPrimaryReactionLibrary()) initializeCoreEdgeModelWithPRL();
// else initializeCoreEdgeModelWithoutPRL();
/*
* MRH 12-Jun-2009
*
* I've lumped the initializeCoreEdgeModel w/ and w/o a seed mechanism
* (which used to be the PRL) into one function. Before, RMG would
* complete one iteration (construct the edge species/rxns) before adding
* the seed mechanism to the rxn, thereby possibly estimating kinetic
* parameters for a rxn that exists in a seed mechanism
*/
initializeCoreEdgeModel();
//#]
}
//9/24/07 gmagoon: copied from ReactionSystem.java
public ReactionGenerator getReactionGenerator() {
return reactionGenerator;
}
//10/4/07 gmagoon: moved from ReactionSystem.java
public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) {
reactionGenerator = p_ReactionGenerator;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//10/24/07 gmagoon: changed to use reactionSystemList
//## operation enlargeReactionModel()
public void enlargeReactionModel() {
//#[ operation enlargeReactionModel()
if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger");
System.out.println("\nEnlarging reaction model");
reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList);
return;
//#]
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//## operation hasPrimaryReactionLibrary()
public boolean hasPrimaryReactionLibrary() {
//#[ operation hasPrimaryReactionLibrary()
if (primaryReactionLibrary == null) return false;
return (primaryReactionLibrary.size() > 0);
//#]
}
public boolean hasSeedMechanisms() {
if (getSeedMechanism() == null) return false;
return (seedMechanism.size() > 0);
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public PrimaryReactionLibrary getPrimaryReactionLibrary() {
return primaryReactionLibrary;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public void setPrimaryReactionLibrary(PrimaryReactionLibrary p_PrimaryReactionLibrary) {
primaryReactionLibrary = p_PrimaryReactionLibrary;
}
//10/4/07 gmagoon: added
public LinkedHashSet getSpeciesSeed() {
return speciesSeed;
}
//10/4/07 gmagoon: added
public void setSpeciesSeed(LinkedHashSet p_speciesSeed) {
speciesSeed = p_speciesSeed;
}
//10/4/07 gmagoon: added
public LibraryReactionGenerator getLibraryReactionGenerator() {
return lrg;
}
//10/4/07 gmagoon: added
public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) {
lrg = p_lrg;
}
public static Temperature getTemp4BestKinetics() {
return temp4BestKinetics;
}
public static void setTemp4BestKinetics(Temperature firstSysTemp) {
temp4BestKinetics = firstSysTemp;
}
public SeedMechanism getSeedMechanism() {
return seedMechanism;
}
public void setSeedMechanism(SeedMechanism p_seedMechanism) {
seedMechanism = p_seedMechanism;
}
public PrimaryThermoLibrary getPrimaryThermoLibrary() {
return primaryThermoLibrary;
}
public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) {
primaryThermoLibrary = p_primaryThermoLibrary;
}
public static double getAtol(){
return atol;
}
public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) {
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true;
return true;
//if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions
else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented
return true;
}
}
else //the case where intermediate conversions are specified
if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed
return true;
}
return false; //return false if none of the above criteria are met
}
public void readAndMakePRL(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (Ilib==0) {
setPrimaryReactionLibrary(new PrimaryReactionLibrary(name, path));
Ilib++;
}
else {
getPrimaryReactionLibrary().appendPrimaryReactionLibrary(name,path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (Ilib==0) {
setPrimaryReactionLibrary(null);
}
else System.out.println("Primary Reaction Libraries in use: " + getPrimaryReactionLibrary().getName());
}
public void readAndMakePTL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
++numPTLs;
}
else {
getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (numPTLs == 0) setPrimaryThermoLibrary(null);
}
public void setSpectroscopicDataMode(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String sdeType = st.nextToken().toLowerCase();
if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
else if (sdeType.equals("off") || sdeType.equals("none")) {
SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
}
else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
public void setPressureDependenceType(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String pDepType = st.nextToken();
if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
pDepType.toLowerCase().equals("reservoirstate") ||
pDepType.toLowerCase().equals("chemdis")) {
reactionModelEnlarger = new RateBasedPDepRME();
PDepNetwork.generateNetworks = true;
if (pDepType.toLowerCase().equals("reservoirstate")) {
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
}
else if (pDepType.toLowerCase().equals("modifiedstrongcollision")) {
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
}
else if (pDepType.toLowerCase().equals("chemdis")) {
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
if (SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsEstimator = " + pDepType);
}
// Set temperatures and pressures to use in PDep kinetics estimation
Temperature[] temperatures = new Temperature[8];
temperatures[0] = new Temperature(300, "K");
temperatures[1] = new Temperature(400, "K");
temperatures[2] = new Temperature(600, "K");
temperatures[3] = new Temperature(900, "K");
temperatures[4] = new Temperature(1200, "K");
temperatures[5] = new Temperature(1500, "K");
temperatures[6] = new Temperature(1800, "K");
temperatures[7] = new Temperature(2100, "K");
FastMasterEqn.setTemperatures(temperatures);
PDepRateConstant.setTemperatures(temperatures);
ChebyshevPolynomials.setTlow(temperatures[0]);
ChebyshevPolynomials.setTup(temperatures[7]);
Pressure[] pressures = new Pressure[5];
pressures[0] = new Pressure(0.01, "bar");
pressures[1] = new Pressure(0.1, "bar");
pressures[2] = new Pressure(1, "bar");
pressures[3] = new Pressure(10, "bar");
pressures[4] = new Pressure(100, "bar");
FastMasterEqn.setPressures(pressures);
PDepRateConstant.setPressures(pressures);
ChebyshevPolynomials.setPlow(pressures[0]);
ChebyshevPolynomials.setPup(pressures[4]);
}
else if (pDepType.toLowerCase().equals("off")) {
// No pressure dependence
reactionModelEnlarger = new RateBasedRME();
PDepNetwork.generateNetworks = false;
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
}
}
public String setPDepKineticsModel(String line, BufferedReader reader) throws InvalidSymbolException {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String pDepKinType = st.nextToken();
if (pDepKinType.toLowerCase().equals("chebyshev") ||
pDepKinType.toLowerCase().equals("pdeparrhenius") ||
pDepKinType.toLowerCase().equals("rate")) {
if (pDepKinType.toLowerCase().equals("chebyshev")) {
PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TRange")) {
st = new StringTokenizer(line);
String temp = st.nextToken(); // Should be "TRange:"
String TUNITS = ChemParser.removeBrace(st.nextToken());
double tLow = Double.parseDouble(st.nextToken());
Temperature TMIN = new Temperature(tLow,TUNITS);
ChebyshevPolynomials.setTlow(TMIN);
double tHigh = Double.parseDouble(st.nextToken());
if (tHigh <= tLow) {
throw new InvalidSymbolException("Chebyshev Tmax is less than or equal to Tmin");
}
Temperature TMAX = new Temperature(tHigh,TUNITS);
ChebyshevPolynomials.setTup(TMAX);
if (TMAX.getK() < Global.highTemperature.getK())
throw new InvalidSymbolException("Chebyshev Tmax is lower than the highest simulation temperature "+Global.highTemperature.toString() );
if (TMIN.getK() > Global.lowTemperature.getK())
throw new InvalidSymbolException("Chebyshev Tmin is higher than the lowest simulation temperature "+Global.lowTemperature.toString() );
int tResolution = Integer.parseInt(st.nextToken());
int tbasisFuncs = Integer.parseInt(st.nextToken());
if (tbasisFuncs > tResolution) {
throw new InvalidSymbolException("The number of basis functions cannot exceed the number of grid points");
}
FastMasterEqn.setNumTBasisFuncs(tbasisFuncs);
line = ChemParser.readMeaningfulLine(reader);
String PUNITS = "";
Pressure PMIN = new Pressure();
Pressure PMAX = new Pressure();
int pResolution = 0;
int pbasisFuncs = 0;
if (line.startsWith("PRange")) {
st = new StringTokenizer(line);
temp = st.nextToken(); // Should be "PRange:"
PUNITS = ChemParser.removeBrace(st.nextToken());
double pLow = Double.parseDouble(st.nextToken());
PMIN = new Pressure(pLow,PUNITS);
ChebyshevPolynomials.setPlow(PMIN);
double pHigh = Double.parseDouble(st.nextToken());
if (pHigh <= pLow) {
System.err.println("Pmax is less than or equal to Pmin");
System.exit(0);
}
PMAX = new Pressure(pHigh,PUNITS);
if (PMAX.getPa() < Global.highPressure.getPa())
throw new InvalidSymbolException("Chebyshev Pmax is lower than the highest simulation pressure "+Global.highPressure.toString() );
if (PMIN.getPa() > Global.lowPressure.getPa())
throw new InvalidSymbolException("Chebyshev Pmin is higher than the lowest simulation pressure "+Global.lowPressure.toString() );
ChebyshevPolynomials.setPup(PMAX);
pResolution = Integer.parseInt(st.nextToken());
pbasisFuncs = Integer.parseInt(st.nextToken());
if (pbasisFuncs > pResolution) {
throw new InvalidSymbolException("The number of basis functions cannot exceed the number of grid points");
}
FastMasterEqn.setNumPBasisFuncs(pbasisFuncs);
}
else {
throw new InvalidSymbolException("RMG cannot locate PRange field for Chebyshev polynomials.");
}
// Set temperatures and pressures to use in PDep kinetics estimation
Temperature[] temperatures = new Temperature[tResolution];
for (int i=0; i<temperatures.length; i++) {
double tempValueTilda = Math.cos(i*Math.PI/(temperatures.length-1)); // roots of a Chebyshev polynomial
double tempValue = 2 / (tempValueTilda * ((1/TMAX.getK()) - (1/TMIN.getK())) + (1/TMIN.getK()) + (1/TMAX.getK()));
temperatures[temperatures.length-i-1] = new Temperature(tempValue,TUNITS);
}
FastMasterEqn.setTemperatures(temperatures);
PDepRateConstant.setTemperatures(temperatures);
Pressure[] pressures = new Pressure[pResolution];
for (int j=0; j<pressures.length; j++) {
double pressValueTilda = Math.cos(j*Math.PI/(pressures.length-1)); // roots of a Chebyshev polynomial
double pressValue = Math.pow(10,(pressValueTilda*(Math.log10(PMAX.getBar())-Math.log10(PMIN.getBar()))+Math.log10(PMIN.getBar())+Math.log10(PMAX.getBar()))/2);
pressures[pressures.length-j-1] = new Pressure(pressValue,PUNITS);
}
FastMasterEqn.setPressures(pressures);
PDepRateConstant.setPressures(pressures);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (pDepKinType.toLowerCase().equals("pdeparrhenius")) {
//PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
/*
* Updated by MRH on 10Feb2010
* Allow user to specify # of T's/P's solved for in fame &
* # of PLOG's to report
*/
PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TRange")) {
st = new StringTokenizer(line);
String temp = st.nextToken(); // Should be "TRange:"
String TUNITS = ChemParser.removeBrace(st.nextToken());
int numT = Integer.parseInt(st.nextToken());
Temperature[] listOfTs = new Temperature[numT];
int counter = 0;
while (st.hasMoreTokens()) {
listOfTs[counter] = new Temperature(Double.parseDouble(st.nextToken()),TUNITS);
++counter;
}
if (counter != numT) {
System.out.println("Warning in TRange field of PressureDependence:\n" +
"The stated number of temperatures is: " + numT +
"but the length of the temperature list is: " + counter);
}
line = ChemParser.readMeaningfulLine(reader);
String PUNITS = "";
if (line.startsWith("PRange")) {
st = new StringTokenizer(line);
temp = st.nextToken(); // Should be "PRange:"
PUNITS = ChemParser.removeBrace(st.nextToken());
int numP = Integer.parseInt(st.nextToken());
Pressure[] listOfPs = new Pressure[numP];
counter = 0;
while (st.hasMoreTokens()) {
listOfPs[counter] = new Pressure(Double.parseDouble(st.nextToken()),PUNITS);
++counter;
}
if (counter != numP) {
System.out.println("Warning in PRange field of PressureDependence:\n" +
"The stated number of pressures is: " + numT +
"but the length of the pressure list is: " + counter);
}
FastMasterEqn.setTemperatures(listOfTs);
PDepRateConstant.setTemperatures(listOfTs);
FastMasterEqn.setPressures(listOfPs);
PDepRateConstant.setPressures(listOfPs);
PDepArrheniusKinetics.setNumPressures(numP);
PDepArrheniusKinetics.setPressures(listOfPs);
}
else {
throw new InvalidSymbolException("RMG cannot locate PRange field for PDepArrhenius.");
}
line = ChemParser.readMeaningfulLine(reader);
}
}
// 6Jul2009-MRH:
// RATE mode reports p-dep rxn kinetics as: A 0.0 0.0
// where A is k(T,P) evaluated at the single temperature
// and pressure given in the condition.txt file
else if (pDepKinType.toLowerCase().equals("rate"))
PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PDepKinetics = " + pDepKinType);
}
return line;
}
public ReactionModelEnlarger getReactionModelEnlarger() {
return reactionModelEnlarger;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\rxnSys\ReactionModelGenerator.java
*********************************************************************/
| true | true | public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
//PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below
setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader);
}
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
// int numPTLs = 0;
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// String[] tempString = line.split("Name: ");
// String name = tempString[tempString.length-1].trim();
// line = ChemParser.readMeaningfulLine(reader);
// tempString = line.split("Location: ");
// String path = tempString[tempString.length-1].trim();
// if (numPTLs==0) {
// setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
// ++numPTLs;
// }
// else {
// getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
// ++numPTLs;
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (numPTLs == 0) setPrimaryThermoLibrary(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String t = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
// Global.temperature = new Temperature(t,unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PressureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String p = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
//Global.pressure = new Pressure(p, unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// // add reading curved pressure function here
// pressureModel = new CurvedPM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
speciesnum ++;
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.exit(0);
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("InertGas:")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader);
}
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence flag
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pressuredependence:")) {
setPressureDependenceType(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String pDepType = st.nextToken();
// if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
// pDepType.toLowerCase().equals("reservoirstate") ||
// pDepType.toLowerCase().equals("chemdis")) {
//
// reactionModelEnlarger = new RateBasedPDepRME();
// PDepNetwork.generateNetworks = true;
//
// if (pDepType.toLowerCase().equals("reservoirstate")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
// if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
// System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// }
// else if (pDepType.toLowerCase().equals("modifiedstrongcollision")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
// if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
// System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// }
// else if (pDepType.toLowerCase().equals("chemdis")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
// if (SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
// System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsEstimator = " + pDepType);
// }
//
// // Set temperatures and pressures to use in PDep kinetics estimation
// Temperature[] temperatures = new Temperature[8];
// temperatures[0] = new Temperature(300, "K");
// temperatures[1] = new Temperature(400, "K");
// temperatures[2] = new Temperature(600, "K");
// temperatures[3] = new Temperature(900, "K");
// temperatures[4] = new Temperature(1200, "K");
// temperatures[5] = new Temperature(1500, "K");
// temperatures[6] = new Temperature(1800, "K");
// temperatures[7] = new Temperature(2100, "K");
// FastMasterEqn.setTemperatures(temperatures);
// PDepRateConstant.setTemperatures(temperatures);
// ChebyshevPolynomials.setTlow(temperatures[0]);
// ChebyshevPolynomials.setTup(temperatures[7]);
//
// Pressure[] pressures = new Pressure[5];
// pressures[0] = new Pressure(0.01, "bar");
// pressures[1] = new Pressure(0.1, "bar");
// pressures[2] = new Pressure(1, "bar");
// pressures[3] = new Pressure(10, "bar");
// pressures[4] = new Pressure(100, "bar");
// FastMasterEqn.setPressures(pressures);
// PDepRateConstant.setPressures(pressures);
// ChebyshevPolynomials.setPlow(pressures[0]);
// ChebyshevPolynomials.setPup(pressures[4]);
//
// }
// else if (pDepType.toLowerCase().equals("off")) {
// // No pressure dependence
// reactionModelEnlarger = new RateBasedRME();
// PDepNetwork.generateNetworks = false;
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
// pressure dependence flag
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
line = setPDepKineticsModel(line,reader);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String pDepKinType = st.nextToken();
// if (pDepKinType.toLowerCase().equals("chebyshev") ||
// pDepKinType.toLowerCase().equals("pdeparrhenius") ||
// pDepKinType.toLowerCase().equals("rate")) {
//
// if (pDepKinType.toLowerCase().equals("chebyshev")) {
// PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("TRange")) {
// st = new StringTokenizer(line);
// String temp = st.nextToken(); // Should be "TRange:"
// String TUNITS = ChemParser.removeBrace(st.nextToken());
// double tLow = Double.parseDouble(st.nextToken());
// Temperature TMIN = new Temperature(tLow,TUNITS);
// ChebyshevPolynomials.setTlow(TMIN);
// double tHigh = Double.parseDouble(st.nextToken());
// if (tHigh <= tLow) {
// System.err.println("Tmax is less than or equal to Tmin");
// System.exit(0);
// }
// Temperature TMAX = new Temperature(tHigh,TUNITS);
// ChebyshevPolynomials.setTup(TMAX);
// int tResolution = Integer.parseInt(st.nextToken());
// int tbasisFuncs = Integer.parseInt(st.nextToken());
// if (tbasisFuncs > tResolution) {
// System.err.println("The number of basis functions cannot exceed the number of grid points");
// System.exit(0);
// }
// FastMasterEqn.setNumTBasisFuncs(tbasisFuncs);
// line = ChemParser.readMeaningfulLine(reader);
// String PUNITS = "";
// Pressure PMIN = new Pressure();
// Pressure PMAX = new Pressure();
// int pResolution = 0;
// int pbasisFuncs = 0;
// if (line.startsWith("PRange")) {
// st = new StringTokenizer(line);
// temp = st.nextToken(); // Should be "PRange:"
// PUNITS = ChemParser.removeBrace(st.nextToken());
// double pLow = Double.parseDouble(st.nextToken());
// PMIN = new Pressure(pLow,PUNITS);
// ChebyshevPolynomials.setPlow(PMIN);
// double pHigh = Double.parseDouble(st.nextToken());
// if (pHigh <= pLow) {
// System.err.println("Pmax is less than or equal to Pmin");
// System.exit(0);
// }
// PMAX = new Pressure(pHigh,PUNITS);
// ChebyshevPolynomials.setPup(PMAX);
// pResolution = Integer.parseInt(st.nextToken());
// pbasisFuncs = Integer.parseInt(st.nextToken());
// if (pbasisFuncs > pResolution) {
// System.err.println("The number of basis functions cannot exceed the number of grid points");
// System.exit(0);
// }
// FastMasterEqn.setNumPBasisFuncs(pbasisFuncs);
// }
// else {
// System.err.println("RMG cannot locate PRange field for Chebyshev polynomials.");
// System.exit(0);
// }
//
// // Set temperatures and pressures to use in PDep kinetics estimation
// Temperature[] temperatures = new Temperature[tResolution];
// for (int i=0; i<temperatures.length; i++) {
// double tempValueTilda = Math.cos((2*(i+1)-1)*Math.PI/(2*temperatures.length));
// double tempValue = 2 / (tempValueTilda * ((1/TMAX.getK()) - (1/TMIN.getK())) + (1/TMIN.getK()) + (1/TMAX.getK()));
// temperatures[temperatures.length-i-1] = new Temperature(tempValue,TUNITS);
// }
// FastMasterEqn.setTemperatures(temperatures);
// PDepRateConstant.setTemperatures(temperatures);
//
// Pressure[] pressures = new Pressure[pResolution];
// for (int j=0; j<pressures.length; j++) {
// double pressValueTilda = Math.cos((2*(j+1)-1)*Math.PI/(2*pressures.length));
// double pressValue = Math.pow(10,(pressValueTilda*(Math.log10(PMAX.getBar())-Math.log10(PMIN.getBar()))+Math.log10(PMIN.getBar())+Math.log10(PMAX.getBar()))/2);
// pressures[pressures.length-j-1] = new Pressure(pressValue,PUNITS);
// }
// FastMasterEqn.setPressures(pressures);
// PDepRateConstant.setPressures(pressures);
// line = ChemParser.readMeaningfulLine(reader);
// }
// }
// else if (pDepKinType.toLowerCase().equals("pdeparrhenius")) {
// //PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
// /*
// * Updated by MRH on 10Feb2010
// * Allow user to specify # of T's/P's solved for in fame &
// * # of PLOG's to report
// */
// PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("TRange")) {
// st = new StringTokenizer(line);
// String temp = st.nextToken(); // Should be "TRange:"
// String TUNITS = ChemParser.removeBrace(st.nextToken());
// int numT = Integer.parseInt(st.nextToken());
// Temperature[] listOfTs = new Temperature[numT];
// int counter = 0;
// while (st.hasMoreTokens()) {
// listOfTs[counter] = new Temperature(Double.parseDouble(st.nextToken()),TUNITS);
// ++counter;
// }
// if (counter != numT) {
// System.out.println("Warning in TRange field of PressureDependence:\n" +
// "The stated number of temperatures is: " + numT +
// "but the length of the temperature list is: " + counter);
// }
//
// line = ChemParser.readMeaningfulLine(reader);
// String PUNITS = "";
// if (line.startsWith("PRange")) {
// st = new StringTokenizer(line);
// temp = st.nextToken(); // Should be "PRange:"
// PUNITS = ChemParser.removeBrace(st.nextToken());
// int numP = Integer.parseInt(st.nextToken());
// Pressure[] listOfPs = new Pressure[numP];
// counter = 0;
// while (st.hasMoreTokens()) {
// listOfPs[counter] = new Pressure(Double.parseDouble(st.nextToken()),PUNITS);
// ++counter;
// }
// if (counter != numP) {
// System.out.println("Warning in PRange field of PressureDependence:\n" +
// "The stated number of pressures is: " + numT +
// "but the length of the pressure list is: " + counter);
// }
// FastMasterEqn.setTemperatures(listOfTs);
// PDepRateConstant.setTemperatures(listOfTs);
// FastMasterEqn.setPressures(listOfPs);
// PDepRateConstant.setPressures(listOfPs);
// PDepArrheniusKinetics.setNumPressures(numP);
// PDepArrheniusKinetics.setPressures(listOfPs);
// }
// else {
// System.err.println("RMG cannot locate PRange field for PDepArrhenius.");
// System.exit(0);
// }
//
// line = ChemParser.readMeaningfulLine(reader);
// }
// }
// // 6Jul2009-MRH:
// // RATE mode reports p-dep rxn kinetics as: A 0.0 0.0
// // where A is k(T,P) evaluated at the single temperature
// // and pressure given in the condition.txt file
// else if (pDepKinType.toLowerCase().equals("rate"))
// PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
//
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PDepKinetics = " + pDepKinType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PDepKinetics flag!");
}
// include species (optional)
if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
!PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
double tolerance;
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
// read in atol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
| public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
//PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below
setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader);
}
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
// int numPTLs = 0;
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// String[] tempString = line.split("Name: ");
// String name = tempString[tempString.length-1].trim();
// line = ChemParser.readMeaningfulLine(reader);
// tempString = line.split("Location: ");
// String path = tempString[tempString.length-1].trim();
// if (numPTLs==0) {
// setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
// ++numPTLs;
// }
// else {
// getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
// ++numPTLs;
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (numPTLs == 0) setPrimaryThermoLibrary(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String t = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
// Global.temperature = new Temperature(t,unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PressureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String p = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
//Global.pressure = new Pressure(p, unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// // add reading curved pressure function here
// pressureModel = new CurvedPM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
speciesnum ++;
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.exit(0);
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("InertGas:")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader);
}
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence flag
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pressuredependence:")) {
setPressureDependenceType(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String pDepType = st.nextToken();
// if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
// pDepType.toLowerCase().equals("reservoirstate") ||
// pDepType.toLowerCase().equals("chemdis")) {
//
// reactionModelEnlarger = new RateBasedPDepRME();
// PDepNetwork.generateNetworks = true;
//
// if (pDepType.toLowerCase().equals("reservoirstate")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
// if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
// System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// }
// else if (pDepType.toLowerCase().equals("modifiedstrongcollision")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
// if (SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
// System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// }
// else if (pDepType.toLowerCase().equals("chemdis")) {
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
// if (SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
// System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsEstimator = " + pDepType);
// }
//
// // Set temperatures and pressures to use in PDep kinetics estimation
// Temperature[] temperatures = new Temperature[8];
// temperatures[0] = new Temperature(300, "K");
// temperatures[1] = new Temperature(400, "K");
// temperatures[2] = new Temperature(600, "K");
// temperatures[3] = new Temperature(900, "K");
// temperatures[4] = new Temperature(1200, "K");
// temperatures[5] = new Temperature(1500, "K");
// temperatures[6] = new Temperature(1800, "K");
// temperatures[7] = new Temperature(2100, "K");
// FastMasterEqn.setTemperatures(temperatures);
// PDepRateConstant.setTemperatures(temperatures);
// ChebyshevPolynomials.setTlow(temperatures[0]);
// ChebyshevPolynomials.setTup(temperatures[7]);
//
// Pressure[] pressures = new Pressure[5];
// pressures[0] = new Pressure(0.01, "bar");
// pressures[1] = new Pressure(0.1, "bar");
// pressures[2] = new Pressure(1, "bar");
// pressures[3] = new Pressure(10, "bar");
// pressures[4] = new Pressure(100, "bar");
// FastMasterEqn.setPressures(pressures);
// PDepRateConstant.setPressures(pressures);
// ChebyshevPolynomials.setPlow(pressures[0]);
// ChebyshevPolynomials.setPup(pressures[4]);
//
// }
// else if (pDepType.toLowerCase().equals("off")) {
// // No pressure dependence
// reactionModelEnlarger = new RateBasedRME();
// PDepNetwork.generateNetworks = false;
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
// pressure dependence flag
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
line = setPDepKineticsModel(line,reader);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String pDepKinType = st.nextToken();
// if (pDepKinType.toLowerCase().equals("chebyshev") ||
// pDepKinType.toLowerCase().equals("pdeparrhenius") ||
// pDepKinType.toLowerCase().equals("rate")) {
//
// if (pDepKinType.toLowerCase().equals("chebyshev")) {
// PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("TRange")) {
// st = new StringTokenizer(line);
// String temp = st.nextToken(); // Should be "TRange:"
// String TUNITS = ChemParser.removeBrace(st.nextToken());
// double tLow = Double.parseDouble(st.nextToken());
// Temperature TMIN = new Temperature(tLow,TUNITS);
// ChebyshevPolynomials.setTlow(TMIN);
// double tHigh = Double.parseDouble(st.nextToken());
// if (tHigh <= tLow) {
// System.err.println("Tmax is less than or equal to Tmin");
// System.exit(0);
// }
// Temperature TMAX = new Temperature(tHigh,TUNITS);
// ChebyshevPolynomials.setTup(TMAX);
// int tResolution = Integer.parseInt(st.nextToken());
// int tbasisFuncs = Integer.parseInt(st.nextToken());
// if (tbasisFuncs > tResolution) {
// System.err.println("The number of basis functions cannot exceed the number of grid points");
// System.exit(0);
// }
// FastMasterEqn.setNumTBasisFuncs(tbasisFuncs);
// line = ChemParser.readMeaningfulLine(reader);
// String PUNITS = "";
// Pressure PMIN = new Pressure();
// Pressure PMAX = new Pressure();
// int pResolution = 0;
// int pbasisFuncs = 0;
// if (line.startsWith("PRange")) {
// st = new StringTokenizer(line);
// temp = st.nextToken(); // Should be "PRange:"
// PUNITS = ChemParser.removeBrace(st.nextToken());
// double pLow = Double.parseDouble(st.nextToken());
// PMIN = new Pressure(pLow,PUNITS);
// ChebyshevPolynomials.setPlow(PMIN);
// double pHigh = Double.parseDouble(st.nextToken());
// if (pHigh <= pLow) {
// System.err.println("Pmax is less than or equal to Pmin");
// System.exit(0);
// }
// PMAX = new Pressure(pHigh,PUNITS);
// ChebyshevPolynomials.setPup(PMAX);
// pResolution = Integer.parseInt(st.nextToken());
// pbasisFuncs = Integer.parseInt(st.nextToken());
// if (pbasisFuncs > pResolution) {
// System.err.println("The number of basis functions cannot exceed the number of grid points");
// System.exit(0);
// }
// FastMasterEqn.setNumPBasisFuncs(pbasisFuncs);
// }
// else {
// System.err.println("RMG cannot locate PRange field for Chebyshev polynomials.");
// System.exit(0);
// }
//
// // Set temperatures and pressures to use in PDep kinetics estimation
// Temperature[] temperatures = new Temperature[tResolution];
// for (int i=0; i<temperatures.length; i++) {
// double tempValueTilda = Math.cos((2*(i+1)-1)*Math.PI/(2*temperatures.length));
// double tempValue = 2 / (tempValueTilda * ((1/TMAX.getK()) - (1/TMIN.getK())) + (1/TMIN.getK()) + (1/TMAX.getK()));
// temperatures[temperatures.length-i-1] = new Temperature(tempValue,TUNITS);
// }
// FastMasterEqn.setTemperatures(temperatures);
// PDepRateConstant.setTemperatures(temperatures);
//
// Pressure[] pressures = new Pressure[pResolution];
// for (int j=0; j<pressures.length; j++) {
// double pressValueTilda = Math.cos((2*(j+1)-1)*Math.PI/(2*pressures.length));
// double pressValue = Math.pow(10,(pressValueTilda*(Math.log10(PMAX.getBar())-Math.log10(PMIN.getBar()))+Math.log10(PMIN.getBar())+Math.log10(PMAX.getBar()))/2);
// pressures[pressures.length-j-1] = new Pressure(pressValue,PUNITS);
// }
// FastMasterEqn.setPressures(pressures);
// PDepRateConstant.setPressures(pressures);
// line = ChemParser.readMeaningfulLine(reader);
// }
// }
// else if (pDepKinType.toLowerCase().equals("pdeparrhenius")) {
// //PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
// /*
// * Updated by MRH on 10Feb2010
// * Allow user to specify # of T's/P's solved for in fame &
// * # of PLOG's to report
// */
// PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
// line = ChemParser.readMeaningfulLine(reader);
// if (line.startsWith("TRange")) {
// st = new StringTokenizer(line);
// String temp = st.nextToken(); // Should be "TRange:"
// String TUNITS = ChemParser.removeBrace(st.nextToken());
// int numT = Integer.parseInt(st.nextToken());
// Temperature[] listOfTs = new Temperature[numT];
// int counter = 0;
// while (st.hasMoreTokens()) {
// listOfTs[counter] = new Temperature(Double.parseDouble(st.nextToken()),TUNITS);
// ++counter;
// }
// if (counter != numT) {
// System.out.println("Warning in TRange field of PressureDependence:\n" +
// "The stated number of temperatures is: " + numT +
// "but the length of the temperature list is: " + counter);
// }
//
// line = ChemParser.readMeaningfulLine(reader);
// String PUNITS = "";
// if (line.startsWith("PRange")) {
// st = new StringTokenizer(line);
// temp = st.nextToken(); // Should be "PRange:"
// PUNITS = ChemParser.removeBrace(st.nextToken());
// int numP = Integer.parseInt(st.nextToken());
// Pressure[] listOfPs = new Pressure[numP];
// counter = 0;
// while (st.hasMoreTokens()) {
// listOfPs[counter] = new Pressure(Double.parseDouble(st.nextToken()),PUNITS);
// ++counter;
// }
// if (counter != numP) {
// System.out.println("Warning in PRange field of PressureDependence:\n" +
// "The stated number of pressures is: " + numT +
// "but the length of the pressure list is: " + counter);
// }
// FastMasterEqn.setTemperatures(listOfTs);
// PDepRateConstant.setTemperatures(listOfTs);
// FastMasterEqn.setPressures(listOfPs);
// PDepRateConstant.setPressures(listOfPs);
// PDepArrheniusKinetics.setNumPressures(numP);
// PDepArrheniusKinetics.setPressures(listOfPs);
// }
// else {
// System.err.println("RMG cannot locate PRange field for PDepArrhenius.");
// System.exit(0);
// }
//
// line = ChemParser.readMeaningfulLine(reader);
// }
// }
// // 6Jul2009-MRH:
// // RATE mode reports p-dep rxn kinetics as: A 0.0 0.0
// // where A is k(T,P) evaluated at the single temperature
// // and pressure given in the condition.txt file
// else if (pDepKinType.toLowerCase().equals("rate"))
// PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
//
// }
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PDepKinetics = " + pDepKinType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PDepKinetics flag!");
}
// include species (optional)
if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
!PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
double tolerance;
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
// read in atol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
|
diff --git a/src/ibis/satin/impl/Stats.java b/src/ibis/satin/impl/Stats.java
index 110652a2..6171e17c 100644
--- a/src/ibis/satin/impl/Stats.java
+++ b/src/ibis/satin/impl/Stats.java
@@ -1,770 +1,771 @@
/* $Id$ */
package ibis.satin.impl;
import ibis.util.Timer;
public abstract class Stats extends SharedObjects {
protected StatsMessage createStats() {
StatsMessage s = new StatsMessage();
s.spawns = spawns;
s.jobsExecuted = jobsExecuted;
s.syncs = syncs;
s.aborts = aborts;
s.abortMessages = abortMessages;
s.abortedJobs = abortedJobs;
s.stealAttempts = stealAttempts;
s.stealSuccess = stealSuccess;
s.tupleMsgs = tupleMsgs;
s.tupleBytes = tupleBytes;
s.stolenJobs = stolenJobs;
s.stealRequests = stealRequests;
s.interClusterMessages = interClusterMessages;
s.intraClusterMessages = intraClusterMessages;
s.interClusterBytes = interClusterBytes;
s.intraClusterBytes = intraClusterBytes;
s.stealTime = stealTimer.totalTimeVal();
s.handleStealTime = handleStealTimer.totalTimeVal();
s.abortTime = abortTimer.totalTimeVal();
s.idleTime = idleTimer.totalTimeVal();
s.idleCount = idleTimer.nrTimes();
s.pollTime = pollTimer.totalTimeVal();
s.pollCount = pollTimer.nrTimes();
s.tupleTime = tupleTimer.totalTimeVal();
s.handleTupleTime = handleTupleTimer.totalTimeVal();
s.tupleWaitTime = tupleOrderingWaitTimer.totalTimeVal();
s.tupleWaitCount = tupleOrderingWaitTimer.nrTimes();
s.invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal();
s.invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes();
s.invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal();
s.invocationRecordReadCount = invocationRecordReadTimer.nrTimes();
s.returnRecordWriteTime = returnRecordWriteTimer.totalTimeVal();
s.returnRecordWriteCount = returnRecordWriteTimer.nrTimes();
s.returnRecordReadTime = returnRecordReadTimer.totalTimeVal();
s.returnRecordReadCount = returnRecordReadTimer.nrTimes();
s.returnRecordBytes = returnRecordBytes;
//fault tolerance
if (FAULT_TOLERANCE) {
s.tableResultUpdates = globalResultTable.numResultUpdates;
s.tableLockUpdates = globalResultTable.numLockUpdates;
s.tableUpdateMessages = globalResultTable.numUpdateMessages;
s.tableLookups = globalResultTable.numLookups;
s.tableSuccessfulLookups = globalResultTable.numLookupsSucceded;
s.tableRemoteLookups = globalResultTable.numRemoteLookups;
s.killedOrphans = killedOrphans;
s.restartedJobs = restartedJobs;
s.tableLookupTime = lookupTimer.totalTimeVal();
s.tableUpdateTime = updateTimer.totalTimeVal();
s.tableHandleUpdateTime = handleUpdateTimer.totalTimeVal();
s.tableHandleLookupTime = handleLookupTimer.totalTimeVal();
s.tableSerializationTime = tableSerializationTimer.totalTimeVal();
s.tableDeserializationTime = tableDeserializationTimer
.totalTimeVal();
s.tableCheckTime = redoTimer.totalTimeVal();
s.crashHandlingTime = crashTimer.totalTimeVal();
s.addReplicaTime = addReplicaTimer.totalTimeVal();
}
if (SHARED_OBJECTS) {
s.soInvocations = soInvocations;
s.soInvocationsBytes = soInvocationsBytes;
s.soTransfers = soTransfers;
s.soTransfersBytes = soTransfersBytes;
s.handleSOInvocationsTime = handleSOInvocationsTimer.totalTimeVal();
s.broadcastSOInvocationsTime = broadcastSOInvocationsTimer
.totalTimeVal();
s.soTransferTime = soTransferTimer.totalTimeVal();
s.soSerializationTime = soSerializationTimer.totalTimeVal();
s.soDeserializationTime = soDeserializationTimer.totalTimeVal();
s.soBcastTime = soBroadcastTransferTimer.totalTimeVal();
s.soBcastSerializationTime = soBroadcastSerializationTimer.totalTimeVal();
s.soBcastDeserializationTime = soBroadcastDeserializationTimer.totalTimeVal();
s.soRealMessageCount = soRealMessageCount;
s.soBcasts = soBcasts;
s.soBcastBytes = soBcastBytes;
}
return s;
}
private double perStats(double tm, long cnt) {
if (cnt == 0) {
return 0.0;
}
return tm / cnt;
}
protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats(totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats(totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_CALLS: "
+ nf.format(totalStats.soInvocations) + " invocations, "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: "
+ nf.format(totalStats.soTransfers) + " transfers, "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST: "
+ nf.format(totalStats.soBcasts) + " bcasts, "
+ nf.format(totalStats.soBcastBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_BCASTS: total "
+ Timer.format(totalStats.soBcastTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION: total "
+ Timer.format(totalStats.soBcastSerializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastSerializationTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(totalStats.soBcastDeserializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastDeserializationTime,
totalStats.soBcasts)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
+ - totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime
+ - totalStats.returnRecordReadTime - totalStats.returnRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double soBcastTime = totalStats.soBcastTime / size;
double soBcastPerc = soBcastTime / totalTimer.totalTimeVal()
* 100;
double soBcastSerializationTime = totalStats.soBcastSerializationTime / size;
double soBcastSerializationPerc = soBcastSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soBcastDeserializationTime = totalStats.soBcastDeserializationTime / size;
double soBcastDeserializationPerc = soBcastDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime + soDeserializationTime
+ soBcastTime + soBcastDeserializationTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
out.println("SATIN: SO_BCASTS: avg. per machine "
+ Timer.format(soBcastTime) + " ( "
+ pf.format(soBcastPerc) + " %)");
out.println("SATIN: SO_BCAST_SERIALIZATION: avg. per machine "
+ Timer.format(soBcastSerializationTime) + " ( "
+ pf.format(soBcastSerializationPerc) + " %)");
out.println("SATIN: SO_BCAST_DESERIALIZATION: avg. per machine "
+ Timer.format(soBcastDeserializationTime) + " ( "
+ pf.format(soBcastDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
protected void printDetailedStats() {
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
if (SPAWN_STATS) {
out.println("SATIN '" + ident + "': SPAWN_STATS: spawns = "
+ spawns + " executed = " + jobsExecuted + " syncs = " + syncs);
if (ABORTS) {
out.println("SATIN '" + ident + "': ABORT_STATS 1: aborts = "
+ aborts + " abort msgs = " + abortMessages
+ " aborted jobs = " + abortedJobs);
}
}
if (TUPLE_STATS) {
out.println("SATIN '" + ident
+ "': TUPLE_STATS 1: tuple bcast msgs: " + tupleMsgs
+ ", bytes = " + nf.format(tupleBytes));
}
if (STEAL_STATS) {
out.println("SATIN '" + ident + "': INTRA_STATS: messages = "
+ intraClusterMessages + ", bytes = "
+ nf.format(intraClusterBytes));
out.println("SATIN '" + ident + "': INTER_STATS: messages = "
+ interClusterMessages + ", bytes = "
+ nf.format(interClusterBytes));
out.println("SATIN '" + ident + "': STEAL_STATS 1: attempts = "
+ stealAttempts + " success = " + stealSuccess + " ("
+ (perStats(stealSuccess, stealAttempts) * 100.0)
+ " %)");
out.println("SATIN '" + ident + "': STEAL_STATS 2: requests = "
+ stealRequests + " jobs stolen = " + stolenJobs);
if (STEAL_TIMING) {
out.println("SATIN '" + ident + "': STEAL_STATS 3: attempts = "
+ stealTimer.nrTimes() + " total time = "
+ stealTimer.totalTime() + " avg time = "
+ stealTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 4: handleSteals = "
+ handleStealTimer.nrTimes() + " total time = "
+ handleStealTimer.totalTime() + " avg time = "
+ handleStealTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 5: invocationRecordWrites = "
+ invocationRecordWriteTimer.nrTimes() + " total time = "
+ invocationRecordWriteTimer.totalTime() + " avg time = "
+ invocationRecordWriteTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 6: invocationRecordReads = "
+ invocationRecordReadTimer.nrTimes() + " total time = "
+ invocationRecordReadTimer.totalTime() + " avg time = "
+ invocationRecordReadTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 7: returnRecordWrites = "
+ returnRecordWriteTimer.nrTimes() + " total time = "
+ returnRecordWriteTimer.totalTime() + " avg time = "
+ returnRecordWriteTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 8: returnRecordReads = "
+ returnRecordReadTimer.nrTimes() + " total time = "
+ returnRecordReadTimer.totalTime() + " avg time = "
+ returnRecordReadTimer.averageTime());
}
if (ABORTS && ABORT_TIMING) {
out.println("SATIN '" + ident + "': ABORT_STATS 2: aborts = "
+ abortTimer.nrTimes() + " total time = "
+ abortTimer.totalTime() + " avg time = "
+ abortTimer.averageTime());
}
if (IDLE_TIMING) {
out.println("SATIN '" + ident + "': IDLE_STATS: idle count = "
+ idleTimer.nrTimes() + " total time = "
+ idleTimer.totalTime() + " avg time = "
+ idleTimer.averageTime());
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN '" + ident + "': POLL_STATS: poll count = "
+ pollTimer.nrTimes() + " total time = "
+ pollTimer.totalTime() + " avg time = "
+ pollTimer.averageTime());
}
if (STEAL_TIMING && IDLE_TIMING) {
out.println("SATIN '"
+ ident
+ "': COMM_STATS: software comm time = "
+ Timer.format(stealTimer.totalTimeVal()
+ handleStealTimer.totalTimeVal()
- idleTimer.totalTimeVal()));
}
if (TUPLE_TIMING) {
out.println("SATIN '" + ident + "': TUPLE_STATS 2: bcasts = "
+ tupleTimer.nrTimes() + " total time = "
+ tupleTimer.totalTime() + " avg time = "
+ tupleTimer.averageTime());
out.println("SATIN '" + ident + "': TUPLE_STATS 3: waits = "
+ tupleOrderingWaitTimer.nrTimes() + " total time = "
+ tupleOrderingWaitTimer.totalTime() + " avg time = "
+ tupleOrderingWaitTimer.averageTime());
}
algorithm.printStats(out);
}
if (FAULT_TOLERANCE) {
if (GRT_STATS) {
out.println("SATIN '" + ident + "': "
+ globalResultTable.numResultUpdates
+ " result updates of the table.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numLockUpdates
+ " lock updates of the table.");
out
.println("SATIN '" + ident + "': "
+ globalResultTable.numUpdateMessages
+ " update messages.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numLookupsSucceded
+ " lookups succeded, of which:");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numRemoteLookups + " remote lookups.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.maxNumEntries + " entries maximally.");
}
if (GRT_TIMING) {
out.println("SATIN '" + ident + "': " + lookupTimer.totalTime()
+ " spent in lookups");
out.println("SATIN '" + ident + "': "
+ lookupTimer.averageTime() + " per lookup");
out.println("SATIN '" + ident + "': " + updateTimer.totalTime()
+ " spent in updates");
out.println("SATIN '" + ident + "': "
+ updateTimer.averageTime() + " per update");
out.println("SATIN '" + ident + "': "
+ handleUpdateTimer.totalTime()
+ " spent in handling updates");
out.println("SATIN '" + ident + "': "
+ handleUpdateTimer.averageTime() + " per update handle");
out.println("SATIN '" + ident + "': "
+ handleLookupTimer.totalTime()
+ " spent in handling lookups");
out.println("SATIN '" + ident + "': "
+ handleLookupTimer.averageTime() + " per lookup handle");
}
if (CRASH_TIMING) {
out.println("SATIN '" + ident + "': " + crashTimer.totalTime()
+ " spent in handling crashes");
}
if (TABLE_CHECK_TIMING) {
out.println("SATIN '" + ident + "': " + redoTimer.totalTime()
+ " spent in redoing");
}
if (FT_STATS) {
out.println("SATIN '" + ident + "': " + killedOrphans
+ " orphans killed");
out.println("SATIN '" + ident + "': " + restartedJobs
+ " jobs restarted");
}
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN '" + ident.name() + "': " + soInvocations
+ " shared object invocations sent.");
out.println("SATIN '" + ident.name() + "': " + soTransfers
+ " shared objects transfered.");
}
}
}
| true | true | protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats(totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats(totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_CALLS: "
+ nf.format(totalStats.soInvocations) + " invocations, "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: "
+ nf.format(totalStats.soTransfers) + " transfers, "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST: "
+ nf.format(totalStats.soBcasts) + " bcasts, "
+ nf.format(totalStats.soBcastBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_BCASTS: total "
+ Timer.format(totalStats.soBcastTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION: total "
+ Timer.format(totalStats.soBcastSerializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastSerializationTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(totalStats.soBcastDeserializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastDeserializationTime,
totalStats.soBcasts)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double soBcastTime = totalStats.soBcastTime / size;
double soBcastPerc = soBcastTime / totalTimer.totalTimeVal()
* 100;
double soBcastSerializationTime = totalStats.soBcastSerializationTime / size;
double soBcastSerializationPerc = soBcastSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soBcastDeserializationTime = totalStats.soBcastDeserializationTime / size;
double soBcastDeserializationPerc = soBcastDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime + soDeserializationTime
+ soBcastTime + soBcastDeserializationTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
out.println("SATIN: SO_BCASTS: avg. per machine "
+ Timer.format(soBcastTime) + " ( "
+ pf.format(soBcastPerc) + " %)");
out.println("SATIN: SO_BCAST_SERIALIZATION: avg. per machine "
+ Timer.format(soBcastSerializationTime) + " ( "
+ pf.format(soBcastSerializationPerc) + " %)");
out.println("SATIN: SO_BCAST_DESERIALIZATION: avg. per machine "
+ Timer.format(soBcastDeserializationTime) + " ( "
+ pf.format(soBcastDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
| protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats(totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats(totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_CALLS: "
+ nf.format(totalStats.soInvocations) + " invocations, "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFER: "
+ nf.format(totalStats.soTransfers) + " transfers, "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
out.println("SATIN: SO_BCAST: "
+ nf.format(totalStats.soBcasts) + " bcasts, "
+ nf.format(totalStats.soBcastBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_BCASTS: total "
+ Timer.format(totalStats.soBcastTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_SERIALIZATION: total "
+ Timer.format(totalStats.soBcastSerializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastSerializationTime,
totalStats.soBcasts)));
out.println("SATIN: SO_BCAST_DESERIALIZATION: total "
+ Timer.format(totalStats.soBcastDeserializationTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.soBcastDeserializationTime,
totalStats.soBcasts)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime
- totalStats.returnRecordReadTime - totalStats.returnRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double soBcastTime = totalStats.soBcastTime / size;
double soBcastPerc = soBcastTime / totalTimer.totalTimeVal()
* 100;
double soBcastSerializationTime = totalStats.soBcastSerializationTime / size;
double soBcastSerializationPerc = soBcastSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soBcastDeserializationTime = totalStats.soBcastDeserializationTime / size;
double soBcastDeserializationPerc = soBcastDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime + soDeserializationTime
+ soBcastTime + soBcastDeserializationTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
out.println("SATIN: SO_BCASTS: avg. per machine "
+ Timer.format(soBcastTime) + " ( "
+ pf.format(soBcastPerc) + " %)");
out.println("SATIN: SO_BCAST_SERIALIZATION: avg. per machine "
+ Timer.format(soBcastSerializationTime) + " ( "
+ pf.format(soBcastSerializationPerc) + " %)");
out.println("SATIN: SO_BCAST_DESERIALIZATION: avg. per machine "
+ Timer.format(soBcastDeserializationTime) + " ( "
+ pf.format(soBcastDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
|
diff --git a/src/gui/org/pathvisio/gui/swing/propertypanel/TypedProperty.java b/src/gui/org/pathvisio/gui/swing/propertypanel/TypedProperty.java
index 955fbb58..ec103691 100644
--- a/src/gui/org/pathvisio/gui/swing/propertypanel/TypedProperty.java
+++ b/src/gui/org/pathvisio/gui/swing/propertypanel/TypedProperty.java
@@ -1,716 +1,716 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2009 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.gui.swing.propertypanel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import org.bridgedb.DataSource;
import org.bridgedb.bio.Organism;
import org.pathvisio.gui.swing.SwingEngine;
import org.pathvisio.gui.swing.dialogs.PathwayElementDialog;
import org.pathvisio.model.DataNodeType;
import org.pathvisio.model.GroupStyle;
import org.pathvisio.model.LineStyle;
import org.pathvisio.model.LineType;
import org.pathvisio.model.OrientationType;
import org.pathvisio.model.OutlineType;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.model.PropertyType;
import org.pathvisio.model.ShapeType;
import org.pathvisio.view.VPathway;
/**
* TypedProperty ties together functionality to view / edit a property
* on one or more PathwayElements at the same time
*/
public class TypedProperty implements Comparable<TypedProperty> {
Collection<PathwayElement> elements;
Object value;
Object type;
boolean different;
/**
* @param type is either String for a dynamic property,
* or PropertyType for a static property;
* @param aVPathway is used to register undo actions when setting a value
* to this property. May be null, in which case no undo actions are registered.
*/
public TypedProperty(VPathway aVPathway, Object aType) {
type = aType;
if (!(type instanceof String || type instanceof PropertyType))
{
throw new IllegalArgumentException();
}
vPathway = aVPathway;
elements = new HashSet<PathwayElement>();
}
/**
* Add a PathwayElement to the set of elements that are viewed / edited together
*/
public void addElement(PathwayElement e) {
elements.add(e);
refreshValue();
}
/**
* Remove a PathwayElement to the set of elements that are viewed / edited together
*/
public void removeElement(PathwayElement e) {
elements.remove(e);
refreshValue();
}
/**
* Refresh the viewer / editor value by checking all PathwayElements
* This notifies the TypedProperty that one of the PathwayElements has changed
* or that the PathwayElement list has been changed, and a new value should be cached.
*/
public void refreshValue() {
boolean first = true;
for(PathwayElement e : elements) {
Object o = e.getPropertyEx(type);
if(!first && (o == null || !o.equals(value))) {
different = true;
return;
}
value = o;
first = false;
}
}
/**
* Number of PathwayElement's being edited / viewed
*/
public int elementCount() { return elements.size(); }
/**
* Get a description for the property being edited.
*/
public String getDesc()
{
if (type instanceof PropertyType)
{
return ((PropertyType)type).desc();
}
else
{
return type.toString();
}
}
/**
* Set a value for the property being edited.
* This will update all PathwayElements that are being edited at once.
*/
public void setValue(Object value) {
this.value = value;
if(value != null) {
if (vPathway != null)
{
vPathway.getUndoManager().newAction (
"Change " + type + " property");
}
for(PathwayElement e : elements) {
e.setPropertyEx(type, value);
}
}
}
/**
* The value of the property being viewed / edited.
* This value is cached, call refreshValue() to update the cache.
*/
public Object getValue() {
return value;
}
/**
* The type of the property being edited. This is a String
* if the property is dynamic, or a PropertyType is the property
* is static. (See PathwayElement for an explanation of static / dynamic)
*/
public Object getType() {
return type;
}
/**
* Returns true if the PathwayElement's being edited differ for this Property.
*/
public boolean hasDifferentValues() { return different; }
private VPathway vPathway;
/**
* Returns a TableCellRenderer suitable for rendering this property
*/
public TableCellRenderer getCellRenderer()
{
if(hasDifferentValues()) return differentRenderer;
if (type instanceof PropertyType) switch(((PropertyType)type).type()) {
case COLOR:
return colorRenderer;
case LINETYPE:
return lineTypeRenderer;
case LINESTYLE:
return lineStyleRenderer;
case DATASOURCE:
{
//TODO Make use of DataSourceModel for datasources
Set<DataSource> dataSources = DataSource.getFilteredSet(true, null, null);
if(dataSources.size() != datasourceRenderer.getItemCount()) {
Object[] labels = new Object[dataSources.size()];
Object[] values = new Object[dataSources.size()];
int i = 0;
for(DataSource s : dataSources) {
labels[i] = s.getFullName();
values[i] = s;
i++;
}
datasourceRenderer.updateData(labels, values);
}
return datasourceRenderer;
}
case BOOLEAN:
return checkboxRenderer;
case ORIENTATION:
return orientationRenderer;
case ORGANISM:
return organismRenderer;
case ANGLE:
return angleRenderer;
case DOUBLE:
return doubleRenderer;
case FONT:
return fontRenderer;
case SHAPETYPE:
return shapeTypeRenderer;
case OUTLINETYPE:
return outlineTypeRenderer;
case GENETYPE:
return datanodeTypeRenderer;
}
return null;
}
/**
* Returns a TableCellEditor suitable for editing this property.
*
* @param swingEngine: the comments editor requires a connection to swingEngine, so you need to pass it here.
*/
public TableCellEditor getCellEditor(SwingEngine swingEngine) {
if (type instanceof PropertyType) switch(((PropertyType)type).type()) {
case BOOLEAN:
return checkboxEditor;
case DATASOURCE:
{
List<DataSource> dataSources = new ArrayList<DataSource>();
dataSources.addAll (DataSource.getFilteredSet(true, null,
Organism.fromLatinName(vPathway.getPathwayModel().getMappInfo().getOrganism())));
if(dataSources.size() != datasourceEditor.getItemCount())
{
Collections.sort (dataSources, new Comparator<DataSource>() {
public int compare(DataSource arg0, DataSource arg1)
{
- return arg0.getFullName().toLowerCase().compareTo(arg1.getFullName().toLowerCase());
+ return ("" + arg0.getFullName()).toLowerCase().compareTo(("" + arg1.getFullName()).toLowerCase());
}});
Object[] labels = new Object[dataSources.size()];
Object[] values = new Object[dataSources.size()];
int i = 0;
for(DataSource s : dataSources) {
- labels[i] = s.getFullName();
+ labels[i] = s.getFullName() == null ? s.getSystemCode() : s.getFullName();
values[i] = s;
i++;
}
datasourceEditor.updateData(labels, values);
}
return datasourceEditor;
}
case COLOR:
return colorEditor;
case LINETYPE:
return lineTypeEditor;
case LINESTYLE:
return lineStyleEditor;
case ORIENTATION:
return orientationEditor;
case ORGANISM:
return organismEditor;
case ANGLE:
return angleEditor;
case DOUBLE:
return doubleEditor;
case INTEGER:
return integerEditor;
case FONT:
return fontEditor;
case SHAPETYPE:
return shapeTypeEditor;
case COMMENTS:
CommentsEditor commentsEditor = new CommentsEditor(swingEngine);
commentsEditor.setInput(this);
return commentsEditor;
case OUTLINETYPE:
return outlineTypeEditor;
case GENETYPE:
return datanodeTypeEditor;
case GROUPSTYLETYPE:
return groupStyleEditor;
default:
return null;
}
else return null;
}
/**
* Return the first of the set of PathwayElement's
*/
private PathwayElement getFirstElement() {
PathwayElement first;
//TODO: weird way of getting first element?
for(first = (PathwayElement)elements.iterator().next();;) break;
return first;
}
private static class DoubleEditor extends DefaultCellEditor {
public DoubleEditor() {
super(new JTextField());
}
public Object getCellEditorValue() {
String value = ((JTextField)getComponent()).getText();
Double d = new Double(0);
try {
d = Double.parseDouble(value);
} catch(Exception e) {
//ignore
}
return d;
}
}
private static class IntegerEditor extends DefaultCellEditor {
public IntegerEditor() {
super(new JTextField());
}
public Object getCellEditorValue() {
String value = ((JTextField)getComponent()).getText();
Integer i = new Integer(0);
try {
i = Integer.parseInt(value);
} catch(Exception e) {
//ignore
}
return i;
}
}
private static class AngleEditor extends DefaultCellEditor {
public AngleEditor() {
super(new JTextField());
}
public Object getCellEditorValue() {
String value = ((JTextField)getComponent()).getText();
Double d = new Double(0);
try {
d = Double.parseDouble(value) * Math.PI / 180;
} catch(Exception e) {
//ignore
}
return d;
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
value = (Double)(value) * 180.0 / Math.PI;
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
//TODO: merge with ComboRenderer
private static class ComboEditor extends DefaultCellEditor {
Map<Object, Object> label2value;
Map<Object, Object> value2label;
boolean useIndex;
JComboBox combo;
public ComboEditor(boolean editable, Object[] labels, boolean useIndex) {
this(labels, useIndex);
combo.setEditable(editable);
}
public ComboEditor(Object[] labels, boolean useIndex) {
super(new JComboBox(labels));
combo = (JComboBox)getComponent();
this.useIndex = useIndex;
}
public ComboEditor(Object[] labels, Object[] values) {
this(labels, false);
if(values != null) {
updateData(labels, values);
}
}
public int getItemCount() {
return label2value.size();
}
public void updateData(Object[] labels, Object[] values) {
combo.setModel(new DefaultComboBoxModel(labels));
if(values != null) {
if(labels.length != values.length) {
throw new IllegalArgumentException("Number of labels doesn't equal number of values");
}
if(label2value == null) label2value = new HashMap<Object, Object>();
else label2value.clear();
if(value2label == null) value2label = new HashMap<Object, Object>();
else value2label.clear();
for(int i = 0; i < labels.length; i++) {
label2value.put(labels[i], values[i]);
value2label.put(values[i], labels[i]);
}
}
}
public Object getCellEditorValue() {
if(label2value == null) { //Use index
JComboBox cb = (JComboBox)getComponent();
return useIndex ? cb.getSelectedIndex() : cb.getSelectedItem();
} else {
Object label = super.getCellEditorValue();
return label2value.get(label);
}
}
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
if(value2label != null) {
value = value2label.get(value);
}
if(useIndex) {
combo.setSelectedIndex((Integer)value);
} else {
combo.setSelectedItem(value);
}
return combo;
}
}
private static class CommentsEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
static final String BUTTON_LABEL = "View/edit comments";
JButton button;
PathwayElement currentElement;
TypedProperty property;
protected static final String EDIT = "edit";
private SwingEngine swingEngine;
public CommentsEditor(SwingEngine swingEngine) {
this.swingEngine = swingEngine;
button = new JButton();
button.setText(BUTTON_LABEL);
button.setActionCommand("edit");
button.addActionListener(this);
}
public void setInput(TypedProperty p) {
property = p;
button.setText("");
if(!mayEdit()) fireEditingCanceled();
button.setText(BUTTON_LABEL);
}
boolean mayEdit() { return property.elements.size() == 1; }
public void actionPerformed(ActionEvent e) {
if(!mayEdit()) {
fireEditingCanceled();
return;
}
if (EDIT.equals(e.getActionCommand()) && property != null) {
currentElement = property.getFirstElement();
if(currentElement != null) {
PathwayElementDialog d = PathwayElementDialog.getInstance(swingEngine, currentElement, false, null, this.button);
d.selectPathwayElementPanel(PathwayElementDialog.TAB_COMMENTS);
d.setVisible(true);
fireEditingCanceled(); //Value is directly saved in dialog
}
}
}
public Object getCellEditorValue() {
return currentElement.getComments();
}
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
return button;
}
}
private static class ColorEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
Color currentColor;
JButton button;
JDialog dialog;
protected static final String EDIT = "edit";
public ColorEditor() {
button = new JButton();
button.setActionCommand("edit");
button.addActionListener(this);
button.setBorderPainted(false);
}
public void actionPerformed(ActionEvent e) {
if (EDIT.equals(e.getActionCommand())) {
button.setBackground(currentColor);
Color newColor = JColorChooser.showDialog(button, "Choose a color", currentColor);
if(newColor != null) currentColor = newColor;
fireEditingStopped(); //Make the renderer reappear
}
}
public Object getCellEditorValue() {
return currentColor;
}
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
currentColor = (Color)value;
return button;
}
}
private static ColorRenderer colorRenderer = new ColorRenderer();
private static ComboRenderer lineTypeRenderer = new ComboRenderer(LineType.getNames(), LineType.getValues());
private static ComboRenderer lineStyleRenderer = new ComboRenderer(LineStyle.getNames());
private static ComboRenderer datasourceRenderer = new ComboRenderer(new String[] {}, new String[] {});//data will be added on first use
private static CheckBoxRenderer checkboxRenderer = new CheckBoxRenderer();
private static ComboRenderer orientationRenderer = new ComboRenderer(OrientationType.getNames());
private static ComboRenderer organismRenderer = new ComboRenderer(Organism.latinNames().toArray());
private static FontRenderer fontRenderer = new FontRenderer();
private static ComboRenderer shapeTypeRenderer = new ComboRenderer(ShapeType.getNames(), ShapeType.getValues());
private static ComboRenderer outlineTypeRenderer = new ComboRenderer(OutlineType.getTags(), OutlineType.values());
private static ComboRenderer datanodeTypeRenderer = new ComboRenderer(DataNodeType.getNames());
private static ColorEditor colorEditor = new ColorEditor();
private static ComboEditor lineTypeEditor = new ComboEditor(LineType.getNames(), LineType.getValues());
private static ComboEditor lineStyleEditor = new ComboEditor(LineStyle.getNames(), true);
private static ComboEditor outlineTypeEditor = new ComboEditor(OutlineType.getTags(), OutlineType.values());
private static ComboEditor datasourceEditor = new ComboEditor(new String[] {}, new String[] {}); //data will be added on first use
private static DefaultCellEditor checkboxEditor = new DefaultCellEditor(new JCheckBox());
private static ComboEditor orientationEditor = new ComboEditor(OrientationType.getNames(), true);
private static ComboEditor organismEditor = new ComboEditor(true, Organism.latinNames().toArray(), false);
private static AngleEditor angleEditor = new AngleEditor();
private static DoubleEditor doubleEditor = new DoubleEditor();
private static IntegerEditor integerEditor = new IntegerEditor();
private static ComboEditor fontEditor = new ComboEditor(GraphicsEnvironment
.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(), false);
private static ComboEditor shapeTypeEditor= new ComboEditor(ShapeType.getValues(), false);
private static ComboEditor groupStyleEditor = new ComboEditor(GroupStyle.getNames(), false);
private static DefaultTableCellRenderer angleRenderer = new DefaultTableCellRenderer() {
protected void setValue(Object value) {
super.setValue( (Double)(value) * 180.0 / Math.PI );
}
};
private static ComboEditor datanodeTypeEditor = new ComboEditor(DataNodeType.getNames(), false);
private static DefaultTableCellRenderer doubleRenderer = new DefaultTableCellRenderer() {
protected void setValue(Object value) {
if (value != null){ //hack needed to remove NPE following group refactoring
double d = (Double)value;
super.setValue(d);
}
}
};
private static DefaultTableCellRenderer differentRenderer = new DefaultTableCellRenderer() {
protected void setValue(Object value) {
value = "Different values";
super.setValue(value);
}
};
private static class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setSelected((Boolean)value);
return this;
}
}
//TODO: merge with ComboEditor
private static class ComboRenderer extends JComboBox implements TableCellRenderer {
Map<Object, Object> value2label;
public ComboRenderer(Object[] values) {
super(values);
}
public ComboRenderer(Object[] labels, Object[] values) {
this(labels);
if(labels.length != values.length) {
throw new IllegalArgumentException("Number of labels doesn't equal number of values");
}
updateData(labels, values);
}
public void updateData(Object[] labels, Object[] values) {
setModel(new DefaultComboBoxModel(labels));
if(values != null) {
if(labels.length != values.length) {
throw new IllegalArgumentException("Number of labels doesn't equal number of values");
}
value2label = new HashMap<Object, Object>();
for(int i = 0; i < labels.length; i++) {
value2label.put(values[i], labels[i]);
}
}
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value2label != null) {
value = value2label.get(value);
}
if(value instanceof Integer) {
setSelectedIndex((Integer)value);
} else {
setSelectedItem(value);
}
return this;
}
}
private static class FontRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
String fn = (String)value;
Font f = getFont();
setFont(new Font(fn, f.getStyle(), f.getSize()));
setText(fn);
return this;
}
}
private static class ColorRenderer extends JLabel implements TableCellRenderer {
Border unselectedBorder = null;
Border selectedBorder = null;
boolean isBordered = true;
public ColorRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(
JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) {
Color newColor = color != null ? (Color)color : Color.WHITE;
setBackground(newColor);
if (isBordered) {
if (isSelected) {
if (selectedBorder == null) {
selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
table.getSelectionBackground());
}
setBorder(selectedBorder);
} else {
if (unselectedBorder == null) {
unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
table.getBackground());
}
setBorder(unselectedBorder);
}
}
setToolTipText("RGB value: " + newColor.getRed() + ", "
+ newColor.getGreen() + ", "
+ newColor.getBlue());
return this;
}
}
public int compareTo(TypedProperty arg0)
{
if (arg0 == null) throw new NullPointerException();
if (type.getClass() != arg0.type.getClass())
{
return type instanceof PropertyType ? 1 : -1;
}
else
{
if (type instanceof PropertyType)
{
return ((PropertyType)type).getOrder() - ((PropertyType)arg0.type).getOrder();
}
else
{
return type.toString().compareTo(arg0.type.toString());
}
}
}
}
| false | true | public TableCellEditor getCellEditor(SwingEngine swingEngine) {
if (type instanceof PropertyType) switch(((PropertyType)type).type()) {
case BOOLEAN:
return checkboxEditor;
case DATASOURCE:
{
List<DataSource> dataSources = new ArrayList<DataSource>();
dataSources.addAll (DataSource.getFilteredSet(true, null,
Organism.fromLatinName(vPathway.getPathwayModel().getMappInfo().getOrganism())));
if(dataSources.size() != datasourceEditor.getItemCount())
{
Collections.sort (dataSources, new Comparator<DataSource>() {
public int compare(DataSource arg0, DataSource arg1)
{
return arg0.getFullName().toLowerCase().compareTo(arg1.getFullName().toLowerCase());
}});
Object[] labels = new Object[dataSources.size()];
Object[] values = new Object[dataSources.size()];
int i = 0;
for(DataSource s : dataSources) {
labels[i] = s.getFullName();
values[i] = s;
i++;
}
datasourceEditor.updateData(labels, values);
}
return datasourceEditor;
}
case COLOR:
return colorEditor;
case LINETYPE:
return lineTypeEditor;
case LINESTYLE:
return lineStyleEditor;
case ORIENTATION:
return orientationEditor;
case ORGANISM:
return organismEditor;
case ANGLE:
return angleEditor;
case DOUBLE:
return doubleEditor;
case INTEGER:
return integerEditor;
case FONT:
return fontEditor;
case SHAPETYPE:
return shapeTypeEditor;
case COMMENTS:
CommentsEditor commentsEditor = new CommentsEditor(swingEngine);
commentsEditor.setInput(this);
return commentsEditor;
case OUTLINETYPE:
return outlineTypeEditor;
case GENETYPE:
return datanodeTypeEditor;
case GROUPSTYLETYPE:
return groupStyleEditor;
default:
return null;
}
else return null;
}
| public TableCellEditor getCellEditor(SwingEngine swingEngine) {
if (type instanceof PropertyType) switch(((PropertyType)type).type()) {
case BOOLEAN:
return checkboxEditor;
case DATASOURCE:
{
List<DataSource> dataSources = new ArrayList<DataSource>();
dataSources.addAll (DataSource.getFilteredSet(true, null,
Organism.fromLatinName(vPathway.getPathwayModel().getMappInfo().getOrganism())));
if(dataSources.size() != datasourceEditor.getItemCount())
{
Collections.sort (dataSources, new Comparator<DataSource>() {
public int compare(DataSource arg0, DataSource arg1)
{
return ("" + arg0.getFullName()).toLowerCase().compareTo(("" + arg1.getFullName()).toLowerCase());
}});
Object[] labels = new Object[dataSources.size()];
Object[] values = new Object[dataSources.size()];
int i = 0;
for(DataSource s : dataSources) {
labels[i] = s.getFullName() == null ? s.getSystemCode() : s.getFullName();
values[i] = s;
i++;
}
datasourceEditor.updateData(labels, values);
}
return datasourceEditor;
}
case COLOR:
return colorEditor;
case LINETYPE:
return lineTypeEditor;
case LINESTYLE:
return lineStyleEditor;
case ORIENTATION:
return orientationEditor;
case ORGANISM:
return organismEditor;
case ANGLE:
return angleEditor;
case DOUBLE:
return doubleEditor;
case INTEGER:
return integerEditor;
case FONT:
return fontEditor;
case SHAPETYPE:
return shapeTypeEditor;
case COMMENTS:
CommentsEditor commentsEditor = new CommentsEditor(swingEngine);
commentsEditor.setInput(this);
return commentsEditor;
case OUTLINETYPE:
return outlineTypeEditor;
case GENETYPE:
return datanodeTypeEditor;
case GROUPSTYLETYPE:
return groupStyleEditor;
default:
return null;
}
else return null;
}
|
diff --git a/src/animations/LevitationControl.java b/src/animations/LevitationControl.java
index a800ccb..3dcb8a9 100644
--- a/src/animations/LevitationControl.java
+++ b/src/animations/LevitationControl.java
@@ -1,93 +1,95 @@
package animations;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
public class LevitationControl extends AbstractControl{
private float speed = 2f;
private float topUp = 2f;
private boolean up = true;
private float displacement = (float) Math.random()*topUp*2-topUp;
protected void controlUpdate(float tpf) {
if (getSpeed()>2){
setSpeed(getSpeed() - 200*tpf);
}
- else
+ else{
setTopUp(2);
+ setSpeed(2);
+ }
if (up){
spatial.move(0f, tpf*getSpeed()/20, 0f);
setDisplacement(getDisplacement() + tpf*getSpeed());
if (getDisplacement()>getTopUp()){
up=false;
setDisplacement(-getDisplacement());
}
} else {
spatial.move(0f, -tpf*getSpeed()/20, 0f);
setDisplacement(getDisplacement() + tpf*getSpeed());
if (getDisplacement()>getTopUp()){
up=true;
setDisplacement(-getDisplacement());
}
}
}
protected void controlRender(RenderManager rm, ViewPort vp) {
}
public Control cloneForSpatial(Spatial spatial) {
Control control = new LevitationControl();
control.setSpatial(spatial);
return control;
}
/**
* @return the SPEED
*/
public float getSpeed() {
return speed;
}
/**
* @param SPEED the SPEED to set
*/
public void setSpeed(float Speed) {
this.speed = Speed;
}
/**
* @return the topUp
*/
public float getTopUp() {
return topUp;
}
/**
* @param topUp the topUp to set
*/
public void setTopUp(float topUp) {
this.topUp = topUp;
}
/**
* @return the displacement
*/
public float getDisplacement() {
return displacement;
}
/**
* @param displacement the displacement to set
*/
public void setDisplacement(float displacement) {
this.displacement = displacement;
}
}
| false | true | protected void controlUpdate(float tpf) {
if (getSpeed()>2){
setSpeed(getSpeed() - 200*tpf);
}
else
setTopUp(2);
if (up){
spatial.move(0f, tpf*getSpeed()/20, 0f);
setDisplacement(getDisplacement() + tpf*getSpeed());
if (getDisplacement()>getTopUp()){
up=false;
setDisplacement(-getDisplacement());
}
} else {
spatial.move(0f, -tpf*getSpeed()/20, 0f);
setDisplacement(getDisplacement() + tpf*getSpeed());
if (getDisplacement()>getTopUp()){
up=true;
setDisplacement(-getDisplacement());
}
}
}
| protected void controlUpdate(float tpf) {
if (getSpeed()>2){
setSpeed(getSpeed() - 200*tpf);
}
else{
setTopUp(2);
setSpeed(2);
}
if (up){
spatial.move(0f, tpf*getSpeed()/20, 0f);
setDisplacement(getDisplacement() + tpf*getSpeed());
if (getDisplacement()>getTopUp()){
up=false;
setDisplacement(-getDisplacement());
}
} else {
spatial.move(0f, -tpf*getSpeed()/20, 0f);
setDisplacement(getDisplacement() + tpf*getSpeed());
if (getDisplacement()>getTopUp()){
up=true;
setDisplacement(-getDisplacement());
}
}
}
|
diff --git a/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java b/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java
index 8b99fc98..6a7e7bce 100644
--- a/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java
+++ b/grisu-core/src/main/java/grisu/backend/model/job/gt5/Gram5Client.java
@@ -1,213 +1,213 @@
package grisu.backend.model.job.gt5;
import grith.jgrith.plainProxy.LocalProxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import org.globus.gram.Gram;
import org.globus.gram.GramException;
import org.globus.gram.GramJob;
import org.globus.gram.GramJobListener;
import org.globus.gram.internal.GRAMConstants;
import org.globus.gram.internal.GRAMProtocolErrorConstants;
import org.globus.gsi.GlobusCredentialException;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
public class Gram5Client implements GramJobListener {
private static HashMap<String, Integer> statuses = new HashMap<String, Integer>();
private static HashMap<String, Integer> errors = new HashMap<String, Integer>();
static final Logger myLogger = Logger
.getLogger(Gram5Client.class.getName());
public static void main(String[] args) {
final String testRSL = args[1];
final String contact = "ng1.canterbury.ac.nz";
try {
final Gram gram = new Gram();
Gram.ping(contact);
final GramJob testJob = new GramJob(testRSL);
testJob.setCredentials(LocalProxy.loadGSSCredential());
final Gram5Client gram5 = new Gram5Client();
testJob.addListener(gram5);
// testJob.bind();
testJob.request("ng1.canterbury.ac.nz", true);
testJob.bind();
Gram.registerListener(testJob);
Gram.jobStatus(testJob);
System.out
.println("job status is : " + testJob.getStatusAsString());
System.out.println("the job is : " + testJob.toString());
System.out.println("number of currently active jobs : "
+ Gram.getActiveJobs());
while (true) {
Gram.jobStatus(testJob);
System.out.println("job status is : "
+ testJob.getStatusAsString());
Thread.sleep(1000);
}
} catch (final GlobusCredentialException gx) {
gx.printStackTrace();
} catch (final GramException grx) {
grx.printStackTrace();
} catch (final GSSException gssx) {
gssx.printStackTrace();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
public Gram5Client() {
}
private String getContactString(String handle) {
try {
final URL url = new URL(handle);
myLogger.debug("job handle is " + handle);
myLogger.debug("returned handle is " + url.getHost());
return url.getHost();
} catch (final MalformedURLException ex1) {
java.util.logging.Logger.getLogger(Gram5Client.class.getName())
.log(Level.SEVERE, null, ex1);
return null;
}
}
public int[] getJobStatus(String handle, GSSCredential cred) {
final int[] results = new int[2];
// we need this to catch quick failure
Integer status = statuses.get(handle);
myLogger.debug("status is " + status);
if ((status != null) && (status == GRAMConstants.STATUS_FAILED)) {
myLogger.debug("job failed : " + errors.get(handle));
results[0] = status;
results[1] = errors.get(handle);
return results;
}
final String contact = getContactString(handle);
final GramJob job = new GramJob(null);
try {
// lets try to see if gateway is working first...
Gram.ping(cred,contact);
} catch (final GramException ex) {
myLogger.info(ex);
// have no idea what the status is, gateway is down:
return new int[] { GRAMConstants.STATUS_UNSUBMITTED, 0 };
} catch (final GSSException ex) {
myLogger.error(ex);
}
try {
job.setID(handle);
job.setCredentials(cred);
job.bind();
Gram.jobStatus(job);
myLogger.debug("job status is " + job.getStatusAsString());
myLogger.debug("job error is " + job.getError());
} catch (final GramException ex) {
myLogger.debug("ok, normal method of getting exit status is not working. need to restart job.");
- if (ex.getErrorCode() == 156 /* job contact not found*/) {
+ if (ex.getErrorCode() == 156 && ex.getErrorCode() == 12/* job contact not found*/) {
// maybe the job finished, but maybe we need to kick job manager
myLogger.debug("restarting job");
final String rsl = "&(restart=" + handle + ")";
final GramJob restartJob = new GramJob(rsl);
restartJob.setCredentials(cred);
restartJob.addListener(this);
try {
restartJob.request(contact, false);
} catch (final GramException ex1) {
// ok, now we are really done
return new int[] { GRAMConstants.STATUS_DONE, 0 };
} catch (final GSSException ex1) {
throw new RuntimeException(ex1);
}
// nope, not done yet.
return getJobStatus(handle, cred);
} else {
myLogger.error("something else is wrong. error code is " + ex.getErrorCode());
myLogger.error(ex);
}
} catch (final GSSException ex) {
myLogger.error(ex);
} catch (final MalformedURLException ex) {
myLogger.error(ex);
}
status = job.getStatus();
final int error = job.getError();
return new int[] { status, error };
}
public int kill(String handle, GSSCredential cred) {
try {
final GramJob job = new GramJob(null);
job.setID(handle);
job.setCredentials(cred);
try {
new Gram();
Gram.cancel(job);
// job.signal(job.SIGNAL_CANCEL);
} catch (final GramException ex) {
java.util.logging.Logger.getLogger(Gram5Client.class.getName())
.log(Level.SEVERE, null, ex);
} catch (final GSSException ex) {
java.util.logging.Logger.getLogger(Gram5Client.class.getName())
.log(Level.SEVERE, null, ex);
}
final int status = job.getStatus();
return status;
} catch (final MalformedURLException ex) {
java.util.logging.Logger.getLogger(Gram5Client.class.getName())
.log(Level.SEVERE, null, ex);
throw new RuntimeException(ex);
}
}
public void statusChanged(GramJob job) {
myLogger.debug("job status changed " + job.getStatusAsString());
statuses.put(job.getIDAsString(), job.getStatus());
errors.put(job.getIDAsString(), job.getError());
myLogger.debug("the job is : " + job.toString());
}
public String submit(String rsl, String endPoint, GSSCredential cred) {
final GramJob job = new GramJob(rsl);
job.setCredentials(cred);
job.addListener(this);
try {
job.request(endPoint, false);
Gram.jobStatus(job);
return job.getIDAsString();
} catch (final GramException ex) {
java.util.logging.Logger.getLogger(Gram5Client.class.getName())
.log(Level.SEVERE, null, ex);
return null;
} catch (final GSSException ex) {
java.util.logging.Logger.getLogger(Gram5Client.class.getName())
.log(Level.SEVERE, null, ex);
return null;
}
}
}
| true | true | public int[] getJobStatus(String handle, GSSCredential cred) {
final int[] results = new int[2];
// we need this to catch quick failure
Integer status = statuses.get(handle);
myLogger.debug("status is " + status);
if ((status != null) && (status == GRAMConstants.STATUS_FAILED)) {
myLogger.debug("job failed : " + errors.get(handle));
results[0] = status;
results[1] = errors.get(handle);
return results;
}
final String contact = getContactString(handle);
final GramJob job = new GramJob(null);
try {
// lets try to see if gateway is working first...
Gram.ping(cred,contact);
} catch (final GramException ex) {
myLogger.info(ex);
// have no idea what the status is, gateway is down:
return new int[] { GRAMConstants.STATUS_UNSUBMITTED, 0 };
} catch (final GSSException ex) {
myLogger.error(ex);
}
try {
job.setID(handle);
job.setCredentials(cred);
job.bind();
Gram.jobStatus(job);
myLogger.debug("job status is " + job.getStatusAsString());
myLogger.debug("job error is " + job.getError());
} catch (final GramException ex) {
myLogger.debug("ok, normal method of getting exit status is not working. need to restart job.");
if (ex.getErrorCode() == 156 /* job contact not found*/) {
// maybe the job finished, but maybe we need to kick job manager
myLogger.debug("restarting job");
final String rsl = "&(restart=" + handle + ")";
final GramJob restartJob = new GramJob(rsl);
restartJob.setCredentials(cred);
restartJob.addListener(this);
try {
restartJob.request(contact, false);
} catch (final GramException ex1) {
// ok, now we are really done
return new int[] { GRAMConstants.STATUS_DONE, 0 };
} catch (final GSSException ex1) {
throw new RuntimeException(ex1);
}
// nope, not done yet.
return getJobStatus(handle, cred);
} else {
myLogger.error("something else is wrong. error code is " + ex.getErrorCode());
myLogger.error(ex);
}
} catch (final GSSException ex) {
myLogger.error(ex);
} catch (final MalformedURLException ex) {
myLogger.error(ex);
}
status = job.getStatus();
final int error = job.getError();
return new int[] { status, error };
}
| public int[] getJobStatus(String handle, GSSCredential cred) {
final int[] results = new int[2];
// we need this to catch quick failure
Integer status = statuses.get(handle);
myLogger.debug("status is " + status);
if ((status != null) && (status == GRAMConstants.STATUS_FAILED)) {
myLogger.debug("job failed : " + errors.get(handle));
results[0] = status;
results[1] = errors.get(handle);
return results;
}
final String contact = getContactString(handle);
final GramJob job = new GramJob(null);
try {
// lets try to see if gateway is working first...
Gram.ping(cred,contact);
} catch (final GramException ex) {
myLogger.info(ex);
// have no idea what the status is, gateway is down:
return new int[] { GRAMConstants.STATUS_UNSUBMITTED, 0 };
} catch (final GSSException ex) {
myLogger.error(ex);
}
try {
job.setID(handle);
job.setCredentials(cred);
job.bind();
Gram.jobStatus(job);
myLogger.debug("job status is " + job.getStatusAsString());
myLogger.debug("job error is " + job.getError());
} catch (final GramException ex) {
myLogger.debug("ok, normal method of getting exit status is not working. need to restart job.");
if (ex.getErrorCode() == 156 && ex.getErrorCode() == 12/* job contact not found*/) {
// maybe the job finished, but maybe we need to kick job manager
myLogger.debug("restarting job");
final String rsl = "&(restart=" + handle + ")";
final GramJob restartJob = new GramJob(rsl);
restartJob.setCredentials(cred);
restartJob.addListener(this);
try {
restartJob.request(contact, false);
} catch (final GramException ex1) {
// ok, now we are really done
return new int[] { GRAMConstants.STATUS_DONE, 0 };
} catch (final GSSException ex1) {
throw new RuntimeException(ex1);
}
// nope, not done yet.
return getJobStatus(handle, cred);
} else {
myLogger.error("something else is wrong. error code is " + ex.getErrorCode());
myLogger.error(ex);
}
} catch (final GSSException ex) {
myLogger.error(ex);
} catch (final MalformedURLException ex) {
myLogger.error(ex);
}
status = job.getStatus();
final int error = job.getError();
return new int[] { status, error };
}
|
diff --git a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/BuilderAdapterGenerator.java b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/BuilderAdapterGenerator.java
index fd0fb9a38..9380ff437 100644
--- a/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/BuilderAdapterGenerator.java
+++ b/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/BuilderAdapterGenerator.java
@@ -1,86 +1,86 @@
package org.emftext.sdk.codegen.resource.generators;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.CORE_EXCEPTION;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.INCREMENTAL_PROJECT_BUILDER;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_FILE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_PROGRESS_MONITOR;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_PROJECT;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_RESOURCE;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_RESOURCE_DELTA;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.I_RESOURCE_DELTA_VISITOR;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.MAP;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.RESOURCE_SET_IMPL;
import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.URI;
import org.emftext.sdk.codegen.annotations.SyntaxDependent;
import org.emftext.sdk.codegen.composites.JavaComposite;
import org.emftext.sdk.codegen.composites.StringComposite;
import org.emftext.sdk.codegen.parameters.ArtifactParameter;
import org.emftext.sdk.codegen.resource.GenerationContext;
import org.emftext.sdk.codegen.util.NameUtil;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
@SyntaxDependent
public class BuilderAdapterGenerator extends JavaBaseGenerator<ArtifactParameter<GenerationContext>> {
private final NameUtil nameUtil = new NameUtil();
@Override
public void generateJavaContents(JavaComposite sc) {
sc.add("package " + getResourcePackageName() + ";");
sc.addLineBreak();
sc.add("public class " + getResourceClassName() + " extends " + INCREMENTAL_PROJECT_BUILDER + " {");
sc.addLineBreak();
addFields(sc);
addBuildMethod1(sc);
addBuildMethod2(sc);
sc.add("}");
}
private void addFields(JavaComposite sc) {
ConcreteSyntax syntax = getContext().getConcreteSyntax();
String builderID = nameUtil.getBuilderID(syntax);
sc.addJavadoc("the ID of the default, generated builder");
sc.add("public final static String BUILDER_ID = \"" + builderID + "\";");
sc.addLineBreak();
sc.add("private " + iBuilderClassName + " builder = new " + builderClassName + "();");
sc.addLineBreak();
}
private void addBuildMethod1(StringComposite sc) {
sc.add("public " + I_PROJECT + "[] build(int kind, @SuppressWarnings(\"rawtypes\") " + MAP + " args, final " + I_PROGRESS_MONITOR + " monitor) throws " + CORE_EXCEPTION + " {");
sc.add("return build(kind, args, monitor, builder, getProject());");
sc.add("}");
sc.addLineBreak();
}
private void addBuildMethod2(StringComposite sc) {
sc.add("public " + I_PROJECT + "[] build(int kind, " + MAP + "<?,?> args, final " + I_PROGRESS_MONITOR + " monitor, final " + iBuilderClassName + " builder, " + I_PROJECT + " project) throws " + CORE_EXCEPTION + " {");
sc.add(I_RESOURCE_DELTA + " delta = getDelta(project);");
sc.add("if (delta == null) {");
sc.add("return null;");
sc.add("}");
sc.add("delta.accept(new " + I_RESOURCE_DELTA_VISITOR + "() {");
sc.add("public boolean visit(" + I_RESOURCE_DELTA + " delta) throws " + CORE_EXCEPTION + " {");
sc.add("if (delta.getKind() == " + I_RESOURCE_DELTA + ".REMOVED) {");
sc.add("return false;");
sc.add("}");
sc.add(I_RESOURCE + " resource = delta.getResource();");
- sc.add("if (resource instanceof " + I_FILE + " && \"" + getContext().getConcreteSyntax().getName() + "\".equals(resource.getFileExtension())) {");
+ sc.add("if (resource instanceof " + I_FILE + " && resource.getName().endsWith(\".\" + \"" + getContext().getConcreteSyntax().getName() + "\")) {");
sc.add(URI + " uri = " + URI + ".createPlatformResourceURI(resource.getFullPath().toString(), true);");
sc.add("if (builder.isBuildingNeeded(uri)) {");
sc.add(textResourceClassName + " customResource = (" + textResourceClassName + ") new " + RESOURCE_SET_IMPL + "().getResource(uri, true);");
sc.add(markerHelperClassName + ".unmark(customResource, " + eProblemTypeClassName + ".BUILDER_ERROR);");
sc.add("builder.build(customResource, monitor);");
sc.add("}");
sc.add("return false;");
sc.add("}");
sc.add("return true;");
sc.add("}");
sc.add("});");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
}
}
| true | true | private void addBuildMethod2(StringComposite sc) {
sc.add("public " + I_PROJECT + "[] build(int kind, " + MAP + "<?,?> args, final " + I_PROGRESS_MONITOR + " monitor, final " + iBuilderClassName + " builder, " + I_PROJECT + " project) throws " + CORE_EXCEPTION + " {");
sc.add(I_RESOURCE_DELTA + " delta = getDelta(project);");
sc.add("if (delta == null) {");
sc.add("return null;");
sc.add("}");
sc.add("delta.accept(new " + I_RESOURCE_DELTA_VISITOR + "() {");
sc.add("public boolean visit(" + I_RESOURCE_DELTA + " delta) throws " + CORE_EXCEPTION + " {");
sc.add("if (delta.getKind() == " + I_RESOURCE_DELTA + ".REMOVED) {");
sc.add("return false;");
sc.add("}");
sc.add(I_RESOURCE + " resource = delta.getResource();");
sc.add("if (resource instanceof " + I_FILE + " && \"" + getContext().getConcreteSyntax().getName() + "\".equals(resource.getFileExtension())) {");
sc.add(URI + " uri = " + URI + ".createPlatformResourceURI(resource.getFullPath().toString(), true);");
sc.add("if (builder.isBuildingNeeded(uri)) {");
sc.add(textResourceClassName + " customResource = (" + textResourceClassName + ") new " + RESOURCE_SET_IMPL + "().getResource(uri, true);");
sc.add(markerHelperClassName + ".unmark(customResource, " + eProblemTypeClassName + ".BUILDER_ERROR);");
sc.add("builder.build(customResource, monitor);");
sc.add("}");
sc.add("return false;");
sc.add("}");
sc.add("return true;");
sc.add("}");
sc.add("});");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
}
| private void addBuildMethod2(StringComposite sc) {
sc.add("public " + I_PROJECT + "[] build(int kind, " + MAP + "<?,?> args, final " + I_PROGRESS_MONITOR + " monitor, final " + iBuilderClassName + " builder, " + I_PROJECT + " project) throws " + CORE_EXCEPTION + " {");
sc.add(I_RESOURCE_DELTA + " delta = getDelta(project);");
sc.add("if (delta == null) {");
sc.add("return null;");
sc.add("}");
sc.add("delta.accept(new " + I_RESOURCE_DELTA_VISITOR + "() {");
sc.add("public boolean visit(" + I_RESOURCE_DELTA + " delta) throws " + CORE_EXCEPTION + " {");
sc.add("if (delta.getKind() == " + I_RESOURCE_DELTA + ".REMOVED) {");
sc.add("return false;");
sc.add("}");
sc.add(I_RESOURCE + " resource = delta.getResource();");
sc.add("if (resource instanceof " + I_FILE + " && resource.getName().endsWith(\".\" + \"" + getContext().getConcreteSyntax().getName() + "\")) {");
sc.add(URI + " uri = " + URI + ".createPlatformResourceURI(resource.getFullPath().toString(), true);");
sc.add("if (builder.isBuildingNeeded(uri)) {");
sc.add(textResourceClassName + " customResource = (" + textResourceClassName + ") new " + RESOURCE_SET_IMPL + "().getResource(uri, true);");
sc.add(markerHelperClassName + ".unmark(customResource, " + eProblemTypeClassName + ".BUILDER_ERROR);");
sc.add("builder.build(customResource, monitor);");
sc.add("}");
sc.add("return false;");
sc.add("}");
sc.add("return true;");
sc.add("}");
sc.add("});");
sc.add("return null;");
sc.add("}");
sc.addLineBreak();
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.