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/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java b/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java
index 222dbfcc0..77d5a32e6 100644
--- a/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java
+++ b/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java
@@ -1,463 +1,467 @@
package TFC.Entities.Mobs;
import java.util.ArrayList;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAITempt;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IShearable;
import TFC.TFCItems;
import TFC.API.Entities.IAnimal;
import TFC.Core.TFC_Core;
import TFC.Core.TFC_Time;
import TFC.Entities.AI.AIEatGrass;
import TFC.Entities.AI.EntityAIMateTFC;
public class EntitySheepTFC extends EntitySheep implements IShearable, IAnimal
{
/**
* Holds the RGB table of the sheep colors - in OpenGL glColor3f values - used to render the sheep colored fleece.
*/
public static final float[][] fleeceColorTable = new float[][] {{1.0F, 1.0F, 1.0F}, {0.95F, 0.7F, 0.2F}, {0.9F, 0.5F, 0.85F}, {0.6F, 0.7F, 0.95F}, {0.9F, 0.9F, 0.2F}, {0.5F, 0.8F, 0.1F}, {0.95F, 0.7F, 0.8F}, {0.3F, 0.3F, 0.3F}, {0.6F, 0.6F, 0.6F}, {0.3F, 0.6F, 0.7F}, {0.7F, 0.4F, 0.9F}, {0.2F, 0.4F, 0.8F}, {0.5F, 0.4F, 0.3F}, {0.4F, 0.5F, 0.2F}, {0.8F, 0.3F, 0.3F}, {0.1F, 0.1F, 0.1F}};
/**
* Used to control movement as well as wool regrowth. Set to 40 on handleHealthUpdate and counts down with each
* tick.
*/
private int sheepTimer;
/** The eat grass AI task for this mob. */
public AIEatGrass aiEatGrass = new AIEatGrass(this);
int degreeOfDiversion = 4;
protected long animalID;
protected int sex = 0;
protected int hunger;
protected long hasMilkTime;
protected boolean pregnant;
protected int pregnancyRequiredTime;
protected long timeOfConception;
protected float mateSizeMod;
public float size_mod = 1f;
public boolean inLove;
public EntitySheepTFC(World par1World)
{
super(par1World);
this.setSize(0.9F, 1.3F);
float var2 = 0.23F;
this.getNavigator().setAvoidsWater(true);
this.tasks.addTask(2, new EntityAIMateTFC(this,worldObj, var2));
this.tasks.addTask(3, new EntityAITempt(this, 1.2F, TFCItems.WheatGrain.itemID, false));
this.tasks.addTask(6, this.aiEatGrass);
hunger = 168000;
animalID = TFC_Time.getTotalTicks() + entityId;
pregnant = false;
pregnancyRequiredTime = (int) (4 * TFC_Time.ticksInMonth);
timeOfConception = 0;
mateSizeMod = 0;
sex = rand.nextInt(2);
size_mod = (((rand.nextInt (degreeOfDiversion+1)*(rand.nextBoolean()?1:-1)) / 10f) + 1F) * (1.0F - 0.1F * sex);
// We hijack the growingAge to hold the day of birth rather
// than number of ticks to next growth event. We want spawned
// animals to be adults, so we set their birthdays far enough back
// in time such that they reach adulthood now.
//
this.setAge((int) TFC_Time.getTotalDays() - getNumberOfDaysToAdult());
//For Testing Only(makes spawned animals into babies)
//this.setGrowingAge((int) TFC_Time.getTotalDays());
}
public EntitySheepTFC(World par1World,IAnimal mother, float F_size)
{
this(par1World);
this.posX = ((EntityLivingBase)mother).posX;
this.posY = ((EntityLivingBase)mother).posY;
this.posZ = ((EntityLivingBase)mother).posZ;
size_mod = (((rand.nextInt (degreeOfDiversion+1)*(rand.nextBoolean()?1:-1)) / 10f) + 1F) * (1.0F - 0.1F * sex) * (float)Math.sqrt((mother.getSize() + F_size)/1.9F);
size_mod = Math.min(Math.max(size_mod, 0.7F),1.3f);
// We hijack the growingAge to hold the day of birth rather
// than number of ticks to next growth event.
//
this.setAge((int) TFC_Time.getTotalDays());
}
@Override
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(13, new Integer(0));
this.dataWatcher.addObject(14, new Float(1));
this.dataWatcher.addObject(15, Integer.valueOf(0));
}
@Override
protected void func_110147_ax()
{
super.func_110147_ax();
this.func_110148_a(SharedMonsterAttributes.field_111267_a).func_111128_a(400);//MaxHealth
}
@Override
protected void updateAITasks()
{
this.sheepTimer = this.aiEatGrass.getEatGrassTick();
super.updateAITasks();
}
private float getPercentGrown(IAnimal animal)
{
float birth = animal.getBirthDay();
float time = (int) TFC_Time.getTotalDays();
float percent =(time-birth)/animal.getNumberOfDaysToAdult();
return Math.min(percent, 1f);
}
/**
* Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
* use this to react to sunlight and start to burn.
*/
@Override
public void onLivingUpdate()
{
if (this.worldObj.isRemote)
{
this.sheepTimer = Math.max(0, this.sheepTimer - 1);
}
//Handle Hunger ticking
if (hunger > 168000)
{
hunger = 168000;
}
if (hunger > 0)
{
hunger--;
}
if(super.inLove > 0){
super.inLove = 0;
setInLove(true);
}
syncData();
if(isAdult()){
setGrowingAge(0);
}
else{
setGrowingAge(-1);
}
if(isPregnant())
{
if(TFC_Time.getTotalTicks() >= timeOfConception + pregnancyRequiredTime)
{
int i = rand.nextInt(3) + 1;
for (int x = 0; x<i;x++)
{
EntitySheepTFC baby = new EntitySheepTFC(worldObj, this, mateSizeMod);
+ baby.setLocationAndAngles (posX+(rand.nextFloat()-0.5F)*2F,posY,posZ+(rand.nextFloat()-0.5F)*2F, 0.0F, 0.0F);
+ baby.rotationYawHead = baby.rotationYaw;
+ baby.renderYawOffset = baby.rotationYaw;
worldObj.spawnEntityInWorld(baby);
+ baby.setAge((int)TFC_Time.getTotalDays());
}
pregnant = false;
}
}
/**
* This Cancels out the changes made to growingAge by EntityAgeable
* */
TFC_Core.PreventEntityDataUpdate = true;
super.onLivingUpdate();
TFC_Core.PreventEntityDataUpdate = false;
if (hunger > 144000 && rand.nextInt (100) == 0 && func_110143_aJ() < TFC_Core.getEntityMaxHealth(this) && !isDead)
{
this.heal(1);
}
}
public void syncData()
{
if(dataWatcher!= null)
{
if(!this.worldObj.isRemote){
this.dataWatcher.updateObject(13, Integer.valueOf(sex));
this.dataWatcher.updateObject(14, Float.valueOf(size_mod));
}
else{
sex = this.dataWatcher.getWatchableObjectInt(13);
size_mod = this.dataWatcher.func_111145_d(14);
}
}
}
@Override
public void eatGrassBonus()
{
this.setSheared(false);
hunger += 24000;
}
/**
* Drop 0-2 items of this living's type
*/
@Override
protected void dropFewItems(boolean par1, int par2)
{
float ageMod = TFC_Core.getPercentGrown(this);
if(this.isAdult()){
if(!this.getSheared()) {
this.entityDropItem(new ItemStack(TFCItems.SheepSkin,1), 0.0F);
} else {
this.dropItem(TFCItems.Hide.itemID,1);
}
this.dropItem(Item.bone.itemID, rand.nextInt(5)+2);
}
if (this.isBurning()) {
this.dropItem(TFCItems.muttonCooked.itemID,(int)(ageMod*this.size_mod *(5+rand.nextInt(5))));
} else {
this.dropItem(TFCItems.muttonRaw.itemID,(int)(ageMod*this.size_mod *(5+rand.nextInt(5))));
}
}
@Override
public boolean isBreedingItem(ItemStack par1ItemStack)
{
return !pregnant&&(par1ItemStack.getItem() == TFCItems.WheatGrain ||par1ItemStack.getItem() == TFCItems.OatGrain||par1ItemStack.getItem() == TFCItems.RiceGrain||
par1ItemStack.getItem() == TFCItems.BarleyGrain||par1ItemStack.getItem() == TFCItems.RyeGrain);
}
/**
* Returns the item ID for the item the mob drops on death.
*/
@Override
protected int getDropItemId()
{
return TFCItems.Wool.itemID;
}
/**
* Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig.
*/
@Override
public boolean interact(EntityPlayer par1EntityPlayer)
{
if(!worldObj.isRemote){
par1EntityPlayer.addChatMessage(getGender()==GenderEnum.FEMALE?"Female":"Male");
if(getGender()==GenderEnum.FEMALE && pregnant){
par1EntityPlayer.addChatMessage("Pregnant");
}
//par1EntityPlayer.addChatMessage("12: "+dataWatcher.getWatchableObjectInt(12)+", 15: "+dataWatcher.getWatchableObjectInt(15));
}
if(getGender() == GenderEnum.FEMALE && isAdult() && hasMilkTime < TFC_Time.getTotalTicks()){
ItemStack var2 = par1EntityPlayer.inventory.getCurrentItem();
if (var2 != null && var2.itemID == TFCItems.WoodenBucketEmpty.itemID) {
par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, new ItemStack(TFCItems.WoodenBucketMilk));
hasMilkTime = TFC_Time.getTotalTicks() + (3*TFC_Time.dayLength); //Can be milked ones every 3 days
return true;
}
}
return super.interact(par1EntityPlayer);
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
@Override
public void writeEntityToNBT(NBTTagCompound nbt)
{
super.writeEntityToNBT(nbt);
nbt.setInteger ("Sex", sex);
nbt.setLong ("Animal ID", animalID);
nbt.setFloat ("Size Modifier", size_mod);
nbt.setInteger ("Hunger", hunger);
nbt.setBoolean("Pregnant", pregnant);
nbt.setFloat("MateSize", mateSizeMod);
nbt.setLong("ConceptionTime",timeOfConception);
nbt.setInteger("Age", getBirthDay());
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
@Override
public void readEntityFromNBT(NBTTagCompound nbt)
{
super.readEntityFromNBT(nbt);
animalID = nbt.getLong ("Animal ID");
sex = nbt.getInteger ("Sex");
size_mod = nbt.getFloat ("Size Modifier");
hunger = nbt.getInteger ("Hunger");
pregnant = nbt.getBoolean("Pregnant");
mateSizeMod = nbt.getFloat("MateSize");
timeOfConception = nbt.getLong("ConceptionTime");
this.dataWatcher.updateObject(15, nbt.getInteger ("Age"));
this.setAge(nbt.getInteger ("Age"));
}
@Override
public boolean isShearable(ItemStack item, World world, int X, int Y, int Z)
{
return !getSheared() && isAdult();
}
@Override
public ArrayList<ItemStack> onSheared(ItemStack item, World world, int X, int Y, int Z, int fortune)
{
ArrayList<ItemStack> ret = new ArrayList<ItemStack>();
setSheared(true);
ret.add(new ItemStack(TFCItems.Wool.itemID, 1, getFleeceColor()));
this.worldObj.playSoundAtEntity(this, "mob.sheep.shear", 1.0F, 1.0F);
return ret;
}
@Override
public void setGrowingAge(int par1)
{
if(!TFC_Core.PreventEntityDataUpdate) {
this.dataWatcher.updateObject(12, Integer.valueOf(par1));
}
}
@Override
public boolean isChild()
{
return !isAdult();
}
@Override
public EntityAgeable createChild(EntityAgeable entityageable)
{
return null;
}
@Override
public int getBirthDay()
{
return this.dataWatcher.getWatchableObjectInt(15);
}
@Override
public int getNumberOfDaysToAdult()
{
return TFC_Time.daysInMonth * 3;
}
@Override
public boolean isAdult()
{
return getBirthDay()+getNumberOfDaysToAdult() <= TFC_Time.getTotalDays();
}
@Override
public float getSize()
{
return size_mod;
}
@Override
public boolean isPregnant()
{
return pregnant;
}
@Override
public EntityLiving getEntity()
{
return this;
}
@Override
public boolean canMateWith(IAnimal animal)
{
if(animal.getGender() != this.getGender() && animal.isAdult() && animal instanceof EntitySheepTFC) {
return true;
} else {
return false;
}
}
@Override
public void mate(IAnimal otherAnimal)
{
if (getGender() == GenderEnum.MALE)
{
otherAnimal.mate(this);
return;
}
timeOfConception = TFC_Time.getTotalTicks();
pregnant = true;
resetInLove();
otherAnimal.setInLove(false);
mateSizeMod = otherAnimal.getSize();
}
@Override
public boolean getInLove()
{
return inLove;
}
@Override
public void setInLove(boolean b)
{
this.inLove = b;
}
@Override
public long getAnimalID()
{
return animalID;
}
@Override
public void setAnimalID(long id)
{
animalID = id;
}
@Override
public int getHunger() {
return hunger;
}
@Override
public void setHunger(int h)
{
hunger = h;
}
@Override
public GenderEnum getGender()
{
return GenderEnum.genders[getSex()];
}
@Override
public int getSex() {
return dataWatcher.getWatchableObjectInt(13);
}
@Override
public EntityAgeable createChildTFC(EntityAgeable entityageable) {
return new EntitySheepTFC(worldObj, this, entityageable.getEntityData().getFloat("MateSize"));
}
@Override
public void setAge(int par1) {
this.dataWatcher.updateObject(15, Integer.valueOf(par1));
}
}
| false | true | public void onLivingUpdate()
{
if (this.worldObj.isRemote)
{
this.sheepTimer = Math.max(0, this.sheepTimer - 1);
}
//Handle Hunger ticking
if (hunger > 168000)
{
hunger = 168000;
}
if (hunger > 0)
{
hunger--;
}
if(super.inLove > 0){
super.inLove = 0;
setInLove(true);
}
syncData();
if(isAdult()){
setGrowingAge(0);
}
else{
setGrowingAge(-1);
}
if(isPregnant())
{
if(TFC_Time.getTotalTicks() >= timeOfConception + pregnancyRequiredTime)
{
int i = rand.nextInt(3) + 1;
for (int x = 0; x<i;x++)
{
EntitySheepTFC baby = new EntitySheepTFC(worldObj, this, mateSizeMod);
worldObj.spawnEntityInWorld(baby);
}
pregnant = false;
}
}
/**
* This Cancels out the changes made to growingAge by EntityAgeable
* */
TFC_Core.PreventEntityDataUpdate = true;
super.onLivingUpdate();
TFC_Core.PreventEntityDataUpdate = false;
if (hunger > 144000 && rand.nextInt (100) == 0 && func_110143_aJ() < TFC_Core.getEntityMaxHealth(this) && !isDead)
{
this.heal(1);
}
}
| public void onLivingUpdate()
{
if (this.worldObj.isRemote)
{
this.sheepTimer = Math.max(0, this.sheepTimer - 1);
}
//Handle Hunger ticking
if (hunger > 168000)
{
hunger = 168000;
}
if (hunger > 0)
{
hunger--;
}
if(super.inLove > 0){
super.inLove = 0;
setInLove(true);
}
syncData();
if(isAdult()){
setGrowingAge(0);
}
else{
setGrowingAge(-1);
}
if(isPregnant())
{
if(TFC_Time.getTotalTicks() >= timeOfConception + pregnancyRequiredTime)
{
int i = rand.nextInt(3) + 1;
for (int x = 0; x<i;x++)
{
EntitySheepTFC baby = new EntitySheepTFC(worldObj, this, mateSizeMod);
baby.setLocationAndAngles (posX+(rand.nextFloat()-0.5F)*2F,posY,posZ+(rand.nextFloat()-0.5F)*2F, 0.0F, 0.0F);
baby.rotationYawHead = baby.rotationYaw;
baby.renderYawOffset = baby.rotationYaw;
worldObj.spawnEntityInWorld(baby);
baby.setAge((int)TFC_Time.getTotalDays());
}
pregnant = false;
}
}
/**
* This Cancels out the changes made to growingAge by EntityAgeable
* */
TFC_Core.PreventEntityDataUpdate = true;
super.onLivingUpdate();
TFC_Core.PreventEntityDataUpdate = false;
if (hunger > 144000 && rand.nextInt (100) == 0 && func_110143_aJ() < TFC_Core.getEntityMaxHealth(this) && !isDead)
{
this.heal(1);
}
}
|
diff --git a/electric/electric-core/src/main/java/com/sun/electric/util/config/XmlInitSax.java b/electric/electric-core/src/main/java/com/sun/electric/util/config/XmlInitSax.java
index ba1d499c6..c1223fc7c 100644
--- a/electric/electric-core/src/main/java/com/sun/electric/util/config/XmlInitSax.java
+++ b/electric/electric-core/src/main/java/com/sun/electric/util/config/XmlInitSax.java
@@ -1,325 +1,325 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: XmlInit.java
*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.util.config;
import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import com.sun.electric.util.CollectionFactory;
import com.sun.electric.util.config.XmlConfigVerification.LoopExistsException;
import com.sun.electric.util.config.model.ConfigEntries;
import com.sun.electric.util.config.model.ConfigEntry;
import com.sun.electric.util.config.model.Include;
import com.sun.electric.util.config.model.Injection;
import com.sun.electric.util.config.model.Parameter;
/**
* @author Felix Schmidt
*
*/
public class XmlInitSax extends InitStrategy {
private static Logger logger = Logger.getLogger(XmlInitSax.class.getName());
private String xmlFile;
private static final String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
private static final String XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
public XmlInitSax(String xmlFile) {
this.xmlFile = xmlFile;// new File(xmlFile);
}
public XmlInitSax(URL xmlUrl) {
this.xmlFile = xmlUrl.toString();
}
@Override
public void init(EConfigContainer config) {
ConfigEntries.refresh();
Map<String, Injection> injections = CollectionFactory.createHashMap();
List<Include> includes = CollectionFactory.createArrayList();
SAXParser saxParser = null;
Set<Include> visitedIncludes = CollectionFactory.createHashSet();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
saxParser = factory.newSAXParser();
saxParser.setProperty(SCHEMA_LANGUAGE, XML_SCHEMA);
saxParser.parse(xmlFile, new ParserHandler(injections, includes));
Include mainInclude = new Include(xmlFile, null);
visitedIncludes.add(mainInclude);
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
this.parseIncludes(saxParser, includes, visitedIncludes, injections);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
try {
if (XmlConfigVerification.runVerification(injections)) {
for (Injection in : injections.values()) {
try {
logger.log(Level.FINE,
"bind injection: " + in.getName() + " to " + in.getImplementation());
ConfigEntry<?> entry;
if (ConfigEntries.getEntries().containsKey(in.getName())) {
entry = ConfigEntries.getEntries().get(in.getName());
} else {
entry = in.createConfigEntry(injections);
}
config.addConfigEntry(in.getName(), entry);
} catch (ClassNotFoundException e) {
- logger.log(Level.INFO, "unable to bind injection: " + in.getName());
+ logger.log(Level.CONFIG, "unable to bind injection: " + in.getName());
} catch (LinkageError e) {
- logger.log(Level.INFO, "unable to bind injection dependencies: " + in.getName());
+ logger.log(Level.CONFIG, "unable to bind injection dependencies: " + in.getName());
}
}
}
} catch (LoopExistsException e) {
logger.log(Level.SEVERE, "A loop exists in the configuration");
}
}
private void parseIncludes(SAXParser parser, List<Include> includes, Set<Include> visitedIncludes,
Map<String, Injection> injections) throws Exception {
for (Include include : includes) {
if (!visitedIncludes.contains(include)) {
List<Include> newIncludes = CollectionFactory.createArrayList();
parser.parse(this.getFileObject(include.getFile()),
new ParserHandler(injections, newIncludes));
this.parseIncludes(parser, newIncludes, visitedIncludes, injections);
}
}
}
private File getFileObject(String name) throws Exception {
File result = new File(name);
if (!result.exists()) {
result = new File(ClassLoader.getSystemResource(name).toURI());
}
return result;
}
private static class ParserHandler extends DefaultHandler {
private enum XmlTags {
configuration, injection, parameters, parameter, include, initRuntimeParameter
}
private Injection currentInjection = null;
private List<Parameter> currentParameters = null;
private Parameter currentParameter = null;
private Map<String, Injection> injections = null;
private Include currentInclude = null;
private List<Include> includes;
public ParserHandler(Map<String, Injection> injections, List<Include> includes) {
this.injections = injections;
this.includes = includes;
}
/*
* (non-Javadoc)
*
* @see
* org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (localName.equals(XmlTags.configuration.toString())) {
} else if (localName.equals(XmlTags.injection.toString())) {
this.parseInjectionTag(attributes);
} else if (localName.equals(XmlTags.parameters.toString())) {
this.parseParametersTag(attributes);
} else if (localName.equals(XmlTags.parameter.toString())) {
this.parseParameterTag(attributes);
} else if (localName.equals(XmlTags.include.toString())) {
this.parseIncludeTag(attributes);
} else if (localName.equals(XmlTags.initRuntimeParameter.toString())) {
this.parseInitRuntimeParamterTag(attributes);
} else {
logger.log(Level.SEVERE, "unexpected opening tag: " + localName);
}
}
private void parseInitRuntimeParamterTag(Attributes attributes) throws SAXException {
if (currentParameter != null) {
throw new SAXException("error: closing tag expected");
} else {
String name = attributes.getValue(Parameter.Attributes.name.toString());
String type = attributes.getValue(Parameter.Attributes.type.toString());
Parameter.Type paramType = Parameter.Type.valueOf(type);
currentParameter = new Parameter(name, null, null, paramType, false);
}
}
private void parseInjectionTag(Attributes attributes) throws SAXException {
if (currentInjection != null) {
throw new SAXException("error: closing tag expected");
} else {
String name = attributes.getValue(Injection.Attributes.name.toString());
String impl = attributes.getValue(Injection.Attributes.implementation.toString());
String factoryMethod = attributes.getValue(Injection.Attributes.factoryMethod.toString());
String singleton = attributes.getValue(Injection.Attributes.singleton.toString());
boolean isSingleton = false;
if (singleton != null)
isSingleton = Boolean.parseBoolean(singleton);
currentInjection = new Injection(name, impl, factoryMethod, isSingleton);
}
}
private void parseParametersTag(Attributes attributes) throws SAXException {
if (currentParameters != null) {
throw new SAXException("error: closing tag expected");
} else {
currentParameters = CollectionFactory.createArrayList();
}
}
private void parseParameterTag(Attributes attributes) throws SAXException {
if (currentParameter != null) {
throw new SAXException("error: closing tag expected");
} else {
String name = attributes.getValue(Parameter.Attributes.name.toString());
String ref = attributes.getValue(Parameter.Attributes.ref.toString());
String type = attributes.getValue(Parameter.Attributes.type.toString());
String value = attributes.getValue(Parameter.Attributes.value.toString());
Parameter.Type paramType;
if (ref != null) {
paramType = Parameter.Type.Reference;
} else {
paramType = Parameter.Type.valueOf(type);
}
currentParameter = new Parameter(name, ref, value, paramType, false);
}
}
private void parseIncludeTag(Attributes attributes) throws SAXException {
if (currentParameter != null) {
throw new SAXException("error: closing tag expected");
} else {
String file = attributes.getValue(Include.Attributes.file.toString());
String id = attributes.getValue(Include.Attributes.id.toString());
currentInclude = new Include(file, id);
}
}
/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equals(XmlTags.configuration.toString())) {
} else if (localName.equals(XmlTags.injection.toString())) {
injections.put(currentInjection.getName(), currentInjection);
currentInjection = null;
} else if (localName.equals(XmlTags.parameters.toString())) {
currentInjection.setParameters(currentParameters);
currentParameters = null;
} else if (localName.equals(XmlTags.parameter.toString())) {
currentParameters.add(currentParameter);
currentParameter = null;
} else if (localName.equals(XmlTags.include.toString())) {
includes.add(currentInclude);
currentInclude = null;
} else if (localName.equals(XmlTags.initRuntimeParameter.toString())) {
currentParameters.add(currentParameter);
currentParameter = null;
} else {
logger.log(Level.SEVERE, "unexpected closing tag: " + localName);
}
}
/*
* (non-Javadoc)
*
* @see
* org.xml.sax.helpers.DefaultHandler#error(org.xml.sax.SAXParseException
* )
*/
@Override
public void error(SAXParseException e) throws SAXException {
throw new SAXException(e);
}
/*
* (non-Javadoc)
*
* @see
* org.xml.sax.helpers.DefaultHandler#warning(org.xml.sax.SAXParseException
* )
*/
@Override
public void warning(SAXParseException e) throws SAXException {
throw new SAXException(e);
}
}
}
| false | true | public void init(EConfigContainer config) {
ConfigEntries.refresh();
Map<String, Injection> injections = CollectionFactory.createHashMap();
List<Include> includes = CollectionFactory.createArrayList();
SAXParser saxParser = null;
Set<Include> visitedIncludes = CollectionFactory.createHashSet();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
saxParser = factory.newSAXParser();
saxParser.setProperty(SCHEMA_LANGUAGE, XML_SCHEMA);
saxParser.parse(xmlFile, new ParserHandler(injections, includes));
Include mainInclude = new Include(xmlFile, null);
visitedIncludes.add(mainInclude);
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
this.parseIncludes(saxParser, includes, visitedIncludes, injections);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
try {
if (XmlConfigVerification.runVerification(injections)) {
for (Injection in : injections.values()) {
try {
logger.log(Level.FINE,
"bind injection: " + in.getName() + " to " + in.getImplementation());
ConfigEntry<?> entry;
if (ConfigEntries.getEntries().containsKey(in.getName())) {
entry = ConfigEntries.getEntries().get(in.getName());
} else {
entry = in.createConfigEntry(injections);
}
config.addConfigEntry(in.getName(), entry);
} catch (ClassNotFoundException e) {
logger.log(Level.INFO, "unable to bind injection: " + in.getName());
} catch (LinkageError e) {
logger.log(Level.INFO, "unable to bind injection dependencies: " + in.getName());
}
}
}
} catch (LoopExistsException e) {
logger.log(Level.SEVERE, "A loop exists in the configuration");
}
}
| public void init(EConfigContainer config) {
ConfigEntries.refresh();
Map<String, Injection> injections = CollectionFactory.createHashMap();
List<Include> includes = CollectionFactory.createArrayList();
SAXParser saxParser = null;
Set<Include> visitedIncludes = CollectionFactory.createHashSet();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
saxParser = factory.newSAXParser();
saxParser.setProperty(SCHEMA_LANGUAGE, XML_SCHEMA);
saxParser.parse(xmlFile, new ParserHandler(injections, includes));
Include mainInclude = new Include(xmlFile, null);
visitedIncludes.add(mainInclude);
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
this.parseIncludes(saxParser, includes, visitedIncludes, injections);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
try {
if (XmlConfigVerification.runVerification(injections)) {
for (Injection in : injections.values()) {
try {
logger.log(Level.FINE,
"bind injection: " + in.getName() + " to " + in.getImplementation());
ConfigEntry<?> entry;
if (ConfigEntries.getEntries().containsKey(in.getName())) {
entry = ConfigEntries.getEntries().get(in.getName());
} else {
entry = in.createConfigEntry(injections);
}
config.addConfigEntry(in.getName(), entry);
} catch (ClassNotFoundException e) {
logger.log(Level.CONFIG, "unable to bind injection: " + in.getName());
} catch (LinkageError e) {
logger.log(Level.CONFIG, "unable to bind injection dependencies: " + in.getName());
}
}
}
} catch (LoopExistsException e) {
logger.log(Level.SEVERE, "A loop exists in the configuration");
}
}
|
diff --git a/src/de/schildbach/wallet/TransactionFragment.java b/src/de/schildbach/wallet/TransactionFragment.java
index 3d032e0..83df7f6 100644
--- a/src/de/schildbach/wallet/TransactionFragment.java
+++ b/src/de/schildbach/wallet/TransactionFragment.java
@@ -1,227 +1,227 @@
/*
* Copyright 2010 the original author or authors.
*
* 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 de.schildbach.wallet;
import java.text.DateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.bitcoin.core.Address;
import com.google.bitcoin.core.ScriptException;
import com.google.bitcoin.core.Transaction;
import com.google.bitcoin.core.Utils;
import com.google.bitcoin.core.Wallet;
import de.schildbach.wallet.util.Base64;
import de.schildbach.wallet.util.QrDialog;
import de.schildbach.wallet.util.WalletUtils;
import de.schildbach.wallet_test.R;
/**
* @author Andreas Schildbach
*/
public class TransactionFragment extends DialogFragment
{
public static final String FRAGMENT_TAG = TransactionFragment.class.getName();
private FragmentActivity activity;
private Transaction tx;
private DateFormat dateFormat;
private DateFormat timeFormat;
private final static String KEY_TRANSACTION = "transaction";
public static TransactionFragment instance(final Transaction tx)
{
final TransactionFragment fragment = new TransactionFragment();
final Bundle args = new Bundle();
args.putSerializable(KEY_TRANSACTION, tx);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(final Activity activity)
{
super.onAttach(activity);
this.activity = (FragmentActivity) activity;
dateFormat = android.text.format.DateFormat.getDateFormat(activity);
timeFormat = android.text.format.DateFormat.getTimeFormat(activity);
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState)
{
final Wallet wallet = ((Application) activity.getApplication()).getWallet();
tx = (Transaction) getArguments().getSerializable(KEY_TRANSACTION);
final byte[] serializedTx = tx.unsafeBitcoinSerialize();
Address from = null;
boolean fromMine = false;
try
{
- from = tx.getOutputs().get(0).getScriptPubKey().getToAddress();
+ from = tx.getInputs().get(0).getFromAddress();
fromMine = wallet.isPubKeyHashMine(from.getHash160());
}
catch (final ScriptException x)
{
x.printStackTrace();
}
Address to = null;
boolean toMine = false;
try
{
- to = tx.getInputs().get(0).getFromAddress();
+ to = tx.getOutputs().get(0).getScriptPubKey().getToAddress();
toMine = wallet.isPubKeyHashMine(to.getHash160());
}
catch (final ScriptException x)
{
x.printStackTrace();
}
final boolean sent = tx.sent(wallet);
final boolean pending = wallet.isPending(tx);
final boolean dead = wallet.isDead(tx);
final ContentResolver contentResolver = activity.getContentResolver();
final LayoutInflater inflater = LayoutInflater.from(activity);
final Builder dialog = new AlertDialog.Builder(activity);
final View view = inflater.inflate(R.layout.transaction_fragment, null);
final TextView viewDate = (TextView) view.findViewById(R.id.transaction_fragment_time);
final Date time = tx.getUpdateTime();
if (time != null)
viewDate.setText((DateUtils.isToday(time.getTime()) ? getString(R.string.transaction_fragment_time_today) : dateFormat.format(time))
+ ", " + timeFormat.format(time));
else
view.findViewById(R.id.transaction_fragment_time_row).setVisibility(View.GONE);
final TextView viewAmountLabel = (TextView) view.findViewById(R.id.transaction_fragment_amount_label);
viewAmountLabel.setText(getString(sent ? R.string.transaction_fragment_amount_label_sent
: R.string.transaction_fragment_amount_label_received));
final TextView viewAmount = (TextView) view.findViewById(R.id.transaction_fragment_amount);
try
{
viewAmount.setText((sent ? "-" : "+") + "\u2009" /* thin space */+ Utils.bitcoinValueToFriendlyString(tx.amount(wallet)));
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
final TextView viewFrom = (TextView) view.findViewById(R.id.transaction_fragment_from);
if (from != null)
{
final String label = AddressBookProvider.resolveLabel(contentResolver, from.toString());
final StringBuilder builder = new StringBuilder();
if (fromMine)
builder.append(getString(R.string.transaction_fragment_you)).append(", ");
if (label != null)
{
builder.append(label);
}
else
{
builder.append(from.toString());
viewFrom.setTypeface(Typeface.MONOSPACE);
}
viewFrom.setText(builder.toString());
}
final TextView viewTo = (TextView) view.findViewById(R.id.transaction_fragment_to);
if (to != null)
{
final String label = AddressBookProvider.resolveLabel(contentResolver, to.toString());
final StringBuilder builder = new StringBuilder();
if (toMine)
builder.append(getString(R.string.transaction_fragment_you)).append(", ");
if (label != null)
{
builder.append(label);
}
else
{
builder.append(to.toString());
viewTo.setTypeface(Typeface.MONOSPACE);
}
viewTo.setText(builder.toString());
}
final TextView viewStatus = (TextView) view.findViewById(R.id.transaction_fragment_status);
if (dead)
viewStatus.setText(R.string.transaction_fragment_status_dead);
else if (pending)
viewStatus.setText(R.string.transaction_fragment_status_pending);
else
viewStatus.setText(R.string.transaction_fragment_status_confirmed);
final TextView viewHash = (TextView) view.findViewById(R.id.transaction_fragment_hash);
viewHash.setText(tx.getHash().toString());
final TextView viewLength = (TextView) view.findViewById(R.id.transaction_fragment_length);
viewLength.setText(Integer.toString(serializedTx.length));
final ImageView viewQr = (ImageView) view.findViewById(R.id.transaction_fragment_qr);
final String txStr = "btctx:" + Base64.encodeToString(serializedTx, Base64.NO_WRAP | Base64.NO_PADDING);
final Bitmap qrCodeBitmap = WalletUtils.getQRCodeBitmap(txStr, 512);
viewQr.setImageBitmap(qrCodeBitmap);
viewQr.setOnClickListener(new OnClickListener()
{
public void onClick(final View v)
{
new QrDialog(activity, qrCodeBitmap).show();
}
});
dialog.setView(view);
return dialog.create();
}
}
| false | true | public Dialog onCreateDialog(final Bundle savedInstanceState)
{
final Wallet wallet = ((Application) activity.getApplication()).getWallet();
tx = (Transaction) getArguments().getSerializable(KEY_TRANSACTION);
final byte[] serializedTx = tx.unsafeBitcoinSerialize();
Address from = null;
boolean fromMine = false;
try
{
from = tx.getOutputs().get(0).getScriptPubKey().getToAddress();
fromMine = wallet.isPubKeyHashMine(from.getHash160());
}
catch (final ScriptException x)
{
x.printStackTrace();
}
Address to = null;
boolean toMine = false;
try
{
to = tx.getInputs().get(0).getFromAddress();
toMine = wallet.isPubKeyHashMine(to.getHash160());
}
catch (final ScriptException x)
{
x.printStackTrace();
}
final boolean sent = tx.sent(wallet);
final boolean pending = wallet.isPending(tx);
final boolean dead = wallet.isDead(tx);
final ContentResolver contentResolver = activity.getContentResolver();
final LayoutInflater inflater = LayoutInflater.from(activity);
final Builder dialog = new AlertDialog.Builder(activity);
final View view = inflater.inflate(R.layout.transaction_fragment, null);
final TextView viewDate = (TextView) view.findViewById(R.id.transaction_fragment_time);
final Date time = tx.getUpdateTime();
if (time != null)
viewDate.setText((DateUtils.isToday(time.getTime()) ? getString(R.string.transaction_fragment_time_today) : dateFormat.format(time))
+ ", " + timeFormat.format(time));
else
view.findViewById(R.id.transaction_fragment_time_row).setVisibility(View.GONE);
final TextView viewAmountLabel = (TextView) view.findViewById(R.id.transaction_fragment_amount_label);
viewAmountLabel.setText(getString(sent ? R.string.transaction_fragment_amount_label_sent
: R.string.transaction_fragment_amount_label_received));
final TextView viewAmount = (TextView) view.findViewById(R.id.transaction_fragment_amount);
try
{
viewAmount.setText((sent ? "-" : "+") + "\u2009" /* thin space */+ Utils.bitcoinValueToFriendlyString(tx.amount(wallet)));
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
final TextView viewFrom = (TextView) view.findViewById(R.id.transaction_fragment_from);
if (from != null)
{
final String label = AddressBookProvider.resolveLabel(contentResolver, from.toString());
final StringBuilder builder = new StringBuilder();
if (fromMine)
builder.append(getString(R.string.transaction_fragment_you)).append(", ");
if (label != null)
{
builder.append(label);
}
else
{
builder.append(from.toString());
viewFrom.setTypeface(Typeface.MONOSPACE);
}
viewFrom.setText(builder.toString());
}
final TextView viewTo = (TextView) view.findViewById(R.id.transaction_fragment_to);
if (to != null)
{
final String label = AddressBookProvider.resolveLabel(contentResolver, to.toString());
final StringBuilder builder = new StringBuilder();
if (toMine)
builder.append(getString(R.string.transaction_fragment_you)).append(", ");
if (label != null)
{
builder.append(label);
}
else
{
builder.append(to.toString());
viewTo.setTypeface(Typeface.MONOSPACE);
}
viewTo.setText(builder.toString());
}
final TextView viewStatus = (TextView) view.findViewById(R.id.transaction_fragment_status);
if (dead)
viewStatus.setText(R.string.transaction_fragment_status_dead);
else if (pending)
viewStatus.setText(R.string.transaction_fragment_status_pending);
else
viewStatus.setText(R.string.transaction_fragment_status_confirmed);
final TextView viewHash = (TextView) view.findViewById(R.id.transaction_fragment_hash);
viewHash.setText(tx.getHash().toString());
final TextView viewLength = (TextView) view.findViewById(R.id.transaction_fragment_length);
viewLength.setText(Integer.toString(serializedTx.length));
final ImageView viewQr = (ImageView) view.findViewById(R.id.transaction_fragment_qr);
final String txStr = "btctx:" + Base64.encodeToString(serializedTx, Base64.NO_WRAP | Base64.NO_PADDING);
final Bitmap qrCodeBitmap = WalletUtils.getQRCodeBitmap(txStr, 512);
viewQr.setImageBitmap(qrCodeBitmap);
viewQr.setOnClickListener(new OnClickListener()
{
public void onClick(final View v)
{
new QrDialog(activity, qrCodeBitmap).show();
}
});
dialog.setView(view);
return dialog.create();
}
| public Dialog onCreateDialog(final Bundle savedInstanceState)
{
final Wallet wallet = ((Application) activity.getApplication()).getWallet();
tx = (Transaction) getArguments().getSerializable(KEY_TRANSACTION);
final byte[] serializedTx = tx.unsafeBitcoinSerialize();
Address from = null;
boolean fromMine = false;
try
{
from = tx.getInputs().get(0).getFromAddress();
fromMine = wallet.isPubKeyHashMine(from.getHash160());
}
catch (final ScriptException x)
{
x.printStackTrace();
}
Address to = null;
boolean toMine = false;
try
{
to = tx.getOutputs().get(0).getScriptPubKey().getToAddress();
toMine = wallet.isPubKeyHashMine(to.getHash160());
}
catch (final ScriptException x)
{
x.printStackTrace();
}
final boolean sent = tx.sent(wallet);
final boolean pending = wallet.isPending(tx);
final boolean dead = wallet.isDead(tx);
final ContentResolver contentResolver = activity.getContentResolver();
final LayoutInflater inflater = LayoutInflater.from(activity);
final Builder dialog = new AlertDialog.Builder(activity);
final View view = inflater.inflate(R.layout.transaction_fragment, null);
final TextView viewDate = (TextView) view.findViewById(R.id.transaction_fragment_time);
final Date time = tx.getUpdateTime();
if (time != null)
viewDate.setText((DateUtils.isToday(time.getTime()) ? getString(R.string.transaction_fragment_time_today) : dateFormat.format(time))
+ ", " + timeFormat.format(time));
else
view.findViewById(R.id.transaction_fragment_time_row).setVisibility(View.GONE);
final TextView viewAmountLabel = (TextView) view.findViewById(R.id.transaction_fragment_amount_label);
viewAmountLabel.setText(getString(sent ? R.string.transaction_fragment_amount_label_sent
: R.string.transaction_fragment_amount_label_received));
final TextView viewAmount = (TextView) view.findViewById(R.id.transaction_fragment_amount);
try
{
viewAmount.setText((sent ? "-" : "+") + "\u2009" /* thin space */+ Utils.bitcoinValueToFriendlyString(tx.amount(wallet)));
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
final TextView viewFrom = (TextView) view.findViewById(R.id.transaction_fragment_from);
if (from != null)
{
final String label = AddressBookProvider.resolveLabel(contentResolver, from.toString());
final StringBuilder builder = new StringBuilder();
if (fromMine)
builder.append(getString(R.string.transaction_fragment_you)).append(", ");
if (label != null)
{
builder.append(label);
}
else
{
builder.append(from.toString());
viewFrom.setTypeface(Typeface.MONOSPACE);
}
viewFrom.setText(builder.toString());
}
final TextView viewTo = (TextView) view.findViewById(R.id.transaction_fragment_to);
if (to != null)
{
final String label = AddressBookProvider.resolveLabel(contentResolver, to.toString());
final StringBuilder builder = new StringBuilder();
if (toMine)
builder.append(getString(R.string.transaction_fragment_you)).append(", ");
if (label != null)
{
builder.append(label);
}
else
{
builder.append(to.toString());
viewTo.setTypeface(Typeface.MONOSPACE);
}
viewTo.setText(builder.toString());
}
final TextView viewStatus = (TextView) view.findViewById(R.id.transaction_fragment_status);
if (dead)
viewStatus.setText(R.string.transaction_fragment_status_dead);
else if (pending)
viewStatus.setText(R.string.transaction_fragment_status_pending);
else
viewStatus.setText(R.string.transaction_fragment_status_confirmed);
final TextView viewHash = (TextView) view.findViewById(R.id.transaction_fragment_hash);
viewHash.setText(tx.getHash().toString());
final TextView viewLength = (TextView) view.findViewById(R.id.transaction_fragment_length);
viewLength.setText(Integer.toString(serializedTx.length));
final ImageView viewQr = (ImageView) view.findViewById(R.id.transaction_fragment_qr);
final String txStr = "btctx:" + Base64.encodeToString(serializedTx, Base64.NO_WRAP | Base64.NO_PADDING);
final Bitmap qrCodeBitmap = WalletUtils.getQRCodeBitmap(txStr, 512);
viewQr.setImageBitmap(qrCodeBitmap);
viewQr.setOnClickListener(new OnClickListener()
{
public void onClick(final View v)
{
new QrDialog(activity, qrCodeBitmap).show();
}
});
dialog.setView(view);
return dialog.create();
}
|
diff --git a/immibis/core/covers/CoverImpl.java b/immibis/core/covers/CoverImpl.java
index f4c69ae..e420d14 100644
--- a/immibis/core/covers/CoverImpl.java
+++ b/immibis/core/covers/CoverImpl.java
@@ -1,410 +1,410 @@
package immibis.core.covers;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import net.minecraft.server.AxisAlignedBB;
import net.minecraft.server.Block;
import net.minecraft.server.EntityHuman;
import net.minecraft.server.ItemStack;
import net.minecraft.server.MovingObjectPosition;
import net.minecraft.server.NBTTagCompound;
import net.minecraft.server.NBTTagList;
import net.minecraft.server.Packet;
import net.minecraft.server.Packet250CustomPayload;
import net.minecraft.server.TileEntity;
import net.minecraft.server.Vec3D;
import net.minecraft.server.World;
public class CoverImpl
{
LinkedList parts;
public BlockCoverableBase wrappedBlock;
public double hollow_edge_size;
public TileEntity te;
public CoverImpl(TileEntity var1, double var2)
{
this.parts = new LinkedList();
this.te = var1;
this.hollow_edge_size = var2;
}
public CoverImpl(TileEntity var1)
{
this(var1, 0.25D);
}
void harvestBlock(World var1, EntityHuman var2, int var3, int var4, int var5, int var6)
{
var2.c(0.025F);
TileEntity var7 = var1.getTileEntity(var3, var4, var5);
if (var7 != null && var7 instanceof ICoverableTile)
{
if (var6 == -2)
{
if (this.wrappedBlock != null)
{
this.wrappedBlock.harvestBlockMultipart(var1, var2, var3, var4, var5, var1.getData(var3, var4, var5));
((TileCoverableBase)var7).convertToMultipartBlockInPlace();
}
}
else if (var6 >= 0)
{
CoverImpl var8 = ((ICoverableTile)var7).getCoverImpl();
if (var6 < var8.parts.size())
{
Part var9 = (Part)var8.parts.get(var6);
if (var9 != null)
{
CoverSystemProxy.blockMultipart.a(var1, var3, var4, var5, new ItemStack(CoverSystemProxy.blockMultipart.id, 1, var9.type.id));
var8.parts.remove(var6);
if (var8.parts.size() == 0 && this.wrappedBlock == null)
{
var1.setRawTypeId(var3, var4, var5, 0);
}
var1.notify(var3, var4, var5);
}
}
}
}
}
public void writeToNBT(NBTTagCompound var1)
{
NBTTagList var2 = new NBTTagList();
Iterator var3 = this.parts.iterator();
while (var3.hasNext())
{
Part var4 = (Part)var3.next();
var2.add(var4.writeToNBT());
}
var1.set("Covers", var2);
}
public void readFromNBT(NBTTagCompound var1)
{
this.parts.clear();
NBTTagList var2 = var1.getList("Covers");
if (var2 != null)
{
for (int var3 = 0; var3 < var2.size(); ++var3)
{
this.parts.add(Part.readFromNBT(var2.get(var3)));
}
}
}
public MovingObjectPosition collisionRayTrace(World var1, int var2, int var3, int var4, Vec3D var5, Vec3D var6)
{
int var7 = 0;
var5 = var5.add((double)(-var2), (double)(-var3), (double)(-var4));
var6 = var6.add((double)(-var2), (double)(-var3), (double)(-var4));
- double var8 = var6.d(var5) + 1.0D;
+ double var8 = var6.distanceSquared(var5) + 1.0D;
Part var10 = null;
MovingObjectPosition var11 = null;
int var12 = -1;
MovingObjectPosition var16;
for (Iterator var13 = this.parts.iterator(); var13.hasNext(); ++var7)
{
Part var14 = (Part)var13.next();
AxisAlignedBB var15 = var14.getBoundingBox();
var16 = var15.a(var5, var6);
if (var16 != null)
{
- double var17 = var16.pos.d(var5);
+ double var17 = var16.pos.distanceSquared(var5);
if (var17 < var8)
{
var11 = var16;
var8 = var17;
var10 = var14;
var12 = var7;
}
}
}
if (var10 == null)
{
return null;
}
else
{
AxisAlignedBB var19 = var10.aabb;
byte var21 = 0;
Vec3D var20 = var11.pos;
if (var20.a <= var19.a)
{
var21 = 4;
}
else if (var20.a >= var19.d)
{
var21 = 5;
}
else if (var20.b <= var19.b)
{
var21 = 0;
}
else if (var20.b >= var19.e)
{
var21 = 1;
}
else if (var20.c <= var19.c)
{
var21 = 2;
}
else if (var20.c >= var19.f)
{
var21 = 3;
}
var16 = new MovingObjectPosition(var2, var3, var4, var21, var20.add((double)var2, (double)var3, (double)var4));
var16.subHit = var12;
return var16;
}
}
public boolean addPart(Part var1)
{
if (!this.canPlace(var1.type, var1.pos))
{
return false;
}
else
{
this.parts.add(var1);
return true;
}
}
public boolean canPlaceCentre(double var1)
{
AxisAlignedBB var3 = Part.getBoundingBox(EnumPosition.Centre, var1);
Iterator var4 = this.parts.iterator();
Part var5;
do
{
if (!var4.hasNext())
{
return true;
}
var5 = (Part)var4.next();
}
while (!var5.getBoundingBox().a(var3));
return false;
}
public boolean canPlace(PartType var1, EnumPosition var2)
{
Iterator var3 = this.parts.iterator();
Part var4;
do
{
if (!var3.hasNext())
{
return true;
}
var4 = (Part)var3.next();
if (var4.pos == var2)
{
return false;
}
}
while (var4.pos.clazz == var2.clazz || !var4.getBoundingBox().a(Part.getBoundingBox(var2, var1.size)));
return false;
}
public void getCollidingBoundingBoxes(World var1, int var2, int var3, int var4, AxisAlignedBB var5, ArrayList var6)
{
Iterator var7 = this.parts.iterator();
while (var7.hasNext())
{
Part var8 = (Part)var7.next();
var6.add(var8.getBoundingBox().c((double)var2, (double)var3, (double)var4));
}
}
public boolean isSideOpen(int var1)
{
AxisAlignedBB var2 = AxisAlignedBB.a(0.25D, 0.25D, 0.25D, 0.75D, 0.75D, 0.75D);
switch (var1)
{
case 0:
var2.b = 0.0D;
break;
case 1:
var2.e = 1.0D;
break;
case 2:
var2.c = 0.0D;
break;
case 3:
var2.f = 1.0D;
break;
case 4:
var2.a = 0.0D;
break;
case 5:
var2.d = 1.0D;
}
Iterator var3 = this.parts.iterator();
Part var4;
do
{
if (!var3.hasNext())
{
return true;
}
var4 = (Part)var3.next();
}
while (var4.type.clazz == EnumPartClass.HollowPanel || var4.pos == EnumPosition.Centre || !var4.getBoundingBox().a(var2));
return false;
}
public boolean isSideOpen(int var1, int var2, int var3, int var4, int var5, int var6)
{
AxisAlignedBB var7 = AxisAlignedBB.a(0.25D, 0.25D, 0.25D, 0.75D, 0.75D, 0.75D);
if (var4 < var1)
{
var7.a = 0.0D;
}
if (var4 > var1)
{
var7.d = 1.0D;
}
if (var5 < var2)
{
var7.b = 0.0D;
}
if (var5 > var2)
{
var7.e = 1.0D;
}
if (var6 < var3)
{
var7.c = 0.0D;
}
if (var6 > var3)
{
var7.f = 1.0D;
}
Iterator var8 = this.parts.iterator();
Part var9;
do
{
if (!var8.hasNext())
{
return true;
}
var9 = (Part)var8.next();
}
while (var9.type.clazz == EnumPartClass.HollowPanel || var9.pos == EnumPosition.Centre || !var9.getBoundingBox().a(var7));
return false;
}
public void writeDescriptionPacket(DataOutputStream var1) throws IOException
{
var1.writeShort(this.wrappedBlock == null ? 0 : this.wrappedBlock.id);
var1.writeShort(this.parts.size());
Iterator var2 = this.parts.iterator();
while (var2.hasNext())
{
Part var3 = (Part)var2.next();
var1.writeByte(var3.pos.ordinal());
var1.writeShort(var3.type.id);
}
}
public void readDescriptionPacket(DataInputStream var1) throws IOException
{
short var2 = var1.readShort();
this.wrappedBlock = var2 == 0 ? null : (BlockCoverableBase)Block.byId[var2];
short var3 = var1.readShort();
this.parts.clear();
for (int var4 = 0; var4 < var3; ++var4)
{
EnumPosition var5 = EnumPosition.values()[var1.readByte()];
int var6 = var1.readShort() & 65535;
this.parts.add(new Part((PartType)CoverSystemProxy.parts.get(Integer.valueOf(var6)), var5));
}
}
public void copyPartsTo(CoverImpl var1)
{
Iterator var2 = this.parts.iterator();
while (var2.hasNext())
{
Part var3 = (Part)var2.next();
var1.addPart(var3);
}
}
public Packet getDefaultDescriptionPacket()
{
try
{
ByteArrayOutputStream var1 = new ByteArrayOutputStream();
DataOutputStream var2 = new DataOutputStream(var1);
var2.writeInt(this.te.x);
var2.writeInt(this.te.y);
var2.writeInt(this.te.z);
this.writeDescriptionPacket(var2);
Packet250CustomPayload var3 = new Packet250CustomPayload();
var3.tag = "ImmibisCoreCDP";
var3.data = var1.toByteArray();
var3.length = var3.data.length;
return var3;
}
catch (IOException var4)
{
var4.printStackTrace();
return null;
}
}
}
| false | true | public MovingObjectPosition collisionRayTrace(World var1, int var2, int var3, int var4, Vec3D var5, Vec3D var6)
{
int var7 = 0;
var5 = var5.add((double)(-var2), (double)(-var3), (double)(-var4));
var6 = var6.add((double)(-var2), (double)(-var3), (double)(-var4));
double var8 = var6.d(var5) + 1.0D;
Part var10 = null;
MovingObjectPosition var11 = null;
int var12 = -1;
MovingObjectPosition var16;
for (Iterator var13 = this.parts.iterator(); var13.hasNext(); ++var7)
{
Part var14 = (Part)var13.next();
AxisAlignedBB var15 = var14.getBoundingBox();
var16 = var15.a(var5, var6);
if (var16 != null)
{
double var17 = var16.pos.d(var5);
if (var17 < var8)
{
var11 = var16;
var8 = var17;
var10 = var14;
var12 = var7;
}
}
}
if (var10 == null)
{
return null;
}
else
{
AxisAlignedBB var19 = var10.aabb;
byte var21 = 0;
Vec3D var20 = var11.pos;
if (var20.a <= var19.a)
{
var21 = 4;
}
else if (var20.a >= var19.d)
{
var21 = 5;
}
else if (var20.b <= var19.b)
{
var21 = 0;
}
else if (var20.b >= var19.e)
{
var21 = 1;
}
else if (var20.c <= var19.c)
{
var21 = 2;
}
else if (var20.c >= var19.f)
{
var21 = 3;
}
var16 = new MovingObjectPosition(var2, var3, var4, var21, var20.add((double)var2, (double)var3, (double)var4));
var16.subHit = var12;
return var16;
}
}
| public MovingObjectPosition collisionRayTrace(World var1, int var2, int var3, int var4, Vec3D var5, Vec3D var6)
{
int var7 = 0;
var5 = var5.add((double)(-var2), (double)(-var3), (double)(-var4));
var6 = var6.add((double)(-var2), (double)(-var3), (double)(-var4));
double var8 = var6.distanceSquared(var5) + 1.0D;
Part var10 = null;
MovingObjectPosition var11 = null;
int var12 = -1;
MovingObjectPosition var16;
for (Iterator var13 = this.parts.iterator(); var13.hasNext(); ++var7)
{
Part var14 = (Part)var13.next();
AxisAlignedBB var15 = var14.getBoundingBox();
var16 = var15.a(var5, var6);
if (var16 != null)
{
double var17 = var16.pos.distanceSquared(var5);
if (var17 < var8)
{
var11 = var16;
var8 = var17;
var10 = var14;
var12 = var7;
}
}
}
if (var10 == null)
{
return null;
}
else
{
AxisAlignedBB var19 = var10.aabb;
byte var21 = 0;
Vec3D var20 = var11.pos;
if (var20.a <= var19.a)
{
var21 = 4;
}
else if (var20.a >= var19.d)
{
var21 = 5;
}
else if (var20.b <= var19.b)
{
var21 = 0;
}
else if (var20.b >= var19.e)
{
var21 = 1;
}
else if (var20.c <= var19.c)
{
var21 = 2;
}
else if (var20.c >= var19.f)
{
var21 = 3;
}
var16 = new MovingObjectPosition(var2, var3, var4, var21, var20.add((double)var2, (double)var3, (double)var4));
var16.subHit = var12;
return var16;
}
}
|
diff --git a/src/org/hackystat/projectbrowser/Start.java b/src/org/hackystat/projectbrowser/Start.java
index 6eec156..e31d1fb 100644
--- a/src/org/hackystat/projectbrowser/Start.java
+++ b/src/org/hackystat/projectbrowser/Start.java
@@ -1,48 +1,49 @@
package org.hackystat.projectbrowser;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
* Provides a mechanism for running Project Browser with Jetty.
* @author Philip Johnson
*/
public class Start {
/**
* Run the project browser with Jetty.
* @param args Ignored.
* @throws Exception If problems occur.
*/
public static void main(String[] args) throws Exception {
ProjectBrowserProperties properties = new ProjectBrowserProperties();
int port = properties.getPort();
String contextPath = properties.getContextRoot();
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/" + contextPath);
bb.setWar("webapp");
server.addHandler(bb);
try {
server.start();
System.out.println(" ");
- System.out.println(properties.getHost() + " is now running. Press return to stop server.");
+ System.out.println(properties.getHost() +
+ " is now running. Press return to stop server.");
while (System.in.available() == 0) {
Thread.sleep(5000);
}
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}
| true | true | public static void main(String[] args) throws Exception {
ProjectBrowserProperties properties = new ProjectBrowserProperties();
int port = properties.getPort();
String contextPath = properties.getContextRoot();
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/" + contextPath);
bb.setWar("webapp");
server.addHandler(bb);
try {
server.start();
System.out.println(" ");
System.out.println(properties.getHost() + " is now running. Press return to stop server.");
while (System.in.available() == 0) {
Thread.sleep(5000);
}
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
| public static void main(String[] args) throws Exception {
ProjectBrowserProperties properties = new ProjectBrowserProperties();
int port = properties.getPort();
String contextPath = properties.getContextRoot();
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/" + contextPath);
bb.setWar("webapp");
server.addHandler(bb);
try {
server.start();
System.out.println(" ");
System.out.println(properties.getHost() +
" is now running. Press return to stop server.");
while (System.in.available() == 0) {
Thread.sleep(5000);
}
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
|
diff --git a/src/org/intellij/erlang/psi/impl/ErlangVarProcessor.java b/src/org/intellij/erlang/psi/impl/ErlangVarProcessor.java
index ee493cdd..159a04cb 100644
--- a/src/org/intellij/erlang/psi/impl/ErlangVarProcessor.java
+++ b/src/org/intellij/erlang/psi/impl/ErlangVarProcessor.java
@@ -1,96 +1,96 @@
/*
* Copyright 2012 Sergey Ignatov
*
* 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.intellij.erlang.psi.impl;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.ResolveState;
import com.intellij.psi.scope.BaseScopeProcessor;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.erlang.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.intellij.erlang.psi.impl.ErlangPsiImplUtil.*;
/**
* @author ignatov
*/
public class ErlangVarProcessor extends BaseScopeProcessor {
public static final Key<Map<String, ErlangQVar>> ERLANG_VARIABLE_CONTEXT = Key.create("ERLANG_VARIABLE_CONTEXT");
private List<ErlangQVar> myVarList = new ArrayList<ErlangQVar>(0);
private final String myRequestedName;
private final PsiElement myOrigin;
public ErlangVarProcessor(String requestedName, PsiElement origin) {
myRequestedName = requestedName;
myOrigin = origin;
}
@Override
public boolean execute(@NotNull PsiElement psiElement, ResolveState resolveState) {
if (psiElement instanceof ErlangFunction) return false;
if (psiElement instanceof ErlangSpecification) return false;
ErlangFunctionClause functionClause = PsiTreeUtil.getTopmostParentOfType(myOrigin, ErlangFunctionClause.class);
ErlangSpecification spec = PsiTreeUtil.getTopmostParentOfType(myOrigin, ErlangSpecification.class);
if (!psiElement.equals(myOrigin) && psiElement instanceof ErlangQVar && psiElement.getText().equals(myRequestedName)) {
boolean inFunctionClause = PsiTreeUtil.isAncestor(functionClause, psiElement, false);
boolean inSpecification = PsiTreeUtil.isAncestor(spec, psiElement, false);
boolean inDefinitionOrAssignment = inDefinition(psiElement) || inAssignment(psiElement);
if ((inFunctionClause && inDefinitionOrAssignment) || inModule(psiElement) || inSpecification) {
boolean inArgumentList = inArgumentList(psiElement);
//noinspection unchecked
boolean inArgumentListBeforeAssignment =
PsiTreeUtil.getParentOfType(psiElement, ErlangArgumentList.class, ErlangAssignmentExpression.class) instanceof ErlangArgumentList;
if (inArgumentList && inArgumentListBeforeAssignment) return true;
if (inDifferentCrClauses(psiElement)) return true;
- myVarList.add(0, (ErlangQVar) psiElement); // put all possible variables to list
+ myVarList.add((ErlangQVar) psiElement); // put all possible variables to list
}
}
PsiFile file = psiElement.getContainingFile();
Map<String,ErlangQVar> context = file.getOriginalFile().getUserData(ERLANG_VARIABLE_CONTEXT);
if (context != null) {
ContainerUtil.addIfNotNull(context.get(myRequestedName), myVarList);
}
return true;
}
private boolean inDifferentCrClauses(PsiElement psiElement) {
ErlangCrClause crClause = PsiTreeUtil.getParentOfType(psiElement, ErlangCrClause.class);
ErlangCrClause crClauseOrigin = PsiTreeUtil.getParentOfType(myOrigin, ErlangCrClause.class);
ErlangCaseExpression caseExpression = PsiTreeUtil.getParentOfType(psiElement, ErlangCaseExpression.class);
ErlangCaseExpression caseExpressionOrigin = PsiTreeUtil.getParentOfType(myOrigin, ErlangCaseExpression.class);
if (caseExpressionOrigin != null && caseExpression == caseExpressionOrigin && crClause != crClauseOrigin) return true;
return false;
}
@Nullable
public ErlangQVar getResult() {
return ContainerUtil.getFirstItem(myVarList); // return the topmost one
}
}
| true | true | public boolean execute(@NotNull PsiElement psiElement, ResolveState resolveState) {
if (psiElement instanceof ErlangFunction) return false;
if (psiElement instanceof ErlangSpecification) return false;
ErlangFunctionClause functionClause = PsiTreeUtil.getTopmostParentOfType(myOrigin, ErlangFunctionClause.class);
ErlangSpecification spec = PsiTreeUtil.getTopmostParentOfType(myOrigin, ErlangSpecification.class);
if (!psiElement.equals(myOrigin) && psiElement instanceof ErlangQVar && psiElement.getText().equals(myRequestedName)) {
boolean inFunctionClause = PsiTreeUtil.isAncestor(functionClause, psiElement, false);
boolean inSpecification = PsiTreeUtil.isAncestor(spec, psiElement, false);
boolean inDefinitionOrAssignment = inDefinition(psiElement) || inAssignment(psiElement);
if ((inFunctionClause && inDefinitionOrAssignment) || inModule(psiElement) || inSpecification) {
boolean inArgumentList = inArgumentList(psiElement);
//noinspection unchecked
boolean inArgumentListBeforeAssignment =
PsiTreeUtil.getParentOfType(psiElement, ErlangArgumentList.class, ErlangAssignmentExpression.class) instanceof ErlangArgumentList;
if (inArgumentList && inArgumentListBeforeAssignment) return true;
if (inDifferentCrClauses(psiElement)) return true;
myVarList.add(0, (ErlangQVar) psiElement); // put all possible variables to list
}
}
PsiFile file = psiElement.getContainingFile();
Map<String,ErlangQVar> context = file.getOriginalFile().getUserData(ERLANG_VARIABLE_CONTEXT);
if (context != null) {
ContainerUtil.addIfNotNull(context.get(myRequestedName), myVarList);
}
return true;
}
| public boolean execute(@NotNull PsiElement psiElement, ResolveState resolveState) {
if (psiElement instanceof ErlangFunction) return false;
if (psiElement instanceof ErlangSpecification) return false;
ErlangFunctionClause functionClause = PsiTreeUtil.getTopmostParentOfType(myOrigin, ErlangFunctionClause.class);
ErlangSpecification spec = PsiTreeUtil.getTopmostParentOfType(myOrigin, ErlangSpecification.class);
if (!psiElement.equals(myOrigin) && psiElement instanceof ErlangQVar && psiElement.getText().equals(myRequestedName)) {
boolean inFunctionClause = PsiTreeUtil.isAncestor(functionClause, psiElement, false);
boolean inSpecification = PsiTreeUtil.isAncestor(spec, psiElement, false);
boolean inDefinitionOrAssignment = inDefinition(psiElement) || inAssignment(psiElement);
if ((inFunctionClause && inDefinitionOrAssignment) || inModule(psiElement) || inSpecification) {
boolean inArgumentList = inArgumentList(psiElement);
//noinspection unchecked
boolean inArgumentListBeforeAssignment =
PsiTreeUtil.getParentOfType(psiElement, ErlangArgumentList.class, ErlangAssignmentExpression.class) instanceof ErlangArgumentList;
if (inArgumentList && inArgumentListBeforeAssignment) return true;
if (inDifferentCrClauses(psiElement)) return true;
myVarList.add((ErlangQVar) psiElement); // put all possible variables to list
}
}
PsiFile file = psiElement.getContainingFile();
Map<String,ErlangQVar> context = file.getOriginalFile().getUserData(ERLANG_VARIABLE_CONTEXT);
if (context != null) {
ContainerUtil.addIfNotNull(context.get(myRequestedName), myVarList);
}
return true;
}
|
diff --git a/src/main/java/net/sourceforge/subsonic/dao/MusicFolderDao.java b/src/main/java/net/sourceforge/subsonic/dao/MusicFolderDao.java
index 3d16659..4aa190e 100644
--- a/src/main/java/net/sourceforge/subsonic/dao/MusicFolderDao.java
+++ b/src/main/java/net/sourceforge/subsonic/dao/MusicFolderDao.java
@@ -1,92 +1,92 @@
/*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package net.sourceforge.subsonic.dao;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import net.sourceforge.subsonic.Logger;
import net.sourceforge.subsonic.domain.MusicFolder;
/**
* Provides database services for music folders.
*
* @author Sindre Mehus
*/
public class MusicFolderDao extends AbstractDao {
private static final Logger LOG = Logger.getLogger(MusicFolderDao.class);
private static final String COLUMNS_FOR_INSERT = "path, name, enabled, changed";
private static final String COLUMNS = "id, "+COLUMNS_FOR_INSERT;
private final MusicFolderRowMapper rowMapper = new MusicFolderRowMapper();
/**
* Returns all music folders.
*
* @return Possibly empty list of all music folders.
*/
public List<MusicFolder> getAllMusicFolders() {
String sql = "select " + COLUMNS + " from music_folder";
return query(sql, rowMapper);
}
/**
* Creates a new music folder.
*
* @param musicFolder The music folder to create.
*/
public void createMusicFolder(MusicFolder musicFolder) {
String sql = "insert into music_folder (" + COLUMNS_FOR_INSERT + ") values (" + questionMarks(COLUMNS_FOR_INSERT) + ")";
- update(sql, musicFolder.getPath(), musicFolder.getName(), musicFolder.isEnabled(), musicFolder.getChanged());
+ update(sql, musicFolder.getPath().getPath(), musicFolder.getName(), musicFolder.isEnabled(), musicFolder.getChanged());
LOG.info("Created music folder " + musicFolder.getPath());
}
/**
* Deletes the music folder with the given ID.
*
* @param id The music folder ID.
*/
public void deleteMusicFolder(Integer id) {
String sql = "delete from music_folder where id=?";
update(sql, id);
LOG.info("Deleted music folder with ID " + id);
}
/**
* Updates the given music folder.
*
* @param musicFolder The music folder to update.
*/
public void updateMusicFolder(MusicFolder musicFolder) {
String sql = "update music_folder set path=?, name=?, enabled=?, changed=? where id=?";
update(sql, musicFolder.getPath().getPath(), musicFolder.getName(),
musicFolder.isEnabled(), musicFolder.getChanged(), musicFolder.getId());
}
private static class MusicFolderRowMapper implements ParameterizedRowMapper<MusicFolder> {
public MusicFolder mapRow(ResultSet rs, int rowNum) throws SQLException {
return new MusicFolder(rs.getInt(1), new File(rs.getString(2)), rs.getString(3), rs.getBoolean(4), rs.getTimestamp(5));
}
}
}
| true | true | public void createMusicFolder(MusicFolder musicFolder) {
String sql = "insert into music_folder (" + COLUMNS_FOR_INSERT + ") values (" + questionMarks(COLUMNS_FOR_INSERT) + ")";
update(sql, musicFolder.getPath(), musicFolder.getName(), musicFolder.isEnabled(), musicFolder.getChanged());
LOG.info("Created music folder " + musicFolder.getPath());
}
| public void createMusicFolder(MusicFolder musicFolder) {
String sql = "insert into music_folder (" + COLUMNS_FOR_INSERT + ") values (" + questionMarks(COLUMNS_FOR_INSERT) + ")";
update(sql, musicFolder.getPath().getPath(), musicFolder.getName(), musicFolder.isEnabled(), musicFolder.getChanged());
LOG.info("Created music folder " + musicFolder.getPath());
}
|
diff --git a/web/src/test/java/org/mule/galaxy/web/server/RegistryServiceTest.java b/web/src/test/java/org/mule/galaxy/web/server/RegistryServiceTest.java
index 553b733f..ee670373 100755
--- a/web/src/test/java/org/mule/galaxy/web/server/RegistryServiceTest.java
+++ b/web/src/test/java/org/mule/galaxy/web/server/RegistryServiceTest.java
@@ -1,248 +1,248 @@
package org.mule.galaxy.web.server;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.mule.galaxy.Artifact;
import org.mule.galaxy.ArtifactVersion;
import org.mule.galaxy.Registry;
import org.mule.galaxy.policy.ApprovalMessage;
import org.mule.galaxy.policy.ArtifactPolicy;
import org.mule.galaxy.test.AbstractGalaxyTest;
import org.mule.galaxy.web.rpc.ArtifactGroup;
import org.mule.galaxy.web.rpc.ArtifactVersionInfo;
import org.mule.galaxy.web.rpc.BasicArtifactInfo;
import org.mule.galaxy.web.rpc.ExtendedArtifactInfo;
import org.mule.galaxy.web.rpc.RegistryService;
import org.mule.galaxy.web.rpc.TransitionResponse;
import org.mule.galaxy.web.rpc.WApprovalMessage;
import org.mule.galaxy.web.rpc.WComment;
import org.mule.galaxy.web.rpc.WGovernanceInfo;
import org.mule.galaxy.web.rpc.WIndex;
import org.mule.galaxy.web.rpc.WWorkspace;
import org.springframework.context.ApplicationContext;
public class RegistryServiceTest extends AbstractGalaxyTest {
protected RegistryService gwtRegistry;
@Override
protected void onSetUp() throws Exception {
super.onSetUp();
createSecureContext(applicationContext, "admin", "admin");
}
@Override
protected String[] getConfigLocations() {
return new String[] { "/META-INF/applicationContext-core.xml",
"/META-INF/applicationContext-acegi-security.xml",
"/META-INF/applicationContext-web.xml" };
}
public void testArtifactOperations() throws Exception {
Collection workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
Collection artifactTypes = gwtRegistry.getArtifactTypes();
assertTrue(artifactTypes.size() > 0);
Collection artifacts = gwtRegistry.getArtifacts(null, null, new HashSet(), null);
- assertEquals(3, artifacts.size());
+ assertTrue(artifacts.size() > 0);
ArtifactGroup g1 = (ArtifactGroup) artifacts.iterator().next();
assertEquals("Mule Configurations", g1.getName());
List columns = g1.getColumns();
assertEquals(6, columns.size());
List rows = g1.getRows();
assertEquals(1, rows.size());
BasicArtifactInfo a = (BasicArtifactInfo) g1.getRows().get(0);
Collection deps = gwtRegistry.getDependencyInfo(a.getId());
assertEquals(0, deps.size());
// Test reretrieving the artifact
g1 = gwtRegistry.getArtifact(a.getId());
g1 = (ArtifactGroup) artifacts.iterator().next();
assertEquals("Mule Configurations", g1.getName());
columns = g1.getColumns();
assertEquals(6, columns.size());
rows = g1.getRows();
assertEquals(1, rows.size());
gwtRegistry.setProperty(a.getId(), "location", "Grand Rapids");
Artifact artifact = registry.getArtifact(a.getId());
assertEquals("Grand Rapids", artifact.getProperty("location"));
// try adding a comment
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertNotNull(auth);
Object principal = auth.getPrincipal();
assertNotNull(principal);
WComment wc = gwtRegistry.addComment(a.getId(), null, "Hello World");
assertNotNull(wc);
WComment wc2 = gwtRegistry.addComment(a.getId(), wc.getId(), "Hello World");
assertNotNull(wc2);
// get the extended artifact info again
g1 = gwtRegistry.getArtifact(a.getId());
rows = g1.getRows();
ExtendedArtifactInfo ext = (ExtendedArtifactInfo) rows.get(0);
List comments = ext.getComments();
assertEquals(1, comments.size());
WComment wc3 = (WComment) comments.get(0);
assertEquals(1, wc3.getComments().size());
assertEquals("/api/registry/Default Workspace/hello-config.xml", ext.getArtifactLink());
assertEquals("/api/comments/Default Workspace/hello-config.xml", ext.getCommentsFeedLink());
// test desc
gwtRegistry.setDescription(a.getId(), "test desc");
}
private static void createSecureContext(final ApplicationContext ctx, final String username, final String password) {
AuthenticationProvider provider = (AuthenticationProvider) ctx.getBean("daoAuthenticationProvider");
Authentication auth = provider.authenticate(new UsernamePasswordAuthenticationToken(username, password));
SecurityContextHolder.getContext().setAuthentication(auth);
}
public void testWorkspaces() throws Exception {
Collection workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
WWorkspace w = (WWorkspace) workspaces.iterator().next();
gwtRegistry.addWorkspace(w.getId(), "Foo");
workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
w = (WWorkspace) workspaces.iterator().next();
assertNotNull(w.getWorkspaces());
assertEquals(1, w.getWorkspaces().size());
assertNotNull(w.getPath());
}
public void testGovernanceOperations() throws Exception {
Collection artifacts = gwtRegistry.getArtifacts(null, null, new HashSet(), null);
ArtifactGroup g1 = (ArtifactGroup) artifacts.iterator().next();
BasicArtifactInfo a = (BasicArtifactInfo) g1.getRows().get(0);
WGovernanceInfo gov = gwtRegistry.getGovernanceInfo(a.getId());
assertEquals("Created", gov.getCurrentPhase());
Collection nextPhases = gov.getNextPhases();
assertNotNull(nextPhases);
assertEquals(1, nextPhases.size());
String next = (String) nextPhases.iterator().next();
TransitionResponse res = gwtRegistry.transition(a.getId(), next);
assertTrue(res.isSuccess());
// activate a policy which will make transitioning fail
FauxPolicy policy = new FauxPolicy();
policyManager.addPolicy(policy);
policyManager.setActivePolicies(lifecycleManager.getDefaultLifecycle(), policy);
// Try transitioning
gov = gwtRegistry.getGovernanceInfo(a.getId());
nextPhases = gov.getNextPhases();
assertNotNull(nextPhases);
assertEquals(1, nextPhases.size());
next = (String) nextPhases.iterator().next();
res = gwtRegistry.transition(a.getId(), next);
assertFalse(res.isSuccess());
assertEquals(1, res.getMessages().size());
WApprovalMessage msg = (WApprovalMessage) res.getMessages().iterator().next();
assertEquals("Not approved", msg.getMessage());
assertFalse(msg.isWarning());
}
public void testVersioningOperations() throws Exception {
Set result = registry.search("select artifact where wsdl.service = 'HelloWorldService'");
Artifact a = (Artifact) result.iterator().next();
registry.newVersion(a, getResourceAsStream("/wsdl/imports/hello.wsdl"), "0.2", getAdmin());
Collection versions = gwtRegistry.getArtifactVersions(a.getId());
assertEquals(2, versions.size());
ArtifactVersionInfo info = (ArtifactVersionInfo) versions.iterator().next();
assertEquals("0.2", info.getVersionLabel());
assertNotNull(info.getLink());
assertNotNull(info.getCreated());
assertEquals("Administrator", info.getAuthorName());
assertEquals("admin", info.getAuthorUsername());
TransitionResponse res = gwtRegistry.setActive(a.getId(), "0.1");
assertTrue(res.isSuccess());
}
public void testIndexes() throws Exception {
Collection indexes = gwtRegistry.getIndexes();
assertTrue(indexes.size() > 0);
WIndex idx = gwtRegistry.getIndex("wsdl.service");
assertNotNull(idx);
assertNotNull(idx.getResultType());
}
private final class FauxPolicy implements ArtifactPolicy {
public String getDescription() {
return "Faux policy description";
}
public boolean applies(Artifact a) {
return true;
}
public String getId() {
return "faux";
}
public String getName() {
return "Faux policy";
}
public Collection<ApprovalMessage> isApproved(Artifact a, ArtifactVersion previous, ArtifactVersion next) {
return Arrays.asList(new ApprovalMessage("Not approved"));
}
public void setRegistry(Registry registry) {
}
}
}
| true | true | public void testArtifactOperations() throws Exception {
Collection workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
Collection artifactTypes = gwtRegistry.getArtifactTypes();
assertTrue(artifactTypes.size() > 0);
Collection artifacts = gwtRegistry.getArtifacts(null, null, new HashSet(), null);
assertEquals(3, artifacts.size());
ArtifactGroup g1 = (ArtifactGroup) artifacts.iterator().next();
assertEquals("Mule Configurations", g1.getName());
List columns = g1.getColumns();
assertEquals(6, columns.size());
List rows = g1.getRows();
assertEquals(1, rows.size());
BasicArtifactInfo a = (BasicArtifactInfo) g1.getRows().get(0);
Collection deps = gwtRegistry.getDependencyInfo(a.getId());
assertEquals(0, deps.size());
// Test reretrieving the artifact
g1 = gwtRegistry.getArtifact(a.getId());
g1 = (ArtifactGroup) artifacts.iterator().next();
assertEquals("Mule Configurations", g1.getName());
columns = g1.getColumns();
assertEquals(6, columns.size());
rows = g1.getRows();
assertEquals(1, rows.size());
gwtRegistry.setProperty(a.getId(), "location", "Grand Rapids");
Artifact artifact = registry.getArtifact(a.getId());
assertEquals("Grand Rapids", artifact.getProperty("location"));
// try adding a comment
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertNotNull(auth);
Object principal = auth.getPrincipal();
assertNotNull(principal);
WComment wc = gwtRegistry.addComment(a.getId(), null, "Hello World");
assertNotNull(wc);
WComment wc2 = gwtRegistry.addComment(a.getId(), wc.getId(), "Hello World");
assertNotNull(wc2);
// get the extended artifact info again
g1 = gwtRegistry.getArtifact(a.getId());
rows = g1.getRows();
ExtendedArtifactInfo ext = (ExtendedArtifactInfo) rows.get(0);
List comments = ext.getComments();
assertEquals(1, comments.size());
WComment wc3 = (WComment) comments.get(0);
assertEquals(1, wc3.getComments().size());
assertEquals("/api/registry/Default Workspace/hello-config.xml", ext.getArtifactLink());
assertEquals("/api/comments/Default Workspace/hello-config.xml", ext.getCommentsFeedLink());
// test desc
gwtRegistry.setDescription(a.getId(), "test desc");
}
| public void testArtifactOperations() throws Exception {
Collection workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
Collection artifactTypes = gwtRegistry.getArtifactTypes();
assertTrue(artifactTypes.size() > 0);
Collection artifacts = gwtRegistry.getArtifacts(null, null, new HashSet(), null);
assertTrue(artifacts.size() > 0);
ArtifactGroup g1 = (ArtifactGroup) artifacts.iterator().next();
assertEquals("Mule Configurations", g1.getName());
List columns = g1.getColumns();
assertEquals(6, columns.size());
List rows = g1.getRows();
assertEquals(1, rows.size());
BasicArtifactInfo a = (BasicArtifactInfo) g1.getRows().get(0);
Collection deps = gwtRegistry.getDependencyInfo(a.getId());
assertEquals(0, deps.size());
// Test reretrieving the artifact
g1 = gwtRegistry.getArtifact(a.getId());
g1 = (ArtifactGroup) artifacts.iterator().next();
assertEquals("Mule Configurations", g1.getName());
columns = g1.getColumns();
assertEquals(6, columns.size());
rows = g1.getRows();
assertEquals(1, rows.size());
gwtRegistry.setProperty(a.getId(), "location", "Grand Rapids");
Artifact artifact = registry.getArtifact(a.getId());
assertEquals("Grand Rapids", artifact.getProperty("location"));
// try adding a comment
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertNotNull(auth);
Object principal = auth.getPrincipal();
assertNotNull(principal);
WComment wc = gwtRegistry.addComment(a.getId(), null, "Hello World");
assertNotNull(wc);
WComment wc2 = gwtRegistry.addComment(a.getId(), wc.getId(), "Hello World");
assertNotNull(wc2);
// get the extended artifact info again
g1 = gwtRegistry.getArtifact(a.getId());
rows = g1.getRows();
ExtendedArtifactInfo ext = (ExtendedArtifactInfo) rows.get(0);
List comments = ext.getComments();
assertEquals(1, comments.size());
WComment wc3 = (WComment) comments.get(0);
assertEquals(1, wc3.getComments().size());
assertEquals("/api/registry/Default Workspace/hello-config.xml", ext.getArtifactLink());
assertEquals("/api/comments/Default Workspace/hello-config.xml", ext.getCommentsFeedLink());
// test desc
gwtRegistry.setDescription(a.getId(), "test desc");
}
|
diff --git a/src/core/org/luaj/vm/LString.java b/src/core/org/luaj/vm/LString.java
index 2e9a864..cb968f0 100644
--- a/src/core/org/luaj/vm/LString.java
+++ b/src/core/org/luaj/vm/LString.java
@@ -1,451 +1,451 @@
/*******************************************************************************
* Copyright (c) 2007 LuaJ. All rights reserved.
*
* 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.luaj.vm;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* A String implementation for Lua using bytes instead of chars.
*
* This should have the following advantages:
*
* (1) We can use strings as byte buffers, as Lua does, and therefore avoid
* questions about how to adapt Lua APIs that use strings with binary data.
*
* (2) Half the memory usage when strings are primarily ASCII
*
*
* TODO: Decide if/when to copy the bytes to a new array to ensure memory does
* not "leak" in the form of unused portions of byte arrays. Currently, for
* efficiency, new LStrings and substrings never create copies.
*/
public class LString extends LValue {
public final byte[] m_bytes;
public final int m_offset;
public final int m_length;
public final int m_hash;
private static LTable s_stringMT;
public static final LString[] LTYPENAMES;
static {
int n = Lua.TYPE_NAMES.length;
LTYPENAMES = new LString[n];
for ( int i=0; i<n; i++ )
LTYPENAMES[i] = new LString(Lua.TYPE_NAMES[i]);
}
/**
* Construct a Lua string from the given Java string.
* Characters are encoded using UTF-8.
*/
public LString(String string) {
// measure bytes required to encode
int b = lengthAsUtf8( string );
byte[] bytes = new byte[b];
encodeToUtf8( string, bytes, 0 );
this.m_bytes = bytes;
this.m_offset = 0;
this.m_length = b;
this.m_hash = hashBytes( bytes, 0, b );
}
/**
* Convert to Java string using UTF-8 encoding
*/
public String toJavaString() {
char[] c=new char[m_length];
int i, j, b, n=0;
for ( i=m_offset, j=m_offset+m_length; i<j; ) {
if ((b = m_bytes[i++]) == 0)
return new String(c,0,n);
c[n++] = (char) (
(b>=0||i>=j)?
b:
(b<-32||i+1>=j)?
(((b&0x3f) << 6)
| (m_bytes[i++]&0x3f)):
(((b&0xf) << 12)
| ((m_bytes[i++]&0x3f)<<6)
| (m_bytes[i++]&0x3f))
);
}
return new String(c,0,n);
}
/**
* Construct a string from the given byte array.
*
* new LString(b) is identical to new LString(b, 0, b.length)
*/
public LString(byte[] bytes) {
this( bytes, 0, bytes.length );
}
/**
* Construct a string from the given byte array and range. For efficiency,
* the byte array is not copied. Lua strings are immutable so the bytes must
* not be modified after the string is constructed.
*/
public LString(byte[] bytes, int off, int len) {
if ( off < 0 || len < 0 || off+len > bytes.length )
throw new IndexOutOfBoundsException();
this.m_bytes = bytes;
this.m_offset = off;
this.m_length = len;
this.m_hash = hashBytes( bytes, off, len );
}
public static LString newStringCopy(LString src) {
return newStringCopy( src.m_bytes, src.m_offset, src.m_length );
}
public static LString newStringCopy(byte[] buf, int off, int len) {
byte[] b = new byte[len];
System.arraycopy( buf, off, b, 0, len );
return new LString( b, 0, len );
}
public static LString newStringNoCopy(byte[] buf, int off, int len) {
return new LString( buf, off, len );
}
/**
* Count the number of bytes required to encode the string as UTF-8.
*/
public static int lengthAsUtf8(String string) {
int n = string.length();
int b = n;
char c;
for ( int i=0; i<n; i++ ) {
if ( (c = string.charAt(i)) >= 0x80 ) {
++b;
if ( c >= 0x800 )
++b;
}
}
return b;
}
/**
* Encode the given Java string as UTF-8 bytes, writing the result to bytes
* starting at offset. The string should be measured first with lengthAsUtf8
* to make sure the given byte array is large enough.
*/
public static void encodeToUtf8(String string, byte[] bytes, final int startOffset) {
final int n = string.length();
for ( int i=0, j=startOffset; i<n; i++ ) {
int c;
if ( (c = string.charAt(i)) < 0x80 ) {
bytes[j++] = (byte) c;
} else if ( c < 0x800 ) {
bytes[j++] = (byte) (0xC0 | ((c>>6) & 0x1f));
bytes[j++] = (byte) (0x80 | ( c & 0x3f));
} else {
bytes[j++] = (byte) (0xE0 | ((c>>12) & 0x0f));
bytes[j++] = (byte) (0x80 | ((c>>6) & 0x3f));
bytes[j++] = (byte) (0x80 | ( c & 0x3f));
}
}
}
public boolean isString() {
return true;
}
public boolean equals(Object o) {
if ( o != null && o instanceof LString ) {
LString s = (LString) o;
return m_hash == s.m_hash &&
m_length == s.m_length &&
( ( m_bytes == s.m_bytes && m_offset == s.m_offset ) ||
equals( m_bytes, m_offset, s.m_bytes, s.m_offset, m_length ) );
}
return false;
}
public int compareTo( LString o ) {
final byte[] a = this.m_bytes;
final byte[] b = o.m_bytes;
int i = this.m_offset;
int j = o.m_offset;
final int imax = i + m_length;
final int jmax = j + o.m_length;
if ( a == b && i == j && imax == jmax )
return 0;
while ( i < imax && j < jmax ) {
- if ( a[i] != b[i] ) {
+ if ( a[i] != b[j] ) {
return ( ( (int)a[i] ) & 0x0FF ) - ( ( (int)b[j] ) & 0x0FF );
}
i++;
j++;
}
return m_length - o.m_length;
}
public int hashCode() {
return m_hash;
}
public int length() {
return m_length;
}
public LString substring( int beginIndex, int endIndex ) {
return new LString( m_bytes, m_offset + beginIndex, endIndex - beginIndex );
}
public int charAt( int index ) {
if ( index < 0 || index >= m_length )
throw new IndexOutOfBoundsException();
return luaByte( index );
}
/** Java version of strpbrk, which is a terribly named C function. */
public int indexOfAny( LString accept ) {
final int ilimit = m_offset + m_length;
final int jlimit = accept.m_offset + accept.m_length;
for ( int i = m_offset; i < ilimit; ++i ) {
for ( int j = accept.m_offset; j < jlimit; ++j ) {
if ( m_bytes[i] == accept.m_bytes[j] ) {
return i - m_offset;
}
}
}
return -1;
}
public int indexOf( byte b, int start ) {
for ( int i = m_offset + start; i < m_length; ++i ) {
if ( m_bytes[i] == b )
return i;
}
return -1;
}
public int indexOf( LString s, int start ) {
final int slen = s.length();
final int limit = m_offset + m_length - slen;
for ( int i = m_offset + start; i <= limit; ++i ) {
if ( equals( m_bytes, i, s.m_bytes, s.m_offset, slen ) ) {
return i;
}
}
return -1;
}
public int lastIndexOf( LString s ) {
final int slen = s.length();
final int limit = m_offset + m_length - slen;
for ( int i = limit; i >= m_offset; --i ) {
if ( equals( m_bytes, i, s.m_bytes, s.m_offset, slen ) ) {
return i;
}
}
return -1;
}
public static LString valueOf( double d ) {
return new LString( String.valueOf( d ) );
}
public static LString valueOf( int x ) {
return new LString( String.valueOf( x ) );
}
public static LString valueOf(String s) {
return new LString( s );
}
/**
* Write the specified substring of this string to the given output stream.
*/
public void write( OutputStream os, int offset, int len ) throws IOException {
if ( offset < 0 || len < 0 )
throw new IndexOutOfBoundsException();
if ( offset + len > m_length )
throw new IndexOutOfBoundsException();
os.write( m_bytes, m_offset+offset, len );
}
public void write(OutputStream os) throws IOException {
write(os, 0, m_length);
}
/**
* Copy the bytes of the string into the given byte array.
*/
public void copyInto( int strOffset, byte[] bytes, int arrayOffset, int len ) {
System.arraycopy( m_bytes, m_offset+strOffset, bytes, arrayOffset, len );
}
/**
* Produce an InputStream instance from which the bytes of this LString can be read.
* Underlying byte array is not copied.
*/
public ByteArrayInputStream toInputStream() {
// Well, this is really something.
// Javadoc for java versions 1.3 and earlier states that if reset() is
// called on a ByteArrayInputStream constructed with the 3-argument
// constructor, then bytes 0 .. offset will be returned by the next
// calls to read(). In JDK 1.4, the behavior improved, so that the
// initial mark is set to the initial offset. We still need to
// override ByteArrayInputStream here just in case we run on a
// JVM with the older behavior.
return new ByteArrayInputStream( m_bytes, m_offset, m_length ) {
public synchronized void reset() {
pos = Math.max( m_offset, mark );
}
};
}
public boolean luaBinCmpUnknown(int opcode, LValue lhs) {
return lhs.luaBinCmpString(opcode, this);
}
public boolean luaBinCmpString(int opcode, LString rhs) {
switch ( opcode ) {
case Lua.OP_EQ: return equals(rhs);
case Lua.OP_LT: return compareTo(rhs) < 0;
case Lua.OP_LE: return compareTo(rhs) <= 0;
}
LuaState.vmerror( "bad cmp opcode" );
return false;
}
public LValue luaBinOpDouble( int opcode, double m_value ) {
return luaToNumber().luaBinOpDouble( opcode, m_value );
}
public LValue luaBinOpInteger( int opcode, int m_value ) {
return luaToNumber().luaBinOpInteger( opcode, m_value );
}
public LValue luaBinOpUnknown( int opcode, LValue lhs ) {
return luaToNumber().luaBinOpUnknown( opcode, lhs );
}
public LValue luaUnaryMinus() {
return luaToNumber().luaUnaryMinus();
}
public LValue luaToNumber() {
return luaToNumber( 10 );
}
public LValue luaToNumber( int base ) {
if ( base >= 2 && base <= 36 ) {
String str = toJavaString().trim();
try {
return LInteger.valueOf( Integer.parseInt( str, base ) );
} catch ( NumberFormatException nfe ) {
if ( base == 10 ) {
try {
return new LDouble( Double.parseDouble( str ) );
} catch ( NumberFormatException nfe2 ) {
}
}
}
}
return LNil.NIL;
}
public LString luaAsString() {
return this;
}
/** Built-in opcode LEN, for Strings and Tables */
public int luaLength() {
return m_length;
}
public int luaGetType() {
return Lua.LUA_TSTRING;
}
public LTable luaGetMetatable() {
synchronized ( LString.class ) {
return s_stringMT;
}
}
/**
* Get the metatable for all string values. Creates the table if it does not
* exist yet, and sets its __index entry to point to itself.
*
* @return metatable that will be used for all strings
*/
public static synchronized LTable getMetatable() {
if ( s_stringMT == null ) {
s_stringMT = new LTable();
s_stringMT.put( TM_INDEX, s_stringMT );
}
return s_stringMT;
}
public static boolean equals( LString a, int i, LString b, int j, int n ) {
return equals( a.m_bytes, a.m_offset + i, b.m_bytes, b.m_offset + j, n );
}
public static boolean equals( byte[] a, int i, byte[] b, int j, int n ) {
if ( a.length < i + n || b.length < j + n )
return false;
final int imax = i + n;
final int jmax = j + n;
while ( i < imax && j < jmax ) {
if ( a[i++] != b[j++] )
return false;
}
return true;
}
private static int hashBytes( byte[] bytes, int offset, int length ) {
// Compute the hash of the given bytes.
// This code comes right out of Lua 5.1.2 (translated from C to Java)
int h = length; /* seed */
int step = (length>>5)+1; /* if string is too long, don't hash all its chars */
for (int l1=length; l1>=step; l1-=step) /* compute hash */
h = h ^ ((h<<5)+(h>>2)+(((int) bytes[offset+l1-1] ) & 0x0FF ));
return h;
}
public int luaByte(int index) {
return m_bytes[m_offset + index] & 0x0FF;
}
public void luaConcatTo(ByteArrayOutputStream baos) {
baos.write( m_bytes, m_offset, m_length );
}
}
| true | true | public int compareTo( LString o ) {
final byte[] a = this.m_bytes;
final byte[] b = o.m_bytes;
int i = this.m_offset;
int j = o.m_offset;
final int imax = i + m_length;
final int jmax = j + o.m_length;
if ( a == b && i == j && imax == jmax )
return 0;
while ( i < imax && j < jmax ) {
if ( a[i] != b[i] ) {
return ( ( (int)a[i] ) & 0x0FF ) - ( ( (int)b[j] ) & 0x0FF );
}
i++;
j++;
}
return m_length - o.m_length;
}
| public int compareTo( LString o ) {
final byte[] a = this.m_bytes;
final byte[] b = o.m_bytes;
int i = this.m_offset;
int j = o.m_offset;
final int imax = i + m_length;
final int jmax = j + o.m_length;
if ( a == b && i == j && imax == jmax )
return 0;
while ( i < imax && j < jmax ) {
if ( a[i] != b[j] ) {
return ( ( (int)a[i] ) & 0x0FF ) - ( ( (int)b[j] ) & 0x0FF );
}
i++;
j++;
}
return m_length - o.m_length;
}
|
diff --git a/sources/gomoku/jeu/Partie.java b/sources/gomoku/jeu/Partie.java
index 7488f19..97c43b5 100644
--- a/sources/gomoku/jeu/Partie.java
+++ b/sources/gomoku/jeu/Partie.java
@@ -1,166 +1,174 @@
package gomoku.jeu;
import java.util.Set;
import gomoku.regles.Variante;
import gomoku.regles.RegleCoup;
import gomoku.regles.RegleAlignement;
import gomoku.jeu.Plateau;
import gomoku.jeu.Grille;
import gomoku.jeu.PierreCoordonnees;
public class Partie {
private JoueurAbstrait jNoir;
private JoueurAbstrait jBlanc;
private Plateau plateau;
private boolean premierCoup = true;
private int doisJouer = Joueur.NOIR;
private int gagnant;
private String CLIouGUI;
private Visuel visualiser;
public Partie(JoueurAbstrait jNoir, JoueurAbstrait jBlanc, Plateau plateau,
Visuel visualiser) {
this.jNoir = jNoir;
this.jBlanc = jBlanc;
this.plateau = plateau;
this.visualiser = visualiser;
}
public int getGagnant() {
return this.gagnant;
}
public void jouer(Coordonnees c) {
+ int cpt = 0;
+ for (int x = 0; x < this.plateau.largeur() ; x++)
+ for (int y = 0; y < this.plateau.hauteur() ; y++)
+ if (this.plateau.contenu(new PierreCoordonnees(x, y)) == Joueur.VIDE) {
+ cpt++;
+ }
+ if (cpt == 0)
+ this.visualiser.laPartieEstNulle();
if (c == null)
this.CLIouGUI = "CLI";
else
this.CLIouGUI = "GUI";
String str;
if (this.coupAjouer()) {
if(this.demanderDeJouer(c))
this.visualiser.afficherLaGrille();
if (this.gagnant != 0) {
if (this.getGagnant() == Joueur.NOIR)
str = this.jNoir.couleurIntToString();
else
str = this.jBlanc.couleurIntToString();
this.visualiser.leJoueurAGagne(str);
} else {
if (this.CLIouGUI.equals("CLI"))
this.jouer(null);
}
} else {
this.visualiser.laPartieEstNulle();
}
}
/** Cette méthode vérifie s'il reste des coups à jouer
* @return true ou false */
public boolean coupAjouer() {
if (!(this.jNoir.getNbCoups() == 0
&& this.jBlanc.getNbCoups() == 0))
return true;
return false;
}
/** Cette méthode demande les coordonnées
* au joueur qui a la main.
* @return une coordonnées */
public Coordonnees demanderCoor() {
if (this.aLaMain(Joueur.NOIR))
return this.jNoir.demanderCoorJoueur(this);
else
return this.jBlanc.demanderCoorJoueur(this);
}
/** Permet de savoir si le joueur a la main
* @param la couleur du joueur
* @return true si la couleur correspond au joueur qui à la main
* false sinon.
*/
public boolean aLaMain(int couleur) {
return couleur == this.doisJouer ? true : false;
}
public boolean demanderDeJouer(Coordonnees c) {
Variante v = ((Grille)plateau).getVariante();
RegleCoup r = v.verifCoup();
if (this.premierCoup) {
this.premierCoup = false;
if (c == null)
c = this.demanderCoor();
this.joueurJoue(c);
return true;
} else {
if (c == null)
c = this.demanderCoor();
if (r.estValide(c, plateau) &&
this.plateau.contenu(c) == Joueur.VIDE)
{
this.joueurJoue(c);
return true;
}
}
return false;
}
public void joueurJoue(Coordonnees c) {
if (this.aLaMain(Joueur.NOIR)) {
this.plateau.placer(c, this.jNoir.couleur());
this.jNoir.joueUnePierre();
}
else {
if (c == null)
this.visualiser.laPartieEstNulle();
this.plateau.placer(c, this.jBlanc.couleur());
this.jBlanc.joueUnePierre();
}
this.verifierCoupGagnant();
}
/** Permet de donner la main au joueur suivant
*/
public void donnerLaMain() {
this.doisJouer = this.aLaMain(Joueur.NOIR) ?
Joueur.BLANC : Joueur.NOIR;
}
public void verifierCoupGagnant() {
Coordonnees c;
Variante v = ((Grille)this.plateau).getVariante();
RegleAlignement regle = v.verifAlignement();
Set<Alignement> align = plateau.rechercherAlignements(this.doisJouer,
regle.tailleMin());
for (Alignement a: align) {
if (regle.estGagnant(a, this.plateau))
this.gagnant = this.doisJouer;
}
if (this.gagnant == 0) {
this.donnerLaMain();
if (this.aLaMain(Joueur.BLANC)) {
if (this.blancEstUneIA()) {
c = this.demanderCoor();
this.joueurJoue(c);
}
}
}
}
/** Permet de savoir si le joueur est une Intelligence
* Artificielle.
* @return true si oui, false sinon
*/
private boolean blancEstUneIA() {
return this.jBlanc.getClass().getName() ==
"gomoku.jeu.JoueurCybernetique" ? true : false;
}
/** Permet de récupérer le plateau
* @return le plateau correspondant à la partie.
*/
public Plateau getPlateau() {
return this.plateau;
}
}
| true | true | public void jouer(Coordonnees c) {
if (c == null)
this.CLIouGUI = "CLI";
else
this.CLIouGUI = "GUI";
String str;
if (this.coupAjouer()) {
if(this.demanderDeJouer(c))
this.visualiser.afficherLaGrille();
if (this.gagnant != 0) {
if (this.getGagnant() == Joueur.NOIR)
str = this.jNoir.couleurIntToString();
else
str = this.jBlanc.couleurIntToString();
this.visualiser.leJoueurAGagne(str);
} else {
if (this.CLIouGUI.equals("CLI"))
this.jouer(null);
}
} else {
this.visualiser.laPartieEstNulle();
}
}
| public void jouer(Coordonnees c) {
int cpt = 0;
for (int x = 0; x < this.plateau.largeur() ; x++)
for (int y = 0; y < this.plateau.hauteur() ; y++)
if (this.plateau.contenu(new PierreCoordonnees(x, y)) == Joueur.VIDE) {
cpt++;
}
if (cpt == 0)
this.visualiser.laPartieEstNulle();
if (c == null)
this.CLIouGUI = "CLI";
else
this.CLIouGUI = "GUI";
String str;
if (this.coupAjouer()) {
if(this.demanderDeJouer(c))
this.visualiser.afficherLaGrille();
if (this.gagnant != 0) {
if (this.getGagnant() == Joueur.NOIR)
str = this.jNoir.couleurIntToString();
else
str = this.jBlanc.couleurIntToString();
this.visualiser.leJoueurAGagne(str);
} else {
if (this.CLIouGUI.equals("CLI"))
this.jouer(null);
}
} else {
this.visualiser.laPartieEstNulle();
}
}
|
diff --git a/br.org.archimedes.io.svg/trunk/src/br/org/archimedes/io/svg/SVGExporter.java b/br.org.archimedes.io.svg/trunk/src/br/org/archimedes/io/svg/SVGExporter.java
index bc2b448e..6847761d 100644
--- a/br.org.archimedes.io.svg/trunk/src/br/org/archimedes/io/svg/SVGExporter.java
+++ b/br.org.archimedes.io.svg/trunk/src/br/org/archimedes/io/svg/SVGExporter.java
@@ -1,204 +1,204 @@
/**
* Copyright (c) 2009 Hugo Corbucci and others.<br>
* 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<br>
* <br>
* Contributors:<br>
* Bruno Klava, Ricardo Sider - initial API and implementation<br>
* <br>
* This file was created on 2009/03/26, 12:05:56, by Ricardo Sider.<br>
* It is part of package br.org.archimedes.io.svg on the br.org.archimedes.io.svg project.<br>
*/
package br.org.archimedes.io.svg;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import br.org.archimedes.exceptions.NotSupportedException;
import br.org.archimedes.gui.opengl.Color;
import br.org.archimedes.infiniteline.InfiniteLine;
import br.org.archimedes.interfaces.ElementExporter;
import br.org.archimedes.interfaces.Exporter;
import br.org.archimedes.io.svg.rcp.ElementExporterEPLoader;
import br.org.archimedes.model.Drawing;
import br.org.archimedes.model.Element;
import br.org.archimedes.model.Layer;
import br.org.archimedes.model.Rectangle;
import br.org.archimedes.rcp.extensionpoints.ElementEPLoader;
import br.org.archimedes.semiline.Semiline;
/**
* Belongs to package br.org.archimedes.io.svg.
*
* @author klava, sider
*/
public class SVGExporter implements Exporter {
/**
* Returns the boundary rectangle containing all the drawing elements. It ignores the infinite
* lines and includes only the initial point of semilines.
*
* @param drawing
* @return the boundary rectangle containing all the drawing elements
*/
private Rectangle getBoundaryRectangle (Drawing drawing) {
Rectangle boundaryRectangle = null;
for (Layer layer : drawing.getLayerMap().values()) {
for (Element element : layer.getElements()) {
if (element instanceof InfiniteLine) {
continue;
}
else if (element instanceof Semiline) {
Semiline semiline = (Semiline) element;
Rectangle rect = new Rectangle(semiline.getInitialPoint().getX(), semiline
.getInitialPoint().getY(), 0, 0);
if (boundaryRectangle == null) {
boundaryRectangle = rect;
}
else {
boundaryRectangle = boundaryRectangle.union(rect);
}
continue;
}
else {
boundaryRectangle = boundaryRectangle.union(element.getBoundaryRectangle());
}
}
}
if (boundaryRectangle == null) {
boundaryRectangle = new Rectangle(0, 0, 0, 0);
}
return boundaryRectangle;
}
/**
* (non-Javadoc).
*
* @see br.org.archimedes.interfaces.Exporter#exportDrawing(br.org.archimedes.interfaces.Drawing,
* java.io.OutputStream)
*/
public void exportDrawing (Drawing drawing, OutputStream output) throws IOException {
String charset = "UTF-8"; //$NON-NLS-1$
// TODO Forçar locale
Rectangle boundaryRectangle = getBoundaryRectangle(drawing);
exportSVGHeader(drawing, output, charset, boundaryRectangle);
byte[] endContainerTagBytes = ("\t" + "</container>" + "\n") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
.getBytes(charset);
ElementEPLoader elementEPLoader = new ElementEPLoader();
ElementExporterEPLoader exporterLoader = new ElementExporterEPLoader();
for (Layer layer : drawing.getLayerMap().values()) {
StringBuilder containerTag = new StringBuilder();
containerTag.append("\t" + "<container name=\"" + layer.getName() //$NON-NLS-1$ //$NON-NLS-2$
+ "\" lineStyle=\"" + layer.getLineStyle().ordinal() //$NON-NLS-1$
+ "\" thickness=\"" + layer.getThickness() //$NON-NLS-1$
+ "\" visible=\"" + layer.isVisible() //$NON-NLS-1$
+ "\" locked=\"" + layer.isLocked() + "\"" + " >" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
writeColor(containerTag, layer.getColor());
writeColor(containerTag, layer.getPrintColor());
output.write(containerTag.toString().getBytes(charset));
for (Element element : layer.getElements()) {
String elementId = elementEPLoader.getElementId(element);
ElementExporter<Element> exporter = exporterLoader.getExporter(elementId);
if (exporter == null) {
System.err.println(Messages.bind(Messages.SVGExporter_NoExporter, elementId));
}
else {
try {
if (element instanceof InfiniteLine || element instanceof Semiline) {
exporter.exportElement(element, output, boundaryRectangle);
}
else {
exporter.exportElement(element, output);
}
}
catch (NotSupportedException e) {
// wont reach here
}
}
}
output.write(endContainerTagBytes);
}
- output.write(("</drawing>" + "\n").getBytes(charset)); //$NON-NLS-1$ //$NON-NLS-2$
+ output.write(("</svg>" + "\n").getBytes(charset)); //$NON-NLS-1$ //$NON-NLS-2$
output.close();
}
/**
* @param drawing
* Drawing to be exported
* @param output
* The outputstream to write on
* @param charset
* The charset to use to write the file @ * @throws IOException Thrown if something
* goes wrong when writing the file
* @throws UnsupportedEncodingException
* Thrown if the system cannot write in the specified charset
*/
private void exportSVGHeader (Drawing drawing, OutputStream output, String charset,
Rectangle boundaryRectangle) throws IOException, UnsupportedEncodingException {
StringBuilder drawingTag = new StringBuilder("<?xml version=\"1.0\" encoding=\"" + charset
+ "\"?>" + "\n");
drawingTag.append("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\""
// + " width="10cm" height="3cm"
+ " viewBox=\"" + (int) Math.ceil(boundaryRectangle.getLowerLeft().getX()) + " "
+ (int) Math.ceil(boundaryRectangle.getLowerLeft().getY()) + " "
+ (int) Math.ceil(boundaryRectangle.getWidth()) + " "
+ (int) Math.ceil(boundaryRectangle.getHeight()) + ">");
output.write(drawingTag.toString().getBytes(charset));
}
/**
* @param builder
* The stringbuilder that should be used to write
* @param color
* The color that should be written
*/
private void writeColor (StringBuilder builder, Color color) {
builder.append("\t" + "\t" + "<color>" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
writeComponent(builder, color.getRed());
writeComponent(builder, color.getGreen());
writeComponent(builder, color.getBlue());
builder.append("\t" + "\t" + "</color>" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
/**
* @param builder
* The stringbuilder that should be used to write
* @param component
* The component to be written
*/
private void writeComponent (StringBuilder builder, int component) {
builder.append("\t" + "\t" + "\t" + "<unsignedByte>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
builder.append(component);
builder.append("</unsignedByte>" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| true | true | public void exportDrawing (Drawing drawing, OutputStream output) throws IOException {
String charset = "UTF-8"; //$NON-NLS-1$
// TODO Forçar locale
Rectangle boundaryRectangle = getBoundaryRectangle(drawing);
exportSVGHeader(drawing, output, charset, boundaryRectangle);
byte[] endContainerTagBytes = ("\t" + "</container>" + "\n") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
.getBytes(charset);
ElementEPLoader elementEPLoader = new ElementEPLoader();
ElementExporterEPLoader exporterLoader = new ElementExporterEPLoader();
for (Layer layer : drawing.getLayerMap().values()) {
StringBuilder containerTag = new StringBuilder();
containerTag.append("\t" + "<container name=\"" + layer.getName() //$NON-NLS-1$ //$NON-NLS-2$
+ "\" lineStyle=\"" + layer.getLineStyle().ordinal() //$NON-NLS-1$
+ "\" thickness=\"" + layer.getThickness() //$NON-NLS-1$
+ "\" visible=\"" + layer.isVisible() //$NON-NLS-1$
+ "\" locked=\"" + layer.isLocked() + "\"" + " >" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
writeColor(containerTag, layer.getColor());
writeColor(containerTag, layer.getPrintColor());
output.write(containerTag.toString().getBytes(charset));
for (Element element : layer.getElements()) {
String elementId = elementEPLoader.getElementId(element);
ElementExporter<Element> exporter = exporterLoader.getExporter(elementId);
if (exporter == null) {
System.err.println(Messages.bind(Messages.SVGExporter_NoExporter, elementId));
}
else {
try {
if (element instanceof InfiniteLine || element instanceof Semiline) {
exporter.exportElement(element, output, boundaryRectangle);
}
else {
exporter.exportElement(element, output);
}
}
catch (NotSupportedException e) {
// wont reach here
}
}
}
output.write(endContainerTagBytes);
}
output.write(("</drawing>" + "\n").getBytes(charset)); //$NON-NLS-1$ //$NON-NLS-2$
output.close();
}
| public void exportDrawing (Drawing drawing, OutputStream output) throws IOException {
String charset = "UTF-8"; //$NON-NLS-1$
// TODO Forçar locale
Rectangle boundaryRectangle = getBoundaryRectangle(drawing);
exportSVGHeader(drawing, output, charset, boundaryRectangle);
byte[] endContainerTagBytes = ("\t" + "</container>" + "\n") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
.getBytes(charset);
ElementEPLoader elementEPLoader = new ElementEPLoader();
ElementExporterEPLoader exporterLoader = new ElementExporterEPLoader();
for (Layer layer : drawing.getLayerMap().values()) {
StringBuilder containerTag = new StringBuilder();
containerTag.append("\t" + "<container name=\"" + layer.getName() //$NON-NLS-1$ //$NON-NLS-2$
+ "\" lineStyle=\"" + layer.getLineStyle().ordinal() //$NON-NLS-1$
+ "\" thickness=\"" + layer.getThickness() //$NON-NLS-1$
+ "\" visible=\"" + layer.isVisible() //$NON-NLS-1$
+ "\" locked=\"" + layer.isLocked() + "\"" + " >" + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
writeColor(containerTag, layer.getColor());
writeColor(containerTag, layer.getPrintColor());
output.write(containerTag.toString().getBytes(charset));
for (Element element : layer.getElements()) {
String elementId = elementEPLoader.getElementId(element);
ElementExporter<Element> exporter = exporterLoader.getExporter(elementId);
if (exporter == null) {
System.err.println(Messages.bind(Messages.SVGExporter_NoExporter, elementId));
}
else {
try {
if (element instanceof InfiniteLine || element instanceof Semiline) {
exporter.exportElement(element, output, boundaryRectangle);
}
else {
exporter.exportElement(element, output);
}
}
catch (NotSupportedException e) {
// wont reach here
}
}
}
output.write(endContainerTagBytes);
}
output.write(("</svg>" + "\n").getBytes(charset)); //$NON-NLS-1$ //$NON-NLS-2$
output.close();
}
|
diff --git a/src/com/android/settings/applications/RunningState.java b/src/com/android/settings/applications/RunningState.java
index beb960578..1b5310de0 100644
--- a/src/com/android/settings/applications/RunningState.java
+++ b/src/com/android/settings/applications/RunningState.java
@@ -1,1154 +1,1156 @@
/*
* 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.settings.applications;
import com.android.settings.R;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.content.res.Resources;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.util.Log;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Singleton for retrieving and monitoring the state about all running
* applications/processes/services.
*/
public class RunningState {
static Object sGlobalLock = new Object();
static RunningState sInstance;
static final int MSG_RESET_CONTENTS = 1;
static final int MSG_UPDATE_CONTENTS = 2;
static final int MSG_REFRESH_UI = 3;
static final int MSG_UPDATE_TIME = 4;
static final long TIME_UPDATE_DELAY = 1000;
static final long CONTENTS_UPDATE_DELAY = 2000;
static final int MAX_SERVICES = 100;
final Context mApplicationContext;
final ActivityManager mAm;
final PackageManager mPm;
OnRefreshUiListener mRefreshUiListener;
final InterestingConfigChanges mInterestingConfigChanges = new InterestingConfigChanges();
// Processes that are hosting a service we are interested in, organized
// by uid and name. Note that this mapping does not change even across
// service restarts, and during a restart there will still be a process
// entry.
final SparseArray<HashMap<String, ProcessItem>> mServiceProcessesByName
= new SparseArray<HashMap<String, ProcessItem>>();
// Processes that are hosting a service we are interested in, organized
// by their pid. These disappear and re-appear as services are restarted.
final SparseArray<ProcessItem> mServiceProcessesByPid
= new SparseArray<ProcessItem>();
// Used to sort the interesting processes.
final ServiceProcessComparator mServiceProcessComparator
= new ServiceProcessComparator();
// Additional interesting processes to be shown to the user, even if
// there is no service running in them.
final ArrayList<ProcessItem> mInterestingProcesses = new ArrayList<ProcessItem>();
// All currently running processes, for finding dependencies etc.
final SparseArray<ProcessItem> mRunningProcesses
= new SparseArray<ProcessItem>();
// The processes associated with services, in sorted order.
final ArrayList<ProcessItem> mProcessItems = new ArrayList<ProcessItem>();
// All processes, used for retrieving memory information.
final ArrayList<ProcessItem> mAllProcessItems = new ArrayList<ProcessItem>();
static class AppProcessInfo {
final ActivityManager.RunningAppProcessInfo info;
boolean hasServices;
boolean hasForegroundServices;
AppProcessInfo(ActivityManager.RunningAppProcessInfo _info) {
info = _info;
}
}
// Temporary structure used when updating above information.
final SparseArray<AppProcessInfo> mTmpAppProcesses = new SparseArray<AppProcessInfo>();
int mSequence = 0;
// ----- following protected by mLock -----
// Lock for protecting the state that will be shared between the
// background update thread and the UI thread.
final Object mLock = new Object();
boolean mResumed;
boolean mHaveData;
boolean mWatchingBackgroundItems;
ArrayList<BaseItem> mItems = new ArrayList<BaseItem>();
ArrayList<MergedItem> mMergedItems = new ArrayList<MergedItem>();
ArrayList<MergedItem> mBackgroundItems = new ArrayList<MergedItem>();
int mNumBackgroundProcesses;
long mBackgroundProcessMemory;
int mNumForegroundProcesses;
long mForegroundProcessMemory;
int mNumServiceProcesses;
long mServiceProcessMemory;
// ----- BACKGROUND MONITORING THREAD -----
final HandlerThread mBackgroundThread;
final class BackgroundHandler extends Handler {
public BackgroundHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_RESET_CONTENTS:
reset();
break;
case MSG_UPDATE_CONTENTS:
synchronized (mLock) {
if (!mResumed) {
return;
}
}
Message cmd = mHandler.obtainMessage(MSG_REFRESH_UI);
cmd.arg1 = update(mApplicationContext, mAm) ? 1 : 0;
mHandler.sendMessage(cmd);
removeMessages(MSG_UPDATE_CONTENTS);
msg = obtainMessage(MSG_UPDATE_CONTENTS);
sendMessageDelayed(msg, CONTENTS_UPDATE_DELAY);
break;
}
}
};
final BackgroundHandler mBackgroundHandler;
final Handler mHandler = new Handler() {
int mNextUpdate = OnRefreshUiListener.REFRESH_TIME;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REFRESH_UI:
mNextUpdate = msg.arg1 != 0
? OnRefreshUiListener.REFRESH_STRUCTURE
: OnRefreshUiListener.REFRESH_DATA;
break;
case MSG_UPDATE_TIME:
synchronized (mLock) {
if (!mResumed) {
return;
}
}
removeMessages(MSG_UPDATE_TIME);
Message m = obtainMessage(MSG_UPDATE_TIME);
sendMessageDelayed(m, TIME_UPDATE_DELAY);
if (mRefreshUiListener != null) {
//Log.i("foo", "Refresh UI: " + mNextUpdate
// + " @ " + SystemClock.uptimeMillis());
mRefreshUiListener.onRefreshUi(mNextUpdate);
mNextUpdate = OnRefreshUiListener.REFRESH_TIME;
}
break;
}
}
};
// ----- DATA STRUCTURES -----
static interface OnRefreshUiListener {
public static final int REFRESH_TIME = 0;
public static final int REFRESH_DATA = 1;
public static final int REFRESH_STRUCTURE = 2;
public void onRefreshUi(int what);
}
static class BaseItem {
final boolean mIsProcess;
PackageItemInfo mPackageInfo;
CharSequence mDisplayLabel;
String mLabel;
String mDescription;
int mCurSeq;
long mActiveSince;
long mSize;
String mSizeStr;
String mCurSizeStr;
boolean mNeedDivider;
boolean mBackground;
public BaseItem(boolean isProcess) {
mIsProcess = isProcess;
}
}
static class ServiceItem extends BaseItem {
ActivityManager.RunningServiceInfo mRunningService;
ServiceInfo mServiceInfo;
boolean mShownAsStarted;
MergedItem mMergedItem;
public ServiceItem() {
super(false);
}
}
static class ProcessItem extends BaseItem {
final HashMap<ComponentName, ServiceItem> mServices
= new HashMap<ComponentName, ServiceItem>();
final SparseArray<ProcessItem> mDependentProcesses
= new SparseArray<ProcessItem>();
final int mUid;
final String mProcessName;
int mPid;
ProcessItem mClient;
int mLastNumDependentProcesses;
int mRunningSeq;
ActivityManager.RunningAppProcessInfo mRunningProcessInfo;
MergedItem mMergedItem;
boolean mInteresting;
// Purely for sorting.
boolean mIsSystem;
boolean mIsStarted;
long mActiveSince;
public ProcessItem(Context context, int uid, String processName) {
super(true);
mDescription = context.getResources().getString(
R.string.service_process_name, processName);
mUid = uid;
mProcessName = processName;
}
void ensureLabel(PackageManager pm) {
if (mLabel != null) {
return;
}
try {
ApplicationInfo ai = pm.getApplicationInfo(mProcessName, 0);
if (ai.uid == mUid) {
mDisplayLabel = ai.loadLabel(pm);
mLabel = mDisplayLabel.toString();
mPackageInfo = ai;
return;
}
} catch (PackageManager.NameNotFoundException e) {
}
// If we couldn't get information about the overall
// process, try to find something about the uid.
String[] pkgs = pm.getPackagesForUid(mUid);
// If there is one package with this uid, that is what we want.
if (pkgs.length == 1) {
try {
ApplicationInfo ai = pm.getApplicationInfo(pkgs[0], 0);
mDisplayLabel = ai.loadLabel(pm);
mLabel = mDisplayLabel.toString();
mPackageInfo = ai;
return;
} catch (PackageManager.NameNotFoundException e) {
}
}
// If there are multiple, see if one gives us the official name
// for this uid.
for (String name : pkgs) {
try {
PackageInfo pi = pm.getPackageInfo(name, 0);
if (pi.sharedUserLabel != 0) {
CharSequence nm = pm.getText(name,
pi.sharedUserLabel, pi.applicationInfo);
if (nm != null) {
mDisplayLabel = nm;
mLabel = nm.toString();
mPackageInfo = pi.applicationInfo;
return;
}
}
} catch (PackageManager.NameNotFoundException e) {
}
}
// If still don't have anything to display, just use the
// service info.
if (mServices.size() > 0) {
mPackageInfo = mServices.values().iterator().next()
.mServiceInfo.applicationInfo;
mDisplayLabel = mPackageInfo.loadLabel(pm);
mLabel = mDisplayLabel.toString();
return;
}
// Finally... whatever, just pick the first package's name.
try {
ApplicationInfo ai = pm.getApplicationInfo(pkgs[0], 0);
mDisplayLabel = ai.loadLabel(pm);
mLabel = mDisplayLabel.toString();
mPackageInfo = ai;
return;
} catch (PackageManager.NameNotFoundException e) {
}
}
boolean updateService(Context context,
ActivityManager.RunningServiceInfo service) {
final PackageManager pm = context.getPackageManager();
boolean changed = false;
ServiceItem si = mServices.get(service.service);
if (si == null) {
changed = true;
si = new ServiceItem();
si.mRunningService = service;
try {
si.mServiceInfo = pm.getServiceInfo(service.service, 0);
} catch (PackageManager.NameNotFoundException e) {
}
si.mDisplayLabel = makeLabel(pm,
si.mRunningService.service.getClassName(), si.mServiceInfo);
mLabel = mDisplayLabel != null ? mDisplayLabel.toString() : null;
si.mPackageInfo = si.mServiceInfo.applicationInfo;
mServices.put(service.service, si);
}
si.mCurSeq = mCurSeq;
si.mRunningService = service;
long activeSince = service.restarting == 0 ? service.activeSince : -1;
if (si.mActiveSince != activeSince) {
si.mActiveSince = activeSince;
changed = true;
}
if (service.clientPackage != null && service.clientLabel != 0) {
if (si.mShownAsStarted) {
si.mShownAsStarted = false;
changed = true;
}
try {
Resources clientr = pm.getResourcesForApplication(service.clientPackage);
String label = clientr.getString(service.clientLabel);
si.mDescription = context.getResources().getString(
R.string.service_client_name, label);
} catch (PackageManager.NameNotFoundException e) {
si.mDescription = null;
}
} else {
if (!si.mShownAsStarted) {
si.mShownAsStarted = true;
changed = true;
}
si.mDescription = context.getResources().getString(
R.string.service_started_by_app);
}
return changed;
}
boolean updateSize(Context context, long pss, int curSeq) {
mSize = pss * 1024;
if (mCurSeq == curSeq) {
String sizeStr = Formatter.formatShortFileSize(
context, mSize);
if (!sizeStr.equals(mSizeStr)){
mSizeStr = sizeStr;
// We update this on the second tick where we update just
// the text in the current items, so no need to say we
// changed here.
return false;
}
}
return false;
}
boolean buildDependencyChain(Context context, PackageManager pm, int curSeq) {
final int NP = mDependentProcesses.size();
boolean changed = false;
for (int i=0; i<NP; i++) {
ProcessItem proc = mDependentProcesses.valueAt(i);
if (proc.mClient != this) {
changed = true;
proc.mClient = this;
}
proc.mCurSeq = curSeq;
proc.ensureLabel(pm);
changed |= proc.buildDependencyChain(context, pm, curSeq);
}
if (mLastNumDependentProcesses != mDependentProcesses.size()) {
changed = true;
mLastNumDependentProcesses = mDependentProcesses.size();
}
return changed;
}
void addDependentProcesses(ArrayList<BaseItem> dest,
ArrayList<ProcessItem> destProc) {
final int NP = mDependentProcesses.size();
for (int i=0; i<NP; i++) {
ProcessItem proc = mDependentProcesses.valueAt(i);
proc.addDependentProcesses(dest, destProc);
dest.add(proc);
if (proc.mPid > 0) {
destProc.add(proc);
}
}
}
}
static class MergedItem extends BaseItem {
ProcessItem mProcess;
final ArrayList<ProcessItem> mOtherProcesses = new ArrayList<ProcessItem>();
final ArrayList<ServiceItem> mServices = new ArrayList<ServiceItem>();
private int mLastNumProcesses = -1, mLastNumServices = -1;
MergedItem() {
super(false);
}
boolean update(Context context, boolean background) {
mPackageInfo = mProcess.mPackageInfo;
mDisplayLabel = mProcess.mDisplayLabel;
mLabel = mProcess.mLabel;
mBackground = background;
if (!mBackground) {
int numProcesses = (mProcess.mPid > 0 ? 1 : 0) + mOtherProcesses.size();
int numServices = mServices.size();
if (mLastNumProcesses != numProcesses || mLastNumServices != numServices) {
mLastNumProcesses = numProcesses;
mLastNumServices = numServices;
int resid = R.string.running_processes_item_description_s_s;
if (numProcesses != 1) {
resid = numServices != 1
? R.string.running_processes_item_description_p_p
: R.string.running_processes_item_description_p_s;
} else if (numServices != 1) {
resid = R.string.running_processes_item_description_s_p;
}
mDescription = context.getResources().getString(resid, numProcesses,
numServices);
}
}
mActiveSince = -1;
for (int i=0; i<mServices.size(); i++) {
ServiceItem si = mServices.get(i);
if (si.mActiveSince >= 0 && mActiveSince < si.mActiveSince) {
mActiveSince = si.mActiveSince;
}
}
return false;
}
boolean updateSize(Context context) {
mSize = mProcess.mSize;
for (int i=0; i<mOtherProcesses.size(); i++) {
mSize += mOtherProcesses.get(i).mSize;
}
String sizeStr = Formatter.formatShortFileSize(
context, mSize);
if (!sizeStr.equals(mSizeStr)){
mSizeStr = sizeStr;
// We update this on the second tick where we update just
// the text in the current items, so no need to say we
// changed here.
return false;
}
return false;
}
}
static class ServiceProcessComparator implements Comparator<ProcessItem> {
public int compare(ProcessItem object1, ProcessItem object2) {
if (object1.mIsStarted != object2.mIsStarted) {
// Non-started processes go last.
return object1.mIsStarted ? -1 : 1;
}
if (object1.mIsSystem != object2.mIsSystem) {
// System processes go below non-system.
return object1.mIsSystem ? 1 : -1;
}
if (object1.mActiveSince != object2.mActiveSince) {
// Remaining ones are sorted with the longest running
// services last.
return (object1.mActiveSince > object2.mActiveSince) ? -1 : 1;
}
return 0;
}
}
static CharSequence makeLabel(PackageManager pm,
String className, PackageItemInfo item) {
if (item != null && (item.labelRes != 0
|| item.nonLocalizedLabel != null)) {
CharSequence label = item.loadLabel(pm);
if (label != null) {
return label;
}
}
String label = className;
int tail = label.lastIndexOf('.');
if (tail >= 0) {
label = label.substring(tail+1, label.length());
}
return label;
}
static RunningState getInstance(Context context) {
synchronized (sGlobalLock) {
if (sInstance == null) {
sInstance = new RunningState(context);
}
return sInstance;
}
}
private RunningState(Context context) {
mApplicationContext = context.getApplicationContext();
mAm = (ActivityManager)mApplicationContext.getSystemService(Context.ACTIVITY_SERVICE);
mPm = mApplicationContext.getPackageManager();
mResumed = false;
mBackgroundThread = new HandlerThread("RunningState:Background");
mBackgroundThread.start();
mBackgroundHandler = new BackgroundHandler(mBackgroundThread.getLooper());
}
void resume(OnRefreshUiListener listener) {
synchronized (mLock) {
mResumed = true;
mRefreshUiListener = listener;
if (mInterestingConfigChanges.applyNewConfig(mApplicationContext.getResources())) {
mHaveData = false;
mBackgroundHandler.removeMessages(MSG_RESET_CONTENTS);
mBackgroundHandler.removeMessages(MSG_UPDATE_CONTENTS);
mBackgroundHandler.sendEmptyMessage(MSG_RESET_CONTENTS);
}
if (!mBackgroundHandler.hasMessages(MSG_UPDATE_CONTENTS)) {
mBackgroundHandler.sendEmptyMessage(MSG_UPDATE_CONTENTS);
}
mHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
void updateNow() {
synchronized (mLock) {
mBackgroundHandler.removeMessages(MSG_UPDATE_CONTENTS);
mBackgroundHandler.sendEmptyMessage(MSG_UPDATE_CONTENTS);
}
}
boolean hasData() {
synchronized (mLock) {
return mHaveData;
}
}
void waitForData() {
synchronized (mLock) {
while (!mHaveData) {
try {
mLock.wait(0);
} catch (InterruptedException e) {
}
}
}
}
void pause() {
synchronized (mLock) {
mResumed = false;
mRefreshUiListener = null;
mHandler.removeMessages(MSG_UPDATE_TIME);
}
}
private boolean isInterestingProcess(ActivityManager.RunningAppProcessInfo pi) {
if ((pi.flags&ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE) != 0) {
return true;
}
if ((pi.flags&ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT) == 0
&& pi.importance >= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& pi.importance < ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE
&& pi.importanceReasonCode
== ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN) {
return true;
}
return false;
}
private void reset() {
mServiceProcessesByName.clear();
mServiceProcessesByPid.clear();
mInterestingProcesses.clear();
mRunningProcesses.clear();
mProcessItems.clear();
mAllProcessItems.clear();
}
private boolean update(Context context, ActivityManager am) {
final PackageManager pm = context.getPackageManager();
mSequence++;
boolean changed = false;
// Retrieve list of services, filtering out anything that definitely
// won't be shown in the UI.
List<ActivityManager.RunningServiceInfo> services
= am.getRunningServices(MAX_SERVICES);
int NS = services != null ? services.size() : 0;
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
// We are not interested in services that have not been started
// and don't have a known client, because
// there is nothing the user can do about them.
if (!si.started && si.clientLabel == 0) {
services.remove(i);
i--;
NS--;
continue;
}
// We likewise don't care about services running in a
// persistent process like the system or phone.
if ((si.flags&ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS)
!= 0) {
services.remove(i);
i--;
NS--;
continue;
}
}
// Retrieve list of running processes, organizing them into a sparse
// array for easy retrieval.
List<ActivityManager.RunningAppProcessInfo> processes
= am.getRunningAppProcesses();
final int NP = processes != null ? processes.size() : 0;
mTmpAppProcesses.clear();
for (int i=0; i<NP; i++) {
ActivityManager.RunningAppProcessInfo pi = processes.get(i);
mTmpAppProcesses.put(pi.pid, new AppProcessInfo(pi));
}
// Initial iteration through running services to collect per-process
// info about them.
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
if (si.restarting == 0 && si.pid > 0) {
AppProcessInfo ainfo = mTmpAppProcesses.get(si.pid);
if (ainfo != null) {
ainfo.hasServices = true;
if (si.foreground) {
ainfo.hasForegroundServices = true;
}
}
}
}
// Update state we are maintaining about process that are running services.
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
// If this service's process is in use at a higher importance
// due to another process bound to one of its services, then we
// won't put it in the top-level list of services. Instead we
// want it to be included in the set of processes that the other
// process needs.
if (si.restarting == 0 && si.pid > 0) {
AppProcessInfo ainfo = mTmpAppProcesses.get(si.pid);
if (ainfo != null && !ainfo.hasForegroundServices) {
// This process does not have any foreground services.
// If its importance is greater than the service importance
// then there is something else more significant that is
// keeping it around that it should possibly be included as
// a part of instead of being shown by itself.
if (ainfo.info.importance
< ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
// Follow process chain to see if there is something
// else that could be shown
boolean skip = false;
ainfo = mTmpAppProcesses.get(ainfo.info.importanceReasonPid);
while (ainfo != null) {
if (ainfo.hasServices || isInterestingProcess(ainfo.info)) {
skip = true;
break;
}
ainfo = mTmpAppProcesses.get(ainfo.info.importanceReasonPid);
}
if (skip) {
continue;
}
}
}
}
HashMap<String, ProcessItem> procs = mServiceProcessesByName.get(si.uid);
if (procs == null) {
procs = new HashMap<String, ProcessItem>();
mServiceProcessesByName.put(si.uid, procs);
}
ProcessItem proc = procs.get(si.process);
if (proc == null) {
changed = true;
proc = new ProcessItem(context, si.uid, si.process);
procs.put(si.process, proc);
}
if (proc.mCurSeq != mSequence) {
int pid = si.restarting == 0 ? si.pid : 0;
if (pid != proc.mPid) {
changed = true;
if (proc.mPid != pid) {
if (proc.mPid != 0) {
mServiceProcessesByPid.remove(proc.mPid);
}
if (pid != 0) {
mServiceProcessesByPid.put(pid, proc);
}
proc.mPid = pid;
}
}
proc.mDependentProcesses.clear();
proc.mCurSeq = mSequence;
}
changed |= proc.updateService(context, si);
}
// Now update the map of other processes that are running (but
// don't have services actively running inside them).
for (int i=0; i<NP; i++) {
ActivityManager.RunningAppProcessInfo pi = processes.get(i);
ProcessItem proc = mServiceProcessesByPid.get(pi.pid);
if (proc == null) {
// This process is not one that is a direct container
// of a service, so look for it in the secondary
// running list.
proc = mRunningProcesses.get(pi.pid);
if (proc == null) {
changed = true;
proc = new ProcessItem(context, pi.uid, pi.processName);
proc.mPid = pi.pid;
mRunningProcesses.put(pi.pid, proc);
}
proc.mDependentProcesses.clear();
}
if (isInterestingProcess(pi)) {
if (!mInterestingProcesses.contains(proc)) {
changed = true;
mInterestingProcesses.add(proc);
}
proc.mCurSeq = mSequence;
proc.mInteresting = true;
proc.ensureLabel(pm);
} else {
proc.mInteresting = false;
}
proc.mRunningSeq = mSequence;
proc.mRunningProcessInfo = pi;
}
// Build the chains from client processes to the process they are
// dependent on; also remove any old running processes.
int NRP = mRunningProcesses.size();
- for (int i=0; i<NRP; i++) {
+ for (int i = 0; i < NRP;) {
ProcessItem proc = mRunningProcesses.valueAt(i);
if (proc.mRunningSeq == mSequence) {
int clientPid = proc.mRunningProcessInfo.importanceReasonPid;
if (clientPid != 0) {
ProcessItem client = mServiceProcessesByPid.get(clientPid);
if (client == null) {
client = mRunningProcesses.get(clientPid);
}
if (client != null) {
client.mDependentProcesses.put(proc.mPid, proc);
}
} else {
// In this pass the process doesn't have a client.
// Clear to make sure that, if it later gets the same one,
// we will detect the change.
proc.mClient = null;
}
+ i++;
} else {
changed = true;
mRunningProcesses.remove(mRunningProcesses.keyAt(i));
+ NRP--;
}
}
// Remove any old interesting processes.
int NHP = mInterestingProcesses.size();
for (int i=0; i<NHP; i++) {
ProcessItem proc = mInterestingProcesses.get(i);
if (!proc.mInteresting || mRunningProcesses.get(proc.mPid) == null) {
changed = true;
mInterestingProcesses.remove(i);
i--;
NHP--;
}
}
// Follow the tree from all primary service processes to all
// processes they are dependent on, marking these processes as
// still being active and determining if anything has changed.
final int NAP = mServiceProcessesByPid.size();
for (int i=0; i<NAP; i++) {
ProcessItem proc = mServiceProcessesByPid.valueAt(i);
if (proc.mCurSeq == mSequence) {
changed |= proc.buildDependencyChain(context, pm, mSequence);
}
}
// Look for services and their primary processes that no longer exist...
ArrayList<Integer> uidToDelete = null;
for (int i=0; i<mServiceProcessesByName.size(); i++) {
HashMap<String, ProcessItem> procs = mServiceProcessesByName.valueAt(i);
Iterator<ProcessItem> pit = procs.values().iterator();
while (pit.hasNext()) {
ProcessItem pi = pit.next();
if (pi.mCurSeq == mSequence) {
pi.ensureLabel(pm);
if (pi.mPid == 0) {
// Sanity: a non-process can't be dependent on
// anything.
pi.mDependentProcesses.clear();
}
} else {
changed = true;
pit.remove();
if (procs.size() == 0) {
if (uidToDelete == null) {
uidToDelete = new ArrayList<Integer>();
}
uidToDelete.add(mServiceProcessesByName.keyAt(i));
}
if (pi.mPid != 0) {
mServiceProcessesByPid.remove(pi.mPid);
}
continue;
}
Iterator<ServiceItem> sit = pi.mServices.values().iterator();
while (sit.hasNext()) {
ServiceItem si = sit.next();
if (si.mCurSeq != mSequence) {
changed = true;
sit.remove();
}
}
}
}
if (uidToDelete != null) {
for (int i = 0; i < uidToDelete.size(); i++) {
int uid = uidToDelete.get(i);
mServiceProcessesByName.remove(uid);
}
}
if (changed) {
// First determine an order for the services.
ArrayList<ProcessItem> sortedProcesses = new ArrayList<ProcessItem>();
for (int i=0; i<mServiceProcessesByName.size(); i++) {
for (ProcessItem pi : mServiceProcessesByName.valueAt(i).values()) {
pi.mIsSystem = false;
pi.mIsStarted = true;
pi.mActiveSince = Long.MAX_VALUE;
for (ServiceItem si : pi.mServices.values()) {
if (si.mServiceInfo != null
&& (si.mServiceInfo.applicationInfo.flags
& ApplicationInfo.FLAG_SYSTEM) != 0) {
pi.mIsSystem = true;
}
if (si.mRunningService != null
&& si.mRunningService.clientLabel != 0) {
pi.mIsStarted = false;
if (pi.mActiveSince > si.mRunningService.activeSince) {
pi.mActiveSince = si.mRunningService.activeSince;
}
}
}
sortedProcesses.add(pi);
}
}
Collections.sort(sortedProcesses, mServiceProcessComparator);
ArrayList<BaseItem> newItems = new ArrayList<BaseItem>();
ArrayList<MergedItem> newMergedItems = new ArrayList<MergedItem>();
mProcessItems.clear();
for (int i=0; i<sortedProcesses.size(); i++) {
ProcessItem pi = sortedProcesses.get(i);
pi.mNeedDivider = false;
int firstProc = mProcessItems.size();
// First add processes we are dependent on.
pi.addDependentProcesses(newItems, mProcessItems);
// And add the process itself.
newItems.add(pi);
if (pi.mPid > 0) {
mProcessItems.add(pi);
}
// Now add the services running in it.
MergedItem mergedItem = null;
boolean haveAllMerged = false;
boolean needDivider = false;
for (ServiceItem si : pi.mServices.values()) {
si.mNeedDivider = needDivider;
needDivider = true;
newItems.add(si);
if (si.mMergedItem != null) {
if (mergedItem != null && mergedItem != si.mMergedItem) {
haveAllMerged = false;
}
mergedItem = si.mMergedItem;
} else {
haveAllMerged = false;
}
}
if (!haveAllMerged || mergedItem == null
|| mergedItem.mServices.size() != pi.mServices.size()) {
// Whoops, we need to build a new MergedItem!
mergedItem = new MergedItem();
for (ServiceItem si : pi.mServices.values()) {
mergedItem.mServices.add(si);
si.mMergedItem = mergedItem;
}
mergedItem.mProcess = pi;
mergedItem.mOtherProcesses.clear();
for (int mpi=firstProc; mpi<(mProcessItems.size()-1); mpi++) {
mergedItem.mOtherProcesses.add(mProcessItems.get(mpi));
}
}
mergedItem.update(context, false);
newMergedItems.add(mergedItem);
}
// Finally, interesting processes need to be shown and will
// go at the top.
NHP = mInterestingProcesses.size();
for (int i=0; i<NHP; i++) {
ProcessItem proc = mInterestingProcesses.get(i);
if (proc.mClient == null && proc.mServices.size() <= 0) {
if (proc.mMergedItem == null) {
proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
}
proc.mMergedItem.update(context, false);
newMergedItems.add(0, proc.mMergedItem);
mProcessItems.add(proc);
}
}
synchronized (mLock) {
mItems = newItems;
mMergedItems = newMergedItems;
}
}
// Count number of interesting other (non-active) processes, and
// build a list of all processes we will retrieve memory for.
mAllProcessItems.clear();
mAllProcessItems.addAll(mProcessItems);
int numBackgroundProcesses = 0;
int numForegroundProcesses = 0;
int numServiceProcesses = 0;
NRP = mRunningProcesses.size();
for (int i=0; i<NRP; i++) {
ProcessItem proc = mRunningProcesses.valueAt(i);
if (proc.mCurSeq != mSequence) {
// We didn't hit this process as a dependency on one
// of our active ones, so add it up if needed.
if (proc.mRunningProcessInfo.importance >=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
numBackgroundProcesses++;
mAllProcessItems.add(proc);
} else if (proc.mRunningProcessInfo.importance <=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
numForegroundProcesses++;
mAllProcessItems.add(proc);
} else {
Log.i("RunningState", "Unknown non-service process: "
+ proc.mProcessName + " #" + proc.mPid);
}
} else {
numServiceProcesses++;
}
}
long backgroundProcessMemory = 0;
long foregroundProcessMemory = 0;
long serviceProcessMemory = 0;
ArrayList<MergedItem> newBackgroundItems = null;
try {
final int numProc = mAllProcessItems.size();
int[] pids = new int[numProc];
for (int i=0; i<numProc; i++) {
pids[i] = mAllProcessItems.get(i).mPid;
}
long[] pss = ActivityManagerNative.getDefault()
.getProcessPss(pids);
int bgIndex = 0;
for (int i=0; i<pids.length; i++) {
ProcessItem proc = mAllProcessItems.get(i);
changed |= proc.updateSize(context, pss[i], mSequence);
if (proc.mCurSeq == mSequence) {
serviceProcessMemory += proc.mSize;
} else if (proc.mRunningProcessInfo.importance >=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
backgroundProcessMemory += proc.mSize;
MergedItem mergedItem;
if (newBackgroundItems != null) {
mergedItem = proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
newBackgroundItems.add(mergedItem);
} else {
if (bgIndex >= mBackgroundItems.size()
|| mBackgroundItems.get(bgIndex).mProcess != proc) {
newBackgroundItems = new ArrayList<MergedItem>(numBackgroundProcesses);
for (int bgi=0; bgi<bgIndex; bgi++) {
newBackgroundItems.add(mBackgroundItems.get(bgi));
}
mergedItem = proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
newBackgroundItems.add(mergedItem);
} else {
mergedItem = mBackgroundItems.get(bgIndex);
}
}
mergedItem.update(context, true);
mergedItem.updateSize(context);
bgIndex++;
} else if (proc.mRunningProcessInfo.importance <=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
foregroundProcessMemory += proc.mSize;
}
}
} catch (RemoteException e) {
}
if (newBackgroundItems == null) {
// One or more at the bottom may no longer exist.
if (mBackgroundItems.size() > numBackgroundProcesses) {
newBackgroundItems = new ArrayList<MergedItem>(numBackgroundProcesses);
for (int bgi=0; bgi<numBackgroundProcesses; bgi++) {
newBackgroundItems.add(mBackgroundItems.get(bgi));
}
}
}
for (int i=0; i<mMergedItems.size(); i++) {
mMergedItems.get(i).updateSize(context);
}
synchronized (mLock) {
mNumBackgroundProcesses = numBackgroundProcesses;
mNumForegroundProcesses = numForegroundProcesses;
mNumServiceProcesses = numServiceProcesses;
mBackgroundProcessMemory = backgroundProcessMemory;
mForegroundProcessMemory = foregroundProcessMemory;
mServiceProcessMemory = serviceProcessMemory;
if (newBackgroundItems != null) {
mBackgroundItems = newBackgroundItems;
if (mWatchingBackgroundItems) {
changed = true;
}
}
if (!mHaveData) {
mHaveData = true;
mLock.notifyAll();
}
}
return changed;
}
ArrayList<BaseItem> getCurrentItems() {
synchronized (mLock) {
return mItems;
}
}
void setWatchingBackgroundItems(boolean watching) {
synchronized (mLock) {
mWatchingBackgroundItems = watching;
}
}
ArrayList<MergedItem> getCurrentMergedItems() {
synchronized (mLock) {
return mMergedItems;
}
}
ArrayList<MergedItem> getCurrentBackgroundItems() {
synchronized (mLock) {
return mBackgroundItems;
}
}
}
| false | true | private boolean update(Context context, ActivityManager am) {
final PackageManager pm = context.getPackageManager();
mSequence++;
boolean changed = false;
// Retrieve list of services, filtering out anything that definitely
// won't be shown in the UI.
List<ActivityManager.RunningServiceInfo> services
= am.getRunningServices(MAX_SERVICES);
int NS = services != null ? services.size() : 0;
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
// We are not interested in services that have not been started
// and don't have a known client, because
// there is nothing the user can do about them.
if (!si.started && si.clientLabel == 0) {
services.remove(i);
i--;
NS--;
continue;
}
// We likewise don't care about services running in a
// persistent process like the system or phone.
if ((si.flags&ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS)
!= 0) {
services.remove(i);
i--;
NS--;
continue;
}
}
// Retrieve list of running processes, organizing them into a sparse
// array for easy retrieval.
List<ActivityManager.RunningAppProcessInfo> processes
= am.getRunningAppProcesses();
final int NP = processes != null ? processes.size() : 0;
mTmpAppProcesses.clear();
for (int i=0; i<NP; i++) {
ActivityManager.RunningAppProcessInfo pi = processes.get(i);
mTmpAppProcesses.put(pi.pid, new AppProcessInfo(pi));
}
// Initial iteration through running services to collect per-process
// info about them.
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
if (si.restarting == 0 && si.pid > 0) {
AppProcessInfo ainfo = mTmpAppProcesses.get(si.pid);
if (ainfo != null) {
ainfo.hasServices = true;
if (si.foreground) {
ainfo.hasForegroundServices = true;
}
}
}
}
// Update state we are maintaining about process that are running services.
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
// If this service's process is in use at a higher importance
// due to another process bound to one of its services, then we
// won't put it in the top-level list of services. Instead we
// want it to be included in the set of processes that the other
// process needs.
if (si.restarting == 0 && si.pid > 0) {
AppProcessInfo ainfo = mTmpAppProcesses.get(si.pid);
if (ainfo != null && !ainfo.hasForegroundServices) {
// This process does not have any foreground services.
// If its importance is greater than the service importance
// then there is something else more significant that is
// keeping it around that it should possibly be included as
// a part of instead of being shown by itself.
if (ainfo.info.importance
< ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
// Follow process chain to see if there is something
// else that could be shown
boolean skip = false;
ainfo = mTmpAppProcesses.get(ainfo.info.importanceReasonPid);
while (ainfo != null) {
if (ainfo.hasServices || isInterestingProcess(ainfo.info)) {
skip = true;
break;
}
ainfo = mTmpAppProcesses.get(ainfo.info.importanceReasonPid);
}
if (skip) {
continue;
}
}
}
}
HashMap<String, ProcessItem> procs = mServiceProcessesByName.get(si.uid);
if (procs == null) {
procs = new HashMap<String, ProcessItem>();
mServiceProcessesByName.put(si.uid, procs);
}
ProcessItem proc = procs.get(si.process);
if (proc == null) {
changed = true;
proc = new ProcessItem(context, si.uid, si.process);
procs.put(si.process, proc);
}
if (proc.mCurSeq != mSequence) {
int pid = si.restarting == 0 ? si.pid : 0;
if (pid != proc.mPid) {
changed = true;
if (proc.mPid != pid) {
if (proc.mPid != 0) {
mServiceProcessesByPid.remove(proc.mPid);
}
if (pid != 0) {
mServiceProcessesByPid.put(pid, proc);
}
proc.mPid = pid;
}
}
proc.mDependentProcesses.clear();
proc.mCurSeq = mSequence;
}
changed |= proc.updateService(context, si);
}
// Now update the map of other processes that are running (but
// don't have services actively running inside them).
for (int i=0; i<NP; i++) {
ActivityManager.RunningAppProcessInfo pi = processes.get(i);
ProcessItem proc = mServiceProcessesByPid.get(pi.pid);
if (proc == null) {
// This process is not one that is a direct container
// of a service, so look for it in the secondary
// running list.
proc = mRunningProcesses.get(pi.pid);
if (proc == null) {
changed = true;
proc = new ProcessItem(context, pi.uid, pi.processName);
proc.mPid = pi.pid;
mRunningProcesses.put(pi.pid, proc);
}
proc.mDependentProcesses.clear();
}
if (isInterestingProcess(pi)) {
if (!mInterestingProcesses.contains(proc)) {
changed = true;
mInterestingProcesses.add(proc);
}
proc.mCurSeq = mSequence;
proc.mInteresting = true;
proc.ensureLabel(pm);
} else {
proc.mInteresting = false;
}
proc.mRunningSeq = mSequence;
proc.mRunningProcessInfo = pi;
}
// Build the chains from client processes to the process they are
// dependent on; also remove any old running processes.
int NRP = mRunningProcesses.size();
for (int i=0; i<NRP; i++) {
ProcessItem proc = mRunningProcesses.valueAt(i);
if (proc.mRunningSeq == mSequence) {
int clientPid = proc.mRunningProcessInfo.importanceReasonPid;
if (clientPid != 0) {
ProcessItem client = mServiceProcessesByPid.get(clientPid);
if (client == null) {
client = mRunningProcesses.get(clientPid);
}
if (client != null) {
client.mDependentProcesses.put(proc.mPid, proc);
}
} else {
// In this pass the process doesn't have a client.
// Clear to make sure that, if it later gets the same one,
// we will detect the change.
proc.mClient = null;
}
} else {
changed = true;
mRunningProcesses.remove(mRunningProcesses.keyAt(i));
}
}
// Remove any old interesting processes.
int NHP = mInterestingProcesses.size();
for (int i=0; i<NHP; i++) {
ProcessItem proc = mInterestingProcesses.get(i);
if (!proc.mInteresting || mRunningProcesses.get(proc.mPid) == null) {
changed = true;
mInterestingProcesses.remove(i);
i--;
NHP--;
}
}
// Follow the tree from all primary service processes to all
// processes they are dependent on, marking these processes as
// still being active and determining if anything has changed.
final int NAP = mServiceProcessesByPid.size();
for (int i=0; i<NAP; i++) {
ProcessItem proc = mServiceProcessesByPid.valueAt(i);
if (proc.mCurSeq == mSequence) {
changed |= proc.buildDependencyChain(context, pm, mSequence);
}
}
// Look for services and their primary processes that no longer exist...
ArrayList<Integer> uidToDelete = null;
for (int i=0; i<mServiceProcessesByName.size(); i++) {
HashMap<String, ProcessItem> procs = mServiceProcessesByName.valueAt(i);
Iterator<ProcessItem> pit = procs.values().iterator();
while (pit.hasNext()) {
ProcessItem pi = pit.next();
if (pi.mCurSeq == mSequence) {
pi.ensureLabel(pm);
if (pi.mPid == 0) {
// Sanity: a non-process can't be dependent on
// anything.
pi.mDependentProcesses.clear();
}
} else {
changed = true;
pit.remove();
if (procs.size() == 0) {
if (uidToDelete == null) {
uidToDelete = new ArrayList<Integer>();
}
uidToDelete.add(mServiceProcessesByName.keyAt(i));
}
if (pi.mPid != 0) {
mServiceProcessesByPid.remove(pi.mPid);
}
continue;
}
Iterator<ServiceItem> sit = pi.mServices.values().iterator();
while (sit.hasNext()) {
ServiceItem si = sit.next();
if (si.mCurSeq != mSequence) {
changed = true;
sit.remove();
}
}
}
}
if (uidToDelete != null) {
for (int i = 0; i < uidToDelete.size(); i++) {
int uid = uidToDelete.get(i);
mServiceProcessesByName.remove(uid);
}
}
if (changed) {
// First determine an order for the services.
ArrayList<ProcessItem> sortedProcesses = new ArrayList<ProcessItem>();
for (int i=0; i<mServiceProcessesByName.size(); i++) {
for (ProcessItem pi : mServiceProcessesByName.valueAt(i).values()) {
pi.mIsSystem = false;
pi.mIsStarted = true;
pi.mActiveSince = Long.MAX_VALUE;
for (ServiceItem si : pi.mServices.values()) {
if (si.mServiceInfo != null
&& (si.mServiceInfo.applicationInfo.flags
& ApplicationInfo.FLAG_SYSTEM) != 0) {
pi.mIsSystem = true;
}
if (si.mRunningService != null
&& si.mRunningService.clientLabel != 0) {
pi.mIsStarted = false;
if (pi.mActiveSince > si.mRunningService.activeSince) {
pi.mActiveSince = si.mRunningService.activeSince;
}
}
}
sortedProcesses.add(pi);
}
}
Collections.sort(sortedProcesses, mServiceProcessComparator);
ArrayList<BaseItem> newItems = new ArrayList<BaseItem>();
ArrayList<MergedItem> newMergedItems = new ArrayList<MergedItem>();
mProcessItems.clear();
for (int i=0; i<sortedProcesses.size(); i++) {
ProcessItem pi = sortedProcesses.get(i);
pi.mNeedDivider = false;
int firstProc = mProcessItems.size();
// First add processes we are dependent on.
pi.addDependentProcesses(newItems, mProcessItems);
// And add the process itself.
newItems.add(pi);
if (pi.mPid > 0) {
mProcessItems.add(pi);
}
// Now add the services running in it.
MergedItem mergedItem = null;
boolean haveAllMerged = false;
boolean needDivider = false;
for (ServiceItem si : pi.mServices.values()) {
si.mNeedDivider = needDivider;
needDivider = true;
newItems.add(si);
if (si.mMergedItem != null) {
if (mergedItem != null && mergedItem != si.mMergedItem) {
haveAllMerged = false;
}
mergedItem = si.mMergedItem;
} else {
haveAllMerged = false;
}
}
if (!haveAllMerged || mergedItem == null
|| mergedItem.mServices.size() != pi.mServices.size()) {
// Whoops, we need to build a new MergedItem!
mergedItem = new MergedItem();
for (ServiceItem si : pi.mServices.values()) {
mergedItem.mServices.add(si);
si.mMergedItem = mergedItem;
}
mergedItem.mProcess = pi;
mergedItem.mOtherProcesses.clear();
for (int mpi=firstProc; mpi<(mProcessItems.size()-1); mpi++) {
mergedItem.mOtherProcesses.add(mProcessItems.get(mpi));
}
}
mergedItem.update(context, false);
newMergedItems.add(mergedItem);
}
// Finally, interesting processes need to be shown and will
// go at the top.
NHP = mInterestingProcesses.size();
for (int i=0; i<NHP; i++) {
ProcessItem proc = mInterestingProcesses.get(i);
if (proc.mClient == null && proc.mServices.size() <= 0) {
if (proc.mMergedItem == null) {
proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
}
proc.mMergedItem.update(context, false);
newMergedItems.add(0, proc.mMergedItem);
mProcessItems.add(proc);
}
}
synchronized (mLock) {
mItems = newItems;
mMergedItems = newMergedItems;
}
}
// Count number of interesting other (non-active) processes, and
// build a list of all processes we will retrieve memory for.
mAllProcessItems.clear();
mAllProcessItems.addAll(mProcessItems);
int numBackgroundProcesses = 0;
int numForegroundProcesses = 0;
int numServiceProcesses = 0;
NRP = mRunningProcesses.size();
for (int i=0; i<NRP; i++) {
ProcessItem proc = mRunningProcesses.valueAt(i);
if (proc.mCurSeq != mSequence) {
// We didn't hit this process as a dependency on one
// of our active ones, so add it up if needed.
if (proc.mRunningProcessInfo.importance >=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
numBackgroundProcesses++;
mAllProcessItems.add(proc);
} else if (proc.mRunningProcessInfo.importance <=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
numForegroundProcesses++;
mAllProcessItems.add(proc);
} else {
Log.i("RunningState", "Unknown non-service process: "
+ proc.mProcessName + " #" + proc.mPid);
}
} else {
numServiceProcesses++;
}
}
long backgroundProcessMemory = 0;
long foregroundProcessMemory = 0;
long serviceProcessMemory = 0;
ArrayList<MergedItem> newBackgroundItems = null;
try {
final int numProc = mAllProcessItems.size();
int[] pids = new int[numProc];
for (int i=0; i<numProc; i++) {
pids[i] = mAllProcessItems.get(i).mPid;
}
long[] pss = ActivityManagerNative.getDefault()
.getProcessPss(pids);
int bgIndex = 0;
for (int i=0; i<pids.length; i++) {
ProcessItem proc = mAllProcessItems.get(i);
changed |= proc.updateSize(context, pss[i], mSequence);
if (proc.mCurSeq == mSequence) {
serviceProcessMemory += proc.mSize;
} else if (proc.mRunningProcessInfo.importance >=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
backgroundProcessMemory += proc.mSize;
MergedItem mergedItem;
if (newBackgroundItems != null) {
mergedItem = proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
newBackgroundItems.add(mergedItem);
} else {
if (bgIndex >= mBackgroundItems.size()
|| mBackgroundItems.get(bgIndex).mProcess != proc) {
newBackgroundItems = new ArrayList<MergedItem>(numBackgroundProcesses);
for (int bgi=0; bgi<bgIndex; bgi++) {
newBackgroundItems.add(mBackgroundItems.get(bgi));
}
mergedItem = proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
newBackgroundItems.add(mergedItem);
} else {
mergedItem = mBackgroundItems.get(bgIndex);
}
}
mergedItem.update(context, true);
mergedItem.updateSize(context);
bgIndex++;
} else if (proc.mRunningProcessInfo.importance <=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
foregroundProcessMemory += proc.mSize;
}
}
} catch (RemoteException e) {
}
if (newBackgroundItems == null) {
// One or more at the bottom may no longer exist.
if (mBackgroundItems.size() > numBackgroundProcesses) {
newBackgroundItems = new ArrayList<MergedItem>(numBackgroundProcesses);
for (int bgi=0; bgi<numBackgroundProcesses; bgi++) {
newBackgroundItems.add(mBackgroundItems.get(bgi));
}
}
}
for (int i=0; i<mMergedItems.size(); i++) {
mMergedItems.get(i).updateSize(context);
}
synchronized (mLock) {
mNumBackgroundProcesses = numBackgroundProcesses;
mNumForegroundProcesses = numForegroundProcesses;
mNumServiceProcesses = numServiceProcesses;
mBackgroundProcessMemory = backgroundProcessMemory;
mForegroundProcessMemory = foregroundProcessMemory;
mServiceProcessMemory = serviceProcessMemory;
if (newBackgroundItems != null) {
mBackgroundItems = newBackgroundItems;
if (mWatchingBackgroundItems) {
changed = true;
}
}
if (!mHaveData) {
mHaveData = true;
mLock.notifyAll();
}
}
return changed;
}
| private boolean update(Context context, ActivityManager am) {
final PackageManager pm = context.getPackageManager();
mSequence++;
boolean changed = false;
// Retrieve list of services, filtering out anything that definitely
// won't be shown in the UI.
List<ActivityManager.RunningServiceInfo> services
= am.getRunningServices(MAX_SERVICES);
int NS = services != null ? services.size() : 0;
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
// We are not interested in services that have not been started
// and don't have a known client, because
// there is nothing the user can do about them.
if (!si.started && si.clientLabel == 0) {
services.remove(i);
i--;
NS--;
continue;
}
// We likewise don't care about services running in a
// persistent process like the system or phone.
if ((si.flags&ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS)
!= 0) {
services.remove(i);
i--;
NS--;
continue;
}
}
// Retrieve list of running processes, organizing them into a sparse
// array for easy retrieval.
List<ActivityManager.RunningAppProcessInfo> processes
= am.getRunningAppProcesses();
final int NP = processes != null ? processes.size() : 0;
mTmpAppProcesses.clear();
for (int i=0; i<NP; i++) {
ActivityManager.RunningAppProcessInfo pi = processes.get(i);
mTmpAppProcesses.put(pi.pid, new AppProcessInfo(pi));
}
// Initial iteration through running services to collect per-process
// info about them.
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
if (si.restarting == 0 && si.pid > 0) {
AppProcessInfo ainfo = mTmpAppProcesses.get(si.pid);
if (ainfo != null) {
ainfo.hasServices = true;
if (si.foreground) {
ainfo.hasForegroundServices = true;
}
}
}
}
// Update state we are maintaining about process that are running services.
for (int i=0; i<NS; i++) {
ActivityManager.RunningServiceInfo si = services.get(i);
// If this service's process is in use at a higher importance
// due to another process bound to one of its services, then we
// won't put it in the top-level list of services. Instead we
// want it to be included in the set of processes that the other
// process needs.
if (si.restarting == 0 && si.pid > 0) {
AppProcessInfo ainfo = mTmpAppProcesses.get(si.pid);
if (ainfo != null && !ainfo.hasForegroundServices) {
// This process does not have any foreground services.
// If its importance is greater than the service importance
// then there is something else more significant that is
// keeping it around that it should possibly be included as
// a part of instead of being shown by itself.
if (ainfo.info.importance
< ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
// Follow process chain to see if there is something
// else that could be shown
boolean skip = false;
ainfo = mTmpAppProcesses.get(ainfo.info.importanceReasonPid);
while (ainfo != null) {
if (ainfo.hasServices || isInterestingProcess(ainfo.info)) {
skip = true;
break;
}
ainfo = mTmpAppProcesses.get(ainfo.info.importanceReasonPid);
}
if (skip) {
continue;
}
}
}
}
HashMap<String, ProcessItem> procs = mServiceProcessesByName.get(si.uid);
if (procs == null) {
procs = new HashMap<String, ProcessItem>();
mServiceProcessesByName.put(si.uid, procs);
}
ProcessItem proc = procs.get(si.process);
if (proc == null) {
changed = true;
proc = new ProcessItem(context, si.uid, si.process);
procs.put(si.process, proc);
}
if (proc.mCurSeq != mSequence) {
int pid = si.restarting == 0 ? si.pid : 0;
if (pid != proc.mPid) {
changed = true;
if (proc.mPid != pid) {
if (proc.mPid != 0) {
mServiceProcessesByPid.remove(proc.mPid);
}
if (pid != 0) {
mServiceProcessesByPid.put(pid, proc);
}
proc.mPid = pid;
}
}
proc.mDependentProcesses.clear();
proc.mCurSeq = mSequence;
}
changed |= proc.updateService(context, si);
}
// Now update the map of other processes that are running (but
// don't have services actively running inside them).
for (int i=0; i<NP; i++) {
ActivityManager.RunningAppProcessInfo pi = processes.get(i);
ProcessItem proc = mServiceProcessesByPid.get(pi.pid);
if (proc == null) {
// This process is not one that is a direct container
// of a service, so look for it in the secondary
// running list.
proc = mRunningProcesses.get(pi.pid);
if (proc == null) {
changed = true;
proc = new ProcessItem(context, pi.uid, pi.processName);
proc.mPid = pi.pid;
mRunningProcesses.put(pi.pid, proc);
}
proc.mDependentProcesses.clear();
}
if (isInterestingProcess(pi)) {
if (!mInterestingProcesses.contains(proc)) {
changed = true;
mInterestingProcesses.add(proc);
}
proc.mCurSeq = mSequence;
proc.mInteresting = true;
proc.ensureLabel(pm);
} else {
proc.mInteresting = false;
}
proc.mRunningSeq = mSequence;
proc.mRunningProcessInfo = pi;
}
// Build the chains from client processes to the process they are
// dependent on; also remove any old running processes.
int NRP = mRunningProcesses.size();
for (int i = 0; i < NRP;) {
ProcessItem proc = mRunningProcesses.valueAt(i);
if (proc.mRunningSeq == mSequence) {
int clientPid = proc.mRunningProcessInfo.importanceReasonPid;
if (clientPid != 0) {
ProcessItem client = mServiceProcessesByPid.get(clientPid);
if (client == null) {
client = mRunningProcesses.get(clientPid);
}
if (client != null) {
client.mDependentProcesses.put(proc.mPid, proc);
}
} else {
// In this pass the process doesn't have a client.
// Clear to make sure that, if it later gets the same one,
// we will detect the change.
proc.mClient = null;
}
i++;
} else {
changed = true;
mRunningProcesses.remove(mRunningProcesses.keyAt(i));
NRP--;
}
}
// Remove any old interesting processes.
int NHP = mInterestingProcesses.size();
for (int i=0; i<NHP; i++) {
ProcessItem proc = mInterestingProcesses.get(i);
if (!proc.mInteresting || mRunningProcesses.get(proc.mPid) == null) {
changed = true;
mInterestingProcesses.remove(i);
i--;
NHP--;
}
}
// Follow the tree from all primary service processes to all
// processes they are dependent on, marking these processes as
// still being active and determining if anything has changed.
final int NAP = mServiceProcessesByPid.size();
for (int i=0; i<NAP; i++) {
ProcessItem proc = mServiceProcessesByPid.valueAt(i);
if (proc.mCurSeq == mSequence) {
changed |= proc.buildDependencyChain(context, pm, mSequence);
}
}
// Look for services and their primary processes that no longer exist...
ArrayList<Integer> uidToDelete = null;
for (int i=0; i<mServiceProcessesByName.size(); i++) {
HashMap<String, ProcessItem> procs = mServiceProcessesByName.valueAt(i);
Iterator<ProcessItem> pit = procs.values().iterator();
while (pit.hasNext()) {
ProcessItem pi = pit.next();
if (pi.mCurSeq == mSequence) {
pi.ensureLabel(pm);
if (pi.mPid == 0) {
// Sanity: a non-process can't be dependent on
// anything.
pi.mDependentProcesses.clear();
}
} else {
changed = true;
pit.remove();
if (procs.size() == 0) {
if (uidToDelete == null) {
uidToDelete = new ArrayList<Integer>();
}
uidToDelete.add(mServiceProcessesByName.keyAt(i));
}
if (pi.mPid != 0) {
mServiceProcessesByPid.remove(pi.mPid);
}
continue;
}
Iterator<ServiceItem> sit = pi.mServices.values().iterator();
while (sit.hasNext()) {
ServiceItem si = sit.next();
if (si.mCurSeq != mSequence) {
changed = true;
sit.remove();
}
}
}
}
if (uidToDelete != null) {
for (int i = 0; i < uidToDelete.size(); i++) {
int uid = uidToDelete.get(i);
mServiceProcessesByName.remove(uid);
}
}
if (changed) {
// First determine an order for the services.
ArrayList<ProcessItem> sortedProcesses = new ArrayList<ProcessItem>();
for (int i=0; i<mServiceProcessesByName.size(); i++) {
for (ProcessItem pi : mServiceProcessesByName.valueAt(i).values()) {
pi.mIsSystem = false;
pi.mIsStarted = true;
pi.mActiveSince = Long.MAX_VALUE;
for (ServiceItem si : pi.mServices.values()) {
if (si.mServiceInfo != null
&& (si.mServiceInfo.applicationInfo.flags
& ApplicationInfo.FLAG_SYSTEM) != 0) {
pi.mIsSystem = true;
}
if (si.mRunningService != null
&& si.mRunningService.clientLabel != 0) {
pi.mIsStarted = false;
if (pi.mActiveSince > si.mRunningService.activeSince) {
pi.mActiveSince = si.mRunningService.activeSince;
}
}
}
sortedProcesses.add(pi);
}
}
Collections.sort(sortedProcesses, mServiceProcessComparator);
ArrayList<BaseItem> newItems = new ArrayList<BaseItem>();
ArrayList<MergedItem> newMergedItems = new ArrayList<MergedItem>();
mProcessItems.clear();
for (int i=0; i<sortedProcesses.size(); i++) {
ProcessItem pi = sortedProcesses.get(i);
pi.mNeedDivider = false;
int firstProc = mProcessItems.size();
// First add processes we are dependent on.
pi.addDependentProcesses(newItems, mProcessItems);
// And add the process itself.
newItems.add(pi);
if (pi.mPid > 0) {
mProcessItems.add(pi);
}
// Now add the services running in it.
MergedItem mergedItem = null;
boolean haveAllMerged = false;
boolean needDivider = false;
for (ServiceItem si : pi.mServices.values()) {
si.mNeedDivider = needDivider;
needDivider = true;
newItems.add(si);
if (si.mMergedItem != null) {
if (mergedItem != null && mergedItem != si.mMergedItem) {
haveAllMerged = false;
}
mergedItem = si.mMergedItem;
} else {
haveAllMerged = false;
}
}
if (!haveAllMerged || mergedItem == null
|| mergedItem.mServices.size() != pi.mServices.size()) {
// Whoops, we need to build a new MergedItem!
mergedItem = new MergedItem();
for (ServiceItem si : pi.mServices.values()) {
mergedItem.mServices.add(si);
si.mMergedItem = mergedItem;
}
mergedItem.mProcess = pi;
mergedItem.mOtherProcesses.clear();
for (int mpi=firstProc; mpi<(mProcessItems.size()-1); mpi++) {
mergedItem.mOtherProcesses.add(mProcessItems.get(mpi));
}
}
mergedItem.update(context, false);
newMergedItems.add(mergedItem);
}
// Finally, interesting processes need to be shown and will
// go at the top.
NHP = mInterestingProcesses.size();
for (int i=0; i<NHP; i++) {
ProcessItem proc = mInterestingProcesses.get(i);
if (proc.mClient == null && proc.mServices.size() <= 0) {
if (proc.mMergedItem == null) {
proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
}
proc.mMergedItem.update(context, false);
newMergedItems.add(0, proc.mMergedItem);
mProcessItems.add(proc);
}
}
synchronized (mLock) {
mItems = newItems;
mMergedItems = newMergedItems;
}
}
// Count number of interesting other (non-active) processes, and
// build a list of all processes we will retrieve memory for.
mAllProcessItems.clear();
mAllProcessItems.addAll(mProcessItems);
int numBackgroundProcesses = 0;
int numForegroundProcesses = 0;
int numServiceProcesses = 0;
NRP = mRunningProcesses.size();
for (int i=0; i<NRP; i++) {
ProcessItem proc = mRunningProcesses.valueAt(i);
if (proc.mCurSeq != mSequence) {
// We didn't hit this process as a dependency on one
// of our active ones, so add it up if needed.
if (proc.mRunningProcessInfo.importance >=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
numBackgroundProcesses++;
mAllProcessItems.add(proc);
} else if (proc.mRunningProcessInfo.importance <=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
numForegroundProcesses++;
mAllProcessItems.add(proc);
} else {
Log.i("RunningState", "Unknown non-service process: "
+ proc.mProcessName + " #" + proc.mPid);
}
} else {
numServiceProcesses++;
}
}
long backgroundProcessMemory = 0;
long foregroundProcessMemory = 0;
long serviceProcessMemory = 0;
ArrayList<MergedItem> newBackgroundItems = null;
try {
final int numProc = mAllProcessItems.size();
int[] pids = new int[numProc];
for (int i=0; i<numProc; i++) {
pids[i] = mAllProcessItems.get(i).mPid;
}
long[] pss = ActivityManagerNative.getDefault()
.getProcessPss(pids);
int bgIndex = 0;
for (int i=0; i<pids.length; i++) {
ProcessItem proc = mAllProcessItems.get(i);
changed |= proc.updateSize(context, pss[i], mSequence);
if (proc.mCurSeq == mSequence) {
serviceProcessMemory += proc.mSize;
} else if (proc.mRunningProcessInfo.importance >=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
backgroundProcessMemory += proc.mSize;
MergedItem mergedItem;
if (newBackgroundItems != null) {
mergedItem = proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
newBackgroundItems.add(mergedItem);
} else {
if (bgIndex >= mBackgroundItems.size()
|| mBackgroundItems.get(bgIndex).mProcess != proc) {
newBackgroundItems = new ArrayList<MergedItem>(numBackgroundProcesses);
for (int bgi=0; bgi<bgIndex; bgi++) {
newBackgroundItems.add(mBackgroundItems.get(bgi));
}
mergedItem = proc.mMergedItem = new MergedItem();
proc.mMergedItem.mProcess = proc;
newBackgroundItems.add(mergedItem);
} else {
mergedItem = mBackgroundItems.get(bgIndex);
}
}
mergedItem.update(context, true);
mergedItem.updateSize(context);
bgIndex++;
} else if (proc.mRunningProcessInfo.importance <=
ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
foregroundProcessMemory += proc.mSize;
}
}
} catch (RemoteException e) {
}
if (newBackgroundItems == null) {
// One or more at the bottom may no longer exist.
if (mBackgroundItems.size() > numBackgroundProcesses) {
newBackgroundItems = new ArrayList<MergedItem>(numBackgroundProcesses);
for (int bgi=0; bgi<numBackgroundProcesses; bgi++) {
newBackgroundItems.add(mBackgroundItems.get(bgi));
}
}
}
for (int i=0; i<mMergedItems.size(); i++) {
mMergedItems.get(i).updateSize(context);
}
synchronized (mLock) {
mNumBackgroundProcesses = numBackgroundProcesses;
mNumForegroundProcesses = numForegroundProcesses;
mNumServiceProcesses = numServiceProcesses;
mBackgroundProcessMemory = backgroundProcessMemory;
mForegroundProcessMemory = foregroundProcessMemory;
mServiceProcessMemory = serviceProcessMemory;
if (newBackgroundItems != null) {
mBackgroundItems = newBackgroundItems;
if (mWatchingBackgroundItems) {
changed = true;
}
}
if (!mHaveData) {
mHaveData = true;
mLock.notifyAll();
}
}
return changed;
}
|
diff --git a/src/gov/nih/ncgc/bard/tools/PluginValidator.java b/src/gov/nih/ncgc/bard/tools/PluginValidator.java
index 31d6ca0..eea4f84 100644
--- a/src/gov/nih/ncgc/bard/tools/PluginValidator.java
+++ b/src/gov/nih/ncgc/bard/tools/PluginValidator.java
@@ -1,265 +1,265 @@
package gov.nih.ncgc.bard.tools;
import gov.nih.ncgc.bard.plugin.IPlugin;
import javax.ws.rs.*;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* A tool to validate BARD plugins.
*
* TODO Update handling of WAR files so that we add contents of WEB-INF/lib to the current classpath
*
* @author Rajarshi Guha
*/
public class PluginValidator {
private String currentClassName = "";
private List<String> errors;
public PluginValidator() {
errors = new ArrayList<String>();
}
public List<String> getErrors() {
return errors;
}
public class ByteArrayClassLoader extends ClassLoader {
byte[] bytes;
public ByteArrayClassLoader(byte[] bytes) {
this.bytes = bytes;
}
public Class findClass(String name) {
Class klass = null;
try {
klass = defineClass(name, bytes, 0, bytes.length);
} catch (IllegalAccessError e) {
return null;
}
return klass;
}
}
public boolean validate(String filename) throws IOException, InstantiationException, IllegalAccessException {
String basename = (new File(filename)).getName();
boolean atLeastOnePlugin = false;
boolean status = false;
ZipFile zf = new ZipFile(filename);
Enumeration entries = zf.entries();
ByteArrayClassLoader loader;
while (entries.hasMoreElements()) {
ZipEntry ze = (ZipEntry) entries.nextElement();
String entryName = ze.getName();
if (entryName.endsWith(".class")) {
BufferedInputStream bis = new BufferedInputStream(zf.getInputStream(ze));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = bis.read()) != -1) {
baos.write(c);
}
bis.close();
baos.close();
byte[] bytes = baos.toByteArray();
String className = entryName.split("\\.")[0].replace("WEB-INF/classes/", "").replace("/", ".");
loader = new ByteArrayClassLoader(bytes);
Class klass = loader.findClass(className);
if (klass != null && implementsPluginInterface(klass)) {
status = validate(klass, basename);
atLeastOnePlugin = true;
}
} else if (entryName.endsWith(".jar")) { // look for classes in the jar file
JarInputStream jis = new JarInputStream(zf.getInputStream(ze));
ZipEntry entry;
while ((entry = jis.getNextEntry()) != null) {
if (!entry.getName().contains(".class") || entry.getName().contains("$")) continue;
String className = entry.getName().replace(".class", "").replace("/", ".");
if (entry.getSize() <= 0) continue;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
long nbyte = 0;
while (true) {
int n = jis.read(bytes);
if (n == -1) break;
baos.write(bytes, 0, n);
nbyte += n;
}
bytes = baos.toByteArray();
loader = new ByteArrayClassLoader(bytes);
Class klass = loader.findClass(className);
if (klass != null && implementsPluginInterface(klass)) {
status = validate(klass, basename);
atLeastOnePlugin = true;
}
}
jis.close();
}
}
zf.close();
if (!atLeastOnePlugin) {
errors.add("This does not seem to be a BARD plugin as there were no classes implementing the IPlugin interface");
return false;
} else return status;
}
private boolean implementsPluginInterface(Class klass) {
boolean implementsInterface = false;
Class pluginInterface = IPlugin.class;
Class[] interfaces = klass.getInterfaces();
for (Class iface : interfaces) {
if (iface.equals(pluginInterface)) {
implementsInterface = true;
break;
}
}
return implementsInterface;
}
/**
* Validate a class that will expose a BARD plugin service.
*
* @param klass The class in question.
* @param warName If validating via a WAR file, this should be the war file name. Otherwise, null
* @return true if a valid plugin class, otherwise false.
* @throws IllegalAccessException
* @throws InstantiationException
*/
public boolean validate(Class klass, String warName) throws IllegalAccessException, InstantiationException {
// check appropriate interface
boolean implementsInterface = implementsPluginInterface(klass);
if (!implementsInterface) {
errors.add("Does not implement IPlugin");
}
// check that the class has a class level @Path annotation
// if @Path is present, ensure it matches war file name (if we got one)
boolean hasClassLevelPathAnnot = false;
boolean collidesWithRegistry = false;
boolean matchesWarFileName = false;
if (klass.isAnnotationPresent(Path.class)) {
hasClassLevelPathAnnot = true;
Path annot = (Path) klass.getAnnotation(Path.class);
String value = annot.value();
if (value != null && value.indexOf("/plugins/registry") == 0) {
collidesWithRegistry = true;
}
if (warName != null) {
String[] toks = warName.split("\\.");
if (toks.length == 2) {
String tmp = toks[0].replace("bardplugin_", "");
matchesWarFileName = tmp.equals(value.replace("/", ""));
}
}
}
if (!hasClassLevelPathAnnot)
errors.add("Missing the class level @Path annotation");
- if (!matchesWarFileName)
+ if (warName != null && !matchesWarFileName)
errors.add("WAR file name does not correspond to @Path annotation");
if (collidesWithRegistry)
errors.add("Class level @Path annotation cannot start with '/plugins/registry'");
Method[] methods = klass.getMethods();
// check for the _info resource
boolean infoResourcePresent = false;
for (Method method : methods) {
if (method.isAnnotationPresent(Path.class)) {
Path annot = method.getAnnotation(Path.class);
// make sure the @GET annotation is present and the annotation is on the expected method
if (annot.value().equals("/_info") && method.getAnnotation(GET.class) != null && method.getName().equals("getDescription")) {
infoResourcePresent = true;
break;
}
}
}
if (!infoResourcePresent)
errors.add("Missing the getDescription() method with @Path(\"/_info\") and @GET annotations");
// check that we have at least one (public) method that is annotated
// with a GET or a POST and has a non null @Path annotation
// and a @Produces annotations
//
// Note that this check excludes the method annotated with the _info
// resource path
boolean resourcePresent = false;
for (Method method : methods) {
if (method.isAnnotationPresent(Path.class)) {
Path annot = method.getAnnotation(Path.class);
if (annot.value().equals("/_info")) continue;
// check for a @GET/@POST/@PUT
if (method.isAnnotationPresent(GET.class) ||
method.isAnnotationPresent(POST.class) ||
method.isAnnotationPresent(PUT.class)) {
// check for a @Produces
if (method.isAnnotationPresent(Produces.class)) {
resourcePresent = true;
break;
}
}
}
}
if (!resourcePresent)
errors.add("At least one public method must have a @Path annotation (in addition to the _info resource");
boolean hasEmptyCtor = false;
Constructor[] ctors = klass.getConstructors();
for (Constructor ctor : ctors) {
if (ctor.getParameterTypes().length == 0) {
hasEmptyCtor = true;
break;
}
}
if (!hasEmptyCtor) {
errors.add("Cannot instantiate plugin because it does not have an empty constructor");
return false;
}
// ok, now we create the class
IPlugin plugin = (IPlugin) klass.newInstance();
// check for a non-null description, version, manifest
String s = plugin.getDescription();
if (s == null) errors.add("getDescription() returned a null value");
s = plugin.getManifest();
if (s == null) errors.add("getManifest() returned a null value");
s = plugin.getVersion();
if (s == null) errors.add("getVersion() returned a null value");
// validate the manifest document
return errors.size() == 0;
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IOException {
PluginValidator v = new PluginValidator();
// boolean status = v.validate("/Users/guhar/src/bard.plugins/csls/deploy/bardplugin_csls.war");
boolean status = v.validate("/Users/guhar/Downloads/bardplugin_hellofromunm.war");
System.out.println("status = " + status);
if (!status) {
for (String s : v.getErrors()) System.out.println(s);
}
}
}
| true | true | public boolean validate(Class klass, String warName) throws IllegalAccessException, InstantiationException {
// check appropriate interface
boolean implementsInterface = implementsPluginInterface(klass);
if (!implementsInterface) {
errors.add("Does not implement IPlugin");
}
// check that the class has a class level @Path annotation
// if @Path is present, ensure it matches war file name (if we got one)
boolean hasClassLevelPathAnnot = false;
boolean collidesWithRegistry = false;
boolean matchesWarFileName = false;
if (klass.isAnnotationPresent(Path.class)) {
hasClassLevelPathAnnot = true;
Path annot = (Path) klass.getAnnotation(Path.class);
String value = annot.value();
if (value != null && value.indexOf("/plugins/registry") == 0) {
collidesWithRegistry = true;
}
if (warName != null) {
String[] toks = warName.split("\\.");
if (toks.length == 2) {
String tmp = toks[0].replace("bardplugin_", "");
matchesWarFileName = tmp.equals(value.replace("/", ""));
}
}
}
if (!hasClassLevelPathAnnot)
errors.add("Missing the class level @Path annotation");
if (!matchesWarFileName)
errors.add("WAR file name does not correspond to @Path annotation");
if (collidesWithRegistry)
errors.add("Class level @Path annotation cannot start with '/plugins/registry'");
Method[] methods = klass.getMethods();
// check for the _info resource
boolean infoResourcePresent = false;
for (Method method : methods) {
if (method.isAnnotationPresent(Path.class)) {
Path annot = method.getAnnotation(Path.class);
// make sure the @GET annotation is present and the annotation is on the expected method
if (annot.value().equals("/_info") && method.getAnnotation(GET.class) != null && method.getName().equals("getDescription")) {
infoResourcePresent = true;
break;
}
}
}
if (!infoResourcePresent)
errors.add("Missing the getDescription() method with @Path(\"/_info\") and @GET annotations");
// check that we have at least one (public) method that is annotated
// with a GET or a POST and has a non null @Path annotation
// and a @Produces annotations
//
// Note that this check excludes the method annotated with the _info
// resource path
boolean resourcePresent = false;
for (Method method : methods) {
if (method.isAnnotationPresent(Path.class)) {
Path annot = method.getAnnotation(Path.class);
if (annot.value().equals("/_info")) continue;
// check for a @GET/@POST/@PUT
if (method.isAnnotationPresent(GET.class) ||
method.isAnnotationPresent(POST.class) ||
method.isAnnotationPresent(PUT.class)) {
// check for a @Produces
if (method.isAnnotationPresent(Produces.class)) {
resourcePresent = true;
break;
}
}
}
}
if (!resourcePresent)
errors.add("At least one public method must have a @Path annotation (in addition to the _info resource");
boolean hasEmptyCtor = false;
Constructor[] ctors = klass.getConstructors();
for (Constructor ctor : ctors) {
if (ctor.getParameterTypes().length == 0) {
hasEmptyCtor = true;
break;
}
}
if (!hasEmptyCtor) {
errors.add("Cannot instantiate plugin because it does not have an empty constructor");
return false;
}
// ok, now we create the class
IPlugin plugin = (IPlugin) klass.newInstance();
// check for a non-null description, version, manifest
String s = plugin.getDescription();
if (s == null) errors.add("getDescription() returned a null value");
s = plugin.getManifest();
if (s == null) errors.add("getManifest() returned a null value");
s = plugin.getVersion();
if (s == null) errors.add("getVersion() returned a null value");
// validate the manifest document
return errors.size() == 0;
}
| public boolean validate(Class klass, String warName) throws IllegalAccessException, InstantiationException {
// check appropriate interface
boolean implementsInterface = implementsPluginInterface(klass);
if (!implementsInterface) {
errors.add("Does not implement IPlugin");
}
// check that the class has a class level @Path annotation
// if @Path is present, ensure it matches war file name (if we got one)
boolean hasClassLevelPathAnnot = false;
boolean collidesWithRegistry = false;
boolean matchesWarFileName = false;
if (klass.isAnnotationPresent(Path.class)) {
hasClassLevelPathAnnot = true;
Path annot = (Path) klass.getAnnotation(Path.class);
String value = annot.value();
if (value != null && value.indexOf("/plugins/registry") == 0) {
collidesWithRegistry = true;
}
if (warName != null) {
String[] toks = warName.split("\\.");
if (toks.length == 2) {
String tmp = toks[0].replace("bardplugin_", "");
matchesWarFileName = tmp.equals(value.replace("/", ""));
}
}
}
if (!hasClassLevelPathAnnot)
errors.add("Missing the class level @Path annotation");
if (warName != null && !matchesWarFileName)
errors.add("WAR file name does not correspond to @Path annotation");
if (collidesWithRegistry)
errors.add("Class level @Path annotation cannot start with '/plugins/registry'");
Method[] methods = klass.getMethods();
// check for the _info resource
boolean infoResourcePresent = false;
for (Method method : methods) {
if (method.isAnnotationPresent(Path.class)) {
Path annot = method.getAnnotation(Path.class);
// make sure the @GET annotation is present and the annotation is on the expected method
if (annot.value().equals("/_info") && method.getAnnotation(GET.class) != null && method.getName().equals("getDescription")) {
infoResourcePresent = true;
break;
}
}
}
if (!infoResourcePresent)
errors.add("Missing the getDescription() method with @Path(\"/_info\") and @GET annotations");
// check that we have at least one (public) method that is annotated
// with a GET or a POST and has a non null @Path annotation
// and a @Produces annotations
//
// Note that this check excludes the method annotated with the _info
// resource path
boolean resourcePresent = false;
for (Method method : methods) {
if (method.isAnnotationPresent(Path.class)) {
Path annot = method.getAnnotation(Path.class);
if (annot.value().equals("/_info")) continue;
// check for a @GET/@POST/@PUT
if (method.isAnnotationPresent(GET.class) ||
method.isAnnotationPresent(POST.class) ||
method.isAnnotationPresent(PUT.class)) {
// check for a @Produces
if (method.isAnnotationPresent(Produces.class)) {
resourcePresent = true;
break;
}
}
}
}
if (!resourcePresent)
errors.add("At least one public method must have a @Path annotation (in addition to the _info resource");
boolean hasEmptyCtor = false;
Constructor[] ctors = klass.getConstructors();
for (Constructor ctor : ctors) {
if (ctor.getParameterTypes().length == 0) {
hasEmptyCtor = true;
break;
}
}
if (!hasEmptyCtor) {
errors.add("Cannot instantiate plugin because it does not have an empty constructor");
return false;
}
// ok, now we create the class
IPlugin plugin = (IPlugin) klass.newInstance();
// check for a non-null description, version, manifest
String s = plugin.getDescription();
if (s == null) errors.add("getDescription() returned a null value");
s = plugin.getManifest();
if (s == null) errors.add("getManifest() returned a null value");
s = plugin.getVersion();
if (s == null) errors.add("getVersion() returned a null value");
// validate the manifest document
return errors.size() == 0;
}
|
diff --git a/src/com/uiproject/meetingplanner/TrackerEtaList.java b/src/com/uiproject/meetingplanner/TrackerEtaList.java
index e2541f0..de21ef6 100644
--- a/src/com/uiproject/meetingplanner/TrackerEtaList.java
+++ b/src/com/uiproject/meetingplanner/TrackerEtaList.java
@@ -1,150 +1,150 @@
package com.uiproject.meetingplanner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.uiproject.meetingplanner.database.MeetingPlannerDatabaseHelper;
import com.uiproject.meetingplanner.database.MeetingPlannerDatabaseManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class TrackerEtaList extends Activity {
public static final String PREFERENCE_FILENAME = "MeetAppPrefs";
private ListView attendeesList;
private ArrayList<UserInstance> attendees;
private TrackerAdapter adapter;
private MeetingPlannerDatabaseManager db;
private ArrayList<UserInstance> meetingUsers;
private MeetingInstance meetingInfo;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trackeretalist);
db = new MeetingPlannerDatabaseManager(this, MeetingPlannerDatabaseHelper.DATABASE_VERSION);
SharedPreferences settings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE);
- int mid = settings.getInt("currentTrackingMid", -1);
+ int uid = settings.getInt("uid", -1);
db.open();
- meetingInfo = db.getMeeting(mid);
- meetingUsers = db.getMeetingUsersArray(mid);
+ meetingInfo = db.getNextUpcomingMeeting(uid);
+ meetingUsers = db.getMeetingUsersArray(meetingInfo.getMeetingID());
db.close();
TextView tvMeetingName = (TextView) findViewById(R.id.meetingName);
tvMeetingName.setText(meetingInfo.getMeetingTitle());
TextView tvMeetingLocation = (TextView) findViewById(R.id.location);
tvMeetingLocation.setText(meetingInfo.getMeetingAddress());
TextView tvMeetingDate = (TextView) findViewById(R.id.date);
tvMeetingDate.setText(meetingInfo.getMeetingDate());
TextView tvMeetingTime = (TextView) findViewById(R.id.time);
tvMeetingTime.setText(meetingInfo.getMeetingStartTime());
attendeesList = (ListView) findViewById(R.id.attendeesList);
attendeesList.setClickable(false);
attendees = new ArrayList<UserInstance>();
//trackerList.add(new Tracker("Cauchy Choi", "3:00pm"));
//trackerList.add(new Tracker("Tina Chen", "4:00pm"));
adapter = new TrackerAdapter(this, attendees, meetingUsers, meetingInfo);
attendeesList.setAdapter(adapter);
TestReceiver receiver = new TestReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.uiproject.meetingplanner");
registerReceiver(receiver, filter);
// for (int i = 0; i < attendees.size(); i++) {
// eta.setText(attendees.get(i).getUserEta());
// trackerName.setText((attendees.get(i).getUserFirstName() + " " + attendees.get(i).getUserLastName()));
// }
}
public void updateList(Map<Integer, UserInstance> map) {
attendees.clear();
Set<Integer> keys = map.keySet();
for (Integer i : keys){
attendees.add(map.get(i));
Log.d("map size", ""+map.size());
//attendeeNames.add(map2.get(i).getUserFirstName() + " " + map2.get(i).getUserLastName());
}
adapter = new TrackerAdapter(this, attendees, meetingUsers, meetingInfo);
attendeesList.setAdapter(adapter);
}
public void toMap(View button){
TrackerEtaList.this.finish();
}
// menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.logoutonly, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:{
Logout.logout(this);
break;
}
}
return true;
}
public class TestReceiver extends BroadcastReceiver {
public TestReceiver (){
}
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d ("Receiver","Success2");
Bundle message = intent.getBundleExtra("message");
int tag = message.getInt("tag");
Bundle locations = message.getBundle("locations");
Log.d("BUNDLE",locations.toString());
Map<Integer,UserInstance> userLocations = new HashMap<Integer, UserInstance>();
for (String i : locations.keySet()){
Bundle location = locations.getBundle(i);
userLocations.put(Integer.valueOf(i), new UserInstance(Integer.valueOf(i),location.getInt("lat"),location.getInt("lon"),location.getString("eta")));
}
updateList(userLocations);
Log.d("tag","tag: "+tag);
Log.d("AAA","userId: "+6);
Log.d("AAA","lat: "+userLocations.get(1).getUserLocationLat());
Log.d("AAA","lon: "+userLocations.get(1).getUserLocationLon());
Log.d("AAA","eta: "+userLocations.get(1).getUserEta());
}
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trackeretalist);
db = new MeetingPlannerDatabaseManager(this, MeetingPlannerDatabaseHelper.DATABASE_VERSION);
SharedPreferences settings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE);
int mid = settings.getInt("currentTrackingMid", -1);
db.open();
meetingInfo = db.getMeeting(mid);
meetingUsers = db.getMeetingUsersArray(mid);
db.close();
TextView tvMeetingName = (TextView) findViewById(R.id.meetingName);
tvMeetingName.setText(meetingInfo.getMeetingTitle());
TextView tvMeetingLocation = (TextView) findViewById(R.id.location);
tvMeetingLocation.setText(meetingInfo.getMeetingAddress());
TextView tvMeetingDate = (TextView) findViewById(R.id.date);
tvMeetingDate.setText(meetingInfo.getMeetingDate());
TextView tvMeetingTime = (TextView) findViewById(R.id.time);
tvMeetingTime.setText(meetingInfo.getMeetingStartTime());
attendeesList = (ListView) findViewById(R.id.attendeesList);
attendeesList.setClickable(false);
attendees = new ArrayList<UserInstance>();
//trackerList.add(new Tracker("Cauchy Choi", "3:00pm"));
//trackerList.add(new Tracker("Tina Chen", "4:00pm"));
adapter = new TrackerAdapter(this, attendees, meetingUsers, meetingInfo);
attendeesList.setAdapter(adapter);
TestReceiver receiver = new TestReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.uiproject.meetingplanner");
registerReceiver(receiver, filter);
// for (int i = 0; i < attendees.size(); i++) {
// eta.setText(attendees.get(i).getUserEta());
// trackerName.setText((attendees.get(i).getUserFirstName() + " " + attendees.get(i).getUserLastName()));
// }
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trackeretalist);
db = new MeetingPlannerDatabaseManager(this, MeetingPlannerDatabaseHelper.DATABASE_VERSION);
SharedPreferences settings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE);
int uid = settings.getInt("uid", -1);
db.open();
meetingInfo = db.getNextUpcomingMeeting(uid);
meetingUsers = db.getMeetingUsersArray(meetingInfo.getMeetingID());
db.close();
TextView tvMeetingName = (TextView) findViewById(R.id.meetingName);
tvMeetingName.setText(meetingInfo.getMeetingTitle());
TextView tvMeetingLocation = (TextView) findViewById(R.id.location);
tvMeetingLocation.setText(meetingInfo.getMeetingAddress());
TextView tvMeetingDate = (TextView) findViewById(R.id.date);
tvMeetingDate.setText(meetingInfo.getMeetingDate());
TextView tvMeetingTime = (TextView) findViewById(R.id.time);
tvMeetingTime.setText(meetingInfo.getMeetingStartTime());
attendeesList = (ListView) findViewById(R.id.attendeesList);
attendeesList.setClickable(false);
attendees = new ArrayList<UserInstance>();
//trackerList.add(new Tracker("Cauchy Choi", "3:00pm"));
//trackerList.add(new Tracker("Tina Chen", "4:00pm"));
adapter = new TrackerAdapter(this, attendees, meetingUsers, meetingInfo);
attendeesList.setAdapter(adapter);
TestReceiver receiver = new TestReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.uiproject.meetingplanner");
registerReceiver(receiver, filter);
// for (int i = 0; i < attendees.size(); i++) {
// eta.setText(attendees.get(i).getUserEta());
// trackerName.setText((attendees.get(i).getUserFirstName() + " " + attendees.get(i).getUserLastName()));
// }
}
|
diff --git a/hds/src/main/uk/ac/starlink/hds/NDFNdxImpl.java b/hds/src/main/uk/ac/starlink/hds/NDFNdxImpl.java
index d6864c751..e2518e864 100644
--- a/hds/src/main/uk/ac/starlink/hds/NDFNdxImpl.java
+++ b/hds/src/main/uk/ac/starlink/hds/NDFNdxImpl.java
@@ -1,431 +1,433 @@
package uk.ac.starlink.hds;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import uk.ac.starlink.array.AccessMode;
import uk.ac.starlink.array.BridgeNDArray;
import uk.ac.starlink.array.NDArray;
import uk.ac.starlink.array.NDShape;
import uk.ac.starlink.ast.AstPackage;
import uk.ac.starlink.ast.Channel;
import uk.ac.starlink.ast.CmpMap;
import uk.ac.starlink.ast.FrameSet;
import uk.ac.starlink.ast.Mapping;
import uk.ac.starlink.ast.WinMap;
import uk.ac.starlink.ndx.NdxImpl;
import uk.ac.starlink.util.URLUtils;
/**
* Implementation of the NdxImpl interface based on an NDF.
* Since the NDF and NDX data models are pretty similar, the mapping of
* data items between the two forms is quite straightforward.
*
* @author Mark Taylor (Starlink)
*/
class NDFNdxImpl implements NdxImpl {
private final URL persistentUrl;
private final HDSObject ndf;
private final AccessMode mode;
private NDArray image;
private NDArray variance;
private NDArray quality;
/* Indices at which standard Frames are expected in NDF's WCS FrameSet. */
private static final int GRID_FRAME = 1;
private static final int PIXEL_FRAME = 2;
private static final int AXIS_FRAME = 3;
private static Logger logger = Logger.getLogger( "uk.ac.starlink.hds" );
/**
* Present an NdxImpl view of an existing NDF specified by an
* <tt>HDSReference</tt>. The HDS file will only be closed
* (the last primary locator to the structure will only be annulled)
* at such time as the object gets finalised by the garbage collector.
*
* @param nref an HDSReference pointing to the NDF
* @param persistentUrl the URL referring to the NDF; if <tt>nref</tt>
* references a temporary file it should be <tt>null</tt>
* @param mode the read/write/update mode for the array data access
* @throws HDSException if an HDS error occurs, or this doesn't
* look like an NDF
*/
public NDFNdxImpl( HDSReference nref, URL persistentUrl, AccessMode mode )
throws HDSException {
this( nref.getObject( HDSReference.hdsMode( mode ) ), persistentUrl,
mode );
}
/**
* Present an NdxImpl view of an existing NDF specified by an
* <tt>HDSObject</tt>.
* <p>
* A reference is kept to the supplied HDSObject <tt>nobj</tt>,
* but no further action is taken to ensure that a primary locator
* to the NDF structure is retained. Calling code should therefore
* either set <tt>nobj</tt> itself primary (in which case it will
* be annulled during garbage collection when this NDFNdxImpl is no
* longer referenced), or retain a suitable primary locator for as
* long as this NDFNdxImpl will be used.
*
* @param nobj the HDSObject where the NDF lives
* @param persistentUrl the URL referring to <tt>nobj</tt>,
* or <tt>null</tt> if it does not represent a permanent address
* @param mode the read/write/update mode for array data access.
* <tt>nobj</tt> itself must have been opened with a
* compatible access mode
* @throws HDSException if an HDS error occurs, or this doesn't
* look like an NDF
*/
public NDFNdxImpl( HDSObject nobj, URL persistentUrl, AccessMode mode )
throws HDSException {
this.ndf = nobj;
this.persistentUrl = persistentUrl;
this.mode = mode;
NDArray[] arrays = makeArrayData( ndf, persistentUrl, mode );
this.image = arrays[ 0 ];
this.variance = arrays[ 1 ];
this.quality = arrays[ 2 ];
}
public boolean hasTitle() {
try {
return ndf.datThere( "TITLE" );
}
catch ( HDSException e ) {
throw new RuntimeException( e );
}
}
public String getTitle() {
try {
return ndf.datFind( "TITLE" ).datGet0c();
}
catch ( HDSException e ) {
throw new RuntimeException( e );
}
}
public boolean hasWCS() {
return AstPackage.isAvailable() && wcsArray() != null;
}
public Object getWCS() {
try {
/* Get an AST Channel from the WCS component. */
Channel chan = new ARYReadChannel( wcsArray() );
/* Read a FrameSet from it. */
FrameSet fset = (FrameSet) chan.read();
/* This will require some doctoring, since its PIXEL and AXIS
* Frames are not trustworthy (the Fortran NDF library would
* ignore these and regenerate them during a call to NDF_GTWCS).
* First check that it looks as expected. */
if ( fset.getFrame( GRID_FRAME ).getDomain().equals( "GRID" ) &&
fset.getFrame( PIXEL_FRAME ).getDomain().equals( "PIXEL" ) &&
fset.getFrame( AXIS_FRAME ).getDomain().equals( "AXIS" ) ) {
/* Get and check the shape of the image grid. */
NDShape shape = image.getShape();
if ( fset.getFrame( 1 ).getNaxes() != shape.getNumDims() ) {
logger.warning( "Wrong shaped WCS object in NDF" );
return null;
}
/* Remap a PIXEL Frame correctly using the GRID Frame
* and the origin offset. */
int ndim = shape.getNumDims();
double[] ina = new double[ ndim ];
double[] inb = new double[ ndim ];
double[] outa = new double[ ndim ];
double[] outb = new double[ ndim ];
long[] origin = shape.getOrigin();
for ( int i = 0; i < ndim; i++ ) {
ina[ i ] = 0.0;
inb[ i ] = 1.0;
outa[ i ] = ina[ i ] + origin[ i ] - 1.5;
outb[ i ] = inb[ i ] + origin[ i ] - 1.5;
}
Mapping pmap =
new CmpMap( fset.getMapping( PIXEL_FRAME, GRID_FRAME ),
new WinMap( ndim, ina, inb, outa, outb ), true )
.simplify();
fset.remapFrame( PIXEL_FRAME, pmap );
/* The AXIS Frame will probably either be identical to the
* PIXEL Frame or wrong, so just delete it.
* TODO: Should really write code to construct a correct AXIS
* Frame from any existing AXIS component in the NDF. */
fset.removeFrame( AXIS_FRAME );
}
/* Unexpected configuration of frameset read from WCS component. */
else {
logger.warning( "Unexpected Frame configuration in read WCS" );
}
/* Return the doctored or undoctored FrameSet. */
return fset;
}
/* Treat errors by logging an error and returning null. */
catch ( HDSException e ) {
logger.warning( "Trouble reading WCS FrameSet from NDF: " + e );
return null;
}
catch ( IOException e ) {
logger.warning( "Trouble reading WCS FrameSet from NDF: " + e );
return null;
}
}
public boolean hasEtc() {
try {
return moreObject() != null;
}
catch ( HDSException e ) {
throw new RuntimeException( e );
}
}
public Source getEtc() {
try {
HDSObject more = moreObject();
Document doc = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.newDocument();
Node etc = doc.createElement( "etc" );
int ncomp = more.datNcomp();
for ( int i = 0; i < ncomp; i++ ) {
HDSObject extobj = more.datIndex( i + 1 );
String name = extobj.datName();
String type = extobj.datType();
Element extel = doc.createElement( name );
extel.setAttribute( "type", type );
Node content = doc.createComment(
"Extension content not yet implemented" );
extel.appendChild( content );
etc.appendChild( extel );
}
return new DOMSource( etc );
}
catch ( HDSException e ) {
throw new RuntimeException( e );
}
catch ( ParserConfigurationException e ) {
throw new RuntimeException( e );
}
}
public int getBadBits() {
try {
if ( ndf.datThere( "QUALITY" ) ) {
HDSObject qcomp = ndf.datFind( "QUALITY" );
if ( qcomp.datThere( "BADBITS" ) ) {
HDSObject bbobj = qcomp.datFind( "BADBITS" );
if ( ! bbobj.datStruc() &&
( bbobj.datType().equals( "_UBYTE" ) ||
bbobj.datType().equals( "_BYTE" ) ) &&
bbobj.datShape().length == 0 ) {
int bbval = (byte) bbobj.datGet0i();
return bbval;
}
}
}
return 0;
}
catch ( HDSException e ) {
throw new RuntimeException( e );
}
}
public NDArray getImage() {
return image;
}
public boolean hasVariance() {
return variance != null;
}
public NDArray getVariance() {
return variance;
}
public boolean hasQuality() {
return quality != null;
}
public NDArray getQuality() {
return quality;
}
/**
* Constructs the array objects serving a given NDF.
*
* @param ndf the HDSObject where the NDF lives
* @param persistentUrl the URL pointing to the NDF; if it resides
* in a temporary file this should be null
* @param mode the read/write/update access mode for array access
* @return a 3-element array of NDArrays containing image, variance,
* quality (second and/or third element may be null)
* @throws HDSException if there is an HDS error
* @throws IllegalArgumentException if it doesn't look like an NDF
*/
private static NDArray[] makeArrayData( HDSObject ndf, URL persistentUrl,
AccessMode mode )
throws HDSException {
NDArray inda = null;
NDArray vnda = null;
NDArray qnda = null;
/* In the below we subvert the HDSReference class a bit; we need to
* use its string handling properties on URLs which are not file:
* protocol ones, which it wouldn't allow. So pretend they are
* file: ones for as long as HDSReference sees them.
* This may point up a deficiency in the HDSReference class. */
String proto = null;
HDSReference baseRef = null;
URL context = null;
if ( persistentUrl != null ) {
proto = persistentUrl.getProtocol();
try {
String frag = persistentUrl.getRef();
URL baseUrl = new URL( "file:" + persistentUrl.getFile() +
( frag != null ? ( "#" + frag ) : "" ) );
baseRef = new HDSReference( baseUrl );
context = new URL( persistentUrl.getProtocol(),
persistentUrl.getHost(),
persistentUrl.getPort(),
persistentUrl.getFile() );
}
catch ( MalformedURLException e ) {
throw new RuntimeException( e.getMessage(), e );
}
}
String iname = "DATA_ARRAY";
if ( ndf.datThere( iname ) ) {
HDSObject iobj = ndf.datFind( iname );
ArrayStructure iary = new ArrayStructure( iobj );
URL iurl = null;
if ( baseRef != null ) {
HDSReference iref = (HDSReference) baseRef.clone();
iref.push( iname );
iurl = URLUtils.makeURL( context.toString(),
getLocation( iref ) );
}
inda = new BridgeNDArray( new HDSArrayImpl( iary, mode ), iurl );
}
else {
throw new IllegalArgumentException(
"No DATA_ARRAY component - not an NDF" );
}
String vname = "VARIANCE";
if ( ndf.datThere( vname ) ) {
HDSObject vobj = ndf.datFind( vname );
ArrayStructure vary = new ArrayStructure( vobj );
URL vurl = null;
if ( baseRef != null ) {
HDSReference vref = (HDSReference) baseRef.clone();
vref.push( vname );
vurl = URLUtils.makeURL( context.toString(),
getLocation( vref ) );
}
vnda = new BridgeNDArray( new HDSArrayImpl( vary, mode ), vurl );
}
String qname = "QUALITY";
if ( ndf.datThere( qname ) ) {
HDSObject qobj = ndf.datFind( qname );
URL qurl = null;
HDSReference qref = null;
if ( baseRef != null ) {
qref = (HDSReference) baseRef.clone();
qref.push( qname );
qurl = URLUtils.makeURL( context.toString(),
getLocation( qref ) );
}
if ( qobj.datType().equals( "QUALITY" ) ) {
String qsubname = "QUALITY";
if ( qref != null ) {
qref.push( qsubname );
+ qurl = URLUtils.makeURL( context.toString(),
+ getLocation( qref ) );
}
qobj = qobj.datFind( qsubname );
}
ArrayStructure qary = new ArrayStructure( qobj );
qnda = new BridgeNDArray( new HDSArrayImpl( qary, mode ), qurl );
}
return new NDArray[] { inda, vnda, qnda };
}
/**
* Return the location part of a HDSReference as a String.
*/
protected static String getLocation( HDSReference ref ) {
// Clearly just returning the filename and optional fragment
// isn't a full URL reconstruction...
URL url = ref.getURL();
String frag = url.getRef();
if ( frag != null ) {
return url.getPath() + "#" + frag;
}
return url.getPath();
}
/**
* Returns the HDS character array object containing the channelised
* WCS FrameSet representation. If none exists, returns null.
*/
private HDSObject wcsArray() {
try {
if ( ndf.datThere( "WCS" ) ) {
HDSObject wobj = ndf.datFind( "WCS" );
if ( wobj.datThere( "DATA" ) ) {
HDSObject warr = wobj.datFind( "DATA" );
if ( ! warr.datStruc() &&
warr.datType().startsWith( "_CHAR" ) &&
warr.datShape().length == 1 ) {
return warr;
}
}
}
return null;
}
catch ( HDSException e ) {
throw new RuntimeException( e );
}
}
/**
* Returns the .MORE extension component. If none exists, returns null.
*/
private HDSObject moreObject() throws HDSException {
if ( ndf.datThere( "MORE" ) ) {
HDSObject more = ndf.datFind( "MORE" );
if ( more.datStruc() ) {
return more;
}
}
return null;
}
}
| true | true | private static NDArray[] makeArrayData( HDSObject ndf, URL persistentUrl,
AccessMode mode )
throws HDSException {
NDArray inda = null;
NDArray vnda = null;
NDArray qnda = null;
/* In the below we subvert the HDSReference class a bit; we need to
* use its string handling properties on URLs which are not file:
* protocol ones, which it wouldn't allow. So pretend they are
* file: ones for as long as HDSReference sees them.
* This may point up a deficiency in the HDSReference class. */
String proto = null;
HDSReference baseRef = null;
URL context = null;
if ( persistentUrl != null ) {
proto = persistentUrl.getProtocol();
try {
String frag = persistentUrl.getRef();
URL baseUrl = new URL( "file:" + persistentUrl.getFile() +
( frag != null ? ( "#" + frag ) : "" ) );
baseRef = new HDSReference( baseUrl );
context = new URL( persistentUrl.getProtocol(),
persistentUrl.getHost(),
persistentUrl.getPort(),
persistentUrl.getFile() );
}
catch ( MalformedURLException e ) {
throw new RuntimeException( e.getMessage(), e );
}
}
String iname = "DATA_ARRAY";
if ( ndf.datThere( iname ) ) {
HDSObject iobj = ndf.datFind( iname );
ArrayStructure iary = new ArrayStructure( iobj );
URL iurl = null;
if ( baseRef != null ) {
HDSReference iref = (HDSReference) baseRef.clone();
iref.push( iname );
iurl = URLUtils.makeURL( context.toString(),
getLocation( iref ) );
}
inda = new BridgeNDArray( new HDSArrayImpl( iary, mode ), iurl );
}
else {
throw new IllegalArgumentException(
"No DATA_ARRAY component - not an NDF" );
}
String vname = "VARIANCE";
if ( ndf.datThere( vname ) ) {
HDSObject vobj = ndf.datFind( vname );
ArrayStructure vary = new ArrayStructure( vobj );
URL vurl = null;
if ( baseRef != null ) {
HDSReference vref = (HDSReference) baseRef.clone();
vref.push( vname );
vurl = URLUtils.makeURL( context.toString(),
getLocation( vref ) );
}
vnda = new BridgeNDArray( new HDSArrayImpl( vary, mode ), vurl );
}
String qname = "QUALITY";
if ( ndf.datThere( qname ) ) {
HDSObject qobj = ndf.datFind( qname );
URL qurl = null;
HDSReference qref = null;
if ( baseRef != null ) {
qref = (HDSReference) baseRef.clone();
qref.push( qname );
qurl = URLUtils.makeURL( context.toString(),
getLocation( qref ) );
}
if ( qobj.datType().equals( "QUALITY" ) ) {
String qsubname = "QUALITY";
if ( qref != null ) {
qref.push( qsubname );
}
qobj = qobj.datFind( qsubname );
}
ArrayStructure qary = new ArrayStructure( qobj );
qnda = new BridgeNDArray( new HDSArrayImpl( qary, mode ), qurl );
}
return new NDArray[] { inda, vnda, qnda };
}
| private static NDArray[] makeArrayData( HDSObject ndf, URL persistentUrl,
AccessMode mode )
throws HDSException {
NDArray inda = null;
NDArray vnda = null;
NDArray qnda = null;
/* In the below we subvert the HDSReference class a bit; we need to
* use its string handling properties on URLs which are not file:
* protocol ones, which it wouldn't allow. So pretend they are
* file: ones for as long as HDSReference sees them.
* This may point up a deficiency in the HDSReference class. */
String proto = null;
HDSReference baseRef = null;
URL context = null;
if ( persistentUrl != null ) {
proto = persistentUrl.getProtocol();
try {
String frag = persistentUrl.getRef();
URL baseUrl = new URL( "file:" + persistentUrl.getFile() +
( frag != null ? ( "#" + frag ) : "" ) );
baseRef = new HDSReference( baseUrl );
context = new URL( persistentUrl.getProtocol(),
persistentUrl.getHost(),
persistentUrl.getPort(),
persistentUrl.getFile() );
}
catch ( MalformedURLException e ) {
throw new RuntimeException( e.getMessage(), e );
}
}
String iname = "DATA_ARRAY";
if ( ndf.datThere( iname ) ) {
HDSObject iobj = ndf.datFind( iname );
ArrayStructure iary = new ArrayStructure( iobj );
URL iurl = null;
if ( baseRef != null ) {
HDSReference iref = (HDSReference) baseRef.clone();
iref.push( iname );
iurl = URLUtils.makeURL( context.toString(),
getLocation( iref ) );
}
inda = new BridgeNDArray( new HDSArrayImpl( iary, mode ), iurl );
}
else {
throw new IllegalArgumentException(
"No DATA_ARRAY component - not an NDF" );
}
String vname = "VARIANCE";
if ( ndf.datThere( vname ) ) {
HDSObject vobj = ndf.datFind( vname );
ArrayStructure vary = new ArrayStructure( vobj );
URL vurl = null;
if ( baseRef != null ) {
HDSReference vref = (HDSReference) baseRef.clone();
vref.push( vname );
vurl = URLUtils.makeURL( context.toString(),
getLocation( vref ) );
}
vnda = new BridgeNDArray( new HDSArrayImpl( vary, mode ), vurl );
}
String qname = "QUALITY";
if ( ndf.datThere( qname ) ) {
HDSObject qobj = ndf.datFind( qname );
URL qurl = null;
HDSReference qref = null;
if ( baseRef != null ) {
qref = (HDSReference) baseRef.clone();
qref.push( qname );
qurl = URLUtils.makeURL( context.toString(),
getLocation( qref ) );
}
if ( qobj.datType().equals( "QUALITY" ) ) {
String qsubname = "QUALITY";
if ( qref != null ) {
qref.push( qsubname );
qurl = URLUtils.makeURL( context.toString(),
getLocation( qref ) );
}
qobj = qobj.datFind( qsubname );
}
ArrayStructure qary = new ArrayStructure( qobj );
qnda = new BridgeNDArray( new HDSArrayImpl( qary, mode ), qurl );
}
return new NDArray[] { inda, vnda, qnda };
}
|
diff --git a/generic.sesam/search-command-control/default/src/main/java/no/sesat/search/mode/command/SolrSearchCommand.java b/generic.sesam/search-command-control/default/src/main/java/no/sesat/search/mode/command/SolrSearchCommand.java
index 6ff49fd55..cb688942e 100644
--- a/generic.sesam/search-command-control/default/src/main/java/no/sesat/search/mode/command/SolrSearchCommand.java
+++ b/generic.sesam/search-command-control/default/src/main/java/no/sesat/search/mode/command/SolrSearchCommand.java
@@ -1,133 +1,133 @@
/*
* Copyright (2008) Schibsted Søk AS
* This file is part of SESAT.
*
* SESAT 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.
*
* SESAT 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 SESAT. If not, see <http://www.gnu.org/licenses/>.
*/
package no.sesat.search.mode.command;
import java.net.MalformedURLException;
import java.util.Map;
import no.sesat.search.mode.config.SolrCommandConfig;
import no.sesat.search.result.BasicResultItem;
import no.sesat.search.result.BasicResultList;
import no.sesat.search.result.ResultItem;
import no.sesat.search.result.ResultList;
import no.sesat.search.site.config.SiteConfiguration;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
/** Searching against a Solr index using the Solrj client.
* see http://wiki.apache.org/solr/Solrj
*
* The query syntax could be improved
* see http://lucene.apache.org/java/docs/queryparsersyntax.html
*
* @version $Id$
*/
public class SolrSearchCommand extends AbstractSearchCommand{
// Constants -----------------------------------------------------
private static final Logger LOG = Logger.getLogger(SolrSearchCommand.class);
// Attributes ----------------------------------------------------
private SolrServer server;
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
public SolrSearchCommand(final Context cxt) {
super(cxt);
try {
final String serverUrl = ((SolrCommandConfig)cxt.getSearchConfiguration()).getServerUrl();
final SiteConfiguration siteConf = cxt.getDataModel().getSite().getSiteConfiguration();
server = new CommonsHttpSolrServer(siteConf.getProperty(serverUrl));
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
}
}
@Override
public ResultList<ResultItem> execute() {
final ResultList<ResultItem> searchResult = new BasicResultList<ResultItem>();
try {
// set up query
final SolrQuery query = new SolrQuery()
.setQuery(getTransformedQuery())
.setStart(getOffset())
.setRows(getSearchConfiguration().getResultsToReturn())
- .setFields(getSearchConfiguration().getResultFieldMap().values().toArray(new String[]{}));
+ .setFields(getSearchConfiguration().getResultFieldMap().keySet().toArray(new String[]{}));
DUMP.info(query.toString());
// query
final QueryResponse response = server.query(query);
final SolrDocumentList docs = response.getResults();
searchResult.setHitCount((int)docs.getNumFound());
// iterate through docs
for(SolrDocument doc : docs){
searchResult.addResult(createItem(doc));
}
} catch (SolrServerException ex) {
LOG.error(ex.getMessage(), ex);
}
return searchResult;
}
// Public --------------------------------------------------------
// Z implementation ----------------------------------------------
// Y overrides ---------------------------------------------------
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
protected BasicResultItem createItem(final SolrDocument doc) {
BasicResultItem item = new BasicResultItem();
for (final Map.Entry<String,String> entry : getSearchConfiguration().getResultFieldMap().entrySet()){
item = item.addField(entry.getValue(), (String)doc.getFieldValue(entry.getKey()));
}
return item;
}
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| true | true | public ResultList<ResultItem> execute() {
final ResultList<ResultItem> searchResult = new BasicResultList<ResultItem>();
try {
// set up query
final SolrQuery query = new SolrQuery()
.setQuery(getTransformedQuery())
.setStart(getOffset())
.setRows(getSearchConfiguration().getResultsToReturn())
.setFields(getSearchConfiguration().getResultFieldMap().values().toArray(new String[]{}));
DUMP.info(query.toString());
// query
final QueryResponse response = server.query(query);
final SolrDocumentList docs = response.getResults();
searchResult.setHitCount((int)docs.getNumFound());
// iterate through docs
for(SolrDocument doc : docs){
searchResult.addResult(createItem(doc));
}
} catch (SolrServerException ex) {
LOG.error(ex.getMessage(), ex);
}
return searchResult;
}
| public ResultList<ResultItem> execute() {
final ResultList<ResultItem> searchResult = new BasicResultList<ResultItem>();
try {
// set up query
final SolrQuery query = new SolrQuery()
.setQuery(getTransformedQuery())
.setStart(getOffset())
.setRows(getSearchConfiguration().getResultsToReturn())
.setFields(getSearchConfiguration().getResultFieldMap().keySet().toArray(new String[]{}));
DUMP.info(query.toString());
// query
final QueryResponse response = server.query(query);
final SolrDocumentList docs = response.getResults();
searchResult.setHitCount((int)docs.getNumFound());
// iterate through docs
for(SolrDocument doc : docs){
searchResult.addResult(createItem(doc));
}
} catch (SolrServerException ex) {
LOG.error(ex.getMessage(), ex);
}
return searchResult;
}
|
diff --git a/ChairGame/src/mygame/Projectile.java b/ChairGame/src/mygame/Projectile.java
index 9a16c2f..3f9e09c 100644
--- a/ChairGame/src/mygame/Projectile.java
+++ b/ChairGame/src/mygame/Projectile.java
@@ -1,59 +1,60 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mygame;
import com.jme3.math.Vector2f;
import com.jme3.math.Quaternion;
import com.jme3.scene.Spatial;
/**
*
* @author Alex
*/
public class Projectile extends MoveableGameObject {
private OfficeChair owner;
private int damage;
private float angle;
private float speed;
private Vector2f direction;
public Projectile(OfficeChair owner, Vector2f location, Vector2f velocity, int damage) {
- super(new CircleF(location, 0.5f));
+ super(new CircleF(location.add(location.normalize().mult(2)), 0.5f));
+ //super(new CircleF(location, 0.5f));
this.owner = owner;
this.type = GameObjectType.PROJECTILE;
this.velocity = velocity;
this.damage = damage;
}
@Override
public void setSpatial(Spatial spatial) {
super.setSpatial(spatial);
float angle = getOwner().getAngle();
float[] angles = {0, angle, 0};
Quaternion rot = new Quaternion(angles);
this.objectModel.setLocalRotation(rot);// = rot.mult(vel);
}
public OfficeChair getOwner() {
return this.owner;
}
public int getDamage() {
return this.damage;
}
public void update(float tpf) {
super.update(tpf);
}
public void onCollision(GameObject object) {
}
}
| true | true | public Projectile(OfficeChair owner, Vector2f location, Vector2f velocity, int damage) {
super(new CircleF(location, 0.5f));
this.owner = owner;
this.type = GameObjectType.PROJECTILE;
this.velocity = velocity;
this.damage = damage;
}
| public Projectile(OfficeChair owner, Vector2f location, Vector2f velocity, int damage) {
super(new CircleF(location.add(location.normalize().mult(2)), 0.5f));
//super(new CircleF(location, 0.5f));
this.owner = owner;
this.type = GameObjectType.PROJECTILE;
this.velocity = velocity;
this.damage = damage;
}
|
diff --git a/src/com/android/bluetooth/hfp/AtPhonebook.java b/src/com/android/bluetooth/hfp/AtPhonebook.java
index 88b2a73..e2c1227 100755
--- a/src/com/android/bluetooth/hfp/AtPhonebook.java
+++ b/src/com/android/bluetooth/hfp/AtPhonebook.java
@@ -1,612 +1,612 @@
/*
* 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.android.bluetooth.hfp;
import com.android.bluetooth.R;
import com.android.internal.telephony.GsmAlphabet;
import android.bluetooth.BluetoothDevice;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.PhoneLookup;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
/**
* Helper for managing phonebook presentation over AT commands
* @hide
*/
public class AtPhonebook {
private static final String TAG = "BluetoothAtPhonebook";
private static final boolean DBG = false;
/** The projection to use when querying the call log database in response
* to AT+CPBR for the MC, RC, and DC phone books (missed, received, and
* dialed calls respectively)
*/
private static final String[] CALLS_PROJECTION = new String[] {
Calls._ID, Calls.NUMBER, Calls.NUMBER_PRESENTATION
};
/** The projection to use when querying the contacts database in response
* to AT+CPBR for the ME phonebook (saved phone numbers).
*/
private static final String[] PHONES_PROJECTION = new String[] {
Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE
};
/** Android supports as many phonebook entries as the flash can hold, but
* BT periphals don't. Limit the number we'll report. */
private static final int MAX_PHONEBOOK_SIZE = 16384;
private static final String OUTGOING_CALL_WHERE = Calls.TYPE + "=" + Calls.OUTGOING_TYPE;
private static final String INCOMING_CALL_WHERE = Calls.TYPE + "=" + Calls.INCOMING_TYPE;
private static final String MISSED_CALL_WHERE = Calls.TYPE + "=" + Calls.MISSED_TYPE;
private static final String VISIBLE_PHONEBOOK_WHERE = Phone.IN_VISIBLE_GROUP + "=1";
private class PhonebookResult {
public Cursor cursor; // result set of last query
public int numberColumn;
public int numberPresentationColumn;
public int typeColumn;
public int nameColumn;
};
private Context mContext;
private ContentResolver mContentResolver;
private HeadsetStateMachine mStateMachine;
private String mCurrentPhonebook;
private String mCharacterSet = "UTF-8";
private int mCpbrIndex1, mCpbrIndex2;
private boolean mCheckingAccessPermission;
// package and class name to which we send intent to check phone book access permission
private static final String ACCESS_AUTHORITY_PACKAGE = "com.android.settings";
private static final String ACCESS_AUTHORITY_CLASS =
"com.android.settings.bluetooth.BluetoothPermissionRequest";
private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
private final HashMap<String, PhonebookResult> mPhonebooks =
new HashMap<String, PhonebookResult>(4);
final int TYPE_UNKNOWN = -1;
final int TYPE_READ = 0;
final int TYPE_SET = 1;
final int TYPE_TEST = 2;
public AtPhonebook(Context context, HeadsetStateMachine headsetState) {
mContext = context;
mContentResolver = context.getContentResolver();
mStateMachine = headsetState;
mPhonebooks.put("DC", new PhonebookResult()); // dialled calls
mPhonebooks.put("RC", new PhonebookResult()); // received calls
mPhonebooks.put("MC", new PhonebookResult()); // missed calls
mPhonebooks.put("ME", new PhonebookResult()); // mobile phonebook
mCurrentPhonebook = "ME"; // default to mobile phonebook
mCpbrIndex1 = mCpbrIndex2 = -1;
mCheckingAccessPermission = false;
}
public void cleanup() {
mPhonebooks.clear();
}
/** Returns the last dialled number, or null if no numbers have been called */
public String getLastDialledNumber() {
String[] projection = {Calls.NUMBER};
Cursor cursor = mContentResolver.query(Calls.CONTENT_URI, projection,
Calls.TYPE + "=" + Calls.OUTGOING_TYPE, null, Calls.DEFAULT_SORT_ORDER +
" LIMIT 1");
if (cursor == null) return null;
if (cursor.getCount() < 1) {
cursor.close();
return null;
}
cursor.moveToNext();
int column = cursor.getColumnIndexOrThrow(Calls.NUMBER);
String number = cursor.getString(column);
cursor.close();
return number;
}
public boolean getCheckingAccessPermission() {
return mCheckingAccessPermission;
}
public void setCheckingAccessPermission(boolean checkAccessPermission) {
mCheckingAccessPermission = checkAccessPermission;
}
public void setCpbrIndex(int cpbrIndex) {
mCpbrIndex1 = mCpbrIndex2 = cpbrIndex;
}
public void handleCscsCommand(String atString, int type)
{
log("handleCscsCommand - atString = " +atString);
// Select Character Set
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
switch (type) {
case TYPE_READ: // Read
log("handleCscsCommand - Read Command");
atCommandResponse = "+CSCS: \"" + mCharacterSet + "\"";
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_TEST: // Test
log("handleCscsCommand - Test Command");
atCommandResponse = ( "+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")");
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_SET: // Set
log("handleCscsCommand - Set Command");
String[] args = atString.split("=");
if (args.length < 2 || !(args[1] instanceof String)) {
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
String characterSet = ((atString.split("="))[1]);
characterSet = characterSet.replace("\"", "");
if (characterSet.equals("GSM") || characterSet.equals("IRA") ||
characterSet.equals("UTF-8") || characterSet.equals("UTF8")) {
mCharacterSet = characterSet;
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
} else {
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_SUPPORTED;
}
break;
case TYPE_UNKNOWN:
default:
log("handleCscsCommand - Invalid chars");
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
}
if (atCommandResponse != null)
mStateMachine.atResponseStringNative(atCommandResponse);
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
}
public void handleCpbsCommand(String atString, int type) {
// Select PhoneBook memory Storage
log("handleCpbsCommand - atString = " +atString);
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
switch (type) {
case TYPE_READ: // Read
log("handleCpbsCommand - read command");
// Return current size and max size
if ("SM".equals(mCurrentPhonebook)) {
atCommandResponse = "+CPBS: \"SM\",0," + getMaxPhoneBookSize(0);
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
if (atCommandResponse != null)
mStateMachine.atResponseStringNative(atCommandResponse);
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true);
if (pbr == null) {
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_SUPPORTED;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
int size = pbr.cursor.getCount();
atCommandResponse = "+CPBS: \"" + mCurrentPhonebook + "\"," + size + "," + getMaxPhoneBookSize(size);
pbr.cursor.close();
pbr.cursor = null;
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_TEST: // Test
log("handleCpbsCommand - test command");
atCommandResponse = ("+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")");
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_SET: // Set
log("handleCpbsCommand - set command");
String[] args = atString.split("=");
// Select phonebook memory
if (args.length < 2 || !(args[1] instanceof String)) {
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
String pb = ((String)args[1]).trim();
while (pb.endsWith("\"")) pb = pb.substring(0, pb.length() - 1);
while (pb.startsWith("\"")) pb = pb.substring(1, pb.length());
if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
if (DBG) log("Dont know phonebook: '" + pb + "'");
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
mCurrentPhonebook = pb;
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_UNKNOWN:
default:
log("handleCpbsCommand - invalid chars");
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
}
if (atCommandResponse != null)
mStateMachine.atResponseStringNative(atCommandResponse);
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
}
public void handleCpbrCommand(String atString, int type, BluetoothDevice remoteDevice) {
log("handleCpbrCommand - atString = " +atString);
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
switch (type) {
case TYPE_TEST: // Test
/* Ideally we should return the maximum range of valid index's
* for the selected phone book, but this causes problems for the
* Parrot CK3300. So instead send just the range of currently
* valid index's.
*/
log("handleCpbrCommand - test command");
int size;
if ("SM".equals(mCurrentPhonebook)) {
size = 0;
} else {
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true); //false);
if (pbr == null) {
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
size = pbr.cursor.getCount();
log("handleCpbrCommand - size = "+size);
pbr.cursor.close();
pbr.cursor = null;
}
if (size == 0) {
/* Sending "+CPBR: (1-0)" can confused some carkits, send "1-1" * instead */
size = 1;
}
atCommandResponse = "+CPBR: (1-" + size + "),30,30";
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
if (atCommandResponse != null)
mStateMachine.atResponseStringNative(atCommandResponse);
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
// Read PhoneBook Entries
case TYPE_READ:
case TYPE_SET: // Set & read
// Phone Book Read Request
// AT+CPBR=<index1>[,<index2>]
log("handleCpbrCommand - set/read command");
if (mCpbrIndex1 != -1) {
/* handling a CPBR at the moment, reject this CPBR command */
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
// Parse indexes
int index1;
int index2;
if ((atString.split("=")).length < 2) {
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
String atCommand = (atString.split("="))[1];
String[] indices = atCommand.split(",");
for(int i = 0; i < indices.length; i++)
//replace AT command separator ';' from the index if any
indices[i] = indices[i].replace(';', ' ').trim();
try {
index1 = Integer.parseInt(indices[0]);
if (indices.length == 1)
index2 = index1;
else
index2 = Integer.parseInt(indices[1]);
}
catch (Exception e) {
log("handleCpbrCommand - exception - invalid chars: " + e.toString());
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
mCpbrIndex1 = index1;
mCpbrIndex2 = index2;
mCheckingAccessPermission = true;
if (checkAccessPermission(remoteDevice)) {
mCheckingAccessPermission = false;
atCommandResult = processCpbrCommand();
mCpbrIndex1 = mCpbrIndex2 = -1;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
break;
}
// no reponse here, will continue the process in handleAccessPermissionResult
break;
case TYPE_UNKNOWN:
default:
log("handleCpbrCommand - invalid chars");
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
mStateMachine.atResponseCodeNative(atCommandResult, atCommandErrorCode);
}
}
/** Get the most recent result for the given phone book,
* with the cursor ready to go.
* If force then re-query that phonebook
* Returns null if the cursor is not ready
*/
private synchronized PhonebookResult getPhonebookResult(String pb, boolean force) {
if (pb == null) {
return null;
}
PhonebookResult pbr = mPhonebooks.get(pb);
if (pbr == null) {
pbr = new PhonebookResult();
}
if (force || pbr.cursor == null) {
if (!queryPhonebook(pb, pbr)) {
return null;
}
}
return pbr;
}
private synchronized boolean queryPhonebook(String pb, PhonebookResult pbr) {
String where;
boolean ancillaryPhonebook = true;
if (pb.equals("ME")) {
ancillaryPhonebook = false;
where = VISIBLE_PHONEBOOK_WHERE;
} else if (pb.equals("DC")) {
where = OUTGOING_CALL_WHERE;
} else if (pb.equals("RC")) {
where = INCOMING_CALL_WHERE;
} else if (pb.equals("MC")) {
where = MISSED_CALL_WHERE;
} else {
return false;
}
if (pbr.cursor != null) {
pbr.cursor.close();
pbr.cursor = null;
}
if (ancillaryPhonebook) {
pbr.cursor = mContentResolver.query(
Calls.CONTENT_URI, CALLS_PROJECTION, where, null,
Calls.DEFAULT_SORT_ORDER + " LIMIT " + MAX_PHONEBOOK_SIZE);
if (pbr.cursor == null) return false;
pbr.numberColumn = pbr.cursor.getColumnIndexOrThrow(Calls.NUMBER);
pbr.numberPresentationColumn =
pbr.cursor.getColumnIndexOrThrow(Calls.NUMBER_PRESENTATION);
pbr.typeColumn = -1;
pbr.nameColumn = -1;
} else {
pbr.cursor = mContentResolver.query(Phone.CONTENT_URI, PHONES_PROJECTION,
where, null, Phone.NUMBER + " LIMIT " + MAX_PHONEBOOK_SIZE);
if (pbr.cursor == null) return false;
pbr.numberColumn = pbr.cursor.getColumnIndex(Phone.NUMBER);
pbr.numberPresentationColumn = -1;
pbr.typeColumn = pbr.cursor.getColumnIndex(Phone.TYPE);
pbr.nameColumn = pbr.cursor.getColumnIndex(Phone.DISPLAY_NAME);
}
Log.i(TAG, "Refreshed phonebook " + pb + " with " + pbr.cursor.getCount() + " results");
return true;
}
synchronized void resetAtState() {
mCharacterSet = "UTF-8";
mCpbrIndex1 = mCpbrIndex2 = -1;
mCheckingAccessPermission = false;
}
private synchronized int getMaxPhoneBookSize(int currSize) {
// some car kits ignore the current size and request max phone book
// size entries. Thus, it takes a long time to transfer all the
// entries. Use a heuristic to calculate the max phone book size
// considering future expansion.
// maxSize = currSize + currSize / 2 rounded up to nearest power of 2
// If currSize < 100, use 100 as the currSize
int maxSize = (currSize < 100) ? 100 : currSize;
maxSize += maxSize / 2;
return roundUpToPowerOfTwo(maxSize);
}
private int roundUpToPowerOfTwo(int x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
// process CPBR command after permission check
/*package*/ int processCpbrCommand()
{
log("processCpbrCommand");
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
StringBuilder response = new StringBuilder();
String record;
// Shortcut SM phonebook
if ("SM".equals(mCurrentPhonebook)) {
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
return atCommandResult;
}
// Check phonebook
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true); //false);
if (pbr == null) {
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
return atCommandResult;
}
// More sanity checks
// Send OK instead of ERROR if these checks fail.
// When we send error, certain kits like BMW disconnect the
// Handsfree connection.
if (pbr.cursor.getCount() == 0 || mCpbrIndex1 <= 0 || mCpbrIndex2 < mCpbrIndex1 ||
mCpbrIndex2 > pbr.cursor.getCount() || mCpbrIndex1 > pbr.cursor.getCount()) {
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
return atCommandResult;
}
// Process
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(mCpbrIndex1 - 1);
log("mCpbrIndex1 = "+mCpbrIndex1+ " and mCpbrIndex2 = "+mCpbrIndex2);
for (int index = mCpbrIndex1; index <= mCpbrIndex2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
int type = -1;
- if (pbr.nameColumn == -1) {
+ if (pbr.nameColumn == -1 && number != null && number.length() > 0) {
// try caller id lookup
// TODO: This code is horribly inefficient. I saw it
// take 7 seconds to process 100 missed calls.
Cursor c = mContentResolver.
query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE},
null, null, null);
if (c != null) {
if (c.moveToFirst()) {
name = c.getString(0);
type = c.getInt(1);
}
c.close();
}
if (DBG && name == null) log("Caller ID lookup failed for " + number);
} else {
name = pbr.cursor.getString(pbr.nameColumn);
}
if (name == null) name = "";
name = name.trim();
if (name.length() > 28) name = name.substring(0, 28);
if (pbr.typeColumn != -1) {
type = pbr.cursor.getInt(pbr.typeColumn);
name = name + "/" + getPhoneType(type);
}
if (number == null) number = "";
int regionType = PhoneNumberUtils.toaFromString(number);
number = number.trim();
number = PhoneNumberUtils.stripSeparators(number);
if (number.length() > 30) number = number.substring(0, 30);
int numberPresentation = Calls.PRESENTATION_ALLOWED;
if (pbr.numberPresentationColumn != -1) {
numberPresentation = pbr.cursor.getInt(pbr.numberPresentationColumn);
}
if (numberPresentation != Calls.PRESENTATION_ALLOWED) {
number = "";
// TODO: there are 3 types of numbers should have resource
// strings for: unknown, private, and payphone
name = mContext.getString(R.string.unknownNumber);
}
// TODO(): Handle IRA commands. It's basically
// a 7 bit ASCII character set.
if (!name.equals("") && mCharacterSet.equals("GSM")) {
byte[] nameByte = GsmAlphabet.stringToGsm8BitPacked(name);
if (nameByte == null) {
name = mContext.getString(R.string.unknownNumber);
} else {
name = new String(nameByte);
}
}
record = "+CPBR: " + index + ",\"" + number + "\"," + regionType + ",\"" + name + "\"";
record = record + "\r\n\r\n";
atCommandResponse = record;
log("processCpbrCommand - atCommandResponse = "+atCommandResponse);
mStateMachine.atResponseStringNative(atCommandResponse);
if (!pbr.cursor.moveToNext()) {
break;
}
}
if(pbr != null && pbr.cursor != null) {
pbr.cursor.close();
pbr.cursor = null;
}
return atCommandResult;
}
// Check if the remote device has premission to read our phone book
// Return true if it has the permission
// false if not known and we have sent our Intent to check
private boolean checkAccessPermission(BluetoothDevice remoteDevice) {
log("checkAccessPermission");
boolean trust = remoteDevice.getTrustState();
if (trust) {
return true;
}
log("checkAccessPermission - ACTION_CONNECTION_ACCESS_REQUEST");
Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST);
intent.setClassName(ACCESS_AUTHORITY_PACKAGE, ACCESS_AUTHORITY_CLASS);
intent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, remoteDevice);
// Leave EXTRA_PACKAGE_NAME and EXTRA_CLASS_NAME field empty
// BluetoothHandsfree's broadcast receiver is anonymous, cannot be targeted
mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
return false;
}
private static String getPhoneType(int type) {
switch (type) {
case Phone.TYPE_HOME:
return "H";
case Phone.TYPE_MOBILE:
return "M";
case Phone.TYPE_WORK:
return "W";
case Phone.TYPE_FAX_HOME:
case Phone.TYPE_FAX_WORK:
return "F";
case Phone.TYPE_OTHER:
case Phone.TYPE_CUSTOM:
default:
return "O";
}
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
| true | true | /*package*/ int processCpbrCommand()
{
log("processCpbrCommand");
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
StringBuilder response = new StringBuilder();
String record;
// Shortcut SM phonebook
if ("SM".equals(mCurrentPhonebook)) {
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
return atCommandResult;
}
// Check phonebook
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true); //false);
if (pbr == null) {
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
return atCommandResult;
}
// More sanity checks
// Send OK instead of ERROR if these checks fail.
// When we send error, certain kits like BMW disconnect the
// Handsfree connection.
if (pbr.cursor.getCount() == 0 || mCpbrIndex1 <= 0 || mCpbrIndex2 < mCpbrIndex1 ||
mCpbrIndex2 > pbr.cursor.getCount() || mCpbrIndex1 > pbr.cursor.getCount()) {
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
return atCommandResult;
}
// Process
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(mCpbrIndex1 - 1);
log("mCpbrIndex1 = "+mCpbrIndex1+ " and mCpbrIndex2 = "+mCpbrIndex2);
for (int index = mCpbrIndex1; index <= mCpbrIndex2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
int type = -1;
if (pbr.nameColumn == -1) {
// try caller id lookup
// TODO: This code is horribly inefficient. I saw it
// take 7 seconds to process 100 missed calls.
Cursor c = mContentResolver.
query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE},
null, null, null);
if (c != null) {
if (c.moveToFirst()) {
name = c.getString(0);
type = c.getInt(1);
}
c.close();
}
if (DBG && name == null) log("Caller ID lookup failed for " + number);
} else {
name = pbr.cursor.getString(pbr.nameColumn);
}
if (name == null) name = "";
name = name.trim();
if (name.length() > 28) name = name.substring(0, 28);
if (pbr.typeColumn != -1) {
type = pbr.cursor.getInt(pbr.typeColumn);
name = name + "/" + getPhoneType(type);
}
if (number == null) number = "";
int regionType = PhoneNumberUtils.toaFromString(number);
number = number.trim();
number = PhoneNumberUtils.stripSeparators(number);
if (number.length() > 30) number = number.substring(0, 30);
int numberPresentation = Calls.PRESENTATION_ALLOWED;
if (pbr.numberPresentationColumn != -1) {
numberPresentation = pbr.cursor.getInt(pbr.numberPresentationColumn);
}
if (numberPresentation != Calls.PRESENTATION_ALLOWED) {
number = "";
// TODO: there are 3 types of numbers should have resource
// strings for: unknown, private, and payphone
name = mContext.getString(R.string.unknownNumber);
}
// TODO(): Handle IRA commands. It's basically
// a 7 bit ASCII character set.
if (!name.equals("") && mCharacterSet.equals("GSM")) {
byte[] nameByte = GsmAlphabet.stringToGsm8BitPacked(name);
if (nameByte == null) {
name = mContext.getString(R.string.unknownNumber);
} else {
name = new String(nameByte);
}
}
record = "+CPBR: " + index + ",\"" + number + "\"," + regionType + ",\"" + name + "\"";
record = record + "\r\n\r\n";
atCommandResponse = record;
log("processCpbrCommand - atCommandResponse = "+atCommandResponse);
mStateMachine.atResponseStringNative(atCommandResponse);
if (!pbr.cursor.moveToNext()) {
break;
}
}
if(pbr != null && pbr.cursor != null) {
pbr.cursor.close();
pbr.cursor = null;
}
return atCommandResult;
}
| /*package*/ int processCpbrCommand()
{
log("processCpbrCommand");
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
StringBuilder response = new StringBuilder();
String record;
// Shortcut SM phonebook
if ("SM".equals(mCurrentPhonebook)) {
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
return atCommandResult;
}
// Check phonebook
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true); //false);
if (pbr == null) {
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
return atCommandResult;
}
// More sanity checks
// Send OK instead of ERROR if these checks fail.
// When we send error, certain kits like BMW disconnect the
// Handsfree connection.
if (pbr.cursor.getCount() == 0 || mCpbrIndex1 <= 0 || mCpbrIndex2 < mCpbrIndex1 ||
mCpbrIndex2 > pbr.cursor.getCount() || mCpbrIndex1 > pbr.cursor.getCount()) {
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
return atCommandResult;
}
// Process
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(mCpbrIndex1 - 1);
log("mCpbrIndex1 = "+mCpbrIndex1+ " and mCpbrIndex2 = "+mCpbrIndex2);
for (int index = mCpbrIndex1; index <= mCpbrIndex2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
int type = -1;
if (pbr.nameColumn == -1 && number != null && number.length() > 0) {
// try caller id lookup
// TODO: This code is horribly inefficient. I saw it
// take 7 seconds to process 100 missed calls.
Cursor c = mContentResolver.
query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE},
null, null, null);
if (c != null) {
if (c.moveToFirst()) {
name = c.getString(0);
type = c.getInt(1);
}
c.close();
}
if (DBG && name == null) log("Caller ID lookup failed for " + number);
} else {
name = pbr.cursor.getString(pbr.nameColumn);
}
if (name == null) name = "";
name = name.trim();
if (name.length() > 28) name = name.substring(0, 28);
if (pbr.typeColumn != -1) {
type = pbr.cursor.getInt(pbr.typeColumn);
name = name + "/" + getPhoneType(type);
}
if (number == null) number = "";
int regionType = PhoneNumberUtils.toaFromString(number);
number = number.trim();
number = PhoneNumberUtils.stripSeparators(number);
if (number.length() > 30) number = number.substring(0, 30);
int numberPresentation = Calls.PRESENTATION_ALLOWED;
if (pbr.numberPresentationColumn != -1) {
numberPresentation = pbr.cursor.getInt(pbr.numberPresentationColumn);
}
if (numberPresentation != Calls.PRESENTATION_ALLOWED) {
number = "";
// TODO: there are 3 types of numbers should have resource
// strings for: unknown, private, and payphone
name = mContext.getString(R.string.unknownNumber);
}
// TODO(): Handle IRA commands. It's basically
// a 7 bit ASCII character set.
if (!name.equals("") && mCharacterSet.equals("GSM")) {
byte[] nameByte = GsmAlphabet.stringToGsm8BitPacked(name);
if (nameByte == null) {
name = mContext.getString(R.string.unknownNumber);
} else {
name = new String(nameByte);
}
}
record = "+CPBR: " + index + ",\"" + number + "\"," + regionType + ",\"" + name + "\"";
record = record + "\r\n\r\n";
atCommandResponse = record;
log("processCpbrCommand - atCommandResponse = "+atCommandResponse);
mStateMachine.atResponseStringNative(atCommandResponse);
if (!pbr.cursor.moveToNext()) {
break;
}
}
if(pbr != null && pbr.cursor != null) {
pbr.cursor.close();
pbr.cursor = null;
}
return atCommandResult;
}
|
diff --git a/SpectroEdit/src/net/bluecow/spectro/detection/Beat.java b/SpectroEdit/src/net/bluecow/spectro/detection/Beat.java
index 401e460..d65229e 100644
--- a/SpectroEdit/src/net/bluecow/spectro/detection/Beat.java
+++ b/SpectroEdit/src/net/bluecow/spectro/detection/Beat.java
@@ -1,63 +1,65 @@
package net.bluecow.spectro.detection;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import net.bluecow.spectro.SpectroEditSession;
public class Beat
{
public Beat(long highestIndex, float highestPoint,int indexInList)
{
soundIntensity = highestPoint;
sampleLocation = highestIndex;
this.indexInList = indexInList;
}
public static final int FRAME_SIZE = 1320;
double soundIntensity;
public long sampleLocation;
public boolean predictedBeat;
Color col = Color.green;
public int indexInList;
public String toString()
{
return ""+sampleLocation;//"b "+(double)(sampleLocation*1320.0/44100.0);
}
public static void writeBeatsToFile(ArrayList<Beat> beats)
{
System.out.println("Writing beats to file");
try {
String fileName = SpectroEditSession.fileName;
- fileName.substring(0,fileName.indexOf("."));
- File f = new File(SpectroEditSession.fileName);
+ fileName = fileName.substring(0,fileName.indexOf("."));
+ fileName = fileName +".txt";
+ System.out.println(fileName);
+ File f = new File(fileName);
/*
int counter = 0;
while(f.exists())
{
f = new File("test"+counter+".txt");
counter++;
}
*/
f.createNewFile();
FileOutputStream output = new FileOutputStream(f);
PrintStream print = new PrintStream(output);
for(Beat b:beats)
{
print.println(b.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true | true | public static void writeBeatsToFile(ArrayList<Beat> beats)
{
System.out.println("Writing beats to file");
try {
String fileName = SpectroEditSession.fileName;
fileName.substring(0,fileName.indexOf("."));
File f = new File(SpectroEditSession.fileName);
/*
int counter = 0;
while(f.exists())
{
f = new File("test"+counter+".txt");
counter++;
}
*/
f.createNewFile();
FileOutputStream output = new FileOutputStream(f);
PrintStream print = new PrintStream(output);
for(Beat b:beats)
{
print.println(b.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
| public static void writeBeatsToFile(ArrayList<Beat> beats)
{
System.out.println("Writing beats to file");
try {
String fileName = SpectroEditSession.fileName;
fileName = fileName.substring(0,fileName.indexOf("."));
fileName = fileName +".txt";
System.out.println(fileName);
File f = new File(fileName);
/*
int counter = 0;
while(f.exists())
{
f = new File("test"+counter+".txt");
counter++;
}
*/
f.createNewFile();
FileOutputStream output = new FileOutputStream(f);
PrintStream print = new PrintStream(output);
for(Beat b:beats)
{
print.println(b.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/modules/org.restlet.ext.spring_2.5/src/org/restlet/ext/spring/SpringComponent.java b/modules/org.restlet.ext.spring_2.5/src/org/restlet/ext/spring/SpringComponent.java
index 22bc57614..485c60976 100644
--- a/modules/org.restlet.ext.spring_2.5/src/org/restlet/ext/spring/SpringComponent.java
+++ b/modules/org.restlet.ext.spring_2.5/src/org/restlet/ext/spring/SpringComponent.java
@@ -1,164 +1,164 @@
/**
* Copyright 2005-2008 Noelios Technologies.
*
* The contents of this file are subject to the terms of the following open
* source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 (the "Licenses"). You can
* select the license that you prefer but you may not use this file except in
* compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.gnu.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.sun.com/cddl/cddl.html
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royaltee free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.ext.spring;
import java.util.ArrayList;
import java.util.List;
import org.restlet.Client;
import org.restlet.Restlet;
import org.restlet.Server;
import org.restlet.data.Protocol;
/**
* Component that is easily configurable from Spring. Here is a usage example:
*
* <pre>
* <bean id="component"
* class="org.restlet.ext.spring.SpringComponent">
* <property name="clientsList">
* <list>
* <value>file</value>
* </list>
* </property>
* <property name="server" ref="server" />
* <property name="defaultTarget" ref="application" />
* <property name="hosts">
* <list>
* <ref bean="virtualHost" />
* </list>
* </property>
* </bean>
*
* <bean id="component.context"
* class="org.springframework.beans.factory.config.PropertyPathFactoryBean" />
*
* <bean id="server" class="org.restlet.ext.spring.SpringServer">
* <constructor-arg value="http" />
* <constructor-arg value="8182" />
* <property name="parameters">
* <props>
* <prop key="key1">value1</prop>
* <prop key="key2">value2</prop>
* </props>
* </property>
* </bean>
* </pre>
*
* Concurrency note: instances of this class or its subclasses can be invoked by
* several threads at the same time and therefore must be thread-safe. You
* should be especially careful when storing state in member variables.
*
* @see <a href="http://www.springframework.org/">Spring home page< /a>
* @author Jerome Louvel
*/
public class SpringComponent extends org.restlet.Component {
/**
* Adds a client to the list of connectors. The value can be either a
* protocol name, a Protocol instance or a Client instance.
*
* @param clientInfo
* The client info.
*/
public void setClient(Object clientInfo) {
final List<Object> clients = new ArrayList<Object>();
clients.add(clientInfo);
setClientsList(clients);
}
/**
* Sets the list of clients, either as protocol names, Protocol instances or
* Client instances.
*
* @param clients
* The list of clients.
*/
public synchronized void setClientsList(List<Object> clients) {
for (final Object client : clients) {
if (client instanceof String) {
getClients().add(Protocol.valueOf((String) client));
} else if (client instanceof Protocol) {
getClients().add((Protocol) client);
- } else if (client instanceof Server) {
+ } else if (client instanceof Client) {
getClients().add((Client) client);
} else {
getLogger()
.warning(
"Unknown object found in the clients list. Only instances of String, org.restlet.data.Protocol and org.restlet.Client are allowed.");
}
}
}
/**
* Attaches a target Restlet to the default host.
*
* @param target
* The target Restlet.
*/
public void setDefaultTarget(Restlet target) {
getDefaultHost().attach(target);
}
/**
* Adds a server to the list of connectors. The value can be either a
* protocol name, a Protocol instance or a Server instance.
*
* @param serverInfo
* The server info.
*/
public void setServer(Object serverInfo) {
final List<Object> servers = new ArrayList<Object>();
servers.add(serverInfo);
setServersList(servers);
}
/**
* Sets the list of servers, either as protocol names, Protocol instances or
* Server instances.
*
* @param serversInfo
* The list of servers.
*/
public void setServersList(List<Object> serversInfo) {
for (final Object serverInfo : serversInfo) {
if (serverInfo instanceof String) {
getServers().add(Protocol.valueOf((String) serverInfo));
} else if (serverInfo instanceof Protocol) {
getServers().add((Protocol) serverInfo);
} else if (serverInfo instanceof Server) {
getServers().add((Server) serverInfo);
} else {
getLogger()
.warning(
"Unknown object found in the servers list. Only instances of String, org.restlet.data.Protocol and org.restlet.Server are allowed.");
}
}
}
}
| true | true | public synchronized void setClientsList(List<Object> clients) {
for (final Object client : clients) {
if (client instanceof String) {
getClients().add(Protocol.valueOf((String) client));
} else if (client instanceof Protocol) {
getClients().add((Protocol) client);
} else if (client instanceof Server) {
getClients().add((Client) client);
} else {
getLogger()
.warning(
"Unknown object found in the clients list. Only instances of String, org.restlet.data.Protocol and org.restlet.Client are allowed.");
}
}
}
| public synchronized void setClientsList(List<Object> clients) {
for (final Object client : clients) {
if (client instanceof String) {
getClients().add(Protocol.valueOf((String) client));
} else if (client instanceof Protocol) {
getClients().add((Protocol) client);
} else if (client instanceof Client) {
getClients().add((Client) client);
} else {
getLogger()
.warning(
"Unknown object found in the clients list. Only instances of String, org.restlet.data.Protocol and org.restlet.Client are allowed.");
}
}
}
|
diff --git a/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/views/table/tree/DefinitionFeatureTreeViewer.java b/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/views/table/tree/DefinitionFeatureTreeViewer.java
index d5ca85c60..d2a6d3293 100644
--- a/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/views/table/tree/DefinitionFeatureTreeViewer.java
+++ b/hale/eu.esdihumboldt.hale/src/eu/esdihumboldt/hale/rcp/views/table/tree/DefinitionFeatureTreeViewer.java
@@ -1,242 +1,242 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.hale.rcp.views.table.tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TreeColumnViewerLabelProvider;
import org.eclipse.jface.viewers.TreeNode;
import org.eclipse.jface.viewers.TreeNodeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.TreeColumn;
import org.opengis.feature.Feature;
import org.opengis.metadata.lineage.Lineage;
import org.opengis.metadata.lineage.ProcessStep;
import eu.esdihumboldt.hale.rcp.utils.tree.DefaultTreeNode;
import eu.esdihumboldt.hale.rcp.utils.tree.MultiColumnTreeNodeLabelProvider;
import eu.esdihumboldt.hale.schemaprovider.model.AttributeDefinition;
import eu.esdihumboldt.hale.schemaprovider.model.SchemaElement;
import eu.esdihumboldt.hale.schemaprovider.model.TypeDefinition;
/**
* Tree viewer for features of a common feature type, based on the corresponding
* {@link SchemaElement}
*
* @author Simon Templer
* @partner 01 / Fraunhofer Institute for Computer Graphics Research
* @version $Id$
*/
public class DefinitionFeatureTreeViewer {
private static Logger _log = Logger.getLogger(DefinitionFeatureTreeViewer.class);
private final TreeViewer treeViewer;
/**
* Create a feature tree viewer
*
* @param parent the parent composite of the tree widget
*/
public DefinitionFeatureTreeViewer(final Composite parent) {
super();
treeViewer = new TreeViewer(parent, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER);
treeViewer.setContentProvider(new TreeNodeContentProvider());
treeViewer.getTree().setHeaderVisible(true);
treeViewer.getTree().setLinesVisible(true);
treeViewer.getTree().setToolTipText("");
setInput(null, null);
}
/**
* Set the tree view input
*
* @param type the feature type
* @param features the features to display
*/
public void setInput(SchemaElement type, Iterable<Feature> features) {
// remove old columns
TreeColumn[] columns = treeViewer.getTree().getColumns();
if (columns != null) {
for (TreeColumn column : columns) {
column.dispose();
}
}
// create row definitions from type definition
if (type != null) {
DefaultTreeNode root = new DefaultTreeNode();
DefaultTreeNode attributes = new DefaultTreeNode("Attributes");
root.addChild(attributes);
addProperties(attributes, type.getType());
DefaultTreeNode metadata = new DefaultTreeNode("Metadata");
root.addChild(metadata);
// create row defs for metadata
if (features != null) {
boolean displayLineage = false;
int lineageLength = 0;
int featuresSize = 0;
for (Feature f : features) {
featuresSize++;
Lineage l = (Lineage) f.getUserData().get("METADATA_LINEAGE");
if (l != null && l.getProcessSteps().size() > 0) {
displayLineage = true;
if (lineageLength < l.getProcessSteps().size()) {
lineageLength = l.getProcessSteps().size();
}
}
}
if (displayLineage) {
Object[][] processStepsText = new Object[lineageLength][featuresSize + 1];
int featureIndex = 0;
for (Feature f : features) {
Lineage l = (Lineage) f.getUserData().get("METADATA_LINEAGE");
if (l != null && l.getProcessSteps().size() > 0) {
int psIndex = 0;
for (ProcessStep ps : l.getProcessSteps()) {
processStepsText[psIndex][featureIndex + 1] = ps.getDescription().toString();
psIndex++;
}
}
featureIndex++;
}
DefaultTreeNode lineage = new DefaultTreeNode("Lineage");
metadata.addChild(lineage);
for (int i = 0; i < lineageLength; i++) {
processStepsText[i][0] = "Process Step " + (i + 1);
DefaultTreeNode processStep = new DefaultTreeNode(processStepsText[i]);
lineage.addChild(processStep);
}
}
}
// remove parent
for (TreeNode child : root.getChildren()) {
child.setParent(null);
}
// set children as input
treeViewer.setInput(root.getChildren());
}
else {
treeViewer.setInput(null);
}
Layout layout = treeViewer.getTree().getParent().getLayout();
// add type column
if (type != null) {
TreeViewerColumn column = new TreeViewerColumn(treeViewer, SWT.LEFT);
column.getColumn().setText(type.getElementName().getLocalPart());
column.setLabelProvider(new TreeColumnViewerLabelProvider(
new MultiColumnTreeNodeLabelProvider(0)));
if (layout instanceof TreeColumnLayout) {
((TreeColumnLayout) layout).setColumnData(column.getColumn(), new ColumnWeightData(1));
}
}
// add columns for features
int index = 1;
if (features != null) {
// sort features
List<Feature> sortedFeatures = new ArrayList<Feature>();
for (Feature f : features) {
sortedFeatures.add(f);
}
Collections.sort(sortedFeatures, new Comparator<Feature>() {
@Override
public int compare(Feature o1, Feature o2) {
return o1.getIdentifier().getID().compareTo(o2.getIdentifier().getID());
}
});
for (Feature feature : sortedFeatures) {
TreeViewerColumn column = new TreeViewerColumn(treeViewer, SWT.LEFT);
column.getColumn().setText(feature.getIdentifier().toString());
column.setLabelProvider(new TreeColumnViewerLabelProvider(
new PropertyItemLabelProvider(feature, index)));
if (layout instanceof TreeColumnLayout) {
((TreeColumnLayout) layout).setColumnData(column.getColumn(), new ColumnWeightData(1));
}
// add tool tip
new ColumnBrowserTip(treeViewer, 400, 300, true, index, null);
index++;
}
}
treeViewer.refresh();
treeViewer.getTree().getParent().layout(true, true);
// auto-expand attributes/metadata
- treeViewer.expandToLevel(1);
+ treeViewer.expandToLevel(2);
}
/**
* Add child nodes for the properties of the given feature type
*
* @param parent the parent node
* @param type the feature type
*/
private void addProperties(DefaultTreeNode parent,
TypeDefinition type) {
SortedMap<String, AttributeDefinition> sortedProperties = new TreeMap<String, AttributeDefinition>();
for (AttributeDefinition attribute : type.getAttributes()) {
sortedProperties.put(attribute.getName(), attribute);
}
for (Entry<String, AttributeDefinition> entry : sortedProperties.entrySet()) {
String name = entry.getKey();
if (entry.getValue().getAttributeType() != null) {
String typeName = entry.getValue().getAttributeType().getName().getLocalPart();
DefaultTreeNode childNode = new PropertyItem(name, name + ":<" + //$NON-NLS-1$
typeName + ">", entry.getValue().isAttribute()); //$NON-NLS-1$
TypeDefinition childType = entry.getValue().getAttributeType();
addProperties(childNode, childType);
parent.addChild(childNode);
}
else {
_log.warn("An attribute without an AttributeType was encountered: " + name);
}
}
}
}
| true | true | public void setInput(SchemaElement type, Iterable<Feature> features) {
// remove old columns
TreeColumn[] columns = treeViewer.getTree().getColumns();
if (columns != null) {
for (TreeColumn column : columns) {
column.dispose();
}
}
// create row definitions from type definition
if (type != null) {
DefaultTreeNode root = new DefaultTreeNode();
DefaultTreeNode attributes = new DefaultTreeNode("Attributes");
root.addChild(attributes);
addProperties(attributes, type.getType());
DefaultTreeNode metadata = new DefaultTreeNode("Metadata");
root.addChild(metadata);
// create row defs for metadata
if (features != null) {
boolean displayLineage = false;
int lineageLength = 0;
int featuresSize = 0;
for (Feature f : features) {
featuresSize++;
Lineage l = (Lineage) f.getUserData().get("METADATA_LINEAGE");
if (l != null && l.getProcessSteps().size() > 0) {
displayLineage = true;
if (lineageLength < l.getProcessSteps().size()) {
lineageLength = l.getProcessSteps().size();
}
}
}
if (displayLineage) {
Object[][] processStepsText = new Object[lineageLength][featuresSize + 1];
int featureIndex = 0;
for (Feature f : features) {
Lineage l = (Lineage) f.getUserData().get("METADATA_LINEAGE");
if (l != null && l.getProcessSteps().size() > 0) {
int psIndex = 0;
for (ProcessStep ps : l.getProcessSteps()) {
processStepsText[psIndex][featureIndex + 1] = ps.getDescription().toString();
psIndex++;
}
}
featureIndex++;
}
DefaultTreeNode lineage = new DefaultTreeNode("Lineage");
metadata.addChild(lineage);
for (int i = 0; i < lineageLength; i++) {
processStepsText[i][0] = "Process Step " + (i + 1);
DefaultTreeNode processStep = new DefaultTreeNode(processStepsText[i]);
lineage.addChild(processStep);
}
}
}
// remove parent
for (TreeNode child : root.getChildren()) {
child.setParent(null);
}
// set children as input
treeViewer.setInput(root.getChildren());
}
else {
treeViewer.setInput(null);
}
Layout layout = treeViewer.getTree().getParent().getLayout();
// add type column
if (type != null) {
TreeViewerColumn column = new TreeViewerColumn(treeViewer, SWT.LEFT);
column.getColumn().setText(type.getElementName().getLocalPart());
column.setLabelProvider(new TreeColumnViewerLabelProvider(
new MultiColumnTreeNodeLabelProvider(0)));
if (layout instanceof TreeColumnLayout) {
((TreeColumnLayout) layout).setColumnData(column.getColumn(), new ColumnWeightData(1));
}
}
// add columns for features
int index = 1;
if (features != null) {
// sort features
List<Feature> sortedFeatures = new ArrayList<Feature>();
for (Feature f : features) {
sortedFeatures.add(f);
}
Collections.sort(sortedFeatures, new Comparator<Feature>() {
@Override
public int compare(Feature o1, Feature o2) {
return o1.getIdentifier().getID().compareTo(o2.getIdentifier().getID());
}
});
for (Feature feature : sortedFeatures) {
TreeViewerColumn column = new TreeViewerColumn(treeViewer, SWT.LEFT);
column.getColumn().setText(feature.getIdentifier().toString());
column.setLabelProvider(new TreeColumnViewerLabelProvider(
new PropertyItemLabelProvider(feature, index)));
if (layout instanceof TreeColumnLayout) {
((TreeColumnLayout) layout).setColumnData(column.getColumn(), new ColumnWeightData(1));
}
// add tool tip
new ColumnBrowserTip(treeViewer, 400, 300, true, index, null);
index++;
}
}
treeViewer.refresh();
treeViewer.getTree().getParent().layout(true, true);
// auto-expand attributes/metadata
treeViewer.expandToLevel(1);
}
| public void setInput(SchemaElement type, Iterable<Feature> features) {
// remove old columns
TreeColumn[] columns = treeViewer.getTree().getColumns();
if (columns != null) {
for (TreeColumn column : columns) {
column.dispose();
}
}
// create row definitions from type definition
if (type != null) {
DefaultTreeNode root = new DefaultTreeNode();
DefaultTreeNode attributes = new DefaultTreeNode("Attributes");
root.addChild(attributes);
addProperties(attributes, type.getType());
DefaultTreeNode metadata = new DefaultTreeNode("Metadata");
root.addChild(metadata);
// create row defs for metadata
if (features != null) {
boolean displayLineage = false;
int lineageLength = 0;
int featuresSize = 0;
for (Feature f : features) {
featuresSize++;
Lineage l = (Lineage) f.getUserData().get("METADATA_LINEAGE");
if (l != null && l.getProcessSteps().size() > 0) {
displayLineage = true;
if (lineageLength < l.getProcessSteps().size()) {
lineageLength = l.getProcessSteps().size();
}
}
}
if (displayLineage) {
Object[][] processStepsText = new Object[lineageLength][featuresSize + 1];
int featureIndex = 0;
for (Feature f : features) {
Lineage l = (Lineage) f.getUserData().get("METADATA_LINEAGE");
if (l != null && l.getProcessSteps().size() > 0) {
int psIndex = 0;
for (ProcessStep ps : l.getProcessSteps()) {
processStepsText[psIndex][featureIndex + 1] = ps.getDescription().toString();
psIndex++;
}
}
featureIndex++;
}
DefaultTreeNode lineage = new DefaultTreeNode("Lineage");
metadata.addChild(lineage);
for (int i = 0; i < lineageLength; i++) {
processStepsText[i][0] = "Process Step " + (i + 1);
DefaultTreeNode processStep = new DefaultTreeNode(processStepsText[i]);
lineage.addChild(processStep);
}
}
}
// remove parent
for (TreeNode child : root.getChildren()) {
child.setParent(null);
}
// set children as input
treeViewer.setInput(root.getChildren());
}
else {
treeViewer.setInput(null);
}
Layout layout = treeViewer.getTree().getParent().getLayout();
// add type column
if (type != null) {
TreeViewerColumn column = new TreeViewerColumn(treeViewer, SWT.LEFT);
column.getColumn().setText(type.getElementName().getLocalPart());
column.setLabelProvider(new TreeColumnViewerLabelProvider(
new MultiColumnTreeNodeLabelProvider(0)));
if (layout instanceof TreeColumnLayout) {
((TreeColumnLayout) layout).setColumnData(column.getColumn(), new ColumnWeightData(1));
}
}
// add columns for features
int index = 1;
if (features != null) {
// sort features
List<Feature> sortedFeatures = new ArrayList<Feature>();
for (Feature f : features) {
sortedFeatures.add(f);
}
Collections.sort(sortedFeatures, new Comparator<Feature>() {
@Override
public int compare(Feature o1, Feature o2) {
return o1.getIdentifier().getID().compareTo(o2.getIdentifier().getID());
}
});
for (Feature feature : sortedFeatures) {
TreeViewerColumn column = new TreeViewerColumn(treeViewer, SWT.LEFT);
column.getColumn().setText(feature.getIdentifier().toString());
column.setLabelProvider(new TreeColumnViewerLabelProvider(
new PropertyItemLabelProvider(feature, index)));
if (layout instanceof TreeColumnLayout) {
((TreeColumnLayout) layout).setColumnData(column.getColumn(), new ColumnWeightData(1));
}
// add tool tip
new ColumnBrowserTip(treeViewer, 400, 300, true, index, null);
index++;
}
}
treeViewer.refresh();
treeViewer.getTree().getParent().layout(true, true);
// auto-expand attributes/metadata
treeViewer.expandToLevel(2);
}
|
diff --git a/otp-standalone/src/main/java/org/opentripplanner/standalone/OTPMain.java b/otp-standalone/src/main/java/org/opentripplanner/standalone/OTPMain.java
index f56bb5558..6b33d4170 100644
--- a/otp-standalone/src/main/java/org/opentripplanner/standalone/OTPMain.java
+++ b/otp-standalone/src/main/java/org/opentripplanner/standalone/OTPMain.java
@@ -1,71 +1,80 @@
/* 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 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.opentripplanner.standalone;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
public class OTPMain {
private static final Logger LOG = LoggerFactory.getLogger(OTPMain.class);
@Parameter(names = { "-h", "--help"}, description = "Print this help message and exit", help = true)
private boolean help;
@Parameter(names = { "-v", "--verbose" }, description = "Verbose output")
private boolean verbose = false;
@Parameter(names = { "-p", "--port"}, description = "server port")
private int port = 8080;
@Parameter(names = { "-g", "--graphs"}, description = "path to graph directory")
private String graphDirectory = "/var/otp/graphs";
@Parameter(names = { "-r", "--router"}, description = "default router ID")
private String defaultRouterId = "";
@Parameter(names = { "-b", "--buildonly"}, description = "build graph but do not start server")
private boolean startServer = true;
@Parameter(names = { "-s", "--static"}, description = "path to static content")
private String staticDirectory = "/var/otp/static";
@Parameter(description = "files") // the rest of the parameters in one array
private List<String> files = new ArrayList<String>();
public static void main(String[] args) {
OTPMain main = new OTPMain();
JCommander jc = new JCommander(main, args);
if (main.help) {
jc.usage();
System.exit(0);
}
- main.run();
+ while (true) {
+ try {
+ main.run();
+ return;
+ }
+ catch (Throwable throwable) {
+ LOG.error("An uncaught " + throwable.getClass().getSimpleName()
+ + " occurred inside OTP. Restarting server.", throwable);
+ }
+ }
}
private void run() {
LOG.info("Starting OTP server on port {} using graphs at {}", port, graphDirectory);
GrizzlyServer server = new GrizzlyServer();
server.start(new String[] { graphDirectory, defaultRouterId, String.valueOf(port) });
}
}
| true | true | public static void main(String[] args) {
OTPMain main = new OTPMain();
JCommander jc = new JCommander(main, args);
if (main.help) {
jc.usage();
System.exit(0);
}
main.run();
}
| public static void main(String[] args) {
OTPMain main = new OTPMain();
JCommander jc = new JCommander(main, args);
if (main.help) {
jc.usage();
System.exit(0);
}
while (true) {
try {
main.run();
return;
}
catch (Throwable throwable) {
LOG.error("An uncaught " + throwable.getClass().getSimpleName()
+ " occurred inside OTP. Restarting server.", throwable);
}
}
}
|
diff --git a/source/RMG/jing/chem/Species.java b/source/RMG/jing/chem/Species.java
index c18ef599..41df8e22 100644
--- a/source/RMG/jing/chem/Species.java
+++ b/source/RMG/jing/chem/Species.java
@@ -1,1988 +1,1988 @@
////////////////////////////////////////////////////////////////////////////////
//
// 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.chem;
import java.io.*;
import java.util.*;
import jing.mathTool.*;
//import jing.mathTool.Queue;
import jing.chemUtil.*;
import jing.chemParser.*;
import jing.chemUtil.Node;
import jing.param.Global;
import jing.param.Temperature;
//## package jing::chem
//----------------------------------------------------------------------------
// jing\chem\Species.java
//----------------------------------------------------------------------------
//## class Species
public class Species {
protected boolean GATPFitExecuted = false;
protected int ID; //## attribute ID
protected static int TOTAL_NUMBER = 0; //## attribute TOTAL_NUMBER
protected static boolean addID = true;
protected ChemGraph chemGraph; //## attribute chemGraph
/**
The initial value is the parameter for N2, now it is treated as a default value if no further detailed information provided.
unit: cm-1
*/
protected double deltaEDown = 461; //## attribute deltaEDown
protected String name = null; //## attribute name
protected LinkedHashSet resonanceIsomers = new LinkedHashSet(); //## attribute resonanceIsomers
protected boolean therfitExecuted = false; //## attribute therfitExecuted
protected String InChI = null; //## attribute InChI
protected TransportData chemkinTransData;
protected NASAThermoData nasaThermoData;
protected String nasaThermoSource;
protected ThreeFrequencyModel threeFrequencyModel;
//protected WilhoitThermoData wilhoitThermoData;
/**
* The spectroscopic data for the species (vibrational frequencies,
* rotational frequencies, symmetry number, and hindered frequency-barrier
* pairs. Will eventually replace ThreeFrequencyModel.
*/
protected SpectroscopicData spectroscopicData;
// Flag to tag certain species as library only... i.e. we won't try them against RMG templates.
// They will only react as defined in the primary kinetic library. GJB
protected boolean IsReactive = true;
// flag to tag certain species as having a constant concentration
// they won't be consumed by reactions (will lead to mass creation!)
protected boolean constantConcentration = false;
// Flag which specifies whether to generate InChIs
public static boolean useInChI = false;
public static boolean useSolvation = false;
protected HashSet paths;
// Constructors
//## operation Species()
private Species() {
initRelations();
//#[ operation Species()
//#]
}
//## operation Species(String,ChemGraph)
private Species(int id, String p_name, ChemGraph p_chemGraph) {
initRelations();
ID = id;
//#[ operation Species(String,ChemGraph)
name = p_name;
chemGraph = p_chemGraph;
generateResonanceIsomers();
if (!constantConcentration) {
findStablestThermoData();
} else {
//findSolvationData();
}
calculateTransportParameters();
selectDeltaEDown();
generateNASAThermoData();
// generateSpectroscopicData(); // only get it if you need it!!!
/*
* MRH 9MAR2010:
* Commenting InChI generation when making a new species.
*
* Presently, the only time an InChI is needed in any RMG "default package"
* class is in the post-processing (e.g. write the InChI with the
* RMG_Dictionary.txt file, write the InChI with the chem.inp file).
* Generating an InChI for every species made slows down RMG and is
* unnecessary. RMG will now only generate InChIs for the core species.
*/
// if (useInChI) InChI = p_chemGraph.getInChI();
//#]
}
//## operation addResonanceIsomer(ChemGraph)
public boolean addResonanceIsomer(ChemGraph p_resonanceIsomer) {
//#[ operation addResonanceIsomer(ChemGraph)
if (resonanceIsomers == null) resonanceIsomers = new LinkedHashSet();
p_resonanceIsomer.setSpecies(this);
return resonanceIsomers.add(p_resonanceIsomer);
//#]
}
//## operation calculateCp(Temperature)
public double calculateCp(Temperature p_temperature) {
//#[ operation calculateCp(Temperature)
return getThermoData().calculateCp(p_temperature);
//#]
}
//## operation calculateG(Temperature)
public double calculateG(Temperature p_temperature) {
//#[ operation calculateG(Temperature)
//return getThermoData().calculateG(p_temperature);
return nasaThermoData.calculateFreeEnergy(p_temperature);
//#]
}
//## operation calculateGLowerBound(Temperature)
//svp
public double calculateGLowerBound(Temperature p_temperature) {
//#[ operation calculateGLowerBound(Temperature)
return getThermoData().calculateGLowerBound(p_temperature);
//#]
}
//## operation calculateGUpperBound(Temperature)
//svp
public double calculateGUpperBound(Temperature p_temperature) {
//#[ operation calculateGUpperBound(Temperature)
return getThermoData().calculateGUpperBound(p_temperature);
//#]
}
//## operation calculateH(Temperature)
public double calculateH(Temperature p_temperature) {
//#[ operation calculateH(Temperature)
//return getThermoData().calculateH(p_temperature);
return nasaThermoData.calculateEnthalpy(p_temperature);
//#]
}
//## operation calculateLJParameters()
public void calculateTransportParameters() {
if (hasResonanceIsomers()){
Iterator cgIter = getResonanceIsomers();
/*
* TransportData will be found for all resonance structures for a
* given species. The purpose of this while loop is to determine
* if one of the resonance structures exists in a primary transport
* library. So, the while loop will continue until:
* (a) all resonance structures are exhausted
* (b) the chemgraph is found in a primary transport library
* If (a), we want the transportdata of the most stable chemgraph
* (for consistency)
* If (b), we want the found transport data
*/
while (cgIter.hasNext()) {
ChemGraph cg = (ChemGraph)cgIter.next();
chemkinTransData = cg.getTransportData();
if (chemkinTransData.fromPrimaryTransportLibrary) break;
}
if (!chemkinTransData.fromPrimaryTransportLibrary)
chemkinTransData = getChemGraph().getTransportData();
}
else chemkinTransData = getChemGraph().getTransportData();
//int cNum = getChemGraph().getCarbonNumber();
// int cNum = getChemGraph().getHeavyAtomNumber();
//
// selectLJParametersForSpecialMolecule();
// if (cNum == 1) chemkinTransData = new TransportData(3.758, 148.6);
// else if (cNum == 2) chemkinTransData = new TransportData(4.443, 110.7);
// else if (cNum == 3) chemkinTransData = new TransportData(5.118, 237.1);
// else if (cNum == 4) chemkinTransData = new TransportData(4.687, 531.4);
// else if (cNum == 5) chemkinTransData = new TransportData(5.784, 341.1);
// else chemkinTransData = new TransportData(5.949, 399.3);
return;
}
//## operation calculateS(Temperature)
public double calculateS(Temperature p_temperature) {
//#[ operation calculateS(Temperature)
//return getThermoData().calculateS(p_temperature);
return nasaThermoData.calculateEntropy(p_temperature);
//#]
}
//## operation doDelocalization(ChemGraph,Stack)
private ChemGraph doDelocalization(ChemGraph p_chemGraph, Stack p_path) {
//#[ operation doDelocalization(ChemGraph,Stack)
if (p_path.isEmpty() || p_path.size() != 3) throw new InvalidDelocalizationPathException();
Graph graph = Graph.copy(p_chemGraph.getGraph());
// n1-a1-n2-a2-n3.
Node node1 = graph.getNodeAt((Integer)p_path.pop());
Node node2 = graph.getNodeAt((Integer)p_path.pop());
Node node3 = graph.getNodeAt((Integer)p_path.pop());
Arc arc1 = graph.getArcBetween(node1,node2);
Arc arc2 = graph.getArcBetween(node2,node3);
// deal with node1
Atom atom1 = (Atom)node1.getElement();
Atom newAtom1 = (Atom)atom1.changeRadical(1,null);
node1.setElement(newAtom1);
// deal with arc1
Bond bond1 = (Bond)arc1.getElement();
Bond newBond1 = bond1.changeBond(-1);
arc1.setElement(newBond1);
// deal with node2, actually do nothing
// deal with arc2
Bond bond2 = (Bond)arc2.getElement();
Bond newBond2 = bond2.changeBond(1);
arc2.setElement(newBond2);
// deal with node3
Atom atom3 = (Atom)node3.getElement();
Atom newAtom3 = (Atom)atom3.changeRadical(-1,null);
node3.setElement(newAtom3);
node1.updateFgElement();
node1.updateFeElement();
node2.updateFgElement();
node2.updateFeElement();
node3.updateFgElement();
node3.updateFeElement();
p_path = null;
try {
ChemGraph newIsomer = ChemGraph.make(graph);
if (addResonanceIsomer(newIsomer)) return newIsomer;
else return null;
}
catch (ForbiddenStructureException e) {
return null;
}
//#]
}
//## operation findAllDelocalizationPaths(Node)
private HashSet findAllDelocalizationPaths(Node p_radical) {
//#[ operation findAllDelocalizationPaths(Node)
HashSet allPaths = new HashSet();
Atom atom = (Atom)p_radical.getElement();
if (!atom.isRadical()) return allPaths;
Iterator iter = p_radical.getNeighbor();
while (iter.hasNext()) {
Arc arc1 = (Arc)iter.next();
Bond bond1 = (Bond)arc1.getElement();
if (bond1.isSingle() || bond1.isDouble()) {
Node node1 = arc1.getOtherNode(p_radical);
Iterator iter2 = node1.getNeighbor();
while (iter2.hasNext()) {
Arc arc2 = (Arc)iter2.next();
if (arc2 != arc1) {
Bond bond2 = (Bond)arc2.getElement();
if (bond2.isDouble() || bond2.isTriple()) {
Node node2 = arc2.getOtherNode(node1);
Stack path = new Stack();
path.push(p_radical.getID());
path.push(node1.getID());
path.push(node2.getID());
allPaths.add(path);
}
}
}
}
}
return allPaths;
//#]
}
//## operation findStablestThermoData()
public void findStablestThermoData() {
//#[ operation findStablestThermoData()
double H = chemGraph.getThermoData().getH298();
ChemGraph stablest = chemGraph;
if (resonanceIsomers != null) {
Iterator iter = resonanceIsomers.iterator();
while (iter.hasNext()) {
ChemGraph g = (ChemGraph)iter.next();
double newH = g.getThermoData().getH298();
if (g.fromprimarythermolibrary){
H = newH;
stablest = g;
chemGraph = stablest; // presumably this should be before the return? rwest
return;
}
if (newH < H) {
H = newH;
stablest = g;
}
}
}
chemGraph = stablest;
//#]
}
public void generateNASAThermoData() {
//nasaThermoData = Therfit.generateNASAThermoData(this);
nasaThermoData = GATPFit.generateNASAThermoData(this);
nasaThermoSource = getThermoData().source;
GATPFitExecuted = (nasaThermoData != null);
}
/**
Requires:
Effects: generate all the possible resonance isomers for the primary chemGraph
Modifies: this.resonanceIsomers
*/
//## operation generateResonanceIsomers()
public void generateResonanceIsomers() {
//#[ operation generateResonanceIsomers()
if (chemGraph == null) throw new NullPointerException();
// check if the representation of chemGraph is correct
if (!chemGraph.repOk()) {
resonanceIsomers = null;
throw new InvalidChemGraphException();
}
// generate RI for radical
generateResonanceIsomersFromRadicalCenter();
// generaate RI for O2, removed, don't allow .o-o.
//generateResonanceIsomersForOxygen();
if (resonanceIsomers.size() == 1) {
ChemGraph cg = (ChemGraph)(resonanceIsomers.iterator().next());
if (cg == chemGraph) resonanceIsomers.clear();
else addResonanceIsomer(chemGraph);
}
if (chemGraph.getRadicalNumber() >= 2){
//find if there are radicals next to each other and in that case
//increase the bond order by 1
Iterator radicalnodeIter = chemGraph.getRadicalNode().iterator();
while (radicalnodeIter.hasNext()){
Node n1 = (Node)radicalnodeIter.next();
Iterator arcs = n1.getNeighbor();
while (arcs.hasNext()){
Arc arc1 = (Arc)arcs.next();
Bond bond1 = (Bond)arc1.getElement();
Node n2 = arc1.getOtherNode(n1);
Atom a2 = (Atom)n2.getElement();
if (a2.isRadical() && !bond1.isTriple()){
Graph newG = Graph.copy(chemGraph.getGraph());
Node newn1 = newG.getNodeAt(n1.getID());
Atom newa1 = (Atom)newn1.getElement();
newa1.changeRadical(-1, null);
newn1.setElement(newa1);
Node newn2 = newG.getNodeAt(n2.getID());
Atom newa2 = (Atom)newn2.getElement();
newa2.changeRadical(-1,null);
newn2.setElement(newa2);
Arc newarc1 = newG.getArcBetween(n2.getID(), n1.getID());
Bond newb1 = (Bond)newarc1.getElement();
newb1.changeBond(1);
newarc1.setElement(newb1);
ChemGraph newchemG;
try {
newchemG = ChemGraph.make(newG);
addResonanceIsomer(newchemG);
} catch (InvalidChemGraphException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ForbiddenStructureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
/*Graph g = Graph.copy(chemGraph.getGraph());
// generate node-electron stucture
int nodeNumber = g.getNodeNumber();
int [] electronOnNode = new int[nodeNumber+1];
Iterator nodeIter = g.getNodeList();
while (nodeIter.hasNext()) {
Node node = (Node)nodeIter.next();
Atom atom = (Atom)node.getElement();
if (atom.isRadical()) {
int ID = node.getID().intValue();
electronOnNode[ID] = atom.getRadicalNumber();
Iterator arcIter = node.getNeighbor();
arcLoop:while (arcIter.hasNext()) {
Arc arc = (Arc)arcIter.next();
Bond bond = (Bond)arc.getElement();
if (bond.isBenzene() || bond.isTriple()) {
electronOnNode[ID] = 1;
break arcLoop;
}
else if (bond.isDouble()) {
electronOnNode[node.getID().intValue()-1] += 1;
}
}
}
}
*/
// combine them accordingly
//resonanceIsomer = combineElectronBetweenNodes(g);
return;
//#]
}
//## operation generateResonanceIsomersForOxygen()
public void generateResonanceIsomersForOxygen() {
//#[ operation generateResonanceIsomersForOxygen()
// form a O2 graph
Graph g1 = new Graph();
Node n1 = g1.addNodeAt(1,Atom.make(ChemElement.make("O"), FreeElectron.make("0")));
Node n2 = g1.addNodeAt(2,Atom.make(ChemElement.make("O"), FreeElectron.make("0")));
g1.addArcBetween(n1,Bond.make("D"),n2);
// form a .o-o. graph
Graph g2 = new Graph();
Node n3 = g2.addNodeAt(1,Atom.make(ChemElement.make("O"), FreeElectron.make("1")));
Node n4 = g2.addNodeAt(2,Atom.make(ChemElement.make("O"), FreeElectron.make("1")));
g2.addArcBetween(n3,Bond.make("S"),n4);
try {
if (chemGraph.getGraph().isEquivalent(g1)) {
ChemGraph cg = ChemGraph.make(g2);
addResonanceIsomer(cg);
}
else if (chemGraph.getGraph().isEquivalent(g2)) {
ChemGraph cg = ChemGraph.make(g1,true);
addResonanceIsomer(cg);
}
return;
}
catch (ForbiddenStructureException e) {
return;
}
//#]
}
//## operation generateResonanceIsomersFromRadicalCenter()
private void generateResonanceIsomersFromRadicalCenter() {
//#[ operation generateResonanceIsomersFromRadicalCenter()
/*
* Updated on 27-May-2009 by Michael Harper
* (in consultation w/Richard West and Josh Allen)
* Problem: Running RMG produced a "Exception in thread "main" ...
* java.lang.ArrayIndexOutOfBoundsException at ...
* jing.mathTool.Queue.enqueue(Queue.java)", etc.
* The out-of-bounds index was the undoChemGraph index. The size
* of the undoChemGraph was set to 4 times the number
* of atoms in the chemgraph. For some species, this
* value was exceeded, causing RMG to fail.
* Solution: Change undoChemGraph from Queue() to LinkedList().
* Note: RMG-defined Queue.java is obsolete
* Examples: Try running a condition.txt file with the following
* sets of species. Before, an exception would be caught.
* Test Case 1:
* 1 C 0 {2,T}
* 2 C 0 {1,T} {3,S}
* 3 C 0 {2,S} {4,T}
* 4 C 0 {3,T}
*
* 1 C 1 {2,D}
* 2 C 0 {1,D} {3,D}
* 3 C 1 {2,D}
* Test Case 2:
* 1 C 2 {2,D}
* 2 O 0 {1,D}
*
* 1 C 1 {2,D}
* 2 C 0 {1,D} {3,D}
* 3 C 0 {2,D} {4,D}
* 4 O 0 {3,D}
*/
// only radical is considered here
if (chemGraph.getRadicalNumber() <= 0) return;
addResonanceIsomer(chemGraph);
LinkedList undoChemGraph = new LinkedList();
undoChemGraph.add(chemGraph);
// Queue undoChemGraph = new Queue(4*chemGraph.getAtomNumber());
// undoChemGraph.enqueue(chemGraph);
HashSet processedChemGraph = new HashSet();
while (!undoChemGraph.isEmpty()) {
ChemGraph cg = (ChemGraph)undoChemGraph.remove();
// ChemGraph cg = (ChemGraph)undoChemGraph.dequeue();
HashSet radicalNode = cg.getRadicalNode();
Iterator radicalIter = radicalNode.iterator();
while (radicalIter.hasNext()) {
Node radical = (Node)radicalIter.next();
int radicalNumber = ((Atom)radical.getElement()).getRadicalNumber();
if (radicalNumber > 0) {
HashSet allPath = findAllDelocalizationPaths(radical);
Iterator pathIter = allPath.iterator();
while (pathIter.hasNext()) {
Stack path = (Stack)pathIter.next();
ChemGraph newCG = doDelocalization(cg, path);
if (newCG!=null && !processedChemGraph.contains(newCG)) {
undoChemGraph.add(newCG);
// undoChemGraph.enqueue(newCG);
}
}
}
}
processedChemGraph.add(cg);
}
/*for (Iterator iter = getResonanceIsomers(); iter.hasNext(); ){
ChemGraph cg = (ChemGraph)iter.next();
makeSingletAndTriplet(cg);
}*/
//#]
}
private void makeSingletAndTriplet(ChemGraph cg) {
HashSet radicalNode = cg.getRadicalNode();
Iterator radicalIter = radicalNode.iterator();
while (radicalIter.hasNext()) {
Node radical = (Node)radicalIter.next();
int radicalNumber = ((Atom)radical.getElement()).getRadicalNumber();
if (radicalNumber == 2 && radical.getFeElement().spin == null) {
// make singlet
Graph graph = Graph.copy(cg.getGraph());
int nodeID = radical.getID();
Node newNode = graph.getNodeAt(nodeID);
newNode.getFeElement().spin = "S";
try {
ChemGraph newIsomer = ChemGraph.make(graph);
addResonanceIsomer(newIsomer);
}
catch (ForbiddenStructureException e) {
}
// make triplet
Graph graph2 = Graph.copy(cg.getGraph());
Node newNode2 = graph.getNodeAt(nodeID);
newNode.getFeElement().spin = "T";
try {
ChemGraph newIsomer = ChemGraph.make(graph2);
addResonanceIsomer(newIsomer);
}
catch (ForbiddenStructureException e) {
}
}
else if (radicalNumber == 2 && radical.getFeElement().spin.equals("T")) {
// make singlet
Graph graph = Graph.copy(cg.getGraph());
int nodeID = radical.getID();
Node newNode = graph.getNodeAt(nodeID);
newNode.getFeElement().spin = "S";
try {
ChemGraph newIsomer = ChemGraph.make(graph);
addResonanceIsomer(newIsomer);
}
catch (ForbiddenStructureException e) {
}
// make nonSinglet
Graph graph2 = Graph.copy(cg.getGraph());
Node newNode2 = graph.getNodeAt(nodeID);
newNode.getFeElement().spin = null;
try {
ChemGraph newIsomer = ChemGraph.make(graph2);
addResonanceIsomer(newIsomer);
}
catch (ForbiddenStructureException e) {
}
}
else if (radicalNumber == 2 && radical.getFeElement().spin.equals("S")) {
// make triplet
Graph graph = Graph.copy(cg.getGraph());
int nodeID = radical.getID();
Node newNode = graph.getNodeAt(nodeID);
newNode.getFeElement().spin = "T";
try {
ChemGraph newIsomer = ChemGraph.make(graph);
addResonanceIsomer(newIsomer);
}
catch (ForbiddenStructureException e) {
}
// make nonSinglet
Graph graph2 = Graph.copy(cg.getGraph());
Node newNode2 = graph.getNodeAt(nodeID);
newNode.getFeElement().spin = null;
try {
ChemGraph newIsomer = ChemGraph.make(graph2);
addResonanceIsomer(newIsomer);
}
catch (ForbiddenStructureException e) {
}
}
}
}
public void generateSpectroscopicData() {
if (SpectroscopicData.mode == SpectroscopicData.Mode.THREEFREQUENCY) {
generateThreeFrequencyModel();
spectroscopicData = null;
}
else if (SpectroscopicData.mode == SpectroscopicData.Mode.FREQUENCYGROUPS) {
spectroscopicData = FrequencyGroups.getINSTANCE().generateFreqData(this);
threeFrequencyModel = null;
}
else {
spectroscopicData = null;
threeFrequencyModel = null;
}
}
public void generateThreeFrequencyModel() {
threeFrequencyModel = null;
// Do nothing if molecule is triatomic or smaller
if (isTriatomicOrSmaller())
return;
// Create three frequency model for this species
threeFrequencyModel = Therfit.generateThreeFrequencyModel(this);
therfitExecuted = (threeFrequencyModel != null);
}
public String getChemkinName() {
//#[ operation getChemkinName()
if (addID){
String chemkinName = getName() + "(" + getID() + ")";
/* Updated by MRH on 1-Jun-2008
If statement used to check if chemkinName length was greater than 16
I've changed it to length 10. Chemkin format dictates that any
"A+B(+m)=C+D(+m)" be of length 52 or less. Assuming we have 2 reactants
and 2 products for a pressure-dependent network, we already use:
- 2 characters (for the + symbol)
- 1 character (for the = symbol)
- 8 characters (4 for each of the (+m) symbols)
This leaves 52 - 11 - 41 characters for 4 species. Thus, I've changed
the criteria from length 16 to length 10.
*/
if (chemkinName.length() > 10) chemkinName = "SPC(" + getID() + ")";
return chemkinName;
}
else
return getName();
//#]
}
//## operation getInternalRotor()
public int getInternalRotor() {
//#[ operation getInternalRotor()
return getChemGraph().getInternalRotor();
//#]
}
//## operation getMolecularWeight()
public double getMolecularWeight() {
//#[ operation getMolecularWeight()
return getChemGraph().getMolecularWeight();
//#]
}
//## operation getNasaThermoData()
public NASAThermoData getNasaThermoData() {
//#[ operation getNasaThermoData()
//if (nasaThermoData==null && !therfitExecuted) generateNASAThermoData();
if (nasaThermoData==null) generateNASAThermoData();
return nasaThermoData;
//#]
}
//## operation getResonanceIsomers()
public Iterator getResonanceIsomers() {
//#[ operation getResonanceIsomers()
return resonanceIsomers.iterator();
//#]
}
public HashSet getResonanceIsomersHashSet(){
return resonanceIsomers;
}
/**
Requires:
Effects: return the thermo data of the stablest resonance isomer.
Modifies:
*/
//## operation getThermoData()
public ThermoData getThermoData() {
//#[ operation getThermoData()
return chemGraph.getThermoData();
//#]
}
public ThermoData getSolvationDAta(){
return chemGraph.getSolvationData();
//#]
}
//## operation getThreeFrequencyMode()
public ThreeFrequencyModel getThreeFrequencyMode() {
//#[ operation getThreeFrequencyMode()
if (threeFrequencyModel==null && !therfitExecuted) generateThreeFrequencyModel();
return threeFrequencyModel;
//#]
}
//## operation hasResonanceIsomers()
public boolean hasResonanceIsomers() {
//#[ operation hasResonanceIsomers()
if (resonanceIsomers == null) return false;
else return (resonanceIsomers.size() > 0);
//#]
}
//## operation hasThreeFrequencyModel()
public boolean hasThreeFrequencyModel() {
//#[ operation hasThreeFrequencyModel()
return (getThreeFrequencyModel() != null);
//#]
}
public boolean hasSpectroscopicData() {
return (spectroscopicData != null || threeFrequencyModel != null);
}
//## operation isRadical()
public boolean isRadical() {
//#[ operation isRadical()
return chemGraph.isRadical();
//#]
}
//## operation isTriatomicOrSmaller()
public boolean isTriatomicOrSmaller() {
//#[ operation isTriatomicOrSmaller()
return (getChemGraph().getAtomNumber()<=3);
//#]
}
public boolean isMonatomic() {
return (getChemGraph().getAtomNumber() == 1);
}
//## operation make(String,ChemGraph)
public static Species make(String p_name, ChemGraph p_chemGraph) {
//#[ operation make(String,ChemGraph)
double pT = System.currentTimeMillis();
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// first try to get it from the dictionary (which now uses a cache to speed it up)
Species spe = (Species)(dictionary.getSpecies(p_chemGraph));
// if it wasn't there then it's unique and we need to add it
if (spe == null) {
String name = p_name;
if (name == null || name.length()==0) {
name = p_chemGraph.getChemicalFormula();
}
int id= ++TOTAL_NUMBER;
spe = new Species(id,name,p_chemGraph);
//spe.ID =
dictionary.putSpecies(spe, true);
// DEBUG: Tell console I made this species
System.out.println("Created new species: " + spe.getName() + "(" + spe.getID() + ")");
}
else {
if (spe.chemGraph.equals(p_chemGraph)){
//spe.chemGraph.graph = p_chemGraph.graph;
//p_chemGraph = spe.chemGraph;
p_chemGraph.thermoData = spe.chemGraph.thermoData;
p_chemGraph.symmetryNumber = spe.chemGraph.symmetryNumber;
p_chemGraph.internalRotor = spe.chemGraph.internalRotor;
p_chemGraph.solvthermoData = spe.chemGraph.solvthermoData;
}
else if (spe.hasResonanceIsomers()){
Iterator cgIter = spe.getResonanceIsomers();
while(cgIter.hasNext()){
ChemGraph cg = (ChemGraph)cgIter.next();
if (cg.equals(p_chemGraph)){
p_chemGraph.thermoData = spe.chemGraph.thermoData;
p_chemGraph.symmetryNumber = spe.chemGraph.symmetryNumber;
p_chemGraph.internalRotor = spe.chemGraph.internalRotor;
p_chemGraph.solvthermoData = spe.chemGraph.solvthermoData;
break;
}
}
}
else {
System.out.println("Cannot make species which has a chemgraph: "+p_chemGraph.toString());
System.exit(0);
}
}
p_chemGraph.setSpecies(spe);
Global.makeSpecies += (System.currentTimeMillis()-pT)/1000/60;
/*
// added by rwest 2009/05/07 to see how many species are considered and in what order
// N.B. this file is not cleared at the start of a run; results are just appended
String restartFileContent="";
try{
File consideredSpecies = new File ("Restart/consideredSpecies.txt");
FileWriter fw = new FileWriter(consideredSpecies, true);
restartFileContent = restartFileContent + spe.getChemkinName() + " \n "; // name and number
// restartFileContent = restartFileContent + spe.toString(1) + "\n\n"; // full chemgraph
fw.write(restartFileContent);
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart consideredSpecies file");
System.exit(0);
}
*/
return spe;
}
// ## operation make(String,ChemGraph)
/*public static Species make(String p_name, Graph p_graph) throws InvalidChemGraphException, ForbiddenStructureException {
//#[ operation make(String,ChemGraph)
double pT = System.currentTimeMillis();
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
Species spe = dictionary.getSpeciesFromGraph(p_graph);
if (spe == null) {
ChemGraph cg = ChemGraph.make(p_graph);
spe = make(null, cg);
cg.setSpecies(spe);
}
return spe;
//#]
}*/
/*public static Species make(String p_name, ChemGraph p_chemGraph, int id) {
//#[ operation make(String,ChemGraph)
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
Species spe = (Species)(dictionary.getSpecies(p_chemGraph));
if (spe == null) {
String name = p_name;
if (name == null || name.length()==0) {
name = p_chemGraph.getChemicalFormula();
}
spe = new Species(id, name,p_chemGraph);
if (id > TOTAL_NUMBER) TOTAL_NUMBER=id;
dictionary.putSpecies(spe, false);
}
p_chemGraph.setSpecies(spe);
return spe;
//#]
}*/
/**
* Species.make
* As of 4-Sept-2009, this function is only called when making species
* read in from "Restart" files. The Restart files are generated
* after an integration step in RMG, meaning all stored species (core
* and edge) should be unique. Therefore, we do not need to check
* each new species against the SpeciesDictionary.
* MRH 4-Sept-2009
*/
public static Species make(String p_name, ChemGraph p_chemGraph, int id) {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
String name = p_name;
Species spe = new Species(id, name, p_chemGraph);
if (id > TOTAL_NUMBER) TOTAL_NUMBER=id;
dictionary.putSpecies(spe, false);
p_chemGraph.setSpecies(spe);
// DEBUG: Tell console I made this species
System.out.println("Created new species: " + spe.getName() + "(" + spe.getID() + ")");
return spe;
}
//## operation repOk()
public boolean repOk() {
//#[ operation repOk()
if (name == null || name.length() == 0) return false;
if (ID < 0 || ID > TOTAL_NUMBER) return false;
if (chemGraph != null && !chemGraph.repOk()) return false;
Iterator iter = resonanceIsomers.iterator();
while (iter.hasNext()) {
ChemGraph cg = (ChemGraph)iter.next();
if (cg == null || !cg.repOk()) return false;
}
return true;
//#]
}
//## operation selectDeltaEDown()
public void selectDeltaEDown() {
// Doing this by species name is a really bad idea.
String name = getName();
if (name.equals("Ar")) deltaEDown = 374.0;
else if (name.equals("H2")) deltaEDown = 224.0;
else if (name.equals("O2")) deltaEDown = 517.0;
else if (name.equals("N2")) deltaEDown = 461.0;
else if (name.equals("He")) deltaEDown = 291.0;
else if (name.equals("CH4")) deltaEDown = 1285.0;
else if (name.equals("HO2")) deltaEDown = 975.0;
else if (name.equals("H2O2")) deltaEDown = 975.0;
else if (name.equals("CO2")) deltaEDown = 417.0;
else if (name.equals("CO")) deltaEDown = 283.0;
return;
}
//## operation selectLJParametersForSpecialMolecule()
public void selectLJParametersForSpecialMolecule() {
//#[ operation selectLJParametersForSpecialMolecule()
String name = getName();
if (name.equals("H2")) chemkinTransData = new TransportData(2.8327, 59.7);
else if (name.equals("O2")) chemkinTransData = new TransportData(3.467, 106.7);
else if (name.equals("H2O")) chemkinTransData = new TransportData(2.641,809.1);
else if (name.equals("H2O2")) chemkinTransData = new TransportData(4.196,289.3);
else if (name.equals("CO2")) chemkinTransData = new TransportData(3.941,195.2);
else if (name.equals("CO")) chemkinTransData = new TransportData(3.690,91.7);
return;
//#]
}
public String toChemkinString() {
//#[ operation toChemkinString()
return getChemkinName();
//#]
}
//## operation toString()
public String toString() {
//#[ operation toString()
String s = "Species " + String.valueOf(ID) + '\t';
s = s + "Name: " + getName() + '\n';
ChemGraph primary = getChemGraph();
s = s + primary.toString();
int index=0;
for (Iterator iter = resonanceIsomers.iterator(); iter.hasNext(); ) {
index++;
ChemGraph isomer = (ChemGraph)iter.next();
if (isomer!=primary) {
s = s + '\n';
s = s + "isomer" + String.valueOf(index) + ":\n";
s = s + isomer.toString();
}
}
return s;
}
// ## operation toString()
public String toString(int i) {
//#[ operation toString()
String s ="";
ChemGraph primary = getChemGraph();
s = s + primary.toString(i);
int index=0;
/*for (Iterator iter = resonanceIsomers.iterator(); iter.hasNext(); ) {
index++;
ChemGraph isomer = (ChemGraph)iter.next();
if (isomer!=primary) {
s = s + '\n';
s = s + "isomer" + String.valueOf(index) + ":\n";
s = s + isomer.toStringWithoutH(i);
}
}*/
return s;
}
//## operation toStringWithoutH()
public String toStringWithoutH() {
//#[ operation toStringWithoutH()
String s = "Species " + String.valueOf(ID) + '\t';
s = s + "Name: " + getName() + '\n';
ChemGraph primary = getChemGraph();
s = s + primary.toStringWithoutH();
int index=0;
for (Iterator iter = resonanceIsomers.iterator(); iter.hasNext(); ) {
index++;
ChemGraph isomer = (ChemGraph)iter.next();
if (isomer!=primary) {
s = s + '\n';
s = s + "isomer" + String.valueOf(index) + ":\n";
s = s + isomer.toStringWithoutH();
}
}
return s;
}
public String toStringWithoutH(int i) {
//#[ operation toStringWithoutH()
String s ="";
ChemGraph primary = getChemGraph();
s = s + primary.toStringWithoutH(i);
int index=0;
/*for (Iterator iter = resonanceIsomers.iterator(); iter.hasNext(); ) {
index++;
ChemGraph isomer = (ChemGraph)iter.next();
if (isomer!=primary) {
s = s + '\n';
s = s + "isomer" + String.valueOf(index) + ":\n";
s = s + isomer.toStringWithoutH(i);
}
}*/
return s;
}
// Convert ChemGraph (p_chemGraph) to String (InChIstring)
// 6/9/09 gmagoon: updated to also read InChIKey
//output is string array with first ([0]) element being the InChI string (with "InChI="); the second ([1]) element will be the InChIKey (WITHOUT "InChIKey=")
// the function can be easily changed to accomodate other versions of the InChI program by changing the command line options (optionsArgument); for example, if InChIKey generation is turned off, the second element of the string array will be an empty string;
public static String [] generateInChI(ChemGraph p_chemGraph) {
File inchi = new File("InChI");
inchi.mkdir();
String [] result = new String[2];
String InChIstring = "";
String InChIKeystring = "";
String line = "";
String cTable = generateMolFileString(p_chemGraph);
//
File molFile = null;
String workingDirectory = System.getProperty("RMG.workingDirectory");
String inchiDirectory = "InChI";
// Write the cTable to species.mol file
try {
molFile = new File(inchiDirectory + "/species.mol");
FileWriter fw = new FileWriter(molFile);
fw.write(cTable);
fw.close();
} catch (IOException e) {
String err = "Error writing species.mol file for InChI generation: ";
err += e.toString();
System.out.println(err);
}
// Call cINChI-1 executable file
// String optionsArgument = "";
// if (getOs().toLowerCase().contains("windows"))
// optionsArgument = "/DoNotAddH /FixedH /Key";//6/9/09 gmagoon: added fixed H so tautomers are considered separately; this is apparently not an option for version 1.02 (standard inchi); also added Key option to generate inchikey...this is only available in version 1.02beta or later; therefore, this keyword combination will only work for version 1.02beta (as of now)
// else if (getOs().toLowerCase().contains("linux"))
// optionsArgument = "-DoNotAddH -FixedH -Key";
// else if (getOs().toLowerCase().contains("mac"))
// optionsArgument = "-DoNotAddH -FixedH -Key";
//6/9/09 gmagoon: I have reorganized the function in order to get around difficulty when using multiple options...if I just try to pass all options as a string (e.g. "-DoNotAddH -FixedH -Key") it is not correctly interpreted by the InChI program (note that leading "/" is not shown in the resulting "unrecognized option" warning);
//I would have liked to have specified optionsArgument as an array of strings, but I was getting "illegal start of expression" errors in NetBeans IDE
int exitValue = -1;
//while (exitValue != 0) {
/*
* MRH 9MAR2010:
* Addressing Issue#13: InChI not working consistently on Linux / Mac
*
* Switching how the input/error/output of the "InChI" Process is handled.
* MRH has copied the format JWA has used for the fame executable.
* InChI now appears to run very consistently on Linux (in the limited types
* of jobs I have ran - RMG, AdjList2InChI), in addition to running
* consistently on Windows.
*
* Hopefully RW can test the new implementation on Mac
*
* NOTE: For Windows, the InChI.waitFor() must follow the .close()
* methods for the stdout and stderr BufferedReaders. Otherwise,
* the RMG simulation gets hung up at the .waitFor() method and
* is perfecting happy waiting ... causing an infinite runtime.
*
* NOTE: For Linux,
*/
try {
if (getOs().toLowerCase().contains("windows")){
String[] command = {workingDirectory + "/bin/cInChI-1",
"species.mol",
"species.txt",
"/DoNotAddH", "/FixedH", "/Key"};//6/9/09 gmagoon: added fixed H so tautomers are considered separately; this is apparently not an option for version 1.02 (standard inchi); also added Key option to generate inchikey...this is only available in version 1.02beta or later; therefore, this keyword combination will only work for version 1.02beta (as of now)
File runningDir = new File("InChI");
Process InChI = Runtime.getRuntime().exec(command, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
// Clean up i/o streams
stdout.close();
stderr.close();
exitValue = InChI.waitFor();
}
else if (getOs().toLowerCase().contains("linux")){
String[] command = {workingDirectory + "/bin/cInChI-1",
"species.mol",
"species.txt",
"-DoNotAddH", "-FixedH", "-Key"};
File runningDir = new File("InChI");
Process InChI = Runtime.getRuntime().exec(command, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
exitValue = InChI.waitFor();
// Clean up i/o streams
stdout.close();
stderr.close();
}
else if (getOs().toLowerCase().contains("mac")){
String[] command = {workingDirectory + "/bin/cInChI-1",
"species.mol",
"species.txt",
"-DoNotAddH", "-FixedH", "-Key"};
File runningDir = new File("InChI");
Process InChI = Runtime.getRuntime().exec(command, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
exitValue = InChI.waitFor();
// Clean up i/o streams
stdout.close();
stderr.close();
}
}
catch (Exception e) {
String err = "Error running cINChI-1: ";
err += e.toString();
System.out.println(err);
}
//}
// Read in the output of the cINChI-1 executable file (species.txt)
/*
* MRH 9MAR2010:
* This portion of code (reading in the species.txt file and searching
* for the InChI and InChIKey) is now obsolete (see code above).
*/
FileReader in = null;
try {
in = new FileReader(inchiDirectory + "/species.txt");
} catch (FileNotFoundException e) {
String err = "Error reading species.txt file in generating InChI for species " + p_chemGraph.chemicalFormula + " : ";
err += e.toString();
System.out.println(err);
}
if (in != null) {
BufferedReader reader = new BufferedReader(in);
line = ChemParser.readMeaningfulLine(reader, true);
read: while (line != null) {
if (line.startsWith("InChI=")) {//changed from InChI to InChI= (to distinguish fro InChIKey
InChIstring = line;
}
else if (line.startsWith("InChIKey=")) {//changed from "InChI" to "InChI=" (to distinguish from "InChIKey="
InChIKeystring = line.replace("InChIKey=", "");//read in the InChIKey without the preceding "InChIKey="
break;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
result[0]=InChIstring;
result[1]=InChIKeystring;
}
else {
result[0] = "";
result[1] = "";
}
return result;
}
//convert a chemgraph into a string that represents a 2D molefile with all atom positions initialized to zero
//gmagoon 6/2/09: I separated this out from generateInChI so it could be easily be used elsewhere
public static String generateMolFileString(ChemGraph p_chemGraph) {
// Convert chemGraph to string
int randNum = 1;
String p_string = p_chemGraph.toString(randNum);
StringTokenizer st = new StringTokenizer(p_string);
// Extract the necessary information from the adjacency list
// - Element symbol
// - Radical number
// - Bonds (strength and connectivity)
// Define two running counters, atomCount & atomBondCount
int atomCount = 1;
int atomBondCount = 0;
// Assume molecule has <= 100 atoms
// Assume no atom can have > 6 unique bonds
int maxAtoms = 100;
int maxBonds = 6;
String[] elementSymbol = new String[maxAtoms];
String[] radical = new String[maxAtoms];
String[][] atomConnect = new String[maxAtoms][maxBonds];
String[][] bondOrder = new String[maxAtoms][maxBonds];
// Atom-by-atom, extract the necessary information
String line = st.nextToken();
while (st.hasMoreTokens()) {
// If the next token is the next integer in the series
if (line.equals(Integer.toString(atomCount))) {
// Grab element symbol and radical number
elementSymbol[atomCount-1] = st.nextToken();
radical[atomCount-1] = st.nextToken();
// If bonds exist ....
if (st.hasMoreTokens()) {
// Grab the first {bond}
line = st.nextToken();
int atomPartnerCount = 0;
while (line.endsWith("}")) {
++atomBondCount;
String insideBraces = ChemParser.removeBrace(line);
int commaPos = insideBraces.indexOf(",");
// Store bond order and atom connectivity
atomConnect[atomCount-1][atomPartnerCount] = insideBraces.substring(0,commaPos);
bondOrder[atomCount-1][atomPartnerCount] = insideBraces.substring(commaPos+1);
if (st.hasMoreTokens())
line = st.nextToken();
else
line = "";
++atomPartnerCount;
}
} else
line = "";
++atomCount;
} else
line = st.nextToken();
}
int mRad = 1;
int radCount = 0;
// Assume the species does not contain > 4 radicals
int maxRad = 4;
int[] radLocation = new int[maxRad];
int[] radType = new int[maxRad];
for (int numRads=0; numRads<(atomCount-1); numRads++) {
if (!radical[numRads].equals("0") & !radical[numRads].equals("null")) {
// If a radical exists on the atom, store its location
radLocation[radCount] = numRads+1;
// Convert RMG's radical number definition to a .mol file's
// radical number definition
if (radical[numRads].equals("2S"))
radType[radCount] = 1;
else if (radical[numRads].equals("1") | radical[numRads].equals("3"))
radType[radCount] = 2;
else if (radical[numRads].equals("2") | radical[numRads].equals("2T"))
radType[radCount] = 3;
++radCount;
// If at least one radical exist, .mol file will have 2 "M" lines
mRad = 2;
}
}
// Convert the information into a connection table (as defined by a .mol file)
// Create the "Header Block"
String cTable = "\n\n\n";
// Create the "Counts Line"
if (atomCount-1 < 10) {
cTable += " " + (atomCount-1);
} else
cTable += " " + (atomCount-1);
if (atomBondCount/2 < 10) {
cTable += " " + (atomBondCount/2) + " 0 0 0 0 0 0 0 0 " + mRad + " V2000";
} else
cTable += " " + (atomBondCount/2) + " 0 0 0 0 0 0 0 0 " + mRad + " V2000";
// Create the "Atom Block"
for (int numAtoms=0; numAtoms<atomCount-1; numAtoms++) {
// Assume no 3-d information available
// Set all atoms x,y,z-coordinates at (0.0,0.0,0.0)
cTable += "\n 0.0 0.0 0.0 " + elementSymbol[numAtoms] + " " + " 0 0 0 0 0 0 0 0 0 0 0 0";
}
// Create the "Bond Block"
// Convert Chemical Bond from S, D, T, etc. to 1, 2, 3, etc.
int[] bondStrength = new int[atomBondCount/2];
int bondCount = 0;
for (int i=0; i<maxAtoms; i++) { // Assuming <= 50 atoms in a species
for (int j=0; j<maxBonds; j++) { // Assuming no atom has > 6 bonds
if (atomConnect[i][j] != null) {
int secondAtom = Integer.parseInt(atomConnect[i][j]);
if (secondAtom > i) { // Do not want to double count bonds
// Convert Chemical Bond from S, D, T, etc. to 1, 2, 3, etc.
if (bondOrder[i][j].equals("S")) {
bondStrength[bondCount] = 1;
} else if (bondOrder[i][j].equals("D")) {
bondStrength[bondCount] = 2;
} else if (bondOrder[i][j].equals("T")) {
bondStrength[bondCount] = 3;
} else if (bondOrder[i][j].equals("B")) {
bondStrength[bondCount] = 4;
}
cTable += "\n";
if (i+1 < 10 && secondAtom < 10) {
cTable += " " + (i+1) + " " + secondAtom + " " + bondStrength[bondCount] + " 0 0 0 0";
} else if (i+1 < 10 && secondAtom >= 10) {
cTable += " " + (i+1) + " " + secondAtom + " " + bondStrength[bondCount] + " 0 0 0 0";
} else if (i+1 >= 10 && secondAtom < 10) {
cTable += " " + (i+1) + " " + secondAtom + " " + bondStrength[bondCount] + " 0 0 0 0";
} else
cTable += " " + (i+1) + " " + secondAtom + " " + bondStrength[bondCount] + " 0 0 0 0";
++bondCount;
}
} else // There are no more bonds for this atom
break;
}
}
// Create the "Properties Block"
for (int i=0; i<mRad-1; i++) {
cTable += "\nM RAD " + radCount;
for (int j=0; j<radCount; j++) {
if (radLocation[j] < 10) {
cTable += " " + radLocation[j] + " " + radType[j];
} else
cTable += " " + radLocation[j] + " " + radType[j];
}
}
cTable += "\nM END";
return cTable;
}
/**
* Converts a single InChI to its RMG adjacency lists
* @param p_inchi: String containing the InChI
* @return
*/
public static String inchi2AdjList (String p_inchi) {
// Convert InChI to .mol file
inchi2mol(p_inchi);
// Convert .mol file to adjacency list
String adjList = mol2AdjList(p_inchi,"InChI/temp.mol");
return adjList;
}
/**
* Converts a single InChI to its .mol file format. The .mol file
* is saved to the $RMG/InChI directory
* @param p_inchi: String containing the InChI
*/
public static void inchi2mol(String p_inchi) {
String workingDirectory = System.getenv("RMG");
File inchi = new File("InChI");
inchi.mkdir();
String inchiDirectory = "InChI";
File inchiFile = null;
// Save InChI string in inchi.txt file
try {
inchiFile = new File(inchiDirectory + "/inchi.txt");
FileWriter fw = new FileWriter(inchiFile);
/*
* The following change is suggested by G.Magoon at:
* http://github.com/gmagoon/RMG-Java/commit/f652decc547d0a5107435d9bc4ca64d11a9bbe7c
* This fix allows the conversion of InChI --> .mol for InChI v. 1.02beta
* MRH will check if all other InChI executable operations are still functional,
* and for which versions
*
* Windows: InChI --> .mol and .mol --> InChI work for InChI v. 1.01 &
* v. 1.02beta
* Linux: .mol --> InChI works for both v. 1.01 and 1.02beta;
* InChI --> .mol works only for 1.01 (1.02beta states:
* "Option InChI2Struct is currently not supported (use classic interface)
*/
//fw.write(p_inchi);
fw.write(p_inchi+"\n");
fw.close();
} catch (IOException e) {
String err = "Error writing inchi.txt file for InChI-to-molFile conversion: ";
err += e.toString();
System.out.println(err);
}
// Call cINChI-1 executable file
/*
* MRH 11MAR2010:
* Making the InChI executable work on Linux
*
* NOTE: The Windows and Linux/Mac codes are slightly different (the position of
* the InChI.waitFor() method. Getting InChI to work on Windows & Linux is very
* sensitive to the position of this line.
*
* Still need to test on Mac; MRH assumes it will follow Linux.
*/
String[] optionsArgument = new String[2];
int exitValue = -1;
if (getOs().toLowerCase().equals("windows")) {
optionsArgument[0] = "/InChI2Struct";
optionsArgument[1] = "/OutputSDF";
String[] command1 = {workingDirectory + "/bin/cInChI-1",
"inchi.txt",
"temp.txt",
optionsArgument[0]};
String[] command2 = {workingDirectory + "/bin/cInChI-1",
"temp.txt",
"temp.mol",
optionsArgument[1]};
try {
File runningDir = new File("InChI");
Process InChI = Runtime.getRuntime().exec(command1, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
// Clean up i/o streams
stdout.close();
stderr.close();
exitValue = InChI.waitFor();
InChI = Runtime.getRuntime().exec(command2, null, runningDir);
stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
// Clean up i/o streams
stdout.close();
stderr.close();
exitValue = InChI.waitFor();
}
catch (Exception e) {
String err = "Error running cInChI-1 while converting InChI to .mol file: ";
err += e.toString();
System.out.println(err);
}
} else if (getOs().toLowerCase().equals("linux")) {
optionsArgument[0] = "-InChI2Struct";
optionsArgument[1] = "-OutputSDF";
String[] command1 = {workingDirectory + "/bin/cInChI-1",
"inchi.txt",
"temp.txt",
optionsArgument[0]};
String[] command2 = {workingDirectory + "/bin/cInChI-1",
"temp.txt",
"temp.mol",
optionsArgument[1]};
try {
File runningDir = new File("InChI");
Process InChI = Runtime.getRuntime().exec(command1, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
exitValue = InChI.waitFor();
// Clean up i/o streams
stdout.close();
stderr.close();
InChI = Runtime.getRuntime().exec(command2, null, runningDir);
stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
exitValue = InChI.waitFor();
// Clean up i/o streams
stdout.close();
stderr.close();
}
catch (Exception e) {
String err = "Error running cInChI-1 while converting InChI to .mol file: ";
err += e.toString();
System.out.println(err);
}
} else if (getOs().toLowerCase().equals("mac")) {
optionsArgument[0] = "-InChI2Struct";
optionsArgument[1] = "-OutputSDF";
String[] command1 = {workingDirectory + "/bin/cInChI-1",
"inchi.txt",
"temp.txt",
optionsArgument[0]};
String[] command2 = {workingDirectory + "/bin/cInChI-1",
"temp.txt",
"temp.mol",
optionsArgument[1]};
try {
File runningDir = new File("InChI");
Process InChI = Runtime.getRuntime().exec(command1, null, runningDir);
BufferedReader stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
exitValue = InChI.waitFor();
// Clean up i/o streams
stdout.close();
stderr.close();
InChI = Runtime.getRuntime().exec(command2, null, runningDir);
stdout = new BufferedReader(new InputStreamReader(InChI.getInputStream()));
stderr = new BufferedReader(new InputStreamReader(InChI.getErrorStream()));
exitValue = InChI.waitFor();
// Clean up i/o streams
stdout.close();
stderr.close();
}
catch (Exception e) {
String err = "Error running cInChI-1 while converting InChI to .mol file: ";
err += e.toString();
System.out.println(err);
}
}
}
/**
* Convert a .mol file to a RMG adjacency list
* @param inchi: String containing the InChI
* @param filePath: Location of the .mol file
* @return
*/
public static String mol2AdjList (String inchi, String filePath) {
// Read in the .mol file
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
String err = "Error reading .mol file: " + e.toString();
System.out.println(err);
}
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.toUpperCase().endsWith("V2000")) {
- line = ChemParser.readMeaningfulLine(reader, true);
+ line = ChemParser.readMeaningfulLine(reader, false);
}
String molFile = "";
while (line != null) {
molFile += line + "\r";
line = ChemParser.readMeaningfulLine(reader, true);
}
// Determine how many lines are in the .mol file
String[] molFileLines = molFile.split("[\r]",0);
int numOfLines = molFileLines.length;
StringTokenizer st = new StringTokenizer(molFileLines[numOfLines-1]);
if (st.nextToken().equals("$$$$")) --numOfLines;
// Extract the information in the first line (Count Line) of the .mol file
st = new StringTokenizer(molFileLines[0]);
- int numOfAtoms = Integer.parseInt(st.nextToken());
- int numOfBonds = Integer.parseInt(st.nextToken());
+ int numOfAtoms = Integer.parseInt(molFileLines[0].substring(0,3).trim());
+ int numOfBonds = Integer.parseInt(molFileLines[0].substring(3,6).trim());
// Next few are irrelevant for RMG (as of 10-Feb-2009)
- int numOfAtomLists = Integer.parseInt(st.nextToken());
- String obsoleteString1 = st.nextToken();
- String chiralFlag = st.nextToken();
- int stextEntries = Integer.parseInt(st.nextToken());
- String obsoleteString2 = st.nextToken();
- String obsoleteString3 = st.nextToken();
- String obsoleteString4 = st.nextToken();
- String obsoleteString5 = st.nextToken();
+ int numOfAtomLists = Integer.parseInt(molFileLines[0].substring(6,9).trim());
+ String obsoleteString1 = molFileLines[0].substring(9,12);
+ String chiralFlag = molFileLines[0].substring(12,15);
+ int stextEntries = Integer.parseInt(molFileLines[0].substring(15,18).trim());
+ String obsoleteString2 = molFileLines[0].substring(18,21);
+ String obsoleteString3 = molFileLines[0].substring(21,24);
+ String obsoleteString4 = molFileLines[0].substring(24,27);
+ String obsoleteString5 = molFileLines[0].substring(27,30);
// Extract the number of M lines
- int numOfMLines = Integer.parseInt(st.nextToken());
+ int numOfMLines = Integer.parseInt(molFileLines[0].substring(30,33).trim());
// Construct each individual line of the adjacency list
String[] adjListElement = new String[numOfAtoms];
String[] adjListRadical = new String[numOfAtoms];
String[] adjListConnectivity = new String[numOfAtoms];
for (int i=0; i<numOfAtoms; i++) {
adjListConnectivity[i] = "";
adjListRadical[i] = "0 ";
}
// Extract the element symbol
for (int i=1; i<numOfAtoms+1; i++) {
st = new StringTokenizer(molFileLines[i]);
// These 3-d geometries may be helpful in the future
double x_coord = Double.parseDouble(st.nextToken());
double y_coord = Double.parseDouble(st.nextToken());
double z_coord = Double.parseDouble(st.nextToken());
// Extract the element symbol
adjListElement[i-1] = " " + st.nextToken() + " ";
/*
* Added by MRH on 4-Sept-2009
* RMG did not convert single heavy atom radicals properly (e.g. CH3, OH, H). The
* problem was the structure of the .mol file. I created mol2AdjList assuming
* the radical information would be present in the "M RAD" lines located at the
* bottom of the .mol file. For InChI-v.1.01, this is not the case for single
* heavy atom radicals. For the time being, I am hardcoding in the fix.
*/
if (numOfAtoms == 1) {
String totalLine = molFileLines[i];
int length = totalLine.length();
// This length-15,length-12 may depend on the version of InChI
int valencyFlag = Integer.parseInt(totalLine.substring(length-15,length-12).trim());
if (valencyFlag != 0) {
// One Hydrogen
if (valencyFlag == 1) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" O ")) adjListRadical[i-1] = "1 ";
else if (adjListElement[i-1].equals(" S ")) adjListRadical[i-1] = "1 ";
// Two Hydrogens
} else if (valencyFlag == 2) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "1 ";
// Three Hydrogens
} else if (valencyFlag == 3) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "1 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "1 ";
// Zero Hydrogens
} else if (valencyFlag == 15) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "4 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "4 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" O ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" S ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" H ")) adjListRadical[i-1] = "1 ";
}
}
}
}
// Extract the connectivity
int Counter = numOfAtoms+1;
while (!molFileLines[Counter].startsWith("M")) {
st = new StringTokenizer(molFileLines[Counter]);
// Extract the two atoms associated with this connection
int atom1 = Integer.parseInt(st.nextToken());
int atom2 = Integer.parseInt(st.nextToken());
// Place the connected atoms in the braces
adjListConnectivity[atom1-1] += "{" + atom2;
adjListConnectivity[atom2-1] += "{" + atom1;
// Extract the type of connection
int connection = Integer.parseInt(st.nextToken());
// Convert the connection and place in braces
if (connection == 1) {
adjListConnectivity[atom1-1] += ",S} ";
adjListConnectivity[atom2-1] += ",S} ";
} else if (connection == 2) {
adjListConnectivity[atom1-1] += ",D} ";
adjListConnectivity[atom2-1] += ",D} ";
} else if (connection == 3) {
adjListConnectivity[atom1-1] += ",T} ";
adjListConnectivity[atom2-1] += ",T} ";
} else if (connection == 4) {
adjListConnectivity[atom1-1] += ",B} ";
adjListConnectivity[atom2-1] += ",B} ";
}
++Counter;
}
// Determine the position and type of the radicals
for (int i=numOfLines-numOfMLines; i<numOfLines-1; i++) {
st = new StringTokenizer(molFileLines[numOfLines-numOfMLines]);
// The following variables hold no meaning
String M = st.nextToken();
String RAD = st.nextToken();
if (RAD.equals("RAD")){
//if (RAD.equals("RAD")||RAD.equals("CHG")) {
// Extract radical information
int numOfRads = Integer.parseInt(st.nextToken());
for (int j=0; j<numOfRads; j++) {
int atom = Integer.parseInt(st.nextToken());
int radType = Integer.parseInt(st.nextToken());
// if(RAD.equals("RAD")){
if (radType == 1)
adjListRadical[atom-1] = "2S ";
else if (radType == 2)
adjListRadical[atom-1] = "1 ";
else if (radType== 3)
adjListRadical[atom-1] = "2T ";
else
adjListRadical[atom-1] = "3 ";
// }
// else if(RAD.equals("CHG")){//gmagoon 9/14/09: adding support for CHG, which is produced in InChI generated mol files for biradicals; there still could be issues for biradicals with radical sites on adjacent atoms, so this should be manually checked
// if (radType == 1 || radType == -1){
// System.out.println("Assuming CHG indicates biradical for " + inchi + " If this is correct, two of these messages for the same InChI should be generated.");
// adjListRadical[atom-1] = "1 ";
// }
// else {
// System.out.println("Ignoring unknown M flag " + RAD + " for " + inchi);
// }
// }
}
}
/*
* If the M line flag is not equal to "RAD", RMG cannot store the information
* (e.g. CHG for InChI=1/C20H40O2/c1-3-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19(4-2)20(21)22/h19H,3-18H2,1-2H3,(H,21,22)/p-1/t19-/m1/s1/fC20H39O2/q-1)
* Inform the user the field is being ignored, but continue constructing
* the adjacency list.
*/
//update gmagoon 9/14/09: CHG is now allowed: see above; update 2: I returned to original case due to difficulties with handling adjacent biradicals
else {
System.out.println("Ignoring unknown M flag " + RAD + " for " + inchi);
}
}
// Construct the entire adjacency list from its individual lines
String adjList = "";
for (int i=0; i<numOfAtoms-1; i++) {
adjList += (i+1) + adjListElement[i] + adjListRadical[i] + adjListConnectivity[i] + "\r";
}
adjList += numOfAtoms + adjListElement[numOfAtoms-1] + adjListRadical[numOfAtoms-1] + adjListConnectivity[numOfAtoms-1];
return adjList;
}
public int getID() {
return ID;
}
public static int getTOTAL_NUMBER() {
return TOTAL_NUMBER;
}
public ChemGraph getChemGraph() {
return chemGraph;
}
public void setChemGraph(ChemGraph p_chemGraph) {
chemGraph = p_chemGraph;
}
public double getDeltaEDown() {
return deltaEDown;
}
public String getName() {
return name;
}
public void setName(String p_name) {
name = p_name;
}
public boolean getTherfitExecuted() {
return therfitExecuted;
}
public TransportData getChemkinTransportData() {
return chemkinTransData;
}
public TransportData newChemkinTransportData() {
chemkinTransData = new TransportData();
return chemkinTransData;
}
public ThreeFrequencyModel getThreeFrequencyModel() {
return threeFrequencyModel;
}
public SpectroscopicData getSpectroscopicData() {
// Generate data if needed
if (spectroscopicData == null && threeFrequencyModel == null)
generateSpectroscopicData();
// Return data in appropriate form
if (spectroscopicData != null)
return spectroscopicData;
else if (threeFrequencyModel != null)
return new SpectroscopicData(threeFrequencyModel);
else if (isTriatomicOrSmaller())
return new SpectroscopicData();
else return null;
}
protected void initRelations() {
chemkinTransData = newChemkinTransportData();
}
public boolean isReactive() {
return IsReactive;
}
public void setReactivity(boolean reactive) {
IsReactive = reactive;
}
public boolean isConstantConcentration() {
return constantConcentration;
}
public void setConstantConcentration(boolean hasconstantconcentration){
constantConcentration = hasconstantconcentration;
}
public void addPdepPaths(HashSet pdepReactionSet) {
if (paths == null)
paths = pdepReactionSet;
else
paths.addAll(pdepReactionSet);
}
public HashSet getPdepPaths(){
return paths;
}
public static void setAddID(boolean p_addID){
addID = p_addID;
}
/**
* Checks to see if the species is an isomer of another species by comparing
* the numbers of each atom type in each species.
* @param species The species to check the current one against
* @return true if they are isomers, false otherwise
*/
public boolean isIsomerOf(Species species) {
// ChemGraph cg1 = getChemGraph();
// ChemGraph cg2 = species.getChemGraph();
boolean areIsomers = true;
// if (cg1.getCarbonNumber() != cg2.getCarbonNumber())
// areIsomers = false;
// if (cg1.getOxygenNumber() != cg2.getOxygenNumber())
// areIsomers = false;
// if (cg1.getHydrogenNumber() != cg2.getHydrogenNumber())
// areIsomers = false;
String inchi1 = getInChI();
String inchi2 = species.getInChI();
String[] inchi1Layers = inchi1.split("/");
String[] inchi2Layers = inchi2.split("/");
if (inchi1Layers[1] != inchi2Layers[1]) areIsomers = false;
// Should add other atom types in the future!
return areIsomers;
}
public String getInChI() {
if (InChI == null) {
String[] inchiANDinchikey = generateInChI(getChemGraph());
InChI = inchiANDinchikey[0];
}
return InChI;
}
public void setInChI(String inchi) {
InChI = inchi;
}
public static String getOs() {
String os = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
os = "windows";
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
os = "linux";
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
os = "mac";
}
return os;
}
public String getNasaThermoSource() {
if (nasaThermoSource == null)
nasaThermoSource = "Estimated by RMG using Group Additivity";
return nasaThermoSource;
}
public boolean equals(Species species) {
return this.getChemGraph().equals(species.getChemGraph());
}
}
/*********************************************************************
File Path : RMG\RMG\jing\chem\Species.java
*********************************************************************/
| false | true | public static String mol2AdjList (String inchi, String filePath) {
// Read in the .mol file
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
String err = "Error reading .mol file: " + e.toString();
System.out.println(err);
}
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.toUpperCase().endsWith("V2000")) {
line = ChemParser.readMeaningfulLine(reader, true);
}
String molFile = "";
while (line != null) {
molFile += line + "\r";
line = ChemParser.readMeaningfulLine(reader, true);
}
// Determine how many lines are in the .mol file
String[] molFileLines = molFile.split("[\r]",0);
int numOfLines = molFileLines.length;
StringTokenizer st = new StringTokenizer(molFileLines[numOfLines-1]);
if (st.nextToken().equals("$$$$")) --numOfLines;
// Extract the information in the first line (Count Line) of the .mol file
st = new StringTokenizer(molFileLines[0]);
int numOfAtoms = Integer.parseInt(st.nextToken());
int numOfBonds = Integer.parseInt(st.nextToken());
// Next few are irrelevant for RMG (as of 10-Feb-2009)
int numOfAtomLists = Integer.parseInt(st.nextToken());
String obsoleteString1 = st.nextToken();
String chiralFlag = st.nextToken();
int stextEntries = Integer.parseInt(st.nextToken());
String obsoleteString2 = st.nextToken();
String obsoleteString3 = st.nextToken();
String obsoleteString4 = st.nextToken();
String obsoleteString5 = st.nextToken();
// Extract the number of M lines
int numOfMLines = Integer.parseInt(st.nextToken());
// Construct each individual line of the adjacency list
String[] adjListElement = new String[numOfAtoms];
String[] adjListRadical = new String[numOfAtoms];
String[] adjListConnectivity = new String[numOfAtoms];
for (int i=0; i<numOfAtoms; i++) {
adjListConnectivity[i] = "";
adjListRadical[i] = "0 ";
}
// Extract the element symbol
for (int i=1; i<numOfAtoms+1; i++) {
st = new StringTokenizer(molFileLines[i]);
// These 3-d geometries may be helpful in the future
double x_coord = Double.parseDouble(st.nextToken());
double y_coord = Double.parseDouble(st.nextToken());
double z_coord = Double.parseDouble(st.nextToken());
// Extract the element symbol
adjListElement[i-1] = " " + st.nextToken() + " ";
/*
* Added by MRH on 4-Sept-2009
* RMG did not convert single heavy atom radicals properly (e.g. CH3, OH, H). The
* problem was the structure of the .mol file. I created mol2AdjList assuming
* the radical information would be present in the "M RAD" lines located at the
* bottom of the .mol file. For InChI-v.1.01, this is not the case for single
* heavy atom radicals. For the time being, I am hardcoding in the fix.
*/
if (numOfAtoms == 1) {
String totalLine = molFileLines[i];
int length = totalLine.length();
// This length-15,length-12 may depend on the version of InChI
int valencyFlag = Integer.parseInt(totalLine.substring(length-15,length-12).trim());
if (valencyFlag != 0) {
// One Hydrogen
if (valencyFlag == 1) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" O ")) adjListRadical[i-1] = "1 ";
else if (adjListElement[i-1].equals(" S ")) adjListRadical[i-1] = "1 ";
// Two Hydrogens
} else if (valencyFlag == 2) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "1 ";
// Three Hydrogens
} else if (valencyFlag == 3) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "1 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "1 ";
// Zero Hydrogens
} else if (valencyFlag == 15) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "4 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "4 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" O ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" S ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" H ")) adjListRadical[i-1] = "1 ";
}
}
}
}
// Extract the connectivity
int Counter = numOfAtoms+1;
while (!molFileLines[Counter].startsWith("M")) {
st = new StringTokenizer(molFileLines[Counter]);
// Extract the two atoms associated with this connection
int atom1 = Integer.parseInt(st.nextToken());
int atom2 = Integer.parseInt(st.nextToken());
// Place the connected atoms in the braces
adjListConnectivity[atom1-1] += "{" + atom2;
adjListConnectivity[atom2-1] += "{" + atom1;
// Extract the type of connection
int connection = Integer.parseInt(st.nextToken());
// Convert the connection and place in braces
if (connection == 1) {
adjListConnectivity[atom1-1] += ",S} ";
adjListConnectivity[atom2-1] += ",S} ";
} else if (connection == 2) {
adjListConnectivity[atom1-1] += ",D} ";
adjListConnectivity[atom2-1] += ",D} ";
} else if (connection == 3) {
adjListConnectivity[atom1-1] += ",T} ";
adjListConnectivity[atom2-1] += ",T} ";
} else if (connection == 4) {
adjListConnectivity[atom1-1] += ",B} ";
adjListConnectivity[atom2-1] += ",B} ";
}
++Counter;
}
// Determine the position and type of the radicals
for (int i=numOfLines-numOfMLines; i<numOfLines-1; i++) {
st = new StringTokenizer(molFileLines[numOfLines-numOfMLines]);
// The following variables hold no meaning
String M = st.nextToken();
String RAD = st.nextToken();
if (RAD.equals("RAD")){
//if (RAD.equals("RAD")||RAD.equals("CHG")) {
// Extract radical information
int numOfRads = Integer.parseInt(st.nextToken());
for (int j=0; j<numOfRads; j++) {
int atom = Integer.parseInt(st.nextToken());
int radType = Integer.parseInt(st.nextToken());
// if(RAD.equals("RAD")){
if (radType == 1)
adjListRadical[atom-1] = "2S ";
else if (radType == 2)
adjListRadical[atom-1] = "1 ";
else if (radType== 3)
adjListRadical[atom-1] = "2T ";
else
adjListRadical[atom-1] = "3 ";
// }
// else if(RAD.equals("CHG")){//gmagoon 9/14/09: adding support for CHG, which is produced in InChI generated mol files for biradicals; there still could be issues for biradicals with radical sites on adjacent atoms, so this should be manually checked
// if (radType == 1 || radType == -1){
// System.out.println("Assuming CHG indicates biradical for " + inchi + " If this is correct, two of these messages for the same InChI should be generated.");
// adjListRadical[atom-1] = "1 ";
// }
// else {
// System.out.println("Ignoring unknown M flag " + RAD + " for " + inchi);
// }
// }
}
}
/*
* If the M line flag is not equal to "RAD", RMG cannot store the information
* (e.g. CHG for InChI=1/C20H40O2/c1-3-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19(4-2)20(21)22/h19H,3-18H2,1-2H3,(H,21,22)/p-1/t19-/m1/s1/fC20H39O2/q-1)
* Inform the user the field is being ignored, but continue constructing
* the adjacency list.
*/
//update gmagoon 9/14/09: CHG is now allowed: see above; update 2: I returned to original case due to difficulties with handling adjacent biradicals
else {
System.out.println("Ignoring unknown M flag " + RAD + " for " + inchi);
}
}
// Construct the entire adjacency list from its individual lines
String adjList = "";
for (int i=0; i<numOfAtoms-1; i++) {
adjList += (i+1) + adjListElement[i] + adjListRadical[i] + adjListConnectivity[i] + "\r";
}
adjList += numOfAtoms + adjListElement[numOfAtoms-1] + adjListRadical[numOfAtoms-1] + adjListConnectivity[numOfAtoms-1];
return adjList;
}
| public static String mol2AdjList (String inchi, String filePath) {
// Read in the .mol file
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
String err = "Error reading .mol file: " + e.toString();
System.out.println(err);
}
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.toUpperCase().endsWith("V2000")) {
line = ChemParser.readMeaningfulLine(reader, false);
}
String molFile = "";
while (line != null) {
molFile += line + "\r";
line = ChemParser.readMeaningfulLine(reader, true);
}
// Determine how many lines are in the .mol file
String[] molFileLines = molFile.split("[\r]",0);
int numOfLines = molFileLines.length;
StringTokenizer st = new StringTokenizer(molFileLines[numOfLines-1]);
if (st.nextToken().equals("$$$$")) --numOfLines;
// Extract the information in the first line (Count Line) of the .mol file
st = new StringTokenizer(molFileLines[0]);
int numOfAtoms = Integer.parseInt(molFileLines[0].substring(0,3).trim());
int numOfBonds = Integer.parseInt(molFileLines[0].substring(3,6).trim());
// Next few are irrelevant for RMG (as of 10-Feb-2009)
int numOfAtomLists = Integer.parseInt(molFileLines[0].substring(6,9).trim());
String obsoleteString1 = molFileLines[0].substring(9,12);
String chiralFlag = molFileLines[0].substring(12,15);
int stextEntries = Integer.parseInt(molFileLines[0].substring(15,18).trim());
String obsoleteString2 = molFileLines[0].substring(18,21);
String obsoleteString3 = molFileLines[0].substring(21,24);
String obsoleteString4 = molFileLines[0].substring(24,27);
String obsoleteString5 = molFileLines[0].substring(27,30);
// Extract the number of M lines
int numOfMLines = Integer.parseInt(molFileLines[0].substring(30,33).trim());
// Construct each individual line of the adjacency list
String[] adjListElement = new String[numOfAtoms];
String[] adjListRadical = new String[numOfAtoms];
String[] adjListConnectivity = new String[numOfAtoms];
for (int i=0; i<numOfAtoms; i++) {
adjListConnectivity[i] = "";
adjListRadical[i] = "0 ";
}
// Extract the element symbol
for (int i=1; i<numOfAtoms+1; i++) {
st = new StringTokenizer(molFileLines[i]);
// These 3-d geometries may be helpful in the future
double x_coord = Double.parseDouble(st.nextToken());
double y_coord = Double.parseDouble(st.nextToken());
double z_coord = Double.parseDouble(st.nextToken());
// Extract the element symbol
adjListElement[i-1] = " " + st.nextToken() + " ";
/*
* Added by MRH on 4-Sept-2009
* RMG did not convert single heavy atom radicals properly (e.g. CH3, OH, H). The
* problem was the structure of the .mol file. I created mol2AdjList assuming
* the radical information would be present in the "M RAD" lines located at the
* bottom of the .mol file. For InChI-v.1.01, this is not the case for single
* heavy atom radicals. For the time being, I am hardcoding in the fix.
*/
if (numOfAtoms == 1) {
String totalLine = molFileLines[i];
int length = totalLine.length();
// This length-15,length-12 may depend on the version of InChI
int valencyFlag = Integer.parseInt(totalLine.substring(length-15,length-12).trim());
if (valencyFlag != 0) {
// One Hydrogen
if (valencyFlag == 1) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" O ")) adjListRadical[i-1] = "1 ";
else if (adjListElement[i-1].equals(" S ")) adjListRadical[i-1] = "1 ";
// Two Hydrogens
} else if (valencyFlag == 2) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "1 ";
// Three Hydrogens
} else if (valencyFlag == 3) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "1 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "1 ";
// Zero Hydrogens
} else if (valencyFlag == 15) {
if (adjListElement[i-1].equals(" C ")) adjListRadical[i-1] = "4 ";
else if (adjListElement[i-1].equals(" Si ")) adjListRadical[i-1] = "4 ";
else if (adjListElement[i-1].equals(" N ")) adjListRadical[i-1] = "3 ";
else if (adjListElement[i-1].equals(" O ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" S ")) adjListRadical[i-1] = "2 ";
else if (adjListElement[i-1].equals(" H ")) adjListRadical[i-1] = "1 ";
}
}
}
}
// Extract the connectivity
int Counter = numOfAtoms+1;
while (!molFileLines[Counter].startsWith("M")) {
st = new StringTokenizer(molFileLines[Counter]);
// Extract the two atoms associated with this connection
int atom1 = Integer.parseInt(st.nextToken());
int atom2 = Integer.parseInt(st.nextToken());
// Place the connected atoms in the braces
adjListConnectivity[atom1-1] += "{" + atom2;
adjListConnectivity[atom2-1] += "{" + atom1;
// Extract the type of connection
int connection = Integer.parseInt(st.nextToken());
// Convert the connection and place in braces
if (connection == 1) {
adjListConnectivity[atom1-1] += ",S} ";
adjListConnectivity[atom2-1] += ",S} ";
} else if (connection == 2) {
adjListConnectivity[atom1-1] += ",D} ";
adjListConnectivity[atom2-1] += ",D} ";
} else if (connection == 3) {
adjListConnectivity[atom1-1] += ",T} ";
adjListConnectivity[atom2-1] += ",T} ";
} else if (connection == 4) {
adjListConnectivity[atom1-1] += ",B} ";
adjListConnectivity[atom2-1] += ",B} ";
}
++Counter;
}
// Determine the position and type of the radicals
for (int i=numOfLines-numOfMLines; i<numOfLines-1; i++) {
st = new StringTokenizer(molFileLines[numOfLines-numOfMLines]);
// The following variables hold no meaning
String M = st.nextToken();
String RAD = st.nextToken();
if (RAD.equals("RAD")){
//if (RAD.equals("RAD")||RAD.equals("CHG")) {
// Extract radical information
int numOfRads = Integer.parseInt(st.nextToken());
for (int j=0; j<numOfRads; j++) {
int atom = Integer.parseInt(st.nextToken());
int radType = Integer.parseInt(st.nextToken());
// if(RAD.equals("RAD")){
if (radType == 1)
adjListRadical[atom-1] = "2S ";
else if (radType == 2)
adjListRadical[atom-1] = "1 ";
else if (radType== 3)
adjListRadical[atom-1] = "2T ";
else
adjListRadical[atom-1] = "3 ";
// }
// else if(RAD.equals("CHG")){//gmagoon 9/14/09: adding support for CHG, which is produced in InChI generated mol files for biradicals; there still could be issues for biradicals with radical sites on adjacent atoms, so this should be manually checked
// if (radType == 1 || radType == -1){
// System.out.println("Assuming CHG indicates biradical for " + inchi + " If this is correct, two of these messages for the same InChI should be generated.");
// adjListRadical[atom-1] = "1 ";
// }
// else {
// System.out.println("Ignoring unknown M flag " + RAD + " for " + inchi);
// }
// }
}
}
/*
* If the M line flag is not equal to "RAD", RMG cannot store the information
* (e.g. CHG for InChI=1/C20H40O2/c1-3-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19(4-2)20(21)22/h19H,3-18H2,1-2H3,(H,21,22)/p-1/t19-/m1/s1/fC20H39O2/q-1)
* Inform the user the field is being ignored, but continue constructing
* the adjacency list.
*/
//update gmagoon 9/14/09: CHG is now allowed: see above; update 2: I returned to original case due to difficulties with handling adjacent biradicals
else {
System.out.println("Ignoring unknown M flag " + RAD + " for " + inchi);
}
}
// Construct the entire adjacency list from its individual lines
String adjList = "";
for (int i=0; i<numOfAtoms-1; i++) {
adjList += (i+1) + adjListElement[i] + adjListRadical[i] + adjListConnectivity[i] + "\r";
}
adjList += numOfAtoms + adjListElement[numOfAtoms-1] + adjListRadical[numOfAtoms-1] + adjListConnectivity[numOfAtoms-1];
return adjList;
}
|
diff --git a/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/SerializedHierarchicalHeatMapView.java b/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/SerializedHierarchicalHeatMapView.java
index 736998e79..7854082e8 100644
--- a/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/SerializedHierarchicalHeatMapView.java
+++ b/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/storagebased/SerializedHierarchicalHeatMapView.java
@@ -1,29 +1,29 @@
package org.caleydo.core.view.opengl.canvas.storagebased;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.caleydo.core.command.ECommandType;
import org.caleydo.core.serialize.ASerializedView;
import org.caleydo.core.view.opengl.camera.ViewFrustum;
/**
* Serialized form of the {@link GLHierarchicalHeatMap} view.
* @author Werner Puff
*/
@XmlRootElement
@XmlType
public class SerializedHierarchicalHeatMapView
extends ASerializedView {
@Override
public ECommandType getCreationCommandType() {
- return ECommandType.CMD_ID;
+ return ECommandType.CREATE_GL_TEXTURE_HEAT_MAP_3D;
}
@Override
public ViewFrustum getViewFrustum() {
return null;
}
}
| true | true | public ECommandType getCreationCommandType() {
return ECommandType.CMD_ID;
}
| public ECommandType getCreationCommandType() {
return ECommandType.CREATE_GL_TEXTURE_HEAT_MAP_3D;
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxCheck.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxCheck.java
index 23f41ce89..d0e9764b2 100755
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxCheck.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxCheck.java
@@ -1,2537 +1,2537 @@
/*
* Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.sun.tools.mjavac.code.*;
import com.sun.tools.mjavac.code.Lint.LintCategory;
import com.sun.tools.mjavac.code.Symbol.*;
import com.sun.tools.mjavac.code.Type.ClassType;
import com.sun.tools.mjavac.code.Type.ErrorType;
import com.sun.tools.mjavac.code.Type.ForAll;
import com.sun.tools.mjavac.code.Type.TypeVar;
import com.sun.tools.mjavac.code.Type.MethodType;
import static com.sun.tools.mjavac.code.Flags.*;
import static com.sun.tools.mjavac.code.Kinds.*;
import static com.sun.tools.mjavac.code.TypeTags.*;
import static com.sun.tools.mjavac.code.TypeTags.WILDCARD;
import com.sun.tools.mjavac.comp.Infer;
import com.sun.tools.mjavac.jvm.ByteCodes;
import com.sun.tools.mjavac.jvm.ClassReader;
import com.sun.tools.mjavac.jvm.Target;
import com.sun.tools.mjavac.util.*;
import com.sun.tools.mjavac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javafx.code.JavafxClassSymbol;
import com.sun.tools.javafx.code.JavafxFlags;
import com.sun.tools.javafx.code.JavafxSymtab;
import com.sun.tools.javafx.code.JavafxTypes;
import com.sun.tools.javafx.comp.JavafxAttr.Sequenceness;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.javafx.util.MsgSym;
import com.sun.javafx.api.JavafxBindStatus;
import com.sun.tools.javafx.code.JavafxVarSymbol;
import java.util.LinkedHashSet;
import static com.sun.tools.javafx.code.JavafxFlags.*;
/** Type checking helper class for the attribution phase.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavafxCheck {
protected static final Context.Key<JavafxCheck> javafxCheckKey =
new Context.Key<JavafxCheck>();
private final JavafxDefs defs;
private final Name.Table names;
private final Log log;
private final JCDiagnostic.Factory diags;
private final Messages messages;
private final Options options;
private final JavafxSymtab syms;
private final Infer infer;
private final Target target;
private final Source source;
private final JavafxTypes types;
private final JavafxAttr attr;
private final JavafxTreeInfo treeinfo;
private final JavafxResolve rs;
// The set of lint options currently in effect. It is initialized
// from the context, and then is set/reset as needed by Attr as it
// visits all the various parts of the trees during attribution.
private Lint lint;
enum WriteKind {
ASSIGN,
INIT_NON_BIND,
INIT_BIND,
VAR_QUERY
}
public static JavafxCheck instance(Context context) {
JavafxCheck instance = context.get(javafxCheckKey);
if (instance == null)
instance = new JavafxCheck(context);
return instance;
}
public static void preRegister(final Context context) {
context.put(javafxCheckKey, new Context.Factory<JavafxCheck>() {
public JavafxCheck make() {
return new JavafxCheck(context);
}
});
}
protected JavafxCheck(Context context) {
context.put(javafxCheckKey, this);
defs = JavafxDefs.instance(context);
names = Name.Table.instance(context);
log = Log.instance(context);
diags = JCDiagnostic.Factory.instance(context);
messages = Messages.instance(context);
syms = (JavafxSymtab) Symtab.instance(context);
infer = Infer.instance(context);
types = JavafxTypes.instance(context);
attr = JavafxAttr.instance(context);
options = Options.instance(context);
target = Target.instance(context);
source = Source.instance(context);
lint = Lint.instance(context);
treeinfo = (JavafxTreeInfo)JavafxTreeInfo.instance(context);
allowGenerics = source.allowGenerics();
//allowAnnotations = source.allowAnnotations();
complexInference = options.get("-complexinference") != null;
boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
deprecationHandler = new MandatoryWarningHandler(log,verboseDeprecated, MsgSym.MESSAGEPREFIX_DEPRECATED);
warnOnUsePackageHandler = new MandatoryWarningHandler(log, true, MsgSym.MESSAGEPREFIX_WARNONUSE);
uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked, MsgSym.MESSAGEPREFIX_UNCHECKED);
rs = JavafxResolve.instance(context);
}
/** Switch: generics enabled?
*/
boolean allowGenerics;
/** Switch: annotations enabled?
*/
//boolean allowAnnotations;
/** Switch: -complexinference option set?
*/
boolean complexInference;
/** A table mapping flat names of all compiled classes in this run to their
* symbols; maintained from outside.
*/
public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
/** A handler for messages about deprecated usage.
*/
private MandatoryWarningHandler deprecationHandler;
/** A handler for messages about -XDwarnOnUse package usage.
*/
private MandatoryWarningHandler warnOnUsePackageHandler;
/** A handler for messages about unchecked or unsafe usage.
*/
private MandatoryWarningHandler uncheckedHandler;
/* *************************************************************************
* Errors and Warnings
**************************************************************************/
Lint setLint(Lint newLint) {
Lint prev = lint;
lint = newLint;
return prev;
}
/** Warn about deprecated symbol.
* @param pos Position to be used for error reporting.
* @param sym The deprecated symbol.
*/
void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
if (!lint.isSuppressed(LintCategory.DEPRECATION))
deprecationHandler.report(pos, MsgSym.MESSAGE_HAS_BEEN_DEPRECATED, sym, sym.location());
}
/** Warn about a -XDwarnOnUse package symbol.
* @param pos Position to be used for error reporting.
* @param sym The deprecated symbol.
*/
void warnWarnOnUsePackage(DiagnosticPosition pos, Symbol sym) {
warnOnUsePackageHandler.report(pos, MsgSym.MESSAGE_JAVAFX_WARN_ON_USE_PACKAGE, sym);
}
/** Warn about unchecked operation.
* @param pos Position to be used for error reporting.
* @param msg A string describing the problem.
*/
public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
if (!lint.isSuppressed(LintCategory.UNCHECKED))
uncheckedHandler.report(pos, msg, args);
}
/**
* Report any deferred diagnostics.
*/
public void reportDeferredDiagnostics() {
deprecationHandler.reportDeferredDiagnostic();
warnOnUsePackageHandler.reportDeferredDiagnostic();
uncheckedHandler.reportDeferredDiagnostic();
}
/** Report a failure to complete a class.
* @param pos Position to be used for error reporting.
* @param ex The failure to report.
*/
public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
log.error(pos, MsgSym.MESSAGE_CANNOT_ACCESS, ex.sym, ex.errmsg);
if (ex instanceof ClassReader.BadClassFile) throw new Abort();
else return syms.errType;
}
/** Report a type error.
* @param pos Position to be used for error reporting.
* @param problem A string describing the error.
* @param found The type that was found.
* @param req The type that was required.
*/
Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
String foundAsJavaFXType = types.toJavaFXString(found);
String requiredAsJavaFXType = types.toJavaFXString(req);
log.error(pos, MsgSym.MESSAGE_PROB_FOUND_REQ, problem, foundAsJavaFXType, requiredAsJavaFXType);
return syms.errType;
}
Type typeError(DiagnosticPosition pos, Object problem, Object found, Object req) {
Object requiredAsJavaFXType = req;
if (req instanceof Type) {
requiredAsJavaFXType = types.toJavaFXString((Type) requiredAsJavaFXType);
}
Object foundAsJavaFXType = found;
if (foundAsJavaFXType instanceof Type) {
foundAsJavaFXType = types.toJavaFXString((Type) foundAsJavaFXType);
}
log.error(pos, MsgSym.MESSAGE_PROB_FOUND_REQ, problem, foundAsJavaFXType, requiredAsJavaFXType);
return syms.errType;
}
Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
String foundAsJavaFXType = types.toJavaFXString(found);
String requiredAsJavaFXType = types.toJavaFXString(req);
log.error(pos, MsgSym.MESSAGE_PROB_FOUND_REQ_1, problem, foundAsJavaFXType, requiredAsJavaFXType, explanation);
return syms.errType;
}
/** Report an error that wrong type tag was found.
* @param pos Position to be used for error reporting.
* @param required An internationalized string describing the type tag
* required.
* @param found The type that was found.
*/
Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
Object requiredAsJavaFXType = required;
if (required instanceof Type) {
requiredAsJavaFXType = types.toJavaFXString((Type) requiredAsJavaFXType);
}
Object foundAsJavaFXType = found;
if (foundAsJavaFXType instanceof Type) {
foundAsJavaFXType = types.toJavaFXString((Type) foundAsJavaFXType);
}
log.error(pos, MsgSym.MESSAGE_TYPE_FOUND_REQ, foundAsJavaFXType, requiredAsJavaFXType);
return syms.errType;
}
/** Report an error that symbol cannot be referenced before super
* has been called.
* @param pos Position to be used for error reporting.
* @param sym The referenced symbol.
*/
void earlyRefError(DiagnosticPosition pos, Symbol sym) {
log.error(pos, MsgSym.MESSAGE_CANNOT_REF_BEFORE_CTOR_CALLED, sym);
}
/** Report duplicate declaration error.
*/
void duplicateError(DiagnosticPosition pos, Symbol sym) {
if (sym.type == null || !sym.type.isErroneous()) {
log.error(pos, MsgSym.MESSAGE_ALREADY_DEFINED, sym, types.location(sym));
}
}
/** Report array/varargs duplicate declaration
*/
void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
log.error(pos, MsgSym.MESSAGE_ARRAY_AND_VARARGS, sym1, sym2, sym2.location());
}
}
/* ************************************************************************
* duplicate declaration checking
*************************************************************************/
/** Check that variable does not hide variable with same name in
* immediately enclosing local scope.
* @param pos Position for error reporting.
* @param v The symbol.
* @param s The scope.
*/
void checkTransparentVar(DiagnosticPosition pos, JavafxVarSymbol v, Scope s) {
if (s.next != null) {
for (Scope.Entry e = s.next.lookup(v.name);
e.scope != null && e.sym.owner == v.owner;
e = e.next()) {
if (e.sym.kind == VAR &&
(e.sym.owner.kind & (VAR | MTH)) != 0 &&
v.name != names.error) {
duplicateError(pos, e.sym);
return;
}
}
}
}
/** Check that a class or interface does not hide a class or
* interface with same name in immediately enclosing local scope.
* @param pos Position for error reporting.
* @param c The symbol.
* @param s The scope.
*/
void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
if (s.next != null) {
for (Scope.Entry e = s.next.lookup(c.name);
e.scope != null && e.sym.owner == c.owner;
e = e.next()) {
if (e.sym.kind == TYP &&
(e.sym.owner.kind & (VAR | MTH)) != 0 &&
c.name != names.error) {
duplicateError(pos, e.sym);
return;
}
}
}
}
/** Check that class does not have the same name as one of
* its enclosing classes, or as a class defined in its enclosing scope.
* return true if class is unique in its enclosing scope.
* @param pos Position for error reporting.
* @param name The class name.
* @param s The enclosing scope.
*/
boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
if (e.sym.kind == TYP && e.sym.name != names.error) {
duplicateError(pos, e.sym);
return false;
}
}
for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
duplicateError(pos, sym);
return true;
}
}
return true;
}
/* *************************************************************************
* Class name generation
**************************************************************************/
/** Return name of local class.
* This is of the form <enclClass> $ n <classname>
* where
* enclClass is the flat name of the enclosing class,
* classname is the simple name of the local class
*/
Name localClassName(ClassSymbol c) {
for (int i=1; ; i++) {
Name flatname = names.
fromString("" + c.owner.enclClass().flatname +
target.syntheticNameChar() + i +
c.name);
if (compiled.get(flatname) == null) return flatname;
}
}
/* *************************************************************************
* Type Checking
**************************************************************************/
/** Check that a given type is assignable to a given proto-type.
* If it is, return the type, otherwise return errType.
* @param pos Position to be used for error reporting.
* @param found The type that was found.
* @param req The type that was required.
*/
Type checkType(DiagnosticPosition pos, Type foundRaw, Type reqRaw, Sequenceness pSequenceness) {
return checkType(pos, foundRaw, reqRaw, pSequenceness, true);
}
Type checkType(DiagnosticPosition pos, Type found, Type req, Sequenceness pSequenceness, boolean giveWarnings) {
Type realFound = found;
if (req.tag == ERROR)
return req;
if (found == syms.unreachableType)
return found;
if (found.tag == FORALL) {
if (req == syms.javafx_UnspecifiedType)
// Is this the right thing to do? FIXME
return types.erasure(found);
else
return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
}
if (req.tag == NONE || req == syms.javafx_UnspecifiedType)
return found;
if (types.isSequence(req)) {
pSequenceness = Sequenceness.REQUIRED;
}
if (types.isSequence(found)) {
if (pSequenceness == Sequenceness.DISALLOWED && req != syms.objectType) {
log.error(pos, MsgSym.MESSAGE_JAVAFX_BAD_SEQUENCE, types.toJavaFXString(req));
return syms.errType;
}
}
Type reqUnboxed, foundUnboxed;
if (req.tag == CLASS) {
reqUnboxed = types.unboxedType(req);
if (reqUnboxed.tag == NONE)
reqUnboxed = req;
}
else
reqUnboxed = req;
if (found.tag == CLASS) {
foundUnboxed = types.unboxedType(found);
if (foundUnboxed.tag == NONE)
foundUnboxed = found;
}
else
foundUnboxed = found;
if (types.isAssignable(foundUnboxed, reqUnboxed, convertWarner(pos, found, req))) {
Type foundElem = types.elementTypeOrType(found);
Type reqElem = types.elementTypeOrType(req);
if (foundElem.tag == VOID && reqElem.tag != VOID) {
return typeError(pos, JCDiagnostic.fragment(MsgSym.MESSAGE_INCOMPATIBLE_TYPES), found, req);
}
if (reqElem.tag <= LONG && foundElem.tag >= FLOAT && foundElem.tag <= DOUBLE && giveWarnings) {
// FUTURE/FIXME: return typeError(pos, JCDiagnostic.fragment(MsgSym.MESSAGE_INCOMPATIBLE_TYPES), found, req);
String foundAsJavaFXType = types.toJavaFXString(foundUnboxed);
String requiredAsJavaFXType = types.toJavaFXString(reqUnboxed);
log.warning(pos,
MsgSym.MESSAGE_PROB_FOUND_REQ,
JCDiagnostic.fragment(MsgSym.MESSAGE_POSSIBLE_LOSS_OF_PRECISION),
foundAsJavaFXType,
requiredAsJavaFXType);
}
return realFound;
}
// use the JavafxClassSymbol's supertypes to see if req is in the supertypes of found.
for (Type baseType : types.supertypesClosure(found, true)) {
if (types.isAssignable(baseType, req, convertWarner(pos, found, req)))
return realFound;
}
Type foundElem = types.elementTypeOrType(found);
Type reqElem = types.elementTypeOrType(req);
if (foundElem.tag <= DOUBLE && reqElem.tag <= DOUBLE) {
if (foundElem.tag == VOID && reqElem.tag != VOID) {
return typeError(pos, JCDiagnostic.fragment(MsgSym.MESSAGE_INCOMPATIBLE_TYPES), found, req);
}
if (giveWarnings) {
String foundAsJavaFXType = types.toJavaFXString(found);
String requiredAsJavaFXType = types.toJavaFXString(req);
log.warning(pos.getStartPosition(), MsgSym.MESSAGE_PROB_FOUND_REQ, JCDiagnostic.fragment(MsgSym.MESSAGE_POSSIBLE_LOSS_OF_PRECISION),
foundAsJavaFXType, requiredAsJavaFXType);
}
return realFound;
}
if (found.isSuperBound()) {
log.error(pos, MsgSym.MESSAGE_ASSIGNMENT_FROM_SUPER_BOUND, found);
return syms.errType;
}
if (req.isExtendsBound()) {
log.error(pos, MsgSym.MESSAGE_ASSIGNMENT_TO_EXTENDS_BOUND, req);
return syms.errType;
}
return typeError(pos, JCDiagnostic.fragment(MsgSym.MESSAGE_INCOMPATIBLE_TYPES), found, req);
}
/** Instantiate polymorphic type to some prototype, unless
* prototype is `anyPoly' in which case polymorphic type
* is returned unchanged.
*/
Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) {
if (pt == Infer.anyPoly && complexInference) {
return t;
} else if (pt == Infer.anyPoly || pt.tag == NONE) {
Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
return instantiatePoly(pos, t, newpt, warn);
} else if (pt.tag == ERROR) {
return pt;
} else {
try {
return infer.instantiateExpr(t, pt, warn);
} catch (Infer.NoInstanceException ex) {
if (ex.isAmbiguous) {
JCDiagnostic d = ex.getDiagnostic();
log.error(pos,
d!=null ? MsgSym.MESSAGE_UNDETERMINDED_TYPE_1 : MsgSym.MESSAGE_UNDETERMINDED_TYPE,
t, d);
return syms.errType;
} else {
JCDiagnostic d = ex.getDiagnostic();
return typeError(pos,
JCDiagnostic.fragment(d!=null ? MsgSym.MESSAGE_INCOMPATIBLE_TYPES_1 : MsgSym.MESSAGE_INCOMPATIBLE_TYPES, d),
t, pt);
}
}
}
}
void checkInstanceOf(DiagnosticPosition pos, Type s, Type t) {
if (!types.isCastableNoConversion(s, t, Warner.noWarnings)) {
typeError(pos,
JCDiagnostic.fragment(MsgSym.MESSAGE_INCONVERTIBLE_TYPES),
s, t);
}
}
/** Check that a given type can be cast to a given target type.
* Return the result of the cast.
* @param pos Position to be used for error reporting.
* @param found The type that is being cast.
* @param req The target type of the cast.
*/
Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
if (found.tag == FORALL && found instanceof ForAll) {
instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
return req;
} else if (types.isCastable(found, req, castWarner(pos, found, req))) {
return req;
} else {
return typeError(pos,
JCDiagnostic.fragment(MsgSym.MESSAGE_INCONVERTIBLE_TYPES),
found, req);
}
}
//where
/** Is type a type variable, or a (possibly multi-dimensional) array of
* type variables?
*/
boolean isTypeVar(Type t) {
return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
}
/** Check that a type is within some bounds.
*
* Used in TypeApply to verify that, e.g., X in V<X> is a valid
* type argument.
* @param pos Position to be used for error reporting.
* @param a The type that should be bounded by bs.
* @param bs The bound.
*/
private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
if (a.isUnbound()) {
return;
} else if (a.tag != WILDCARD) {
a = types.upperBound(a);
for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
if (!types.isSubtype(a, l.head)) {
log.error(pos, MsgSym.MESSAGE_NOT_WITHIN_BOUNDS, a);
return;
}
}
} else if (a.isExtendsBound()) {
if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
log.error(pos, MsgSym.MESSAGE_NOT_WITHIN_BOUNDS, a);
} else if (a.isSuperBound()) {
if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
log.error(pos, MsgSym.MESSAGE_NOT_WITHIN_BOUNDS, a);
}
}
/** Check that type is different from 'void'.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkNonVoid(DiagnosticPosition pos, Type t) {
if (t.tag == VOID) {
log.error(pos, MsgSym.MESSAGE_VOID_NOT_ALLOWED_HERE);
return syms.errType;
} else {
return t;
}
}
/** Check that type is a class or interface type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkClassType(DiagnosticPosition pos, Type t) {
if (t.tag != CLASS && t.tag != ERROR)
return typeTagError(pos,
JCDiagnostic.fragment(MsgSym.MESSAGE_TYPE_REQ_CLASS),
(t.tag == TYPEVAR)
? JCDiagnostic.fragment(MsgSym.MESSAGE_TYPE_PARAMETER, t)
: t);
else
return t;
}
/** Is given blank final variable assignable, i.e. in a scope where it
* may be assigned to even though it is final?
* @param v The blank final variable.
* @param env The current environment.
*/
boolean isAssignableAsBlankFinal(JavafxVarSymbol v, JavafxEnv<JavafxAttrContext> env) {
Symbol owner = env.info.scope.owner;
// owner refers to the innermost variable, method or
// initializer block declaration at this point.
return
v.owner == owner
||
((owner.name == names.init || // i.e. we are in a constructor
owner.kind == VAR || // i.e. we are in a variable initializer
(owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
&&
v.owner == owner.owner
&&
((v.flags() & STATIC) != 0) == JavafxResolve.isStatic(env));
}
/** Check that variable can be assigned to.
* @param pos The current source code position.
* @param v The assigned varaible
* @param base If the variable is referred to in a Select, the part
* to the left of the `.', null otherwise.
* @param env The current environment.
*/
void checkAssignable(DiagnosticPosition pos, JavafxVarSymbol v, JFXTree base, Type site, JavafxEnv<JavafxAttrContext> env, WriteKind writeKind) {
//TODO: for attributes they are always final -- this should really be checked in JavafxClassReader
//TODO: rebutal, actual we should just use a different final
if ((v.flags() & FINAL) != 0 && !types.isJFXClass(v.owner) &&
((v.flags() & HASINIT) != 0
||
!((base == null ||
(base.getFXTag() == JavafxTag.IDENT && JavafxTreeInfo.name(base) == names._this)) &&
isAssignableAsBlankFinal(v, env)))) {
log.error(pos, MsgSym.MESSAGE_CANNOT_ASSIGN_VAL_TO_FINAL_VAR, v);
} else if ((v.flags() & JavafxFlags.IS_DEF) != 0L) {
log.error(pos, MsgSym.MESSAGE_JAVAFX_CANNOT_ASSIGN_TO_DEF, v);
} else if ((v.flags() & Flags.PARAMETER) != 0L) {
log.error(pos, MsgSym.MESSAGE_JAVAFX_CANNOT_ASSIGN_TO_PARAMETER, v);
} else {
// now check access permissions for write/init
switch (writeKind) {
case INIT_NON_BIND:
if ((v.flags() & JavafxFlags.PUBLIC_INIT) != 0L) {
// it is an initialization, and init is explicitly allowed
return;
}
break;
}
if (!rs.isAccessibleForWrite(env, site, v)) {
String msg;
switch (writeKind) {
case INIT_BIND:
msg = MsgSym.MESSAGE_JAVAFX_REPORT_BIND_ACCESS;
break;
case INIT_NON_BIND:
msg = MsgSym.MESSAGE_JAVAFX_REPORT_INIT_ACCESS;
break;
case VAR_QUERY:
msg = MsgSym.MESSAGE_JAVAFX_REPORT_VAR_QUERY_ACCESS;
break;
case ASSIGN:
default:
msg = MsgSym.MESSAGE_JAVAFX_REPORT_WRITE_ACCESS;
break;
}
log.error(pos, msg, v,
JavafxCheck.protectionString(v.flags()),
v.location());
}
}
}
/** True if we should warn in 'a.b.' that 'a' is non-constant.
* We don't re-evaluate the select target
* in bidirectional binds. So, we may issue warning.
*/
boolean checkBidiSelect(JFXSelect select, JavafxEnv<JavafxAttrContext> env, Type pt) {
JFXTree base = select.getExpression();
// We don't re-evaluate the select target
// in bidirectional binds. So, we may issue warning.
// Do not warn for this.foo and super.foo
Name baseName = JavafxTreeInfo.name(base);
if (baseName == names._this ||
baseName == names._super) {
return false;
}
// Do not warn for static variable select,
// because the target is a class and so that
// can not change. Also, ClassName.foo is used
// to access super class variable - we do not
// warn that case either.
Symbol sym = JavafxTreeInfo.symbolFor(base);
if (sym instanceof JavafxClassSymbol) {
return false;
}
// If the target of member select is a "def"
// variable and not initialized with bind, then
// we know the target can not change.
if (base instanceof JFXIdent) {
long flags = sym.flags();
boolean isDef = (flags & JavafxFlags.IS_DEF) != 0L;
boolean isBindInit = (flags & JavafxFlags.VARUSE_BOUND_INIT) != 0L;
boolean targetFinal = isDef && !isBindInit;
return !targetFinal;
}
return true;
}
void checkBidiBind(JFXExpression init, JavafxBindStatus bindStatus, JavafxEnv<JavafxAttrContext> env, Type pt) {
if (init.type != null && types.isArray(init.type) && bindStatus.isBound()) {
JCDiagnostic err = diags.fragment(MsgSym.MESSAGE_JAVAFX_UNSUPPORTED_TARGET_IN_BIND);
typeError(init, err, init.type, messages.getLocalizedString(MsgSym.MESSAGEPREFIX_COMPILER_MISC +
MsgSym.MESSAGE_JAVAFX_OBJ_OR_SEQ));
}
else if (bindStatus.isBidiBind()) {
Symbol initSym = null;
JFXTree base = null;
Type site = null;
switch (init.getFXTag()) {
case IDENT: {
initSym = ((JFXIdent) init).sym;
base = null;
site = env.enclClass.sym.type;
break;
}
case SELECT: {
JFXSelect select = (JFXSelect) init;
initSym = select.sym;
base = select.getExpression();
if (checkBidiSelect(select, env, pt))
log.warning(select.getExpression().pos(),
MsgSym.MESSAGE_SELECT_TARGET_NOT_REEVALUATED_FOR_BIDI_BIND,
select.getExpression(), select.name);
site = select.type;
break;
}
}
if (initSym instanceof VarSymbol) {
if (pt != null && bindStatus.isBidiBind() && !types.isSameType(pt, initSym.type)) {
log.error(init.pos(),
MsgSym.MESSAGE_JAVAFX_WRONG_TYPE_FOR_BIDI_BIND,
types.toJavaFXString(initSym.type),
types.toJavaFXString(pt));
}
checkAssignable(init.pos(), (JavafxVarSymbol) initSym, base, site, env, WriteKind.INIT_BIND);
} else {
log.error(init.pos(), MsgSym.MESSAGE_JAVAFX_EXPR_UNSUPPORTED_FOR_BIDI_BIND);
}
}
}
/**
* Return element type for a sequence type, and report error otherwise.
*/
public Type checkSequenceElementType (DiagnosticPosition pos, Type t) {
if (types.isSequence(t))
return types.elementType(t);
if (t.tag != ERROR) {
return typeTagError(pos, types.sequenceType(syms.unknownType), t);
}
return syms.errType;
}
public Type checkSequenceOrArrayType (DiagnosticPosition pos, Type t) {
if (!types.isSequence(t) && t.tag != ARRAY && !t.isErroneous())
return typeTagError(pos,
messages.getLocalizedString(MsgSym.MESSAGEPREFIX_COMPILER_MISC +
MsgSym.MESSAGE_JAVAFX_SEQ_OR_ARRAY),
t);
else
return t;
}
/**
* Check that a method call of the kind t.memberName() is legal.
* t must be a direct supertype of the enclosing class type csym.
*
* @param pos the position in which the error should be reported
* @param csym the enclosing class
* @param t the qualifier type
*/
public void checkSuper(DiagnosticPosition pos, JavafxClassSymbol csym, Type t) {
if (types.isSameType(csym.type, t))
return;
boolean isOk = false;
List<Type> supertypes = types.supertypes(csym.type);
if (supertypes.isEmpty()) {
isOk = types.isSameType(syms.objectType, t);
}
else {
while(supertypes.nonEmpty() && !isOk) {
if (types.isSameType(t, supertypes.head))
isOk = true;
supertypes = supertypes.tail;
}
}
if (!isOk) {
log.error(pos, MsgSym.MESSAGE_JAVAFX_INVALID_SELECT_FOR_SUPER,
types.toJavaFXString(t),
types.toJavaFXString(csym.type));
}
}
/** Check that type is a class or interface type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
* @param noBounds True if type bounds are illegal here.
*/
Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
t = checkClassType(pos, t);
if (noBounds && t.isParameterized()) {
List<Type> args = t.getTypeArguments();
while (args.nonEmpty()) {
if (args.head.tag == WILDCARD)
return typeTagError(pos,
Log.getLocalizedString(MsgSym.MESSAGE_TYPE_REQ_EXACT),
args.head);
args = args.tail;
}
}
return t;
}
/** Check that type is a reifiable class, interface or array type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
return typeTagError(pos,
JCDiagnostic.fragment(MsgSym.MESSAGE_TYPE_REQ_CLASS_ARRAY),
t);
} else if (!types.isReifiable(t)) {
log.error(pos, MsgSym.MESSAGE_ILLEGAL_GENERIC_TYPE_FOR_INSTOF);
return syms.errType;
} else {
return t;
}
}
/** Check that type is a reference type, i.e. a class, interface or array type
* or a type variable.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkRefType(DiagnosticPosition pos, Type t) {
switch (t.tag) {
case CLASS:
case ARRAY:
case TYPEVAR:
case WILDCARD:
case ERROR:
return t;
default:
return typeTagError(pos,
JCDiagnostic.fragment(MsgSym.MESSAGE_TYPE_REQ_REF),
t);
}
}
/** Check that type is a null or reference type.
* @param pos Position to be used for error reporting.
* @param t The type to be checked.
*/
Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
switch (t.tag) {
case CLASS:
case ARRAY:
case TYPEVAR:
case WILDCARD:
case BOT:
case ERROR:
return t;
default:
return typeTagError(pos,
JCDiagnostic.fragment(MsgSym.MESSAGE_TYPE_REQ_REF),
t);
}
}
/** Check that flag set does not contain elements of two conflicting sets.
* Log error if it does.
* Return true if it doesn't.
* @param pos Position to be used for error reporting.
* @param flags The set of flags to be checked.
* @param set1 Conflicting flags set #1.
* @param set2 Conflicting flags set #2.
*/
boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
if ((flags & set1) != 0 && (flags & set2) != 0) {
log.error(pos,
MsgSym.MESSAGE_ILLEGAL_COMBINATION_OF_MODIFIERS,
JavafxTreeInfo.flagNames(JavafxTreeInfo.firstFlag(flags & set1)),
JavafxTreeInfo.flagNames(JavafxTreeInfo.firstFlag(flags & set2)));
return false;
} else
return true;
}
/** Check that flag set does not contain elements of two conflicting sets.
* Log warning if it does.
* Return true if it doesn't.
* @param pos Position to be used for error reporting.
* @param flags The set of flags to be checked.
* @param set1 Conflicting flags set #1.
* @param set2 Conflicting flags set #2.
*/
boolean checkDisjointWarn(DiagnosticPosition pos, long flags, long set1, long set2) {
if ((flags & set1) != 0 && (flags & set2) != 0) {
log.warning(pos,
MsgSym.MESSAGE_JAVAFX_REDUNDANT_ACCESS_MODIFIERS,
JavafxTreeInfo.flagNames(JavafxTreeInfo.firstFlag(flags & set1)),
JavafxTreeInfo.flagNames(JavafxTreeInfo.firstFlag(flags & set2)));
return false;
} else
return true;
}
/** Check that given modifiers are legal for given symbol and
* return modifiers together with any implicit modififiers for that symbol.
* Warning: we can't use flags() here since this method
* is called during class enter, when flags() would cause a premature
* completion.
* @param pos Position to be used for error reporting.
* @param flags The set of modifiers given in a definition.
* @param sym The defined symbol.
*/
long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JFXTree tree) {
long mask;
String msg = MsgSym.MESSAGE_JAVAFX_MOD_NOT_ALLOWED_ON;
String thing;
boolean isScriptLevel = (flags & STATIC) != 0;
switch (sym.kind) {
case VAR:
JavafxVarSymbol vsym = (JavafxVarSymbol)sym;
boolean isDef = ((flags & IS_DEF) != 0);
thing = isDef? "def" : "var";
if (!vsym.isMember()) {
mask = JavafxLocalVarFlags;
msg = MsgSym.MESSAGE_JAVAFX_MOD_NOT_ALLOWED_ON_LOCAL;
} else if (isDef) {
mask = JavafxMemberDefFlags;
msg = MsgSym.MESSAGE_JAVAFX_MOD_NOT_ALLOWED_ON;
} else if (isScriptLevel) {
mask = JavafxScriptVarFlags;
msg = MsgSym.MESSAGE_JAVAFX_MOD_NOT_ALLOWED_ON_SCRIPT;
} else {
mask = JavafxInstanceVarFlags;
msg = MsgSym.MESSAGE_JAVAFX_MOD_NOT_ALLOWED_ON_INSTANCE;
}
break;
case MTH:
if (isScriptLevel) {
mask = JavafxScriptFunctionFlags;
msg = MsgSym.MESSAGE_JAVAFX_MOD_NOT_ALLOWED_ON_SCRIPT;
} else {
mask = JavafxFunctionFlags;
}
thing = "function";
break;
case TYP:
// flags aren't currently different: if (sym.isLocal()) ...
mask = JavafxClassFlags;
thing = "class";
break;
default:
throw new AssertionError();
}
long illegal = flags & JavafxUserFlags & ~mask;
/***
System.err.println(sym);
System.err.printf("%022o mask -- %s\n", mask, JavafxTreeInfo.flagNames(mask));
System.err.printf("%022o ~mask -- %s\n", ~mask, JavafxTreeInfo.flagNames(~mask));
System.err.printf("%022o JavafxUserFlags -- %s\n", JavafxUserFlags, JavafxTreeInfo.flagNames(JavafxUserFlags));
System.err.printf("%022o flags -- %s\n", flags, JavafxTreeInfo.flagNames(flags));
System.err.printf("%022o illegal -- %s\n", illegal, JavafxTreeInfo.flagNames(illegal));
***/
if (illegal != 0) {
log.error(pos, msg, JavafxTreeInfo.flagNames(illegal), thing);
}
else if ((sym.kind == TYP ||
checkDisjoint(pos, flags,
ABSTRACT | MIXIN,
PRIVATE | STATIC))
&&
checkDisjoint(pos, flags,
ABSTRACT | INTERFACE,
FINAL | NATIVE | SYNCHRONIZED)
&&
checkDisjoint(pos, flags,
PUBLIC,
PRIVATE | PROTECTED | PACKAGE_ACCESS | SCRIPT_PRIVATE)
&&
checkDisjoint(pos, flags,
PRIVATE,
PUBLIC | PROTECTED | PACKAGE_ACCESS | SCRIPT_PRIVATE)
&&
checkDisjoint(pos, flags,
SCRIPT_PRIVATE,
PRIVATE | PROTECTED | PUBLIC | PACKAGE_ACCESS)
&&
checkDisjoint(pos, flags,
PACKAGE_ACCESS,
PRIVATE | PROTECTED | PUBLIC | SCRIPT_PRIVATE)
&&
(sym.kind == TYP ||
checkDisjoint(pos, flags,
ABSTRACT | NATIVE,
STRICTFP))
&&
checkDisjointWarn(pos, flags,
PUBLIC,
PUBLIC_INIT | PUBLIC_READ)
&&
checkDisjointWarn(pos, flags,
PUBLIC_INIT,
PUBLIC_READ)
) {
// skip
}
return flags & ~illegal;
}
/* *************************************************************************
* Type Validation
**************************************************************************/
/** Validate a type expression. That is,
* check that all type arguments of a parametric type are within
* their bounds. This must be done in a second phase after type attributon
* since a class might have a subclass as type parameter bound. E.g:
*
* class B<A extends C> { ... }
* class C extends B<C> { ... }
*
* and we can't make sure that the bound is already attributed because
* of possible cycles.
*/
private Validator validator = new Validator();
/** Visitor method: Validate a type expression, if it is not null, catching
* and reporting any completion failures.
*/
void validate(JFXTree tree) {
try {
if (tree != null) tree.accept(validator);
} catch (CompletionFailure ex) {
completionError(tree.pos(), ex);
}
}
/** Visitor method: Validate a list of type expressions.
*/
void validate(List<? extends JFXTree> trees) {
for (List<? extends JFXTree> l = trees; l.nonEmpty(); l = l.tail)
validate(l.head);
}
/** A visitor class for type validation.
*/
class Validator extends JavafxTreeScanner {
@Override
public void visitSelect(JFXSelect tree) {
if (tree.type.tag == CLASS) {
visitSelectInternal(tree);
// Check that this type is either fully parameterized, or
// not parameterized at all.
if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
log.error(tree.pos(), MsgSym.MESSAGE_IMPROPERLY_FORMED_TYPE_PARAM_MISSING);
}
}
public void visitSelectInternal(JFXSelect tree) {
if (tree.type.getEnclosingType().tag != CLASS &&
tree.selected.type.isParameterized()) {
// The enclosing type is not a class, so we are
// looking at a static member type. However, the
// qualifying expression is parameterized.
log.error(tree.pos(), MsgSym.MESSAGE_CANNOT_SELECT_STATIC_CLASS_FROM_PARAM_TYPE);
} else {
// otherwise validate the rest of the expression
validate(tree.selected);
}
}
/** Default visitor method: do nothing.
*/
@Override
public void visitTree(JFXTree tree) {
}
}
/* *************************************************************************
* Exception checking
**************************************************************************/
/* The following methods treat classes as sets that contain
* the class itself and all their subclasses
*/
/** Is given type a subtype of some of the types in given list?
*/
boolean subset(Type t, List<Type> ts) {
for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
if (types.isSubtype(t, l.head)) return true;
return false;
}
/** Is given type a subtype or supertype of
* some of the types in given list?
*/
boolean intersects(Type t, List<Type> ts) {
for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
return false;
}
/** Add type set to given type list, unless it is a subclass of some class
* in the list.
*/
List<Type> incl(Type t, List<Type> ts) {
return subset(t, ts) ? ts : excl(t, ts).prepend(t);
}
/** Remove type set from type set list.
*/
List<Type> excl(Type t, List<Type> ts) {
if (ts.isEmpty()) {
return ts;
} else {
List<Type> ts1 = excl(t, ts.tail);
if (types.isSubtype(ts.head, t)) return ts1;
else if (ts1 == ts.tail) return ts;
else return ts1.prepend(ts.head);
}
}
/** Form the union of two type set lists.
*/
List<Type> union(List<Type> ts1, List<Type> ts2) {
List<Type> ts = ts1;
for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
ts = incl(l.head, ts);
return ts;
}
/** Form the difference of two type lists.
*/
List<Type> diff(List<Type> ts1, List<Type> ts2) {
List<Type> ts = ts1;
for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
ts = excl(l.head, ts);
return ts;
}
/** Form the intersection of two type lists.
*/
public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
List<Type> ts = List.nil();
for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
if (subset(l.head, ts2)) ts = incl(l.head, ts);
for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
if (subset(l.head, ts1)) ts = incl(l.head, ts);
return ts;
}
/** Is exc an exception symbol that need not be declared?
*/
boolean isUnchecked(ClassSymbol exc) {
return
exc.kind == ERR ||
exc.isSubClass(syms.errorType.tsym, types) ||
exc.isSubClass(syms.runtimeExceptionType.tsym, types);
}
/** Is exc an exception type that need not be declared?
*/
boolean isUnchecked(Type exc) {
return
(exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
(exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
exc.tag == BOT;
}
/** Same, but handling completion failures.
*/
boolean isUnchecked(DiagnosticPosition pos, Type exc) {
try {
return isUnchecked(exc);
} catch (CompletionFailure ex) {
completionError(pos, ex);
return true;
}
}
/** Is exc handled by given exception list?
*/
boolean isHandled(Type exc, List<Type> handled) {
return isUnchecked(exc) || subset(exc, handled);
}
/** Return all exceptions in thrown list that are not in handled list.
* @param thrown The list of thrown exceptions.
* @param handled The list of handled exceptions.
*/
List<Type> unHandled(List<Type> thrown, List<Type> handled) {
List<Type> unhandled = List.nil();
for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
return unhandled;
}
/* *************************************************************************
* Overriding/Implementation checking
**************************************************************************/
/** The level of access protection given by a flag set,
* where PRIVATE is highest and PUBLIC is lowest.
*/
static int protection(long flags) {
// because the SCRIPT_PRIVATE bit is too high for the switch, test it later
switch ((short)(flags & Flags.AccessFlags)) {
case PRIVATE: return 3;
case PROTECTED: return 1;
default:
case PUBLIC: return 0;
// 'package' vs script-private
case 0: return ((flags & SCRIPT_PRIVATE)==0)? 2 : 3;
}
}
/** A string describing the access permission given by a flag set.
* This always returns a space-separated list of Java Keywords.
*/
public static String protectionString(long flags) {
long flags1 = flags & (JavafxFlags.JavafxAccessFlags | JavafxFlags.JavafxExplicitAccessFlags);
return JavafxTreeInfo.flagNames(flags1);
}
/** A customized "cannot override" error message.
* @param m The overriding method.
* @param other The overridden method.
* @return An internationalized string.
*/
static Object cannotOverride(MethodSymbol m, MethodSymbol other) {
String key;
if ((other.owner.flags() & INTERFACE) == 0)
key = MsgSym.MESSAGE_CANNOT_OVERRIDE;
else if ((m.owner.flags() & INTERFACE) == 0)
key = MsgSym.MESSAGE_CANNOT_IMPLEMENT;
else
key = MsgSym.MESSAGE_CLASHES_WITH;
return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
}
/** A customized "override" warning message.
* @param m The overriding method.
* @param other The overridden method.
* @return An internationalized string.
*/
static Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
String key;
if ((other.owner.flags() & INTERFACE) == 0)
key = MsgSym.MESSAGE_UNCHECKED_OVERRIDE;
else if ((m.owner.flags() & INTERFACE) == 0)
key = MsgSym.MESSAGE_UNCHECKED_IMPLEMENT;
else
key = MsgSym.MESSAGE_UNCHECKED_CLASH_WITH;
return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
}
/** A customized "override" warning message.
* @param m The overriding method.
* @param other The overridden method.
* @return An internationalized string.
*/
static Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
String key;
if ((other.owner.flags() & INTERFACE) == 0)
key = MsgSym.MESSAGE_VARARGS_OVERRIDE;
else if ((m.owner.flags() & INTERFACE) == 0)
key = MsgSym.MESSAGE_VARARGS_IMPLEMENT;
else
key = MsgSym.MESSAGE_VARARGS_CLASH_WITH;
return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
}
/** Check that this method conforms with overridden method 'other'.
* where `origin' is the class where checking started.
* Complications:
* (1) Do not check overriding of synthetic methods
* (reason: they might be final).
* todo: check whether this is still necessary.
* (2) Admit the case where an interface proxy throws fewer exceptions
* than the method it implements. Augment the proxy methods with the
* undeclared exceptions in this case.
* (3) When generics are enabled, admit the case where an interface proxy
* has a result type
* extended by the result type of the method it implements.
* Change the proxies result type to the smaller type in this case.
*
* @param tree The tree from which positions
* are extracted for errors.
* @param m The overriding method.
* @param other The overridden method.
* @param origin The class of which the overriding method
* is a member.
*/
private void checkOverride(JFXTree tree,
MethodSymbol m,
MethodSymbol other,
ClassSymbol origin) {
// Don't check overriding of synthetic methods or by bridge methods.
if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
return;
}
// Error if static method overrides instance method (JLS 8.4.6.2).
if ((m.flags() & STATIC) != 0 &&
(other.flags() & STATIC) == 0) {
log.error(JavafxTreeInfo.diagnosticPositionFor(m, tree), MsgSym.MESSAGE_OVERRIDE_STATIC,
cannotOverride(m, other));
return;
}
// Error if instance method overrides static or final
// method (JLS 8.4.6.1).
if ((other.flags() & FINAL) != 0 ||
(m.flags() & STATIC) == 0 &&
(other.flags() & STATIC) != 0) {
log.error(JavafxTreeInfo.diagnosticPositionFor(m, tree), MsgSym.MESSAGE_OVERRIDE_METH,
cannotOverride(m, other),
JavafxTreeInfo.flagNames(other.flags() & (FINAL | STATIC)));
return;
}
// Error if bound function overrides non-bound.
if ((other.flags() & BOUND) == 0 && (m.flags() & BOUND) != 0) {
log.error(JavafxTreeInfo.diagnosticPositionFor(m, tree), MsgSym.MESSAGE_JAVAFX_BOUND_OVERRIDE_METH,
cannotOverride(m, other));
return;
}
// Error if non-bound function overrides bound.
if ((other.flags() & BOUND) != 0 && (m.flags() & BOUND) == 0) {
log.error(JavafxTreeInfo.diagnosticPositionFor(m, tree), MsgSym.MESSAGE_JAVAFX_NON_BOUND_OVERRIDE_METH,
cannotOverride(m, other));
return;
}
if ((m.owner.flags() & ANNOTATION) != 0) {
// handled in validateAnnotationMethod
return;
}
// Error if overriding method has weaker access (JLS 8.4.6.3).
/*--------------- Taken out. Javafx doesn't have the JLS 8.4.6.3 rule...
if ((origin.flags() & INTERFACE) == 0 &&
protection(m.flags()) > protection(other.flags())) {
log.error(JavafxTreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
cannotOverride(m, other),
protectionString(other.flags()));
return;
}
----------------- */
Type mt = types.memberType(origin.type, m);
Type ot = types.memberType(origin.type, other);
// Error if overriding result type is different
// (or, in the case of generics mode, not a subtype) of
// overridden result type. We have to rename any type parameters
// before comparing types.
List<Type> mtvars = mt.getTypeArguments();
List<Type> otvars = ot.getTypeArguments();
Type mtres = mt.getReturnType();
Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
overrideWarner.warned = false;
boolean resultTypesOK =
types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
if (!resultTypesOK) {
if (!source.allowCovariantReturns() &&
m.owner != origin &&
m.owner.isSubClass(other.owner, types)) {
// allow limited interoperability with covariant returns
} else {
typeError(JavafxTreeInfo.diagnosticPositionFor(m, tree),
JCDiagnostic.fragment(MsgSym.MESSAGE_OVERRIDE_INCOMPATIBLE_RET,
cannotOverride(m, other)),
mtres, otres);
return;
}
} else if (overrideWarner.warned) {
warnUnchecked(JavafxTreeInfo.diagnosticPositionFor(m, tree),
MsgSym.MESSAGE_PROB_FOUND_REQ,
JCDiagnostic.fragment(MsgSym.MESSAGE_OVERRIDE_UNCHECKED_RET,
uncheckedOverrides(m, other)),
mtres, otres);
}
// Error if overriding method throws an exception not reported
// by overridden method.
List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
if (unhandled.nonEmpty()) {
log.error(JavafxTreeInfo.diagnosticPositionFor(m, tree),
MsgSym.MESSAGE_OVERRIDE_METH_DOES_NOT_THROW,
cannotOverride(m, other),
unhandled.head);
return;
}
// Optional warning if varargs don't agree
if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
&& lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
log.warning(JavafxTreeInfo.diagnosticPositionFor(m, tree),
((m.flags() & Flags.VARARGS) != 0)
? MsgSym.MESSAGE_OVERRIDE_VARARGS_MISSING
: MsgSym.MESSAGE_OVERRIDE_VARARGS_EXTRA,
varargsOverrides(m, other));
}
// Warn if instance method overrides bridge method (compiler spec ??)
if ((other.flags() & BRIDGE) != 0) {
log.warning(JavafxTreeInfo.diagnosticPositionFor(m, tree), MsgSym.MESSAGE_OVERRIDE_BRIDGE,
uncheckedOverrides(m, other));
}
// Warn if a deprecated method overridden by a non-deprecated one.
if ((other.flags() & DEPRECATED) != 0
&& (m.flags() & DEPRECATED) == 0
&& m.outermostClass() != other.outermostClass()
&& !isDeprecatedOverrideIgnorable(other, origin)) {
warnDeprecated(JavafxTreeInfo.diagnosticPositionFor(m, tree), other);
}
}
// where
private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
// If the method, m, is defined in an interface, then ignore the issue if the method
// is only inherited via a supertype and also implemented in the supertype,
// because in that case, we will rediscover the issue when examining the method
// in the supertype.
// If the method, m, is not defined in an interface, then the only time we need to
// address the issue is when the method is the supertype implemementation: any other
// case, we will have dealt with when examining the supertype classes
ClassSymbol mc = m.enclClass();
Type st = types.supertype(origin.type);
if (st.tag != CLASS)
return true;
MethodSymbol stimpl = types.implementation(m, (ClassSymbol)st.tsym, false);
if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
List<Type> intfs = types.interfaces(origin.type);
return (intfs.contains(mc.type) ? false : (stimpl != null));
}
else
return (stimpl != m);
}
// used to check if there were any unchecked conversions
private Warner overrideWarner = new Warner();
/** Check that a class does not inherit two concrete methods
* with the same signature.
* @param pos Position to be used for error reporting.
* @param site The class type to be checked.
*/
private void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
Type sup = types.supertype(site);
if (sup.tag != CLASS) return;
for (Type t1 = sup;
t1.tsym.type.isParameterized();
t1 = types.supertype(t1)) {
for (Scope.Entry e1 = t1.tsym.members().elems;
e1 != null;
e1 = e1.sibling) {
Symbol s1 = e1.sym;
if (s1.kind != MTH ||
(s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
!s1.isInheritedIn(site.tsym, types) ||
types.implementation((MethodSymbol)s1, site.tsym,
true) != s1)
continue;
Type st1 = types.memberType(t1, s1);
int s1ArgsLength = st1.getParameterTypes().length();
if (st1 == s1.type) continue;
for (Type t2 = sup;
t2.tag == CLASS;
t2 = types.supertype(t2)) {
for (Scope.Entry e2 = t1.tsym.members().lookup(s1.name);
e2.scope != null;
e2 = e2.next()) {
Symbol s2 = e2.sym;
if (s2 == s1 ||
s2.kind != MTH ||
(s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
s2.type.getParameterTypes().length() != s1ArgsLength ||
!s2.isInheritedIn(site.tsym, types) ||
types.implementation((MethodSymbol)s2, site.tsym,
true) != s2)
continue;
Type st2 = types.memberType(t2, s2);
if (types.overrideEquivalent(st1, st2))
log.error(pos, MsgSym.MESSAGE_CONCRETE_INHERITANCE_CONFLICT,
s1, t1, s2, t2, sup);
}
}
}
}
}
/** Check that classes (or interfaces) do not each define an abstract
* method with same name and arguments but incompatible return types.
* @param pos Position to be used for error reporting.
* @param t1 The first argument type.
* @param t2 The second argument type.
*/
private boolean checkCompatibleAbstracts(DiagnosticPosition pos,
Type t1,
Type t2,
Type site) {
Symbol sym = firstIncompatibility(t1, t2, site);
if (sym != null) {
if (sym.kind == VAR) {
log.error(pos, MsgSym.MESSAGE_JAVAFX_TYPES_INCOMPATIBLE_VARS,
t1, t2, sym.name);
}
else {
log.error(pos, MsgSym.MESSAGE_TYPES_INCOMPATIBLE_DIFF_RET,
t1, t2, sym.name +
"(" + types.memberType(t2, sym).getParameterTypes() + ")");
}
return false;
}
return true;
}
/** Return the first method which is defined with same args
* but different return types in two given interfaces, or null if none
* exists.
* @param t1 The first type.
* @param t2 The second type.
* @param site The most derived type.
* @returns symbol from t2 that conflicts with one in t1.
*/
private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
closure(t1, interfaces1);
Map<TypeSymbol,Type> interfaces2;
if (t1 == t2)
interfaces2 = interfaces1;
else
closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
for (Type t3 : interfaces1.values()) {
for (Type t4 : interfaces2.values()) {
Symbol s = firstDirectIncompatibility(t3, t4, site);
if (s != null) return s;
}
}
return null;
}
/** Compute all the supertypes of t, indexed by type symbol. */
private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
if (t.tag != CLASS) return;
if (typeMap.put(t.tsym, t) == null) {
closure(types.supertype(t), typeMap);
for (Type i : types.interfaces(t))
closure(i, typeMap);
}
}
/** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
if (t.tag != CLASS) return;
if (typesSkip.get(t.tsym) != null) return;
if (typeMap.put(t.tsym, t) == null) {
closure(types.supertype(t), typesSkip, typeMap);
for (Type i : types.interfaces(t))
closure(i, typesSkip, typeMap);
}
}
/** Return the first method in t2 that conflicts with a method from t1. */
private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
Symbol s = firstDirectMethodIncompatibility(t1, t2, site);
if (s != null) {
return s;
}
else {
return firstDirectVarIncompatibility(t1, t2, site);
}
}
private Symbol firstDirectMethodIncompatibility(Type t1, Type t2, Type site) {
for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
Symbol s1 = e1.sym;
s1.complete();
Type st1 = null;
if (s1.kind != MTH || s1.name == defs.internalRunFunctionName ||
!s1.isInheritedIn(site.tsym, types)) continue;
for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
Symbol s2 = e2.sym;
s2.complete();
if (s1 == s2) continue;
if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
if (st1 == null) st1 = types.memberType(t1, s1);
Type st2 = types.memberType(t2, s2);
if (types.overrideEquivalent(st1, st2)) {
List<Type> tvars1 = st1.getTypeArguments();
List<Type> tvars2 = st2.getTypeArguments();
Type rt1 = st1.getReturnType();
Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
boolean compat =
types.isSameType(rt1, rt2) ||
rt1.tag >= CLASS && rt2.tag >= CLASS &&
(types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
types.covariantReturnType(rt2, rt1, Warner.noWarnings));
if (!compat) return s2;
}
}
}
return null;
}
private Symbol firstDirectVarIncompatibility(Type t1, Type t2, Type site) {
for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
Symbol s1 = e1.sym;
s1.complete();
Type st1 = null;
if (s1.kind != VAR ||
!s1.isInheritedIn(site.tsym, types)) continue;
for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
Symbol s2 = e2.sym;
s2.complete();
if (s1 == s2) continue;
if (s2.kind != VAR || !s2.isInheritedIn(site.tsym, types)) continue;
if (!types.isSameType(s1.type, s2.type)) {
return s2;
}
}
}
return null;
}
/** Check that a given method conforms with any method it overrides.
* @param tree The tree from which positions are extracted
* for errors.
* @param m The overriding method.
*/
void checkOverride(JFXTree tree, MethodSymbol m) {
ClassSymbol origin = (ClassSymbol) m.owner;
boolean doesOverride = false;
if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
log.error(tree.pos(), MsgSym.MESSAGE_ENUM_NO_FINALIZE);
return;
}
}
for (Type t : types.supertypesClosure(origin.type)) {
if (t.tag == CLASS) {
TypeSymbol c = t.tsym;
Scope.Entry e = c.members().lookup(m.name);
while (e.scope != null) {
e.sym.complete();
if (types.overrides(m, e.sym, origin, false)) {
checkOverride(tree, m, (MethodSymbol)e.sym, origin);
doesOverride = !e.sym.type.getReturnType().isErroneous();
}
e = e.next();
}
}
}
boolean declaredOverride = (m.flags() & OVERRIDE) != 0;
if (doesOverride) {
if (!declaredOverride && (m.flags() & (Flags.SYNTHETIC|Flags.STATIC)) == 0) {
log.warning(tree.pos(), MsgSym.MESSAGE_JAVAFX_SHOULD_BE_DECLARED_OVERRIDE, m);
}
} else {
if (declaredOverride) {
log.error(tree.pos(), MsgSym.MESSAGE_JAVAFX_DECLARED_OVERRIDE_DOES_NOT, rs.kindName(m), m);
}
}
}
/** Check to make sure that any mixins don't create var conflicts.
*/
void checkMixinConflicts(JFXClassDeclaration tree) {
for (JFXExpression mixin : tree.getMixing()) {
if (mixin instanceof JFXIdent) {
Symbol symbol = ((JFXIdent)mixin).sym;
if ((symbol.flags_field & JavafxFlags.MIXIN) != 0) {
ClassSymbol mixinSym = (ClassSymbol)symbol;
Scope s = mixinSym.members();
for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
if (e.sym.kind == VAR) {
checkVarOverride(mixin.pos(), (JavafxVarSymbol)e.sym, tree.sym, false);
}
}
}
}
}
}
/** Check that var/def does not override (unless it is hidden by being script private)
*/
void checkVarOverride(DiagnosticPosition diagPos, JavafxVarSymbol vsym) {
checkVarOverride(diagPos, vsym, (ClassSymbol)vsym.owner, true);
}
void checkVarOverride(DiagnosticPosition diagPos, JavafxVarSymbol vsym, ClassSymbol origin, boolean overrides) {
for (Type t : types.supertypesClosure(origin.type)) {
if (t.tag == CLASS) {
TypeSymbol c = t.tsym;
for (Scope.Entry e = c.members().lookup(vsym.name); e.scope != null; e = e.next()) {
Symbol eSym = e.sym;
eSym.complete();
if (!(eSym.owner instanceof ClassSymbol)) continue;
long flags = eSym.flags_field;
boolean isNotScriptPrivate = (flags & JavafxFlags.SCRIPT_PRIVATE) == 0L;
boolean isPublicRead = (flags & (JavafxFlags.PUBLIC_READ|JavafxFlags.PUBLIC_INIT)) != 0L;
boolean isScriptScope = origin.outermostClass() == ((ClassSymbol) eSym.owner).outermostClass();
if (isNotScriptPrivate || isPublicRead || isScriptScope) {
// We have a name clash, the variable name is the name of a member
// which is visible outside the script or which is in the same script
if (!types.isJFXClass(eSym.owner)) {
log.error(diagPos, (vsym.flags_field & JavafxFlags.IS_DEF) == 0L?
MsgSym.MESSAGE_JAVAFX_VAR_OVERRIDES_JAVA_MEMBER :
MsgSym.MESSAGE_JAVAFX_DEF_OVERRIDES_JAVA_MEMBER,
eSym,
eSym.owner);
} else if (overrides) {
log.error(diagPos, (vsym.flags_field & JavafxFlags.IS_DEF) == 0L?
MsgSym.MESSAGE_JAVAFX_VAR_OVERRIDES_MEMBER :
MsgSym.MESSAGE_JAVAFX_DEF_OVERRIDES_MEMBER,
eSym,
eSym.owner);
}
return;
}
}
}
}
}
/** Check that all abstract members of given class have definitions.
* @param pos Position to be used for error reporting.
* @param c The class.
*/
void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
try {
MethodSymbol undef = firstUndef(c, c);
if (undef != null) {
if ((c.flags() & ENUM) != 0 &&
types.supertype(c.type).tsym == syms.enumSym &&
(c.flags() & FINAL) == 0) {
// add the ABSTRACT flag to an enum
c.flags_field |= ABSTRACT;
} else {
MethodSymbol undef1 =
new MethodSymbol(undef.flags(), undef.name,
types.memberType(c.type, undef), undef.owner);
log.error(pos, MsgSym.MESSAGE_DOES_NOT_OVERRIDE_ABSTRACT,
c, undef1, undef1.location());
}
}
} catch (CompletionFailure ex) {
completionError(pos, ex);
}
}
//where
/** Return first abstract member of class `c' that is not defined
* in `impl', null if there is none.
*/
private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
MethodSymbol undef = null;
// Do not bother to search in classes that are not abstract,
// since they cannot have abstract members.
if (c == impl || (c.flags() & (ABSTRACT | INTERFACE | MIXIN)) != 0) {
Scope s = c.members();
for (Scope.Entry e = s.elems;
undef == null && e != null;
e = e.sibling) {
if (e.sym.kind == MTH &&
(e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
MethodSymbol absmeth = (MethodSymbol)e.sym;
MethodSymbol implmeth = types.implementation(absmeth, impl, true);
if (implmeth == null || implmeth == absmeth) {
undef = absmeth;
}
}
}
if (undef == null) {
Type st = types.supertype(c.type);
if (st.tag == CLASS)
undef = firstUndef(impl, (ClassSymbol)st.tsym);
}
for (List<Type> l = types.interfaces(c.type);
undef == null && l.nonEmpty();
l = l.tail) {
undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
}
}
return undef;
}
/** Check for cyclic references. Issue an error if the
* symbol of the type referred to has a LOCKED flag set.
*
* @param pos Position to be used for error reporting.
* @param t The type referred to.
*/
void checkNonCyclic(DiagnosticPosition pos, Type t) {
checkNonCyclicInternal(pos, t, false);
}
void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
checkNonCyclic1(pos, t, new HashSet<TypeVar>());
}
private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) {
final TypeVar tv;
if (seen.contains(t)) {
tv = (TypeVar)t;
tv.bound = new ErrorType();
log.error(pos, MsgSym.MESSAGE_CYCLIC_INHERITANCE, t);
} else if (t.tag == TYPEVAR) {
tv = (TypeVar)t;
seen.add(tv);
for (Type b : types.getBounds(tv))
checkNonCyclic1(pos, b, seen);
}
}
/** Check for cyclic references. Issue an error if the
* symbol of the type referred to has a LOCKED flag set.
*
* @param pos Position to be used for error reporting.
* @param t The type referred to.
* @returns True if the check completed on all attributed classes
*/
private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t, boolean ownerCycle) {
boolean complete = true; // was the check complete?
//- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
Symbol c = t.tsym;
if ((c.flags_field & ACYCLIC) != 0) return true;
if ((c.flags_field & LOCKED) != 0) {
noteCyclic(pos, (ClassSymbol)c, ownerCycle);
} else if (!c.type.isErroneous()) {
try {
c.flags_field |= LOCKED;
if (c.type.tag == CLASS) {
ClassType clazz = (ClassType)c.type;
if (clazz.interfaces_field != null)
for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
complete &= checkNonCyclicInternal(pos, l.head, ownerCycle);
if (clazz.supertype_field != null) {
Type st = clazz.supertype_field;
if (st != null && st.tag == CLASS)
complete &= checkNonCyclicInternal(pos, st, ownerCycle);
}
if (c.owner.kind == TYP)
complete &= checkNonCyclicInternal(pos, c.owner.type, true);
}
} finally {
c.flags_field &= ~LOCKED;
}
}
if (complete)
complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
if (complete) c.flags_field |= ACYCLIC;
return complete;
}
/** Note that we found an inheritance cycle. */
private void noteCyclic(DiagnosticPosition pos, ClassSymbol c, boolean ownerCycle) {
if (!ownerCycle)
log.error(pos, MsgSym.MESSAGE_CYCLIC_INHERITANCE, c);
else
log.error(pos, MsgSym.MESSAGE_CANNOT_INHERIT_FROM_SCRIPT_CLASS, c);
for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
l.head = new ErrorType((ClassSymbol)l.head.tsym);
Type st = types.supertype(c.type);
if (st.tag == CLASS)
((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym);
c.type = new ErrorType(c);
c.flags_field |= ACYCLIC;
}
/** Check that all methods which implement some
* method conform to the method they implement.
* @param tree The class definition whose members are checked.
*/
void checkImplementations(JFXClassDeclaration tree) {
checkImplementations(tree, tree.sym);
}
//where
/** Check that all methods which implement some
* method in `ic' conform to the method they implement.
*/
void checkImplementations(JFXClassDeclaration tree, ClassSymbol ic) {
ClassSymbol origin = tree.sym;
for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
ClassSymbol lc = (ClassSymbol)l.head.tsym;
if ((allowGenerics || origin != lc) && (lc.flags() & (ABSTRACT|MIXIN)) != 0) {
for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
if (e.sym.kind == MTH &&
(e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
MethodSymbol absmeth = (MethodSymbol)e.sym;
MethodSymbol implmeth = types.implementation(absmeth, origin, false);
if (implmeth != null && implmeth != absmeth &&
(implmeth.owner.flags() & INTERFACE) ==
(origin.flags() & INTERFACE)) {
// don't check if implmeth is in a class, yet
// origin is an interface. This case arises only
// if implmeth is declared in Object. The reason is
// that interfaces really don't inherit from
// Object it's just that the compiler represents
// things that way.
checkOverride(tree, implmeth, absmeth, origin);
}
}
}
}
}
}
/** Check that only one extend class is a java or javafx base class.
* @param tree The class definition whose extends are checked.
**/
void checkOneBaseClass(JFXClassDeclaration tree) {
// Get the list of non-mixin extends.
List<JFXExpression> extending = tree.getExtending();
// If there is more than one then we have too many.
if (extending.size() > 1) {
// Get the first extra for error position.
JFXExpression extra = extending.get(1);
log.error(extra.pos(),
MsgSym.MESSAGE_JAVAFX_ONLY_ONE_BASE_CLASS_ALLOWED);
}
}
/** Check that a mixin class is pure of other modifiers.
* @param pos Position to be used for error reporting.
* @param c The class whose modifiers are checked.
**/
void checkPureMixinClass(DiagnosticPosition pos, ClassSymbol c) {
if ((c.flags() & ABSTRACT) != 0) {
log.error(pos, MsgSym.MESSAGE_JAVAFX_PURE_MIXIN);
}
}
/** Check that a mixin class has only mixin extends.
* @param tree The class definition whose extends are checked.
**/
void checkOnlyMixinsAndInterfaces(JFXClassDeclaration tree) {
// Get the list of non-mixin extends.
List<JFXExpression> extending = tree.getExtending();
// Any is too many.
if (extending.size() > 0) {
// Get the first extra for error position.
JFXExpression extra = extending.get(0);
log.error(extra.pos(),
MsgSym.MESSAGE_JAVAFX_ONLY_MIXINS_AND_INTERFACES);
}
}
/** Check that all abstract methods implemented by a class are
* mutually compatible.
* @param pos Position to be used for error reporting.
* @param c The class whose interfaces are checked.
*/
void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
List<Type> supertypes = types.interfaces(c);
Type supertype = types.supertype(c);
if (supertype.tag == CLASS &&
(supertype.tsym.flags() & (ABSTRACT|MIXIN)) != 0) {
supertypes = supertypes.prepend(supertype);
}
for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
!checkCompatibleAbstracts(pos, l.head, l.head, c)) {
return;
}
for (List<Type> m = supertypes; m != l; m = m.tail) {
if (!checkCompatibleAbstracts(pos, l.head, m.head, c)) {
return;
}
}
}
checkCompatibleConcretes(pos, c);
}
/** Check that class c does not implement directly or indirectly
* the same parameterized interface with two different argument lists.
* @param pos Position to be used for error reporting.
* @param type The type whose interfaces are checked.
*/
void checkClassBounds(DiagnosticPosition pos, Type type) {
checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
}
//where
/** Enter all interfaces of type `type' into the hash table `seensofar'
* with their class symbol as key and their type as value. Make
* sure no class is entered with two different types.
*/
void checkClassBounds(DiagnosticPosition pos,
Map<TypeSymbol,Type> seensofar,
Type type) {
if (type.isErroneous()) return;
for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
Type it = l.head;
Type oldit = seensofar.put(it.tsym, it);
if (oldit != null) {
List<Type> oldparams = oldit.allparams();
List<Type> newparams = it.allparams();
if (!types.containsTypeEquivalent(oldparams, newparams))
log.error(pos, MsgSym.MESSAGE_CANNOT_INHERIT_DIFF_ARG,
it.tsym, Type.toString(oldparams),
Type.toString(newparams));
}
checkClassBounds(pos, seensofar, it);
}
Type st = types.supertype(type);
if (st != null) checkClassBounds(pos, seensofar, st);
}
/** Enter interface or mixin into into set.
* If the class is a duplicate, issue a "repeated interface/mixin" error.
*/
void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
// if class is already in the set.
if (its.contains(it)) {
// If class is a mixin.
if ((it.tsym.flags_field & JavafxFlags.MIXIN) != 0)
log.error(pos, MsgSym.MESSAGE_JAVAFX_REPEATED_MIXIN);
else
log.error(pos, MsgSym.MESSAGE_REPEATED_INTERFACE);
} else {
its.add(it);
}
}
/* *************************************************************************
* Miscellaneous
**************************************************************************/
/**
* Return the opcode of the operator but emit an error if it is an
* error.
* @param pos position for error reporting.
* @param operator an operator
* @param tag a tree tag
* @param left type of left hand side
* @param right type of right hand side
*/
int checkOperator(DiagnosticPosition pos,
OperatorSymbol operator,
JavafxTag tag,
Type left,
Type right) {
if (operator.opcode == ByteCodes.error) {
log.error(pos,
MsgSym.MESSAGE_OPERATOR_CANNOT_BE_APPLIED,
treeinfo.operatorName(tag),
left + "," + right);
}
return operator.opcode;
}
/**
* Check for division by integer constant zero
* @param pos Position for error reporting.
* @param operator The operator for the expression
* @param operand The right hand operand for the expression
*/
void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
if (operand.constValue() != null
&& lint.isEnabled(Lint.LintCategory.DIVZERO)
&& operand.tag <= LONG
&& ((Number) (operand.constValue())).longValue() == 0) {
int opc = ((OperatorSymbol)operator).opcode;
if (opc == ByteCodes.idiv || opc == ByteCodes.imod
|| opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
log.warning(pos, MsgSym.MESSAGE_DIV_ZERO);
}
}
}
/** Check that symbol is unique in given scope.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope.
*/
boolean checkUnique(DiagnosticPosition pos, Symbol sym, JavafxEnv<JavafxAttrContext> env) {
boolean shouldContinue = true;
do {
shouldContinue = !attr.isClassOrFuncDef(env, false);
if (!checkUnique(pos, sym, JavafxEnter.enterScope(env)))
return false;
env = env.outer;
} while (env != null && shouldContinue);
return true;
}
boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
if (sym.type != null && sym.type.isErroneous()) {
return true;
}
if (sym.owner.name == names.any) {
return false;
}
for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
sym.complete();
if (sym != e.sym &&
sym.kind == e.sym.kind &&
sym.name != names.error &&
(sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) {
if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
varargsDuplicateError(pos, sym, e.sym);
} else {
duplicateError(pos, e.sym);
}
return false;
}
}
return true;
}
/** Check that single-type import is not already imported or top-level defined,
* but make an exception for two single-type imports which denote the same type.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope
*/
boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
return checkUniqueImport(pos, sym, s, false);
}
/** Check that static single-type import is not already imported or top-level defined,
* but make an exception for two single-type imports which denote the same type.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope
* @param staticImport Whether or not this was a static import
*/
boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
return checkUniqueImport(pos, sym, s, true);
}
/** Check that single-type import is not already imported or top-level defined,
* but make an exception for two single-type imports which denote the same type.
* @param pos Position for error reporting.
* @param sym The symbol.
* @param s The scope.
* @param staticImport Whether or not this was a static import
*/
private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
// is encountered class entered via a class declaration?
boolean isClassDecl = e.scope == s;
if ((isClassDecl || sym != e.sym) &&
sym.kind == e.sym.kind &&
sym.name != names.error) {
if (!e.sym.type.isErroneous()) {
String what = e.sym.toString();
if (!isClassDecl) {
if (staticImport)
log.error(pos, MsgSym.MESSAGE_ALREADY_DEFINED_STATIC_SINGLE_IMPORT, what);
else
log.error(pos, MsgSym.MESSAGE_ALREADY_DEFINED_SINGLE_IMPORT, what);
}
else if (sym != e.sym)
log.error(pos, MsgSym.MESSAGE_ALREADY_DEFINED_THIS_UNIT, what);
}
return false;
}
}
return true;
}
/** Check that a qualified name is in canonical form (for import decls).
*/
public void checkCanonical(JFXTree tree) {
if (!isCanonical(tree))
log.error(tree.pos(), MsgSym.MESSAGE_IMPORT_REQUIRES_CANONICAL,
JavafxTreeInfo.symbol(tree));
}
// where
private boolean isCanonical(JFXTree tree) {
while (tree.getFXTag() == JavafxTag.SELECT) {
JFXSelect s = (JFXSelect) tree;
if (s.sym.owner != JavafxTreeInfo.symbol(s.selected))
return false;
tree = s.selected;
}
return true;
}
private class ConversionWarner extends Warner {
final String key;
final Type found;
final Type expected;
public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
super(pos);
this.key = key;
this.found = found;
this.expected = expected;
}
@Override
public void warnUnchecked() {
boolean localWarned = this.warned;
super.warnUnchecked();
if (localWarned) return; // suppress redundant diagnostics
Object problem = JCDiagnostic.fragment(key);
JavafxCheck.this.warnUnchecked(pos(), MsgSym.MESSAGE_PROB_FOUND_REQ, problem, found, expected);
}
}
public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
return new ConversionWarner(pos, MsgSym.MESSAGE_UNCHECKED_CAST_TO_TYPE, found, expected);
}
public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
return new ConversionWarner(pos, MsgSym.MESSAGE_UNCHECKED_ASSIGN, found, expected);
}
public void warnEmptyRangeLiteral(DiagnosticPosition pos, JFXLiteral lower, JFXLiteral upper, JFXLiteral step, boolean isExclusive) {
double lowerValue = ((Number)lower.getValue()).doubleValue();
double upperValue = ((Number)upper.getValue()).doubleValue();
double stepValue = step != null? ((Number)step.getValue()).doubleValue() : 1;
if ((stepValue > 0 && lowerValue > upperValue)
|| (stepValue < 0 && lowerValue < upperValue)
|| (isExclusive && lowerValue == upperValue)) {
log.warning(pos, MsgSym.MESSAGE_JAVAFX_RANGE_LITERAL_EMPTY);
}
}
public Type checkFunctionType(DiagnosticPosition pos, MethodType m) {
if (m.argtypes.length() > JavafxSymtab.MAX_FIXED_PARAM_LENGTH) {
log.error(pos, MsgSym.MESSAGE_TOO_MANY_PARAMETERS);
return syms.errType;
} else {
return syms.makeFunctionType(m);
}
}
public void checkForwardReferences(JFXTree tree) {
class ForwardReferenceChecker extends JavafxTreeScanner {
ForwardReferenceChecker() {
- warnOnly = options.get("fwdRefError") == null ||
- !options.get("fwdRefError").contains("true");
+ warnOnly = options.get("fwdRefError") != null &&
+ options.get("fwdRefError").contains("false");
}
class VarScope {
VarScope(boolean isStatic) {
this.isStatic = isStatic;
}
Set<JavafxVarSymbol> uninited_vars = new LinkedHashSet<JavafxVarSymbol>();;
Set<JavafxVarSymbol> forward_set_vars = new LinkedHashSet<JavafxVarSymbol>();;
int overrideVarIdx = Integer.MAX_VALUE;
boolean isStatic = false;
}
List<VarScope> scopes = List.nil();
ClassSymbol enclClass = null;
boolean warnOnly;
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
ClassSymbol prevClass = enclClass;
try {
enclClass = tree.sym;
beginScope();
addVars(tree.getMembers());
super.visitClassDeclaration(tree);
endScope();
}
finally {
enclClass = prevClass;
}
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
beginScope(tree.definition.sym.isStatic());
super.visitFunctionValue(tree);
endScope();
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
beginScope();
super.visitOnReplace(tree);
endScope();
}
@Override
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
beginScope();
super.visitKeyFrameLiteral(tree);
endScope();
}
@Override
public void visitInterpolateValue(JFXInterpolateValue tree) {
beginScope();
super.visitInterpolateValue(tree);
endScope();
}
@Override
public void visitInitDefinition(JFXInitDefinition tree) {
beginScope();
super.visitInitDefinition(tree);
endScope();
}
@Override
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
beginScope();
super.visitPostInitDefinition(tree);
endScope();
}
@Override
public void visitBlockExpression(JFXBlock tree) {
addVars(tree.stats);
addVar(tree.value);
super.visitBlockExpression(tree);
}
@Override
public void visitIdent(JFXIdent tree) {
checkForwardReference(tree, tree.sym);
}
@Override
public void visitSelect(JFXSelect tree) {
Symbol selectedSym = JavafxTreeInfo.symbolFor(tree.selected);
boolean shouldWarn = false;
if (selectedSym != null) {
if (selectedSym.kind == TYP) {
shouldWarn = true;
}
if (selectedSym.kind == VAR) {
if (selectedSym.name == names._this ||
selectedSym.name == names._super) {
shouldWarn = true;
}
}
if (shouldWarn) {
checkForwardReference(tree, tree.sym);
}
}
super.visitSelect(tree);
}
@Override
public void visitVarInit(JFXVarInit tree) {
currentScope().uninited_vars.remove(tree.getSymbol());
}
@Override
public void visitVar(JFXVar tree) {
if (tree.getSymbol() != null) {
boolean prevIsStatic = currentScope().isStatic;
try {
currentScope().isStatic = tree.getSymbol().isStatic();
super.scan(tree.getInitializer());
}
finally {
currentScope().isStatic = prevIsStatic;
currentScope().uninited_vars.remove(tree.getSymbol());
}
super.scan(tree.getOnReplace());
super.scan(tree.getOnInvalidate());
}
}
@Override
public void visitAssign(JFXAssign tree) {
Symbol s = JavafxTreeInfo.symbolFor(tree.lhs);
JavafxVarSymbol vsym = (s != null && s.kind == VAR) ?
(JavafxVarSymbol)s : null;
if (vsym != null) {
currentScope().forward_set_vars.add(vsym);
}
super.visitAssign(tree);
if (vsym != null) {
currentScope().forward_set_vars.remove(vsym);
}
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
if (tree.getSymbol() != null) {
int prevOverrideVarIdx = currentScope().overrideVarIdx;
try {
currentScope().overrideVarIdx = tree.getSymbol().getAbsoluteIndex(enclClass.type);
scan(tree.getInitializer());
}
finally {
currentScope().overrideVarIdx = prevOverrideVarIdx;
}
super.scan(tree.getOnReplace());
super.scan(tree.getOnInvalidate());
}
}
private void checkForwardReference(JFXExpression tree, Symbol s) {
if (s != null && s instanceof JavafxVarSymbol) {
JavafxVarSymbol vsym = (JavafxVarSymbol)s;
if (!tree.isBound() &&
vsym.name != names._this &&
vsym.name != names._super &&
!currentScope().forward_set_vars.contains(vsym) &&
currentScope().isStatic == vsym.isStatic() &&
(currentScope().uninited_vars.contains(s) ||
(currentScope().overrideVarIdx <= vsym.getAbsoluteIndex(enclClass.type) &&
enclClass.isSubClass(s.owner, types)))) {
reportForwardReference(tree, s);
}
}
}
private void beginScope() {
beginScope(false);
}
private void beginScope(boolean staticScope) {
scopes = scopes.prepend(new VarScope(staticScope));
}
private void endScope() {
scopes = scopes.tail;
}
private VarScope currentScope() {
return scopes.head;
}
private void addVars(List<? extends JFXTree> trees) {
for (JFXTree t : trees) {
addVar(t);
}
}
private void addVar(JFXTree tree) {
if (tree != null) {
JavafxVarSymbol sym = null;
switch (tree.getFXTag()) {
case VAR_DEF: sym = ((JFXVar)tree).getSymbol(); break;
case VAR_SCRIPT_INIT: sym = ((JFXVarInit)tree).getSymbol(); break;
}
if (sym != null) {
currentScope().uninited_vars.add(sym);
}
}
}
private void reportForwardReference(DiagnosticPosition pos, Symbol s) {
if (warnOnly) {
log.warning(pos,
MsgSym.MESSAGE_ILLEGAL_FORWARD_REF,
rs.kindName(VAR),
s);
}
else {
log.error(pos,
MsgSym.MESSAGE_ILLEGAL_FORWARD_REF,
rs.kindName(VAR),
s);
}
}
}
new ForwardReferenceChecker().scan(tree);
}
}
| true | true | public void checkForwardReferences(JFXTree tree) {
class ForwardReferenceChecker extends JavafxTreeScanner {
ForwardReferenceChecker() {
warnOnly = options.get("fwdRefError") == null ||
!options.get("fwdRefError").contains("true");
}
class VarScope {
VarScope(boolean isStatic) {
this.isStatic = isStatic;
}
Set<JavafxVarSymbol> uninited_vars = new LinkedHashSet<JavafxVarSymbol>();;
Set<JavafxVarSymbol> forward_set_vars = new LinkedHashSet<JavafxVarSymbol>();;
int overrideVarIdx = Integer.MAX_VALUE;
boolean isStatic = false;
}
List<VarScope> scopes = List.nil();
ClassSymbol enclClass = null;
boolean warnOnly;
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
ClassSymbol prevClass = enclClass;
try {
enclClass = tree.sym;
beginScope();
addVars(tree.getMembers());
super.visitClassDeclaration(tree);
endScope();
}
finally {
enclClass = prevClass;
}
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
beginScope(tree.definition.sym.isStatic());
super.visitFunctionValue(tree);
endScope();
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
beginScope();
super.visitOnReplace(tree);
endScope();
}
@Override
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
beginScope();
super.visitKeyFrameLiteral(tree);
endScope();
}
@Override
public void visitInterpolateValue(JFXInterpolateValue tree) {
beginScope();
super.visitInterpolateValue(tree);
endScope();
}
@Override
public void visitInitDefinition(JFXInitDefinition tree) {
beginScope();
super.visitInitDefinition(tree);
endScope();
}
@Override
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
beginScope();
super.visitPostInitDefinition(tree);
endScope();
}
@Override
public void visitBlockExpression(JFXBlock tree) {
addVars(tree.stats);
addVar(tree.value);
super.visitBlockExpression(tree);
}
@Override
public void visitIdent(JFXIdent tree) {
checkForwardReference(tree, tree.sym);
}
@Override
public void visitSelect(JFXSelect tree) {
Symbol selectedSym = JavafxTreeInfo.symbolFor(tree.selected);
boolean shouldWarn = false;
if (selectedSym != null) {
if (selectedSym.kind == TYP) {
shouldWarn = true;
}
if (selectedSym.kind == VAR) {
if (selectedSym.name == names._this ||
selectedSym.name == names._super) {
shouldWarn = true;
}
}
if (shouldWarn) {
checkForwardReference(tree, tree.sym);
}
}
super.visitSelect(tree);
}
@Override
public void visitVarInit(JFXVarInit tree) {
currentScope().uninited_vars.remove(tree.getSymbol());
}
@Override
public void visitVar(JFXVar tree) {
if (tree.getSymbol() != null) {
boolean prevIsStatic = currentScope().isStatic;
try {
currentScope().isStatic = tree.getSymbol().isStatic();
super.scan(tree.getInitializer());
}
finally {
currentScope().isStatic = prevIsStatic;
currentScope().uninited_vars.remove(tree.getSymbol());
}
super.scan(tree.getOnReplace());
super.scan(tree.getOnInvalidate());
}
}
@Override
public void visitAssign(JFXAssign tree) {
Symbol s = JavafxTreeInfo.symbolFor(tree.lhs);
JavafxVarSymbol vsym = (s != null && s.kind == VAR) ?
(JavafxVarSymbol)s : null;
if (vsym != null) {
currentScope().forward_set_vars.add(vsym);
}
super.visitAssign(tree);
if (vsym != null) {
currentScope().forward_set_vars.remove(vsym);
}
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
if (tree.getSymbol() != null) {
int prevOverrideVarIdx = currentScope().overrideVarIdx;
try {
currentScope().overrideVarIdx = tree.getSymbol().getAbsoluteIndex(enclClass.type);
scan(tree.getInitializer());
}
finally {
currentScope().overrideVarIdx = prevOverrideVarIdx;
}
super.scan(tree.getOnReplace());
super.scan(tree.getOnInvalidate());
}
}
private void checkForwardReference(JFXExpression tree, Symbol s) {
if (s != null && s instanceof JavafxVarSymbol) {
JavafxVarSymbol vsym = (JavafxVarSymbol)s;
if (!tree.isBound() &&
vsym.name != names._this &&
vsym.name != names._super &&
!currentScope().forward_set_vars.contains(vsym) &&
currentScope().isStatic == vsym.isStatic() &&
(currentScope().uninited_vars.contains(s) ||
(currentScope().overrideVarIdx <= vsym.getAbsoluteIndex(enclClass.type) &&
enclClass.isSubClass(s.owner, types)))) {
reportForwardReference(tree, s);
}
}
}
private void beginScope() {
beginScope(false);
}
private void beginScope(boolean staticScope) {
scopes = scopes.prepend(new VarScope(staticScope));
}
private void endScope() {
scopes = scopes.tail;
}
private VarScope currentScope() {
return scopes.head;
}
private void addVars(List<? extends JFXTree> trees) {
for (JFXTree t : trees) {
addVar(t);
}
}
private void addVar(JFXTree tree) {
if (tree != null) {
JavafxVarSymbol sym = null;
switch (tree.getFXTag()) {
case VAR_DEF: sym = ((JFXVar)tree).getSymbol(); break;
case VAR_SCRIPT_INIT: sym = ((JFXVarInit)tree).getSymbol(); break;
}
if (sym != null) {
currentScope().uninited_vars.add(sym);
}
}
}
private void reportForwardReference(DiagnosticPosition pos, Symbol s) {
if (warnOnly) {
log.warning(pos,
MsgSym.MESSAGE_ILLEGAL_FORWARD_REF,
rs.kindName(VAR),
s);
}
else {
log.error(pos,
MsgSym.MESSAGE_ILLEGAL_FORWARD_REF,
rs.kindName(VAR),
s);
}
}
}
new ForwardReferenceChecker().scan(tree);
}
| public void checkForwardReferences(JFXTree tree) {
class ForwardReferenceChecker extends JavafxTreeScanner {
ForwardReferenceChecker() {
warnOnly = options.get("fwdRefError") != null &&
options.get("fwdRefError").contains("false");
}
class VarScope {
VarScope(boolean isStatic) {
this.isStatic = isStatic;
}
Set<JavafxVarSymbol> uninited_vars = new LinkedHashSet<JavafxVarSymbol>();;
Set<JavafxVarSymbol> forward_set_vars = new LinkedHashSet<JavafxVarSymbol>();;
int overrideVarIdx = Integer.MAX_VALUE;
boolean isStatic = false;
}
List<VarScope> scopes = List.nil();
ClassSymbol enclClass = null;
boolean warnOnly;
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
ClassSymbol prevClass = enclClass;
try {
enclClass = tree.sym;
beginScope();
addVars(tree.getMembers());
super.visitClassDeclaration(tree);
endScope();
}
finally {
enclClass = prevClass;
}
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
beginScope(tree.definition.sym.isStatic());
super.visitFunctionValue(tree);
endScope();
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
beginScope();
super.visitOnReplace(tree);
endScope();
}
@Override
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
beginScope();
super.visitKeyFrameLiteral(tree);
endScope();
}
@Override
public void visitInterpolateValue(JFXInterpolateValue tree) {
beginScope();
super.visitInterpolateValue(tree);
endScope();
}
@Override
public void visitInitDefinition(JFXInitDefinition tree) {
beginScope();
super.visitInitDefinition(tree);
endScope();
}
@Override
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
beginScope();
super.visitPostInitDefinition(tree);
endScope();
}
@Override
public void visitBlockExpression(JFXBlock tree) {
addVars(tree.stats);
addVar(tree.value);
super.visitBlockExpression(tree);
}
@Override
public void visitIdent(JFXIdent tree) {
checkForwardReference(tree, tree.sym);
}
@Override
public void visitSelect(JFXSelect tree) {
Symbol selectedSym = JavafxTreeInfo.symbolFor(tree.selected);
boolean shouldWarn = false;
if (selectedSym != null) {
if (selectedSym.kind == TYP) {
shouldWarn = true;
}
if (selectedSym.kind == VAR) {
if (selectedSym.name == names._this ||
selectedSym.name == names._super) {
shouldWarn = true;
}
}
if (shouldWarn) {
checkForwardReference(tree, tree.sym);
}
}
super.visitSelect(tree);
}
@Override
public void visitVarInit(JFXVarInit tree) {
currentScope().uninited_vars.remove(tree.getSymbol());
}
@Override
public void visitVar(JFXVar tree) {
if (tree.getSymbol() != null) {
boolean prevIsStatic = currentScope().isStatic;
try {
currentScope().isStatic = tree.getSymbol().isStatic();
super.scan(tree.getInitializer());
}
finally {
currentScope().isStatic = prevIsStatic;
currentScope().uninited_vars.remove(tree.getSymbol());
}
super.scan(tree.getOnReplace());
super.scan(tree.getOnInvalidate());
}
}
@Override
public void visitAssign(JFXAssign tree) {
Symbol s = JavafxTreeInfo.symbolFor(tree.lhs);
JavafxVarSymbol vsym = (s != null && s.kind == VAR) ?
(JavafxVarSymbol)s : null;
if (vsym != null) {
currentScope().forward_set_vars.add(vsym);
}
super.visitAssign(tree);
if (vsym != null) {
currentScope().forward_set_vars.remove(vsym);
}
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
if (tree.getSymbol() != null) {
int prevOverrideVarIdx = currentScope().overrideVarIdx;
try {
currentScope().overrideVarIdx = tree.getSymbol().getAbsoluteIndex(enclClass.type);
scan(tree.getInitializer());
}
finally {
currentScope().overrideVarIdx = prevOverrideVarIdx;
}
super.scan(tree.getOnReplace());
super.scan(tree.getOnInvalidate());
}
}
private void checkForwardReference(JFXExpression tree, Symbol s) {
if (s != null && s instanceof JavafxVarSymbol) {
JavafxVarSymbol vsym = (JavafxVarSymbol)s;
if (!tree.isBound() &&
vsym.name != names._this &&
vsym.name != names._super &&
!currentScope().forward_set_vars.contains(vsym) &&
currentScope().isStatic == vsym.isStatic() &&
(currentScope().uninited_vars.contains(s) ||
(currentScope().overrideVarIdx <= vsym.getAbsoluteIndex(enclClass.type) &&
enclClass.isSubClass(s.owner, types)))) {
reportForwardReference(tree, s);
}
}
}
private void beginScope() {
beginScope(false);
}
private void beginScope(boolean staticScope) {
scopes = scopes.prepend(new VarScope(staticScope));
}
private void endScope() {
scopes = scopes.tail;
}
private VarScope currentScope() {
return scopes.head;
}
private void addVars(List<? extends JFXTree> trees) {
for (JFXTree t : trees) {
addVar(t);
}
}
private void addVar(JFXTree tree) {
if (tree != null) {
JavafxVarSymbol sym = null;
switch (tree.getFXTag()) {
case VAR_DEF: sym = ((JFXVar)tree).getSymbol(); break;
case VAR_SCRIPT_INIT: sym = ((JFXVarInit)tree).getSymbol(); break;
}
if (sym != null) {
currentScope().uninited_vars.add(sym);
}
}
}
private void reportForwardReference(DiagnosticPosition pos, Symbol s) {
if (warnOnly) {
log.warning(pos,
MsgSym.MESSAGE_ILLEGAL_FORWARD_REF,
rs.kindName(VAR),
s);
}
else {
log.error(pos,
MsgSym.MESSAGE_ILLEGAL_FORWARD_REF,
rs.kindName(VAR),
s);
}
}
}
new ForwardReferenceChecker().scan(tree);
}
|
diff --git a/encuestame-business/src/main/java/org/encuestame/business/service/PollService.java b/encuestame-business/src/main/java/org/encuestame/business/service/PollService.java
index 57f83420c..625a5125b 100644
--- a/encuestame-business/src/main/java/org/encuestame/business/service/PollService.java
+++ b/encuestame-business/src/main/java/org/encuestame/business/service/PollService.java
@@ -1,879 +1,879 @@
/*
************************************************************************************
* Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2010
* encuestame Development Team.
* Licensed under the Apache Software License version 2.0
* 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.encuestame.business.service;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.encuestame.core.config.EnMePlaceHolderConfigurer;
import org.encuestame.core.service.imp.IPollService;
import org.encuestame.core.util.ConvertDomainBean;
import org.encuestame.core.util.EnMeUtils;
import org.encuestame.persistence.domain.Email;
import org.encuestame.persistence.domain.HashTag;
import org.encuestame.persistence.domain.question.Question;
import org.encuestame.persistence.domain.question.QuestionAnswer;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.persistence.domain.survey.Poll;
import org.encuestame.persistence.domain.survey.PollFolder;
import org.encuestame.persistence.domain.survey.PollResult;
import org.encuestame.persistence.exception.EnMeExpcetion;
import org.encuestame.persistence.exception.EnMeNoResultsFoundException;
import org.encuestame.persistence.exception.EnMePollNotFoundException;
import org.encuestame.persistence.exception.EnmeFailOperation;
import org.encuestame.utils.DateUtil;
import org.encuestame.utils.MD5Utils;
import org.encuestame.utils.RestFullUtil;
import org.encuestame.utils.ValidationUtils;
import org.encuestame.utils.enums.CommentOptions;
import org.encuestame.utils.enums.NotificationEnum;
import org.encuestame.utils.enums.QuestionPattern;
import org.encuestame.utils.enums.TypeSearch;
import org.encuestame.utils.enums.TypeSearchResult;
import org.encuestame.utils.json.FolderBean;
import org.encuestame.utils.json.QuestionBean;
import org.encuestame.utils.web.HashTagBean;
import org.encuestame.utils.web.PollBean;
import org.encuestame.utils.web.PollBeanResult;
import org.encuestame.utils.web.PollDetailBean;
import org.encuestame.utils.web.UnitLists;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
/**
* Poll Service.
* @author Morales, Diana Paola paola AT encuestame.org
* @since April 01, 2010
*/
@Service
public class PollService extends AbstractSurveyService implements IPollService{
/**
* Log.
*/
private Log log = LogFactory.getLog(this.getClass());
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#filterPollByItemsByType(org.encuestame.utils.enums.TypeSearch, java.lang.String, java.lang.Integer, java.lang.Integer, org.encuestame.utils.enums.TypeSearchResult)
*/
public List<PollBean> filterPollByItemsByType(
final TypeSearch typeSearch,
String keyword, Integer max, Integer start)
throws EnMeNoResultsFoundException, EnMeExpcetion {
log.debug("filterPollByItemsByType");
log.debug("--> "+typeSearch);
log.debug("--> "+keyword);
log.debug("--> "+max);
log.debug("--> "+start);
final List<PollBean> list = new ArrayList<PollBean>();
if (TypeSearch.KEYWORD.equals(typeSearch)) {
list.addAll(this.searchPollByKeyword(keyword, max, start));
} else if (TypeSearch.BYOWNER.equals(typeSearch)) {
list.addAll(ConvertDomainBean.convertListToPollBean(getPollDao()
.findAllPollByEditorOwner(
getUserAccount(getUserPrincipalUsername()), max,
start)));
} else if (TypeSearch.LASTDAY.equals(typeSearch)) {
list.addAll(ConvertDomainBean.convertListToPollBean(this.
getPollDao().retrievePollToday(
getUserAccount(getUserPrincipalUsername())
.getAccount(), max, start,
DateUtil.getNextDayMidnightDate())));
} else if (TypeSearch.LASTWEEK.equals(typeSearch)) {
list.addAll(ConvertDomainBean.convertListToPollBean(this
.getPollDao().retrievePollLastWeek(
getUserAccount(getUserPrincipalUsername())
.getAccount(), max, start,
DateUtil.getNextDayMidnightDate())));
} else if (TypeSearch.FAVOURITES.equals(typeSearch)) {
list.addAll(ConvertDomainBean.convertListToPollBean(getPollDao()
.retrieveFavouritesPoll(
getUserAccount(getUserPrincipalUsername()), max,
start)));
} else if (TypeSearch.ALL.equals(typeSearch)) {
list.addAll(ConvertDomainBean.convertListToPollBean(this
.getPollsByRange(max, start, null)));
} else {
throw new EnMeExpcetion("operation not valid");
}
log.debug("Poll Search Items : "+list.size());
return list;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#createPoll(java.lang.String, java.lang.String[], java.lang.Boolean, java.lang.String, java.lang.Boolean, java.util.List)
*/
public Poll createPoll(final String questionName, final String[] answers,
final Boolean showResults, final String commentOption,
final Boolean notification, final List<HashTagBean> hashtags)
throws EnMeExpcetion {
final UserAccount user = getUserAccount(getUserPrincipalUsername());
Assert.notNull(answers);
log.debug("poll list answer=>" + answers);
Assert.notNull(user);
Assert.notNull(questionName);
final Poll pollDomain = new Poll();
try {
final QuestionBean questionBean = new QuestionBean();
questionBean.setQuestionName(questionName);
final Question question = createQuestion(questionBean, user, QuestionPattern.CUSTOMIZABLE_SELECTION);
log.debug("question found : {"+question);
log.debug("answers found : {"+answers.length);
if (question == null) {
throw new EnMeNoResultsFoundException("Question not valid");
} else if (answers.length == 0 ) {
throw new EnMeNoResultsFoundException("answers are required to create Poll");
}
else{
//TODO: move hash to util.
final String hashPoll = MD5Utils.md5(RandomStringUtils.randomAlphanumeric(500));
log.debug("OPTION SHOW COMMENTS GETTED BEFORE---> " +commentOption);
final CommentOptions commentOpt = CommentOptions.getCommentOption(commentOption);
log.debug("OPTION SHOW COMMENTS GETTED ENUM---> " +commentOpt);
pollDomain.setEditorOwner(user);
pollDomain.setCreatedAt(Calendar.getInstance().getTime());
pollDomain.setPollHash(hashPoll);
pollDomain.setQuestion(question);
pollDomain.setPollCompleted(Boolean.FALSE);
pollDomain.setHits(EnMeUtils.HIT_DEFAULT);
pollDomain.setRelevance(EnMeUtils.RATE_DEFAULT);
pollDomain.setLikeVote(EnMeUtils.LIKE_DEFAULT);
pollDomain.setDislikeVote(EnMeUtils.DISLIKE_DEFAULT);
pollDomain.setNumbervotes(EnMeUtils.VOTE_MIN);
pollDomain.setEditorOwner(user);
pollDomain.setOwner(user.getAccount());
pollDomain.setShowResults(showResults);
pollDomain.setShowComments(commentOpt == null ? null :commentOpt);
pollDomain.setPublish(Boolean.TRUE);
pollDomain.setNotifications(notification);
pollDomain.setPublish(Boolean.TRUE);
if (hashtags.size() > 0) {
- //http://issues.encuestame.org/browse/ENCUESTAME-504
- //pollDomain.getHashTags().addAll(retrieveListOfHashTags(hashtags));
+ //http://issues.encuestame.org/browse/ENCUESTAME-504
+ pollDomain.getHashTags().addAll(retrieveListOfHashTags(hashtags));
}
log.debug("poll list answer=>" + answers.length);
// Add answers
this.createQuestionAnswers(answers, question);
this.getPollDao().saveOrUpdate(pollDomain);
}
} catch (Exception e) {
e.printStackTrace();
log.equals(e);
throw new EnMeExpcetion(e);
}
return pollDomain;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#updatePoll(org.encuestame.utils.web.PollBean)
*/
public Poll updatePoll(final PollBean pollBean)
throws EnMeNoResultsFoundException {
final Poll poll = getPollById(pollBean.getId(),
getUserPrincipalUsername());
Assert.notNull(poll);
final Question questionDomain = poll.getQuestion();
questionDomain
.setQuestion(pollBean.getQuestionBean().getQuestionName());
questionDomain.setSlugQuestion(RestFullUtil.slugify(pollBean
.getQuestionBean().getQuestionName()));
questionDomain.setCreateDate(DateUtil.getCurrentCalendarDate());
getQuestionDao().saveOrUpdate(questionDomain);
Assert.notNull(questionDomain);
poll.setPollCompleted(pollBean.getCompletedPoll());
poll.setShowResults(pollBean.getShowResults());
poll.setShowComments(CommentOptions.getCommentOption(pollBean
.getShowComments()));
poll.setPublish(pollBean.getPublishPoll());
poll.setNotifications(pollBean.getCloseNotification());
poll.getHashTags().addAll(retrieveListOfHashTags(pollBean.getHashTags()));
return poll;
}
/*
* (non-Javadoc)
*
* @see
* org.encuestame.core.service.imp.IPollService#addHashTagToPoll(org.encuestame
* .persistence.domain.survey.Poll, org.encuestame.utils.web.HashTagBean)
*/
public HashTag addHashTagToPoll(final Poll poll, final HashTagBean tagBean)
throws EnMeNoResultsFoundException {
log.debug("Adding hashtag to Poll --->" + poll.getPollId());
log.debug("Adding hashTagBean to Poll ---> " + tagBean.getHashTagName());
tagBean.setHashTagName(ValidationUtils
.removeNonAlphanumericCharacters(tagBean.getHashTagName()));
HashTag tag = getHashTag(tagBean.getHashTagName(), Boolean.FALSE);
if (tag == null) {
tag = createHashTag(tagBean.getHashTagName().toLowerCase());
poll.getHashTags().add(tag);
getPollDao().saveOrUpdate(poll);
log.debug("Added new hashtag done :" + tag.getHashTagId());
return tag;
} else {
poll.getHashTags().add(tag);
getPollDao().saveOrUpdate(poll);
log.debug("Added previous hashtag done :" + tag.getHashTagId());
return tag;
}
}
/**
* Get Poll by Id without user session.
* @param pollId poll id.
* @return
* @throws EnMeNoResultsFoundException
*/
private Poll getPoll(final Long pollId) throws EnMeNoResultsFoundException{
return this.getPollDao().getPollById(pollId);
}
/**
* Retrieve {@link Poll} by {@link UserAccount}
* @param pollId
* @param user
* @return
* @throws EnMeNoResultsFoundException
*/
private Poll getPollbyUserAndId(final Long pollId, final UserAccount user) throws EnMeNoResultsFoundException{
return this.getPollDao().getPollById(pollId, user);
}
/**
* Remove Poll
* @param pollId
* @throws EnMeNoResultsFoundException
*/
public void removePoll(final Long pollId)
throws EnMeNoResultsFoundException {
final Poll pollDomain = this.getPollbyUserAndId(pollId, getUserAccount(getUserPrincipalUsername()));
final List<PollResult> pollResults;
final List<QuestionAnswer> qAnswer;
Question question = new Question();
if (pollDomain != null) {
// Retrieve Poll results, answers and question.
pollResults = getPollDao().retrievePollResults(pollDomain);
if (pollResults.size() > 0) {
// Delete poll results.
for (PollResult pollResult : pollResults) {
getPollDao().delete(pollResult);
}
}
question = pollDomain.getQuestion();
if (question != null) {
// Retrieve answers by Question id.
qAnswer = this
.getQuestionAnswersbyQuestionId(question.getQid());
if (qAnswer.size() > 0) {
for (QuestionAnswer questionAnswer : qAnswer) {
getQuestionDao().delete(questionAnswer);
}
}
// Remove Poll
getPollDao().delete(pollDomain);
// TODO: Remove Hits and social network publications.
// Remove Question
getQuestionDao().delete(question);
} else {
throw new EnMeNoResultsFoundException("Question not found");
}
} else {
throw new EnMeNoResultsFoundException("Poll not found");
}
}
/**
* Search Polls by Question keyword.
* @param keywordQuestion
* @param username
* @param maxResults
* @param start
* @return
* @throws EnMeExpcetion
*/
public List<PollBean> searchPollByKeyword(final String keywordQuestion, final Integer maxResults,
final Integer start) throws EnMeExpcetion{
log.debug("search keyword Poll "+keywordQuestion);
List<Poll> polls = new ArrayList<Poll>();
if (keywordQuestion == null) {
throw new EnMeExpcetion("keyword is mandatory");
} else {
polls = getPollDao().getPollsByQuestionKeyword(keywordQuestion,
getUserAccount(getUserPrincipalUsername()), maxResults, start);
}
log.debug("search keyword polls size "+polls.size());
return ConvertDomainBean.convertListToPollBean(polls);
}
/**
* Search Polls by Folder Id.
* @param folderId
* @param username
* @return
* @throws EnMeNoResultsFoundException
*/
public List<PollBean> searchPollsByFolder(final Long folderId, final String username) throws EnMeNoResultsFoundException{
final PollFolder pollFolder = getPollDao().getPollFolderById(folderId);
List<Poll> polls = new ArrayList<Poll>();
if (pollFolder != null){
polls = getPollDao().getPollsByPollFolderId(getUserAccount(getUserPrincipalUsername()), pollFolder);
}
log.info("search polls by folder size "+polls.size());
return ConvertDomainBean.convertSetToPollBean(polls);
}
/**
* List Poll ByUser.
* @param currentUser currentUser
* @return unitPoll
* @throws EnMeNoResultsFoundException
*/
public List<PollBean> listPollByUser(final Integer maxResults, final Integer start) throws EnMeNoResultsFoundException{
final List<PollBean> unitPoll = new ArrayList<PollBean>();
final List<Poll> polls = getPollDao().findAllPollByEditorOwner(getUserAccount(getUserPrincipalUsername()), maxResults, start);
for (Poll poll : polls) {
unitPoll.add(ConvertDomainBean.convertPollDomainToBean(poll));
}
return unitPoll;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#vote(java.lang.Long, java.lang.String, java.lang.String, java.lang.Long)
*/
public void vote(final Long pollId, final String slug,
final String ipAddress,
final Long answerId)
throws EnMeNoResultsFoundException {
log.trace("vote "+pollId);
log.trace("vote "+slug);
log.trace("vote "+ipAddress);
log.trace("vote "+answerId);
final Poll poll = this.getPollDao().getPollById(pollId, slug, false);
if (poll == null) {
throw new EnMeNoResultsFoundException("poll not found");
}
final PollResult pr = new PollResult();
pr.setAnswer(this.getQuestionAnswerById(answerId));
//validate IP address.
pr.setIpaddress(ipAddress);
pr.setPoll(poll);
pr.setVotationDate(Calendar.getInstance().getTime());
getPollDao().saveOrUpdate(pr);
}
/**
* Get Polls by Folder.
* @param folder
* @param username
* @return
* @throws EnMeNoResultsFoundException
*/
public List<PollBean> getPollsByFolder(final FolderBean folder) throws EnMeNoResultsFoundException{
final List<Poll> polls = getPollDao().getPollsByPollFolder(getUserAccount(getUserPrincipalUsername()), getPollFolder(folder.getId()));
return ConvertDomainBean.convertSetToPollBean(polls);
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#updateQuestionPoll(java.lang.Long, org.encuestame.persistence.domain.question.Question)
*/
public PollBean updateQuestionPoll(final Long pollId, final Question question)
throws EnMeExpcetion {
final Poll poll = this.getPollById(pollId, getUserAccount(getUserPrincipalUsername()));
if (poll == null) {
throw new EnMeNoResultsFoundException("poll not found");
}
else{
poll.setQuestion(question) ;
getPollDao().saveOrUpdate(poll);
}
return ConvertDomainBean.convertPollDomainToBean(poll);
}
/**
* Create url poll Access.
* @param poll
* @param domain
* @param currentUser
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
private String createUrlPollAccess(final Poll poll) {
StringBuffer urlBuffer = new StringBuffer("/poll/");
urlBuffer.append(poll.getPollHash());
urlBuffer.append("/");
urlBuffer.append(poll.getPollId());
urlBuffer.append("/");
urlBuffer.append(poll.getQuestion().getSlugQuestion());
return urlBuffer.toString();
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#createPollNotification(org.encuestame.persistence.domain.survey.Poll)
*/
public void createPollNotification(final Poll poll) throws EnMeNoResultsFoundException {
createNotification(NotificationEnum.POLL_PUBLISHED,
getMessageProperties("notification.poll.publish"),
this.createUrlPollAccess(poll), false);
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#publicPollByList(org.encuestame.persistence.domain.survey.Poll, org.encuestame.utils.web.UnitLists)
*/
@SuppressWarnings("unused")
public void publicPollByList(final Poll poll, final UnitLists emailList) {
final List<Email> emailsList = getEmailListsDao().findEmailsByListId(emailList.getId());
final String urlPoll = this.createUrlPollAccess(poll);
if(emailList !=null){
for (Email emails : emailsList) {
if (EnMePlaceHolderConfigurer.getBooleanProperty("application.email.disabled")) {
getMailService().send(emails.getEmail(),"New Poll", urlPoll);
}
}
}
else{
log.warn("Not Found Emails in your EmailList");
}
}
/**
* Retrieve Folder Poll.
* @param username
* @return
* @throws EnMeNoResultsFoundException exception
*/
public List<FolderBean> retrieveFolderPoll() throws EnMeNoResultsFoundException {
final List<PollFolder> folders = getPollDao().getPollFolderByUserAccount(getUserAccount(getUserPrincipalUsername()));
return ConvertDomainBean.convertListPollFolderToBean(folders);
}
/**
* Create Poll Folder.
* @param folderName
* @param username
* @return
* @throws EnMeNoResultsFoundException
*/
public FolderBean createPollFolder(final String folderName) throws EnMeNoResultsFoundException {
final PollFolder pollFolder = new PollFolder();
pollFolder.setCreatedBy(getUserAccount(getUserPrincipalUsername()));
pollFolder.setCreatedAt(Calendar.getInstance().getTime());
pollFolder.setFolderName(folderName);
pollFolder.setUsers(getUserAccount(getUserPrincipalUsername()).getAccount());
this.getPollDao().saveOrUpdate(pollFolder);
return ConvertDomainBean.convertFolderToBeanFolder(pollFolder);
}
/**
* Update FolderName.
* @param folderId folder id
* @param newFolderName folder name
* @param username username
* @return {@link FolderBean}
* @throws EnMeNoResultsFoundException exception
*/
public FolderBean updateFolderName(final Long folderId,
final String newFolderName,
final String username) throws EnMeNoResultsFoundException{
final PollFolder folder = this.getPollFolder(folderId);
if(folder == null){
throw new EnMeNoResultsFoundException("poll folder not found");
} else {
folder.setFolderName(newFolderName);
getPollDao().saveOrUpdate(folder);
}
return ConvertDomainBean.convertFolderToBeanFolder(folder);
}
/**
* Get Poll Folder.
* @param id
* @return
* @throws EnMeNoResultsFoundException
*/
private PollFolder getPollFolder(final Long id) throws EnMeNoResultsFoundException{
if(id == null){
throw new EnMeNoResultsFoundException("poll folder id not found");
}else {
return this.getPollDao().getPollFolderById(id);
}
}
/**
* Remove PollFolder.
* @param folderId
* @throws EnMeNoResultsFoundException
*/
public void removePollFolder(final Long folderId) throws EnMeNoResultsFoundException{
final PollFolder folder = this.getPollFolder(folderId);
if(folder != null){
getPollDao().delete(folder);
} else {
throw new EnMeNoResultsFoundException("poll folder not found");
}
}
public List<PollBean> listPollByUser(String currentUser)
throws EnMeNoResultsFoundException {
// TODO Auto-generated method stub
return null;
}
/**
* Add poll to Folder.
* @param folderId
* @param username
* @param pollId
* @throws EnMeNoResultsFoundException
*/
public void addPollToFolder(final Long folderId, final Long pollId)
throws EnMeNoResultsFoundException{
final PollFolder pfolder = this.getPollFolderByFolderIdandUser(folderId, getUserAccount(getUserPrincipalUsername()));
if (pfolder != null) {
final Poll poll = getPollDao().getPollById(pollId, getUserAccount(getUserPrincipalUsername()));
if (poll == null){
throw new EnMeNoResultsFoundException("TweetPoll not found");
}
poll.setPollFolder(pfolder);
getPollDao().saveOrUpdate(poll);
} else {
throw new EnMeNoResultsFoundException("TweetPoll folder not found");
}
}
/**
* Get Poll folder.
* @param folderId
* @param userId
* @return
*/
public PollFolder getPollFolderByFolderIdandUser(final Long folderId, final UserAccount userAccount){
return this.getPollDao().getPollFolderByIdandUser(folderId, userAccount);
}
/**
* Get polls by creation date.
* @param userId
* @param date
* @param maxResults
* @param star
* @return
* @throws EnMeNoResultsFoundException
*/
public List<PollBean> getPollsbyDate(final Date date, final Integer maxResults,
final Integer start) throws EnMeNoResultsFoundException{
List<Poll> pollList = new ArrayList<Poll>();
if (date !=null){
pollList = getPollDao().getPollByUserIdDate(date, getUserAccount(getUserPrincipalUsername()), maxResults, start);
}
else{
throw new EnMeNoResultsFoundException("Date not found");
}
return ConvertDomainBean.convertSetToPollBean(pollList);
}
/**
* Get poll by id and user.
* @param pollId
* @param account
* @return
* @throws EnMeNoResultsFoundException
*/
public Poll getPollById(final Long pollId, final UserAccount account) throws EnMeNoResultsFoundException{
final Poll poll = getPollDao().getPollById(pollId, account);
if (poll == null) {
log.error("poll invalid with this id "+pollId+ " and username:{"+account);
throw new EnMePollNotFoundException("poll invalid with this id "+pollId+ " and username:{"+account);
}
return poll;
}
/**
* Retrieve a {@link Poll} based on id.
* @param pollId poll id.
* @param account username account
* @return {@link Poll}
* @throws EnMeNoResultsFoundException
*/
public Poll getPollById(final Long pollId, final String account) throws EnMeNoResultsFoundException {
log.debug("getPollById pollId: "+pollId);
log.debug("getPollById account: "+account);
final Poll poll = this.getPollById(pollId, getUserAccount(account));
if (poll == null) {
log.error("poll invalid with this id "+pollId+ " and username:{"+account);
throw new EnMePollNotFoundException("poll invalid with this id "+pollId+ " and username:{"+account);
}
return poll;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#getPollSlugById(java.lang.Long, java.lang.String)
*/
public Poll getPollSlugById(final Long pollId, final String slug) throws EnMeNoResultsFoundException{
final Poll poll = this.getPollDao().getPollById(pollId, slug, true);
if (poll == null) {
log.error("poll invalid with this id "+pollId+ " and slug:{"+slug);
throw new EnMePollNotFoundException("poll invalid with this id "+pollId+ " and slug:{"+slug);
}
return poll;
}
/*
* (non-Javadoc)
* @see org.encuestame.business.service.imp.IPollService#getPollsByUserName(java.lang.String, java.lang.Integer, java.lang.Integer)
*/
public List<PollBean> getPollsByUserName(
final String username,
final Integer maxResults,
final Integer start) throws EnMeNoResultsFoundException{
log.debug("Poll username "+username);
final List<Poll> polls = getPollDao()
.retrievePollsByUserId(getUserAccount(getUserPrincipalUsername()), maxResults, start);
log.info("Polls size "+ polls.size());
final List<PollBean> pollBean = ConvertDomainBean.convertSetToPollBean(polls);
return pollBean;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#getPolls(java.lang.Integer, java.lang.Integer, java.util.Date)
*/
public List<Poll> getPollsByRange(final Integer maxResults,
final Integer start, final Date range) {
final List<Poll> polls = getPollDao().getPolls(
maxResults, start, range);
return polls;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#changeStatusPoll(java.lang.Long, java.lang.String)
*/
public void changeStatusPoll(final Long pollId, final String username)
throws EnMeNoResultsFoundException, EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setCloseAfterDate(!(poll.getCloseAfterDate() == null ? false
: poll.getCloseAfterDate()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#closeAfterQuotaPoll(java.lang.Long, java.lang.String)
*/
public void closeAfterQuotaPoll(final Long pollId, final String username)
throws EnMeNoResultsFoundException, EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setCloseAfterquota(!(poll.getCloseAfterquota() == null ? false
: poll.getCloseAfterquota()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#ipProtectionPoll(java.lang.Long, java.lang.String)
*/
public void ipProtectionPoll(final Long pollId, final String username)
throws EnMeNoResultsFoundException, EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setIpRestriction(!(poll.getIpRestriction() == null ? false
: poll.getIpRestriction()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#ipEnableNotificationsPoll(java.lang.Long, java.lang.String)
*/
public void enableNotificationsPoll(final Long pollId,
final String username) throws EnMeNoResultsFoundException,
EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setNotifications(!(poll.getNotifications() == null ? false
: poll.getNotifications()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#setAdditionalInfoPoll(java.lang.Long, java.lang.String)
*/
public void setAdditionalInfoPoll(final Long pollId, final String username)
throws EnMeNoResultsFoundException, EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setShowAdditionalInfo(!(poll.getShowAdditionalInfo() == null ? false
: poll.getShowAdditionalInfo()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#setPasswordRestrictionsPoll(java.lang.Long, java.lang.String)
*/
public void setPasswordRestrictionsPoll(final Long pollId,
final String username) throws EnMeNoResultsFoundException,
EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setPasswordRestrictions(!(poll.getPasswordRestrictions() == null ? false
: poll.getPasswordRestrictions()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#setShowResultsPoll(java.lang.Long, java.lang.String)
*/
public void setShowResultsPoll(final Long pollId, final String username)
throws EnMeNoResultsFoundException, EnmeFailOperation {
final Poll poll = getPollById(pollId, username);
if (poll != null) {
poll.setShowResults(!(poll.getShowResults() == null ? false : poll
.getShowResults()));
getPollDao().saveOrUpdate(poll);
} else {
throw new EnmeFailOperation("Fail Change Status Operation");
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#getResultVotes(org.encuestame.persistence.domain.survey.Poll)
*/
public List<PollBeanResult> getResultVotes(final Poll poll) {
log.debug("poll getResultVotes " + poll);
final List<PollBeanResult> results = new ArrayList<PollBeanResult>();
final List<Object[]> list = getPollDao().retrieveResultPolls(poll.getPollId(), poll.getQuestion().getQid());
//log.debug("retrieveResultPolls==> "+list.size());
for (Object[] objects : list) {
final Long answerId = objects[0] == null ? null : Long.valueOf(objects[0].toString());
final String answerString = objects[1] == null ? null : objects[1].toString();
final String color = objects[2] == null ? null : objects[2].toString();
final Long votes = objects[3] == null ? null : Long.valueOf(objects[3].toString());
if (answerId != null) {
final PollBeanResult result = ConvertDomainBean.convertPollResultToBean(answerId, answerString, color, votes, poll.getQuestion());
results.add(result);
} else {
throw new IllegalArgumentException("answer id is empty");
}
}
log.debug("poll PollBeanResult " + results.size());
this.calculatePercents(results);
return results;
}
/**
* Calculate the percents.
* @param beanResults
*/
private void calculatePercents(final List<PollBeanResult> beanResults) {
double totalVotes = 0;
for (PollBeanResult pollBeanResult : beanResults) {
totalVotes += totalVotes + pollBeanResult.getResult();
}
for (PollBeanResult pollBeanResult : beanResults) {
pollBeanResult.setPercent(EnMeUtils.calculatePercent(totalVotes, pollBeanResult.getResult()));
}
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#getPollDetailInfo(java.lang.Long)
*/
public PollDetailBean getPollDetailInfo(final Long pollId) throws EnMeNoResultsFoundException{
final PollDetailBean detail = new PollDetailBean();
final Poll poll = getPoll(pollId);
detail.setPollBean(ConvertDomainBean.convertPollDomainToBean(poll));
detail.setResults(this.getResultVotes(poll));
this.calculatePercents(detail.getResults());
//set the list of answers
detail.setListAnswers(ConvertDomainBean
.convertAnswersToQuestionAnswerBean(getQuestionDao()
.getAnswersByQuestionId(poll.getQuestion().getQid())));
//set the comments.
detail.getPollBean().setTotalComments(this.getTotalCommentsbyType(detail.getPollBean().getId(), TypeSearchResult.POLL));
return detail;
}
/*
* (non-Javadoc)
* @see org.encuestame.core.service.imp.IPollService#validatePollIP(java.lang.String, org.encuestame.persistence.domain.survey.Poll)
*/
public PollResult validatePollIP(final String ip, final Poll poll) {
return getPollDao().validateVoteIP(ip, poll);
}
}
| true | true | public Poll createPoll(final String questionName, final String[] answers,
final Boolean showResults, final String commentOption,
final Boolean notification, final List<HashTagBean> hashtags)
throws EnMeExpcetion {
final UserAccount user = getUserAccount(getUserPrincipalUsername());
Assert.notNull(answers);
log.debug("poll list answer=>" + answers);
Assert.notNull(user);
Assert.notNull(questionName);
final Poll pollDomain = new Poll();
try {
final QuestionBean questionBean = new QuestionBean();
questionBean.setQuestionName(questionName);
final Question question = createQuestion(questionBean, user, QuestionPattern.CUSTOMIZABLE_SELECTION);
log.debug("question found : {"+question);
log.debug("answers found : {"+answers.length);
if (question == null) {
throw new EnMeNoResultsFoundException("Question not valid");
} else if (answers.length == 0 ) {
throw new EnMeNoResultsFoundException("answers are required to create Poll");
}
else{
//TODO: move hash to util.
final String hashPoll = MD5Utils.md5(RandomStringUtils.randomAlphanumeric(500));
log.debug("OPTION SHOW COMMENTS GETTED BEFORE---> " +commentOption);
final CommentOptions commentOpt = CommentOptions.getCommentOption(commentOption);
log.debug("OPTION SHOW COMMENTS GETTED ENUM---> " +commentOpt);
pollDomain.setEditorOwner(user);
pollDomain.setCreatedAt(Calendar.getInstance().getTime());
pollDomain.setPollHash(hashPoll);
pollDomain.setQuestion(question);
pollDomain.setPollCompleted(Boolean.FALSE);
pollDomain.setHits(EnMeUtils.HIT_DEFAULT);
pollDomain.setRelevance(EnMeUtils.RATE_DEFAULT);
pollDomain.setLikeVote(EnMeUtils.LIKE_DEFAULT);
pollDomain.setDislikeVote(EnMeUtils.DISLIKE_DEFAULT);
pollDomain.setNumbervotes(EnMeUtils.VOTE_MIN);
pollDomain.setEditorOwner(user);
pollDomain.setOwner(user.getAccount());
pollDomain.setShowResults(showResults);
pollDomain.setShowComments(commentOpt == null ? null :commentOpt);
pollDomain.setPublish(Boolean.TRUE);
pollDomain.setNotifications(notification);
pollDomain.setPublish(Boolean.TRUE);
if (hashtags.size() > 0) {
//http://issues.encuestame.org/browse/ENCUESTAME-504
//pollDomain.getHashTags().addAll(retrieveListOfHashTags(hashtags));
}
log.debug("poll list answer=>" + answers.length);
// Add answers
this.createQuestionAnswers(answers, question);
this.getPollDao().saveOrUpdate(pollDomain);
}
} catch (Exception e) {
e.printStackTrace();
log.equals(e);
throw new EnMeExpcetion(e);
}
return pollDomain;
}
| public Poll createPoll(final String questionName, final String[] answers,
final Boolean showResults, final String commentOption,
final Boolean notification, final List<HashTagBean> hashtags)
throws EnMeExpcetion {
final UserAccount user = getUserAccount(getUserPrincipalUsername());
Assert.notNull(answers);
log.debug("poll list answer=>" + answers);
Assert.notNull(user);
Assert.notNull(questionName);
final Poll pollDomain = new Poll();
try {
final QuestionBean questionBean = new QuestionBean();
questionBean.setQuestionName(questionName);
final Question question = createQuestion(questionBean, user, QuestionPattern.CUSTOMIZABLE_SELECTION);
log.debug("question found : {"+question);
log.debug("answers found : {"+answers.length);
if (question == null) {
throw new EnMeNoResultsFoundException("Question not valid");
} else if (answers.length == 0 ) {
throw new EnMeNoResultsFoundException("answers are required to create Poll");
}
else{
//TODO: move hash to util.
final String hashPoll = MD5Utils.md5(RandomStringUtils.randomAlphanumeric(500));
log.debug("OPTION SHOW COMMENTS GETTED BEFORE---> " +commentOption);
final CommentOptions commentOpt = CommentOptions.getCommentOption(commentOption);
log.debug("OPTION SHOW COMMENTS GETTED ENUM---> " +commentOpt);
pollDomain.setEditorOwner(user);
pollDomain.setCreatedAt(Calendar.getInstance().getTime());
pollDomain.setPollHash(hashPoll);
pollDomain.setQuestion(question);
pollDomain.setPollCompleted(Boolean.FALSE);
pollDomain.setHits(EnMeUtils.HIT_DEFAULT);
pollDomain.setRelevance(EnMeUtils.RATE_DEFAULT);
pollDomain.setLikeVote(EnMeUtils.LIKE_DEFAULT);
pollDomain.setDislikeVote(EnMeUtils.DISLIKE_DEFAULT);
pollDomain.setNumbervotes(EnMeUtils.VOTE_MIN);
pollDomain.setEditorOwner(user);
pollDomain.setOwner(user.getAccount());
pollDomain.setShowResults(showResults);
pollDomain.setShowComments(commentOpt == null ? null :commentOpt);
pollDomain.setPublish(Boolean.TRUE);
pollDomain.setNotifications(notification);
pollDomain.setPublish(Boolean.TRUE);
if (hashtags.size() > 0) {
//http://issues.encuestame.org/browse/ENCUESTAME-504
pollDomain.getHashTags().addAll(retrieveListOfHashTags(hashtags));
}
log.debug("poll list answer=>" + answers.length);
// Add answers
this.createQuestionAnswers(answers, question);
this.getPollDao().saveOrUpdate(pollDomain);
}
} catch (Exception e) {
e.printStackTrace();
log.equals(e);
throw new EnMeExpcetion(e);
}
return pollDomain;
}
|
diff --git a/ratpack-core/src/main/java/ratpack/http/internal/HeaderHandler.java b/ratpack-core/src/main/java/ratpack/http/internal/HeaderHandler.java
index 2089cf7b7..0a4733507 100644
--- a/ratpack-core/src/main/java/ratpack/http/internal/HeaderHandler.java
+++ b/ratpack-core/src/main/java/ratpack/http/internal/HeaderHandler.java
@@ -1,41 +1,42 @@
/*
* Copyright 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 ratpack.http.internal;
import ratpack.handling.Context;
import ratpack.handling.Handler;
public class HeaderHandler implements Handler {
private final String headerName;
private final String headerValue;
private final Handler handler;
public HeaderHandler(String headerName, String headerValue, Handler handler) {
this.headerName = headerName;
this.headerValue = headerValue;
this.handler = handler;
}
public void handle(Context context) throws Exception {
- if (context.getRequest().getHeaders().get(headerName).equals(headerValue)) {
+ String value = context.getRequest().getHeaders().get(headerName);
+ if (value != null && value.equals(headerValue)) {
handler.handle(context);
} else {
context.next();
}
}
}
| true | true | public void handle(Context context) throws Exception {
if (context.getRequest().getHeaders().get(headerName).equals(headerValue)) {
handler.handle(context);
} else {
context.next();
}
}
| public void handle(Context context) throws Exception {
String value = context.getRequest().getHeaders().get(headerName);
if (value != null && value.equals(headerValue)) {
handler.handle(context);
} else {
context.next();
}
}
|
diff --git a/d2s-tools/src/main/java/org/data2semantics/tools/experiments/LinkPredictionExperiment.java b/d2s-tools/src/main/java/org/data2semantics/tools/experiments/LinkPredictionExperiment.java
index 502535e..a719584 100644
--- a/d2s-tools/src/main/java/org/data2semantics/tools/experiments/LinkPredictionExperiment.java
+++ b/d2s-tools/src/main/java/org/data2semantics/tools/experiments/LinkPredictionExperiment.java
@@ -1,315 +1,315 @@
package org.data2semantics.tools.experiments;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import org.data2semantics.tools.graphs.DirectedMultigraphWithRoot;
import org.data2semantics.tools.graphs.Edge;
import org.data2semantics.tools.graphs.Vertex;
import org.data2semantics.tools.kernels.GraphKernel;
import org.data2semantics.tools.kernels.IntersectionSubTreeKernel;
import org.data2semantics.tools.libsvm.LibSVM;
import org.data2semantics.tools.libsvm.LibSVMModel;
import org.data2semantics.tools.libsvm.LibSVMParameters;
import org.data2semantics.tools.libsvm.LibSVMPrediction;
import cern.colt.Arrays;
import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.util.Pair;
public class LinkPredictionExperiment implements Runnable {
private LinkPredictionDataSet dataSet;
private GraphKernel kernelA, kernelB;
private double weightA, weightB;
private List<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>> trainGraphsA;
private List<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>> trainGraphsB;
private List<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>> testGraphsA;
private List<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>> testGraphsB;
private List<Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>> trainSet;
private List<Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>> testSet;
private long[] seeds;
private double[] cs;
private PrintWriter output;
private ExperimentResults results;
public LinkPredictionExperiment(LinkPredictionDataSet dataSet,
GraphKernel kernelA, GraphKernel kernelB, double weightA, double weightB, long[] seeds,
double[] cs) {
this(dataSet, kernelA, kernelB, weightA, weightB, seeds, cs, System.out);
}
public LinkPredictionExperiment(LinkPredictionDataSet dataSet,
GraphKernel kernelA, GraphKernel kernelB, double weightA, double weightB, long[] seeds,
double[] cs, OutputStream outputStream) {
this.dataSet = dataSet;
this.kernelA = kernelA;
this.kernelB = kernelB;
this.weightA = weightA;
this.weightB = weightB;
this.seeds = seeds;
this.cs = cs;
output = new PrintWriter(outputStream);
results = new ExperimentResults();
results.setAccuracy(new Result());
results.setF1(new Result());
results.setAveragePrecision(new Result());
results.setrPrecision(new Result());
}
public ExperimentResults getResults() {
return results;
}
@Override
public void run() {
double acc = 0, f = 0;
double p5 = 0, p10 = 0, p20 = 0;
double map = 0, rPrec = 0;
double ndcg = 0;
double[] accScores = new double[seeds.length];
double[] fScores = new double[seeds.length];
double[] mapScores = new double[seeds.length];
double[] rPrecScores = new double[seeds.length];
List<String> labels;
for (int i = 0; i < seeds.length; i++) {
createRandomSubSet(100, 100, seeds[i], true);
double[][] matrixA = kernelA.compute(trainGraphsA);
double[][] matrixB = kernelB.compute(trainGraphsB);
double[][] testMatrixA = kernelA.compute(trainGraphsA, testGraphsA);
double[][] testMatrixB = kernelB.compute(trainGraphsB, testGraphsB);
double[][] matrix = combineTrainKernels(matrixA, matrixB);
Collections.shuffle(trainSet, new Random(seeds[i]));
labels = new ArrayList<String>();
for (Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pair : trainSet) {
if (dataSet.getLabels().get(pair)) {
labels.add("true");
} else {
labels.add("false");
}
}
Map<String, Integer> labelMap = new TreeMap<String, Integer>();
labelMap.put("true", -1);
labelMap.put("false", 1);
LibSVMParameters param = new LibSVMParameters(cs, false);
//param.setVerbose(true);
int[] weightLabels = {-1, 1};
double[] weights = {1,1};
param.setWeightLabels(weightLabels);
param.setWeights(weights);
LibSVMModel model = LibSVM.trainSVMModel(matrix, LibSVM.createTargets(labels, labelMap), param);
double[][] testMatrix = combineTestKernels(testMatrixA, testMatrixB);
//double[][] testMatrix = matrix;
labels = new ArrayList<String>();
for (Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pair : testSet) {
if (dataSet.getLabels().get(pair)) {
labels.add("true");
} else {
labels.add("false");
}
}
LibSVMPrediction[] pred = LibSVM.testSVMModel(model, testMatrix);
double[] target = LibSVM.createTargets(labels, labelMap);
/*
int[] ranking = LibSVM.computeRanking(pred);
for (int j = 0; j < 20; j++) {
System.out.print(ranking[j] + "->" + target[ranking[j]] + ", ");
}
System.out.println("");
System.out.println(LibSVM.computeClassCounts(target));
System.out.println(Arrays.toString(pred));
*/
accScores[i] = LibSVM.computeAccuracy(target, LibSVM.extractLabels(pred));
fScores[i] = LibSVM.computeF1(target, LibSVM.extractLabels(pred));
p5 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 5, -1);
p10 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 10, -1);
p20 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 20, -1);
mapScores[i] = LibSVM.computeAveragePrecision(target, LibSVM.computeRanking(pred), -1);
rPrecScores[i] = LibSVM.computeRPrecision(target, LibSVM.computeRanking(pred), -1);
ndcg += LibSVM.computeNDCG(target, LibSVM.computeRanking(pred), target.length, -1);
}
acc = acc / seeds.length;
f = f / seeds.length;
p5 = p5 / seeds.length;
p10 = p10 / seeds.length;
p20 = p20 / seeds.length;
map = map / seeds.length;
rPrec = rPrec / seeds.length;
ndcg = ndcg / seeds.length;
results.setLabel(dataSet.getLabel() + ", Seeds=" + Arrays.toString(seeds) + ", C=" + Arrays.toString(cs) + ", " + kernelA.getLabel() + ", " + kernelB.getLabel());
results.getAccuracy().setLabel("acc");
results.getAccuracy().setScores(accScores);
results.getF1().setLabel("f1");
results.getF1().setScores(fScores);
results.getAveragePrecision().setLabel("map");
results.getAveragePrecision().setScores(mapScores);
- results.getrPrecision().setLabel("R-prec");
+ results.getrPrecision().setLabel("Rpr");
results.getrPrecision().setScores(rPrecScores);
output.println(dataSet.getLabel());
output.println(kernelA.getLabel() + " " + weightA + " AND " + kernelB.getLabel() + " " + weightB + ", Seeds=" + Arrays.toString(seeds) + ", C=" + Arrays.toString(cs));
output.print("Overall Accuracy: " + acc);
output.print(", Average F1: " + f);
output.print(", Average P5: " + p5);
output.print(", Average P10: " + p10);
output.print(", Average P20: " + p20);
output.print(", Average AP: " + map);
output.print(", Average R-prec: " + rPrec);
output.print(", Average NDCG: " + ndcg);
output.println("");
output.flush();
}
private double[][] combineTrainKernels(double[][] matrixA, double[][] matrixB) {
double[][] matrix = new double[trainSet.size()][trainSet.size()];
Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pairA, pairB;
for (int i = 0; i < trainSet.size(); i++) {
pairA = trainSet.get(i);
for (int j = i; j < trainSet.size(); j++) {
pairB = trainSet.get(j);
matrix[i][j] = weightA * matrixA[trainGraphsA.indexOf(pairA.getFirst())][trainGraphsA.indexOf(pairB.getFirst())] +
weightB * matrixB[trainGraphsB.indexOf(pairA.getSecond())][trainGraphsB.indexOf(pairB.getSecond())];
matrix[j][i] = matrix[i][j];
}
}
return matrix;
}
private double[][] combineTestKernels(double[][] matrixA, double[][] matrixB) {
double[][] matrix = new double[testSet.size()][trainSet.size()];
Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pairA, pairB;
for (int i = 0; i < testSet.size(); i++) {
pairA = testSet.get(i);
for (int j = i; j < trainSet.size(); j++) {
pairB = trainSet.get(j);
matrix[i][j] = weightA * matrixA[testGraphsA.indexOf(pairA.getFirst())][trainGraphsA.indexOf(pairB.getFirst())] +
weightB * matrixB[testGraphsB.indexOf(pairA.getSecond())][trainGraphsB.indexOf(pairB.getSecond())];
}
}
return matrix;
}
private void createRandomSubSet(int trainSetSize, int testSetSize, long seed, boolean equalSize) {
List<Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>> allPairs = new ArrayList<Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>>(dataSet.getLabels().keySet());
trainGraphsA = new ArrayList<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>();
trainGraphsB = new ArrayList<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>();
testGraphsA = new ArrayList<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>();
testGraphsB = new ArrayList<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>();
trainSet = new ArrayList<Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>>();
testSet = new ArrayList<Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>>>();
Collections.shuffle(allPairs, new Random(seed));
boolean classLabel = false;
int posClass = 0, testPosClass = 0;
int negClass = 0, testNegClass = 0;
int totalPos = 0;
for (Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>> pair : allPairs) {
if (dataSet.getLabels().get(pair)) {
totalPos++;
}
}
long trainPosSize, trainNegSize;
if (!equalSize) {
trainPosSize = Math.round(((double) totalPos / (double) allPairs.size()) * ((double) trainSetSize));
trainNegSize = Math.round(((double) (allPairs.size() - totalPos) / (double) allPairs.size()) * ((double) trainSetSize));
} else {
trainPosSize = trainSetSize / 2;
trainNegSize = trainSetSize / 2;
}
long testPosSize = Math.round(((double) totalPos / (double) allPairs.size()) * ((double) testSetSize));
long testNegSize = Math.round(((double) (allPairs.size() - totalPos) / (double) allPairs.size()) * ((double) testSetSize));
for (Pair<DirectedMultigraphWithRoot<Vertex<String>,Edge<String>>> pair : allPairs) {
classLabel = dataSet.getLabels().get(pair);
if (classLabel) {
if (posClass < trainPosSize) {
trainSet.add(pair);
posClass++;
if (!trainGraphsA.contains(pair.getFirst())) {
trainGraphsA.add(pair.getFirst());
}
if (!trainGraphsB.contains(pair.getSecond())) {
trainGraphsB.add(pair.getSecond());
}
} else if (testPosClass < testPosSize) {
testSet.add(pair);
testPosClass++;
if (!testGraphsA.contains(pair.getFirst())) {
testGraphsA.add(pair.getFirst());
}
if (!testGraphsB.contains(pair.getSecond())) {
testGraphsB.add(pair.getSecond());
}
}
} else {
if (negClass < trainNegSize) {
trainSet.add(pair);
negClass++;
if (!trainGraphsA.contains(pair.getFirst())) {
trainGraphsA.add(pair.getFirst());
}
if (!trainGraphsB.contains(pair.getSecond())) {
trainGraphsB.add(pair.getSecond());
}
} else if (testNegClass < testNegSize) {
testSet.add(pair);
testNegClass++;
if (!testGraphsA.contains(pair.getFirst())) {
testGraphsA.add(pair.getFirst());
}
if (!testGraphsB.contains(pair.getSecond())) {
testGraphsB.add(pair.getSecond());
}
}
if (posClass == trainPosSize && negClass == trainNegSize && testPosClass == testPosSize && testNegClass == testNegSize) {
break;
}
}
}
}
}
| true | true | public void run() {
double acc = 0, f = 0;
double p5 = 0, p10 = 0, p20 = 0;
double map = 0, rPrec = 0;
double ndcg = 0;
double[] accScores = new double[seeds.length];
double[] fScores = new double[seeds.length];
double[] mapScores = new double[seeds.length];
double[] rPrecScores = new double[seeds.length];
List<String> labels;
for (int i = 0; i < seeds.length; i++) {
createRandomSubSet(100, 100, seeds[i], true);
double[][] matrixA = kernelA.compute(trainGraphsA);
double[][] matrixB = kernelB.compute(trainGraphsB);
double[][] testMatrixA = kernelA.compute(trainGraphsA, testGraphsA);
double[][] testMatrixB = kernelB.compute(trainGraphsB, testGraphsB);
double[][] matrix = combineTrainKernels(matrixA, matrixB);
Collections.shuffle(trainSet, new Random(seeds[i]));
labels = new ArrayList<String>();
for (Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pair : trainSet) {
if (dataSet.getLabels().get(pair)) {
labels.add("true");
} else {
labels.add("false");
}
}
Map<String, Integer> labelMap = new TreeMap<String, Integer>();
labelMap.put("true", -1);
labelMap.put("false", 1);
LibSVMParameters param = new LibSVMParameters(cs, false);
//param.setVerbose(true);
int[] weightLabels = {-1, 1};
double[] weights = {1,1};
param.setWeightLabels(weightLabels);
param.setWeights(weights);
LibSVMModel model = LibSVM.trainSVMModel(matrix, LibSVM.createTargets(labels, labelMap), param);
double[][] testMatrix = combineTestKernels(testMatrixA, testMatrixB);
//double[][] testMatrix = matrix;
labels = new ArrayList<String>();
for (Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pair : testSet) {
if (dataSet.getLabels().get(pair)) {
labels.add("true");
} else {
labels.add("false");
}
}
LibSVMPrediction[] pred = LibSVM.testSVMModel(model, testMatrix);
double[] target = LibSVM.createTargets(labels, labelMap);
/*
int[] ranking = LibSVM.computeRanking(pred);
for (int j = 0; j < 20; j++) {
System.out.print(ranking[j] + "->" + target[ranking[j]] + ", ");
}
System.out.println("");
System.out.println(LibSVM.computeClassCounts(target));
System.out.println(Arrays.toString(pred));
*/
accScores[i] = LibSVM.computeAccuracy(target, LibSVM.extractLabels(pred));
fScores[i] = LibSVM.computeF1(target, LibSVM.extractLabels(pred));
p5 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 5, -1);
p10 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 10, -1);
p20 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 20, -1);
mapScores[i] = LibSVM.computeAveragePrecision(target, LibSVM.computeRanking(pred), -1);
rPrecScores[i] = LibSVM.computeRPrecision(target, LibSVM.computeRanking(pred), -1);
ndcg += LibSVM.computeNDCG(target, LibSVM.computeRanking(pred), target.length, -1);
}
acc = acc / seeds.length;
f = f / seeds.length;
p5 = p5 / seeds.length;
p10 = p10 / seeds.length;
p20 = p20 / seeds.length;
map = map / seeds.length;
rPrec = rPrec / seeds.length;
ndcg = ndcg / seeds.length;
results.setLabel(dataSet.getLabel() + ", Seeds=" + Arrays.toString(seeds) + ", C=" + Arrays.toString(cs) + ", " + kernelA.getLabel() + ", " + kernelB.getLabel());
results.getAccuracy().setLabel("acc");
results.getAccuracy().setScores(accScores);
results.getF1().setLabel("f1");
results.getF1().setScores(fScores);
results.getAveragePrecision().setLabel("map");
results.getAveragePrecision().setScores(mapScores);
results.getrPrecision().setLabel("R-prec");
results.getrPrecision().setScores(rPrecScores);
output.println(dataSet.getLabel());
output.println(kernelA.getLabel() + " " + weightA + " AND " + kernelB.getLabel() + " " + weightB + ", Seeds=" + Arrays.toString(seeds) + ", C=" + Arrays.toString(cs));
output.print("Overall Accuracy: " + acc);
output.print(", Average F1: " + f);
output.print(", Average P5: " + p5);
output.print(", Average P10: " + p10);
output.print(", Average P20: " + p20);
output.print(", Average AP: " + map);
output.print(", Average R-prec: " + rPrec);
output.print(", Average NDCG: " + ndcg);
output.println("");
output.flush();
}
| public void run() {
double acc = 0, f = 0;
double p5 = 0, p10 = 0, p20 = 0;
double map = 0, rPrec = 0;
double ndcg = 0;
double[] accScores = new double[seeds.length];
double[] fScores = new double[seeds.length];
double[] mapScores = new double[seeds.length];
double[] rPrecScores = new double[seeds.length];
List<String> labels;
for (int i = 0; i < seeds.length; i++) {
createRandomSubSet(100, 100, seeds[i], true);
double[][] matrixA = kernelA.compute(trainGraphsA);
double[][] matrixB = kernelB.compute(trainGraphsB);
double[][] testMatrixA = kernelA.compute(trainGraphsA, testGraphsA);
double[][] testMatrixB = kernelB.compute(trainGraphsB, testGraphsB);
double[][] matrix = combineTrainKernels(matrixA, matrixB);
Collections.shuffle(trainSet, new Random(seeds[i]));
labels = new ArrayList<String>();
for (Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pair : trainSet) {
if (dataSet.getLabels().get(pair)) {
labels.add("true");
} else {
labels.add("false");
}
}
Map<String, Integer> labelMap = new TreeMap<String, Integer>();
labelMap.put("true", -1);
labelMap.put("false", 1);
LibSVMParameters param = new LibSVMParameters(cs, false);
//param.setVerbose(true);
int[] weightLabels = {-1, 1};
double[] weights = {1,1};
param.setWeightLabels(weightLabels);
param.setWeights(weights);
LibSVMModel model = LibSVM.trainSVMModel(matrix, LibSVM.createTargets(labels, labelMap), param);
double[][] testMatrix = combineTestKernels(testMatrixA, testMatrixB);
//double[][] testMatrix = matrix;
labels = new ArrayList<String>();
for (Pair<DirectedMultigraphWithRoot<Vertex<String>, Edge<String>>> pair : testSet) {
if (dataSet.getLabels().get(pair)) {
labels.add("true");
} else {
labels.add("false");
}
}
LibSVMPrediction[] pred = LibSVM.testSVMModel(model, testMatrix);
double[] target = LibSVM.createTargets(labels, labelMap);
/*
int[] ranking = LibSVM.computeRanking(pred);
for (int j = 0; j < 20; j++) {
System.out.print(ranking[j] + "->" + target[ranking[j]] + ", ");
}
System.out.println("");
System.out.println(LibSVM.computeClassCounts(target));
System.out.println(Arrays.toString(pred));
*/
accScores[i] = LibSVM.computeAccuracy(target, LibSVM.extractLabels(pred));
fScores[i] = LibSVM.computeF1(target, LibSVM.extractLabels(pred));
p5 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 5, -1);
p10 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 10, -1);
p20 += LibSVM.computePrecisionAt(target, LibSVM.computeRanking(pred), 20, -1);
mapScores[i] = LibSVM.computeAveragePrecision(target, LibSVM.computeRanking(pred), -1);
rPrecScores[i] = LibSVM.computeRPrecision(target, LibSVM.computeRanking(pred), -1);
ndcg += LibSVM.computeNDCG(target, LibSVM.computeRanking(pred), target.length, -1);
}
acc = acc / seeds.length;
f = f / seeds.length;
p5 = p5 / seeds.length;
p10 = p10 / seeds.length;
p20 = p20 / seeds.length;
map = map / seeds.length;
rPrec = rPrec / seeds.length;
ndcg = ndcg / seeds.length;
results.setLabel(dataSet.getLabel() + ", Seeds=" + Arrays.toString(seeds) + ", C=" + Arrays.toString(cs) + ", " + kernelA.getLabel() + ", " + kernelB.getLabel());
results.getAccuracy().setLabel("acc");
results.getAccuracy().setScores(accScores);
results.getF1().setLabel("f1");
results.getF1().setScores(fScores);
results.getAveragePrecision().setLabel("map");
results.getAveragePrecision().setScores(mapScores);
results.getrPrecision().setLabel("Rpr");
results.getrPrecision().setScores(rPrecScores);
output.println(dataSet.getLabel());
output.println(kernelA.getLabel() + " " + weightA + " AND " + kernelB.getLabel() + " " + weightB + ", Seeds=" + Arrays.toString(seeds) + ", C=" + Arrays.toString(cs));
output.print("Overall Accuracy: " + acc);
output.print(", Average F1: " + f);
output.print(", Average P5: " + p5);
output.print(", Average P10: " + p10);
output.print(", Average P20: " + p20);
output.print(", Average AP: " + map);
output.print(", Average R-prec: " + rPrec);
output.print(", Average NDCG: " + ndcg);
output.println("");
output.flush();
}
|
diff --git a/src/main/java/org/mashupmedia/controller/ajax/AjaxSearchController.java b/src/main/java/org/mashupmedia/controller/ajax/AjaxSearchController.java
index c29416e..c1440da 100644
--- a/src/main/java/org/mashupmedia/controller/ajax/AjaxSearchController.java
+++ b/src/main/java/org/mashupmedia/controller/ajax/AjaxSearchController.java
@@ -1,60 +1,60 @@
package org.mashupmedia.controller.ajax;
import java.util.List;
import org.mashupmedia.criteria.MediaItemSearchCriteria;
import org.mashupmedia.exception.PageNotFoundException;
import org.mashupmedia.model.media.MediaItem;
import org.mashupmedia.model.media.MediaItem.MediaType;
import org.mashupmedia.service.MediaManager;
import org.mashupmedia.util.MediaItemHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/ajax/search")
public class AjaxSearchController extends BaseAjaxController {
@Autowired
private MediaManager mediaManager;
@RequestMapping(value = "/media-items-autocomplete", method = RequestMethod.POST)
public String handleMediaItemsAutocomplete(@RequestParam("searchWords") String searchWords, Model model) {
List<String> suggestions = mediaManager.findAutoCompleteMediaItems(searchWords);
model.addAttribute("suggestions", suggestions);
return "ajax/search/suggestions";
}
@RequestMapping(value = "/media-items", method = RequestMethod.POST)
- public String handleMediaItems(@RequestParam(value = "mediaType", required = false) String mediaTypeValue, @RequestParam(value = "page", required = false) Integer pageNumber, @RequestParam("searchWords") String searchWords, Model model) {
+ public String handleMediaItems(@RequestParam(value = "mediaType", required = false) String mediaTypeValue, @RequestParam(value = "pageNumber", required = false) Integer pageNumber, @RequestParam("searchWords") String searchWords, Model model) {
MediaItemSearchCriteria mediaItemSearchCriteria = new MediaItemSearchCriteria();
MediaType mediaType = MediaItemHelper.getMediaType(mediaTypeValue);
if (mediaType == null) {
mediaType = MediaType.SONG;
}
mediaItemSearchCriteria.setMediaType(mediaType);
if (pageNumber == null) {
pageNumber = 0;
}
mediaItemSearchCriteria.setPageNumber(pageNumber);
mediaItemSearchCriteria.setSearchWords(searchWords);
List<MediaItem> mediaItems = mediaManager.findMediaItems(mediaItemSearchCriteria);
if (mediaType == MediaType.SONG) {
model.addAttribute("songs", mediaItems);
return "ajax/search/songs";
}
throw new PageNotFoundException("");
}
}
| true | true | public String handleMediaItems(@RequestParam(value = "mediaType", required = false) String mediaTypeValue, @RequestParam(value = "page", required = false) Integer pageNumber, @RequestParam("searchWords") String searchWords, Model model) {
MediaItemSearchCriteria mediaItemSearchCriteria = new MediaItemSearchCriteria();
MediaType mediaType = MediaItemHelper.getMediaType(mediaTypeValue);
if (mediaType == null) {
mediaType = MediaType.SONG;
}
mediaItemSearchCriteria.setMediaType(mediaType);
if (pageNumber == null) {
pageNumber = 0;
}
mediaItemSearchCriteria.setPageNumber(pageNumber);
mediaItemSearchCriteria.setSearchWords(searchWords);
List<MediaItem> mediaItems = mediaManager.findMediaItems(mediaItemSearchCriteria);
if (mediaType == MediaType.SONG) {
model.addAttribute("songs", mediaItems);
return "ajax/search/songs";
}
throw new PageNotFoundException("");
}
| public String handleMediaItems(@RequestParam(value = "mediaType", required = false) String mediaTypeValue, @RequestParam(value = "pageNumber", required = false) Integer pageNumber, @RequestParam("searchWords") String searchWords, Model model) {
MediaItemSearchCriteria mediaItemSearchCriteria = new MediaItemSearchCriteria();
MediaType mediaType = MediaItemHelper.getMediaType(mediaTypeValue);
if (mediaType == null) {
mediaType = MediaType.SONG;
}
mediaItemSearchCriteria.setMediaType(mediaType);
if (pageNumber == null) {
pageNumber = 0;
}
mediaItemSearchCriteria.setPageNumber(pageNumber);
mediaItemSearchCriteria.setSearchWords(searchWords);
List<MediaItem> mediaItems = mediaManager.findMediaItems(mediaItemSearchCriteria);
if (mediaType == MediaType.SONG) {
model.addAttribute("songs", mediaItems);
return "ajax/search/songs";
}
throw new PageNotFoundException("");
}
|
diff --git a/src/main/java/hudson/plugins/clearcase/ClearToolExec.java b/src/main/java/hudson/plugins/clearcase/ClearToolExec.java
index 91c0d27..3feef71 100755
--- a/src/main/java/hudson/plugins/clearcase/ClearToolExec.java
+++ b/src/main/java/hudson/plugins/clearcase/ClearToolExec.java
@@ -1,181 +1,181 @@
package hudson.plugins.clearcase;
import hudson.AbortException;
import hudson.FilePath;
import hudson.util.ArgumentListBuilder;
import hudson.util.IOException2;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ClearToolExec implements ClearTool {
private Pattern viewListPattern;
private String clearToolExec;
public ClearToolExec(String clearToolExec) {
this.clearToolExec = clearToolExec;
}
public void mkview(ClearToolLauncher launcher, String viewName) throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("mkview");
cmd.add("-snapshot");
cmd.add("-tag");
cmd.add(viewName);
cmd.add(viewName);
launcher.run(cmd.toCommandArray(), null, null, null);
}
public void setcs(ClearToolLauncher launcher, String viewName, String configSpec) throws IOException, InterruptedException {
FilePath configSpecFile = launcher.getWorkspace().createTextTempFile("configspec", ".txt", configSpec);
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("setcs");
cmd.add(".." + File.separatorChar + configSpecFile.getName());
launcher.run(cmd.toCommandArray(), null, null, viewName);
configSpecFile.delete();
}
public void rmview(ClearToolLauncher launcher, String viewName) throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("rmview");
cmd.add("-force");
cmd.add(viewName);
launcher.run(cmd.toCommandArray(), null, null, null);
FilePath viewFilePath = launcher.getWorkspace().child(viewName);
if (viewFilePath.exists()) {
launcher.getListener().getLogger().println("Removing view folder as it was not removed when the view was removed.");
viewFilePath.deleteRecursive();
}
}
public void update(ClearToolLauncher launcher, String viewName) throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("update");
cmd.add("-force");
cmd.add("-log", "NUL");
cmd.add(viewName);
launcher.run(cmd.toCommandArray(), null, null, null);
}
public List<ClearCaseChangeLogEntry> lshistory(ClearToolLauncher launcher, Date lastBuildDate, String viewName, String branch) throws IOException,
InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM.HH:mm:ss");
FilePath viewPath = launcher.getWorkspace().child(viewName);
String[] vobNames = null;
List<FilePath> subFilePaths = viewPath.list((FileFilter) null);
if ((subFilePaths != null) && (subFilePaths.size() > 0)) {
vobNames = new String[subFilePaths.size()];
for (int i = 0; i < subFilePaths.size(); i++) {
if (subFilePaths.get(i).isDirectory()) {
vobNames[i] = subFilePaths.get(i).getName();
}
}
}
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("lshistory");
cmd.add("-r");
- cmd.add("-since", formatter.format(lastBuildDate));
+ cmd.add("-since", formatter.format(lastBuildDate).toLowerCase());
cmd.add("-fmt", ClearToolHistoryParser.getLogFormat());
if ((branch != null) && (branch.length() > 0)) {
cmd.add("-branch", branch);
}
cmd.add("-nco");
if (vobNames != null) {
cmd.add(vobNames);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, viewName)) {
try {
ClearToolHistoryParser parser = new ClearToolHistoryParser();
return parser.parse(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
} catch (ParseException pe) {
throw new IOException2("There was a problem parsing the history log.", pe);
}
}
return new ArrayList<ClearCaseChangeLogEntry>();
}
public void mklabel(ClearToolLauncher launcher, String viewName, String label) throws IOException, InterruptedException {
throw new AbortException();
}
public List<String> lsview(ClearToolLauncher launcher, boolean onlyActiveDynamicViews) throws IOException, InterruptedException {
viewListPattern = getListPattern();
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("lsview");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, null)) {
return parseListOutput(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())), onlyActiveDynamicViews);
}
return new ArrayList<String>();
}
public List<String> lsvob(ClearToolLauncher launcher, boolean onlyMOunted) throws IOException, InterruptedException {
viewListPattern = getListPattern();
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("lsvob");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, null)) {
return parseListOutput(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())), onlyMOunted);
}
return new ArrayList<String>();
}
private List<String> parseListOutput(Reader consoleReader, boolean onlyStarMarked) throws IOException {
List<String> views = new ArrayList<String>();
BufferedReader reader = new BufferedReader(consoleReader);
String line = reader.readLine();
while (line != null) {
Matcher matcher = viewListPattern.matcher(line);
if (matcher.find() && matcher.groupCount() == 3) {
if ((!onlyStarMarked) ||
(onlyStarMarked && matcher.group(1).equals("*")) ) {
String vob = matcher.group(2);
int pos = Math.max(vob.lastIndexOf('\\'), vob.lastIndexOf('/'));
if (pos != -1) {
vob = vob.substring(pos + 1);
}
views.add(vob);
}
}
line = reader.readLine();
}
reader.close();
return views;
}
private Pattern getListPattern() {
if (viewListPattern == null) {
viewListPattern = Pattern.compile("(.)\\s*(\\S*)\\s*(\\S*)");
}
return viewListPattern;
}
}
| true | true | public List<ClearCaseChangeLogEntry> lshistory(ClearToolLauncher launcher, Date lastBuildDate, String viewName, String branch) throws IOException,
InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM.HH:mm:ss");
FilePath viewPath = launcher.getWorkspace().child(viewName);
String[] vobNames = null;
List<FilePath> subFilePaths = viewPath.list((FileFilter) null);
if ((subFilePaths != null) && (subFilePaths.size() > 0)) {
vobNames = new String[subFilePaths.size()];
for (int i = 0; i < subFilePaths.size(); i++) {
if (subFilePaths.get(i).isDirectory()) {
vobNames[i] = subFilePaths.get(i).getName();
}
}
}
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("lshistory");
cmd.add("-r");
cmd.add("-since", formatter.format(lastBuildDate));
cmd.add("-fmt", ClearToolHistoryParser.getLogFormat());
if ((branch != null) && (branch.length() > 0)) {
cmd.add("-branch", branch);
}
cmd.add("-nco");
if (vobNames != null) {
cmd.add(vobNames);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, viewName)) {
try {
ClearToolHistoryParser parser = new ClearToolHistoryParser();
return parser.parse(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
} catch (ParseException pe) {
throw new IOException2("There was a problem parsing the history log.", pe);
}
}
return new ArrayList<ClearCaseChangeLogEntry>();
}
| public List<ClearCaseChangeLogEntry> lshistory(ClearToolLauncher launcher, Date lastBuildDate, String viewName, String branch) throws IOException,
InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM.HH:mm:ss");
FilePath viewPath = launcher.getWorkspace().child(viewName);
String[] vobNames = null;
List<FilePath> subFilePaths = viewPath.list((FileFilter) null);
if ((subFilePaths != null) && (subFilePaths.size() > 0)) {
vobNames = new String[subFilePaths.size()];
for (int i = 0; i < subFilePaths.size(); i++) {
if (subFilePaths.get(i).isDirectory()) {
vobNames[i] = subFilePaths.get(i).getName();
}
}
}
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add(clearToolExec);
cmd.add("lshistory");
cmd.add("-r");
cmd.add("-since", formatter.format(lastBuildDate).toLowerCase());
cmd.add("-fmt", ClearToolHistoryParser.getLogFormat());
if ((branch != null) && (branch.length() > 0)) {
cmd.add("-branch", branch);
}
cmd.add("-nco");
if (vobNames != null) {
cmd.add(vobNames);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, viewName)) {
try {
ClearToolHistoryParser parser = new ClearToolHistoryParser();
return parser.parse(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
} catch (ParseException pe) {
throw new IOException2("There was a problem parsing the history log.", pe);
}
}
return new ArrayList<ClearCaseChangeLogEntry>();
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/FeedProcessor.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/FeedProcessor.java
index 4ade93045..d92f9a7a1 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/FeedProcessor.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/FeedProcessor.java
@@ -1,119 +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.shindig.gadgets;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndPerson;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.StringReader;
import java.util.List;
/**
* Processes RSS & Atom Feeds and converts them into JSON output.
*/
public class FeedProcessor {
/**
* Converts feed XML to JSON.
*
* @param feedUrl The url that the feed was retrieved from.
* @param feedXml The raw XML of the feed to be converted.
* @param getSummaries True if summaries should be returned.
* @param numEntries Number of entries to return.
* @return The JSON representation of the feed.
*/
@SuppressWarnings("unchecked")
public JSONObject process(String feedUrl, String feedXml,
boolean getSummaries, int numEntries) throws GadgetException {
try {
SyndFeed feed = new SyndFeedInput().build(new StringReader(feedXml));
JSONObject json = new JSONObject();
json.put("Title", feed.getTitle());
json.put("URL", feedUrl);
json.put("Description", feed.getDescription());
json.put("Link", feed.getLink());
List<SyndPerson> authors = feed.getAuthors();
String jsonAuthor = null;
if (authors != null && !authors.isEmpty()) {
SyndPerson author = authors.get(0);
if (author.getName() != null) {
jsonAuthor = author.getName();
} else if (author.getEmail() != null) {
jsonAuthor = author.getEmail();
}
}
JSONArray entries = new JSONArray();
json.put("Entry", entries);
int entryCnt = 0;
for (Object obj : feed.getEntries()) {
SyndEntry e = (SyndEntry) obj;
if (entryCnt >= numEntries) {
break;
}
entryCnt++;
JSONObject entry = new JSONObject();
entry.put("Title", e.getTitle());
entry.put("Link", e.getLink());
if (getSummaries) {
if (e.getContents() != null && !e.getContents().isEmpty()) {
entry.put("Summary",
((SyndContent)e.getContents().get(0)).getValue());
} else {
entry.put("Summary",
e.getDescription() != null ? e.getDescription().getValue() : "");
}
}
if (e.getUpdatedDate() != null) {
entry.put("Date", e.getUpdatedDate().getTime());
} else if (e.getPublishedDate() != null) {
entry.put("Date", e.getPublishedDate().getTime());
} else {
entry.put("Date", 0);
}
// if no author at feed level, use the first entry author
if (jsonAuthor == null) {
jsonAuthor = e.getAuthor();
}
entries.put(entry);
}
json.put("Author", (jsonAuthor != null) ? jsonAuthor : "");
return json;
} catch (JSONException e) {
// This shouldn't ever happen.
throw new RuntimeException(e);
} catch (FeedException e) {
throw new GadgetException(GadgetException.Code.MALFORMED_XML_DOCUMENT, e);
+ } catch (IllegalArgumentException e) {
+ throw new GadgetException(GadgetException.Code.MALFORMED_XML_DOCUMENT, e);
}
}
}
| true | true | public JSONObject process(String feedUrl, String feedXml,
boolean getSummaries, int numEntries) throws GadgetException {
try {
SyndFeed feed = new SyndFeedInput().build(new StringReader(feedXml));
JSONObject json = new JSONObject();
json.put("Title", feed.getTitle());
json.put("URL", feedUrl);
json.put("Description", feed.getDescription());
json.put("Link", feed.getLink());
List<SyndPerson> authors = feed.getAuthors();
String jsonAuthor = null;
if (authors != null && !authors.isEmpty()) {
SyndPerson author = authors.get(0);
if (author.getName() != null) {
jsonAuthor = author.getName();
} else if (author.getEmail() != null) {
jsonAuthor = author.getEmail();
}
}
JSONArray entries = new JSONArray();
json.put("Entry", entries);
int entryCnt = 0;
for (Object obj : feed.getEntries()) {
SyndEntry e = (SyndEntry) obj;
if (entryCnt >= numEntries) {
break;
}
entryCnt++;
JSONObject entry = new JSONObject();
entry.put("Title", e.getTitle());
entry.put("Link", e.getLink());
if (getSummaries) {
if (e.getContents() != null && !e.getContents().isEmpty()) {
entry.put("Summary",
((SyndContent)e.getContents().get(0)).getValue());
} else {
entry.put("Summary",
e.getDescription() != null ? e.getDescription().getValue() : "");
}
}
if (e.getUpdatedDate() != null) {
entry.put("Date", e.getUpdatedDate().getTime());
} else if (e.getPublishedDate() != null) {
entry.put("Date", e.getPublishedDate().getTime());
} else {
entry.put("Date", 0);
}
// if no author at feed level, use the first entry author
if (jsonAuthor == null) {
jsonAuthor = e.getAuthor();
}
entries.put(entry);
}
json.put("Author", (jsonAuthor != null) ? jsonAuthor : "");
return json;
} catch (JSONException e) {
// This shouldn't ever happen.
throw new RuntimeException(e);
} catch (FeedException e) {
throw new GadgetException(GadgetException.Code.MALFORMED_XML_DOCUMENT, e);
}
}
| public JSONObject process(String feedUrl, String feedXml,
boolean getSummaries, int numEntries) throws GadgetException {
try {
SyndFeed feed = new SyndFeedInput().build(new StringReader(feedXml));
JSONObject json = new JSONObject();
json.put("Title", feed.getTitle());
json.put("URL", feedUrl);
json.put("Description", feed.getDescription());
json.put("Link", feed.getLink());
List<SyndPerson> authors = feed.getAuthors();
String jsonAuthor = null;
if (authors != null && !authors.isEmpty()) {
SyndPerson author = authors.get(0);
if (author.getName() != null) {
jsonAuthor = author.getName();
} else if (author.getEmail() != null) {
jsonAuthor = author.getEmail();
}
}
JSONArray entries = new JSONArray();
json.put("Entry", entries);
int entryCnt = 0;
for (Object obj : feed.getEntries()) {
SyndEntry e = (SyndEntry) obj;
if (entryCnt >= numEntries) {
break;
}
entryCnt++;
JSONObject entry = new JSONObject();
entry.put("Title", e.getTitle());
entry.put("Link", e.getLink());
if (getSummaries) {
if (e.getContents() != null && !e.getContents().isEmpty()) {
entry.put("Summary",
((SyndContent)e.getContents().get(0)).getValue());
} else {
entry.put("Summary",
e.getDescription() != null ? e.getDescription().getValue() : "");
}
}
if (e.getUpdatedDate() != null) {
entry.put("Date", e.getUpdatedDate().getTime());
} else if (e.getPublishedDate() != null) {
entry.put("Date", e.getPublishedDate().getTime());
} else {
entry.put("Date", 0);
}
// if no author at feed level, use the first entry author
if (jsonAuthor == null) {
jsonAuthor = e.getAuthor();
}
entries.put(entry);
}
json.put("Author", (jsonAuthor != null) ? jsonAuthor : "");
return json;
} catch (JSONException e) {
// This shouldn't ever happen.
throw new RuntimeException(e);
} catch (FeedException e) {
throw new GadgetException(GadgetException.Code.MALFORMED_XML_DOCUMENT, e);
} catch (IllegalArgumentException e) {
throw new GadgetException(GadgetException.Code.MALFORMED_XML_DOCUMENT, e);
}
}
|
diff --git a/core/src/visad/data/text/TextAdapter.java b/core/src/visad/data/text/TextAdapter.java
index a3391eb28..58442fed8 100644
--- a/core/src/visad/data/text/TextAdapter.java
+++ b/core/src/visad/data/text/TextAdapter.java
@@ -1,1845 +1,1846 @@
//
// TextAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2009 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
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
*/
package visad.data.text;
import java.io.IOException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import visad.Set;
import java.net.URL;
import visad.*;
import visad.VisADException;
import visad.data.in.ArithProg;
import visad.util.DataUtility;
import java.util.regex.*;
/** this is an VisAD file adapter for comma-, tab- and blank-separated
* ASCII text file data. It will attempt to create a FlatField from
* the data and descriptions given in the file and/or the constructor.
*
* The text files contained delimited data. The delimiter is
* determined as follows: if the file has a well-known extension
* (.csv, .tsv, .bsv) then the delimiter is implied by the extension.
* In all other cases, the delimiter for the data (and for the
* "column labels") is determined by reading the first line and
* looking, in order, for a tab, comma, or blank. Which ever one
* is found first is taken as the delimiter.
*
* Two extra pieces of information are needed: the VisAD "MathType"
* which is specified as a string (e.g., (x,y)->(temperature))
* and may either be the first line of the file or passed in through
* one of the constructors.
*
* The second item are the "column labels" which contain the names
* of each field in the data. The names of all range components
* specified in the "MathType" must appear. The names of domain
* components are optional. The values in this string are separated
* by the delimiter, as defined above.
*
* See visad.data.text.README.text for more details.
*
* @author Tom Whittaker
*
*/
public class TextAdapter {
private static final String ATTR_COLSPAN = "colspan";
private static final String ATTR_VALUE = "value";
private static final String ATTR_OFFSET = "off";
private static final String ATTR_ERROR = "err";
private static final String ATTR_SCALE = "sca";
private static final String ATTR_POSITION ="pos";
private static final String ATTR_FORMAT = "fmt";
private static final String ATTR_TIMEZONE = "tz";
private static final String ATTR_UNIT= "unit";
private static final String ATTR_MISSING = "mis";
private static final String ATTR_INTERVAL = "int";
private static final String COMMA = ",";
private static final String SEMICOLON = ";";
private static final String TAB = "\t";
private static final String BLANK = " ";
private static final String BLANK_DELIM = "\\s+";
private FlatField ff = null;
private Field field = null;
private boolean debug = false;
private String DELIM;
private boolean DOQUOTE = true;
private boolean GOTTIME = false;
HeaderInfo []infos;
double[] rangeErrorEstimates;
Unit[] rangeUnits;
Set[] rangeSets;
double[] domainErrorEstimates;
Unit[] domainUnits;
int[][] hdrColumns;
int[][] values_to_index;
private Hashtable properties;
private boolean onlyReadOneLine = false;
private Pattern skipPattern;
/**If this is defined then when processing each tuple pass the processor the tuple
and do not try to create the field */
private StreamProcessor streamProcessor;
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename) throws IOException, VisADException {
this(filename, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename, String map, String params)
throws IOException, VisADException {
InputStream is = new FileInputStream(filename);
DELIM = getDelimiter(filename);
readit(is, map, params);
}
/** Create a VisAD FlatField from a remote Text (comma-, tab- or
* blank-separated values) ASCII file
*
* @param url File URL.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url) throws IOException, VisADException {
this(url, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param url File URL.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url, String map, String params)
throws IOException, VisADException {
DELIM = getDelimiter(url.getFile());
InputStream is = url.openStream();
readit(is, map, params);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params)
throws IOException, VisADException {
this(inputStream, delimiter, map,params,false);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,boolean onlyReadOneLine)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, null, onlyReadOneLine);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param properties properties
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, properties, onlyReadOneLine, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param properties properties
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @param skipPatternString if non-null then skip any line that matches this pattern
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine,String skipPatternString)
throws IOException, VisADException {
this(inputStream, delimiter, map, params, properties, onlyReadOneLine, skipPatternString,null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param properties properties
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @param skipPatternString if non-null then skip any line that matches this pattern
* @param streamProcessor Optional processor of the Tuple stream for point obs
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,Hashtable properties, boolean onlyReadOneLine,String skipPatternString,StreamProcessor streamProcessor)
throws IOException, VisADException {
this.onlyReadOneLine = onlyReadOneLine;
this.streamProcessor = streamProcessor;
DELIM = delimiter;
this.properties = properties;
if(skipPatternString!=null && skipPatternString.length()>0) {
skipPattern = Pattern.compile(skipPatternString);
}
readit(inputStream, map, params);
}
public static String getDelimiter(String filename) {
if(filename == null) return null;
filename = filename.trim().toLowerCase();
if (filename.endsWith(".csv")) return COMMA;
if (filename.endsWith(".tsv")) return TAB;
if (filename.endsWith(".bsv")) return BLANK;
return null;
}
/**
* Is the given text line a comment
*
* @return is it a comment line
*/
public static boolean isComment(String line) {
return (line.startsWith("#") ||
line.startsWith("!") ||
line.startsWith("%") ||
line.length() < 1);
}
public static String readLine(BufferedReader bis)
throws IOException {
while (true) {
String line = bis.readLine();
if (line == null) return null;
if (!isText(line)) return null;
if (isComment(line)) continue;
return line.trim();
}
}
void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
List<String[]>nameChanges = new ArrayList<String[]>();
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
// squeeze out extra blank spaces
if (hdrDelim.equals(BLANK) || hdrDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
hdr = hdr.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] sthdr = hdr.split(hdrDelim);
// since blanks separate the metadata, if we have a blank
// delimiter, we run into problems. Loop through the header and
// put humpty dumpty back together again
if (hdrDelim.equals(BLANK_DELIM) || hdrDelim.equals(BLANK)) {
List<String> chunks = new ArrayList<String>();
for (int i = 0; i < sthdr.length; i++) {
String subchunk = sthdr[i].trim();
int m = subchunk.indexOf("[");
if (m == -1) {
chunks.add(subchunk);
continue;
}
// have "[", find "]"
int m2 = subchunk.indexOf("]");
while (m2 < 0 && i < sthdr.length) {
i++;
subchunk += " " +sthdr[i].trim();
m2 = subchunk.indexOf("]");
}
chunks.add(subchunk);
}
sthdr = (String[]) chunks.toArray(new String[chunks.size()]);
}
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 0. Remove any spaces around the "=" signs
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
// 0. Remove any spaces around the "=" signs
String cl = name.substring(m+1,m2).trim();
cl = cl.replaceAll(" +=","=");
cl = cl.replaceAll("= +","=");
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit hdrUnit = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
hdrUnitString = hdrUnitString.trim();
try {
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue) {
try {
hdrUnitString = hdrUnitString.replace(' ','_');
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
hdrUnit = null;
}
}
if(hdrUnit!=null) {
//We clone this unit so it has the original unit string, not the SI unit we get from the parser
try {
hdrUnit = hdrUnit.clone(hdrUnitString);
} catch(Exception ignoreThis) {}
}
}
if (debug) System.out.println("#### assigned Unit as u="+hdrUnit);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, hdrUnit, null, infos[i].isInterval);
// System.err.println("rtname:" + rtname + " " + rt);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (debug && hdrUnit != null)
System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
//Make the realType with just the name
rt = RealType.getRealType(rtname);
//Check if the realtype unit works with the unit from the header
if(rt.getDefaultUnit()!=null && hdrUnit!=null) {
if(!Unit.canConvert(rt.getDefaultUnit(), hdrUnit)) {
rt = null;
}
} else if(hdrUnit!=null) {
rt = null;
}
//If the realtype is bad then we make a new one with the unitsuffix and add
//a name change entry so later we change the mathtype string to have the new name
if(rt == null) {
rt = DataUtility.getUniqueRealType(rtname,hdrUnit, null, infos[i].isInterval);
if (rt != null) {
String newName = rt.getName();
nameChanges.add(new String[]{rtname, newName});
infos[i].name = newName;
if(debug)
System.out.println("made new realtype:" + rt + " unit:" + rt.getDefaultUnit());
}
}
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (hdrUnit == null) hdrUnit = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+hdrUnit);
}
infos[i].unit = hdrUnit;
}
for(String[] tuple: nameChanges) {
if(debug) System.err.println ("changing mathtype component from:" + tuple[0] +" to:" + tuple[1]);
maps = maps.replaceAll("(,|\\() *" + tuple[0]+" *(,|\\))", "$1" + tuple[1]+"$2");
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
mte.printStackTrace();
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
//Note, we need to have a reference to the realTypes list somewhere
//after the above call to stringToType so that the list doesn't get gc'ed
//and the realtypes it contains don't get gc'ed
if(realTypes.size()==0) {
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rangeType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
// debug =true;
rangeType = (TupleType) ((FunctionType)mt).getRange();
numRng = rangeType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rangeType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
Real[] prototypeReals = new Real[nhdr];
TupleType tupleType = null;
int index;
int lineCnt = 0;
while (true) {
String line = readLine(bis);
if (debug) System.out.println("read:"+line);
if (line == null) break;
if(skipPattern!=null && skipPattern.matcher(line).find()) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
// squeeze out extra blank spaces
if (dataDelim.equals(BLANK) || dataDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
line = line.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] tokens = line.split(dataDelim);
int n = tokens.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = null;
double [] rValues = null;
Data [] dataArray= null;
if (streamProcessor==null) {
dValues = new double[numDom];
}
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = tokens[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
dataArray = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
if (streamProcessor==null) {
rValues = new double[numRng];
}
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int tokenIdx = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (tokenIdx >= tokens.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = tokens[tokenIdx++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + tokens[tokenIdx++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
if(dValues!=null)
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
int tupleIndex = values_to_index[1][i];
+ int infosIndex = values_to_index[2][i];
thisMT = rangeType.getComponent(tupleIndex);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=tokenIdx; q < tokens.length; q++) {
String saTmp = tokens[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
tokenIdx++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//tokens[tokenIdx] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
dataArray[tupleIndex] =
new Text((TextType)thisMT, sThisText);
if (debug) System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
// if(true) continue;
double value = getVal(sa,i);
if(rValues!=null)
rValues[tupleIndex] = value;
try {
if(prototypeReals[i]==null) {
- prototypeReals[i] = new Real((RealType) thisMT, value, infos[i].unit);
+ prototypeReals[i] = new Real((RealType) thisMT, value, infos[infosIndex].unit);
}
dataArray[tupleIndex] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
e.printStackTrace();
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (dataArray != null) {
if (streamProcessor!=null) {
streamProcessor.processValues(dataArray);
} else {
if(tupleType == null) {
tuple = new Tuple(dataArray);
tupleType = (TupleType)tuple.getType();
} else {
tuple = new Tuple(tupleType, dataArray, false, false);
}
}
}
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(dataArray);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<dataArray.length;i++) {
if(dataArray[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
if (streamProcessor==null) {
if(dValues!=null)
domainValues.add(dValues);
if(rValues!=null)
rangeValues.add(rValues);
if (tuple != null)
tupleValues.add(tuple);
}
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
if (streamProcessor!=null) {
bis.close();
return;
}
int numSamples = rangeValues.size(); // # lines of data
if (numSamples == 0) {
throw new VisADException("No data available to read");
}
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
// munges a pseudo MathType string into something legal
private String makeMT(String s) {
int k = s.indexOf("->");
if (k < 0) {
// System.out.println("TextAdapter: invalid MathType form; -> required");
return null;
}
StringBuffer sb = new StringBuffer("");
for (int i=0; i<s.length(); i++) {
String r = s.substring(i,i+1);
if (!r.equals(" ") && !r.equals("\t") && !r.equals("\n")) {
sb.append(r);
}
}
String t = sb.toString();
k = t.indexOf("->");
if (t.charAt(k-1) != ')' ) {
if (t.charAt(k+2) != '(' ) {
String t2 = "("+t.substring(0,k) + ")->("+t.substring(k+2)+")";
t = t2;
} else {
String t2 = "("+t.substring(0,k) + ")"+t.substring(k);
t = t2;
}
} else if (t.charAt(k+2) != '(' ) {
String t2 = t.substring(0,k+2)+"("+t.substring(k+2)+")";
t = t2;
}
if (!t.startsWith("((") ) {
String t2= "("+t+")";
t = t2;
}
return t;
}
private static final boolean isText(String s)
{
final int len = (s == null ? -1 : s.length());
if (len <= 0) {
// well, it's not really *binary*, so pretend it's text
return true;
}
for (int i = 0; i < len; i++) {
final char ch = s.charAt(i);
if (Character.isISOControl(ch) && !Character.isWhitespace(ch)) {
// we might want to special-case formfeed/linefeed/newline here...
return false;
}
}
return true;
}
/**
* generate a DateTime from a string
* @param string - Formatted date/time string
*
* @return - the equivalent VisAD DateTime for the string
*
* (lifted from au.gov.bom.aifs.common.ada.VisADXMLAdapter.java)
*/
private static visad.DateTime makeDateTimeFromString(String string,
String format, String tz)
throws java.text.ParseException
{
visad.DateTime dt = null;
// try to parse the string using the supplied DateTime format
try {
if(dateParsers!=null) {
for(int i=0;i<dateParsers.size();i++) {
DateParser dateParser = (DateParser) dateParsers.get(i);
dt = dateParser.createDateTime(string, format, TimeZone.getTimeZone(tz));
if(dt !=null) {
return dt;
}
}
}
String key = format+"__" + tz;
SimpleDateFormat sdf = (SimpleDateFormat) formats.get(key);
if(sdf == null) {
sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone(tz));
sdf.applyPattern(format);
formats.put(key,sdf);
}
Date d = sdf.parse(string);
dt = new DateTime(d);
// dt = visad.DateTime.createDateTime(string, format, TimeZone.getTimeZone(tz));
} catch (VisADException e) {}
if (dt==null) {
throw new java.text.ParseException("Couldn't parse visad.DateTime from \""
+string+"\"", -1);
} else {
return dt;
}
}
/** A set of cached simpledateformats */
private static Hashtable formats = new Hashtable();
/** This list of DateFormatter-s will be checked when we are making a DateTime wiht a given format */
private static List dateParsers;
/** used to allow applications to define their own date parsing */
public static interface DateParser {
/** If this particular DateParser does not know how to handle the give format then this method should return null */
public DateTime createDateTime(String value, String format, TimeZone timezone) throws VisADException;
}
/** used to allow applications to define their own date parsing */
public static void addDateParser(DateParser dateParser) {
if(dateParsers==null) {
dateParsers = new ArrayList();
}
dateParsers.add(dateParser);
}
double getVal(String s, int k) {
int i = values_to_index[2][k];
if (i < 0 || s == null || s.length()<1 || (infos[i].missingString!=null && s.equals(infos[i].missingString))) {
return Double.NaN;
}
HeaderInfo info = infos[i];
// try parsing as a double first
if (info.formatString == null) {
// no format provided : parse as a double
try {
double v;
try {
v = Double.parseDouble(s);
} catch (java.lang.NumberFormatException nfe1) {
//If units are degrees then try to decode this as a lat/lon
// We should probably not rely on throwing an exception to handle this but...
if(info.unit !=null && Unit.canConvert(info.unit, visad.CommonUnit.degree)) {
v=decodeLatLon(s);
} else {
throw nfe1;
}
if(v!=v) throw new java.lang.NumberFormatException(s);
}
if (v == info.missingValue) {
return Double.NaN;
}
v = v * info.scale + info.offset;
return v;
} catch (java.lang.NumberFormatException ne) {
System.out.println("Invalid number format for "+s);
}
} else {
// a format was specified: only support DateTime format
// so try to parse as a DateTime
try{
visad.DateTime dt = makeDateTimeFromString(s, info.formatString, info.tzString);
return dt.getReal().getValue();
} catch (java.text.ParseException pe) {
System.out.println("Invalid number/time format for "+s);
}
}
return Double.NaN;
}
// get the samples from the ArrayList.
float[][] getDomSamples(int comp, int numDomValues, ArrayList domValues) {
float [][] a = new float[1][numDomValues];
for (int i=0; i<numDomValues; i++) {
double[] d = (double[])(domValues.get(i));
a[0][i] = (float)d[comp];
}
return a;
}
/** get the data
* @return a Field of the data read from the file
*
*/
public Field getData() {
return field;
}
/**
* Returns an appropriate 1D domain.
*
* @param type the math-type of the domain
* @param numSamples the number of samples in the domain
* @param domValues domain values are extracted from this array list.
*
* @return a Linear1DSet if the domain samples form an arithmetic
* progression, a Gridded1DDoubleSet if the domain samples are ordered
* but do not form an arithmetic progression, otherwise an Irregular1DSet.
*
* @throws VisADException there was a problem creating the domain set.
*/
private Set createAppropriate1DDomain(MathType type, int numSamples,
ArrayList domValues)
throws VisADException {
if (0 == numSamples) {
// Can't create a domain set with zero samples.
return null;
}
// Extract the first element from each element of the array list.
double[][] values = new double[1][numSamples];
for (int i=0; i<numSamples; ++i) {
double[] d = (double []) domValues.get(i);
values[0][i] = d[0];
}
// This implementation for testing that the values are ordered
// is based on visad.Gridded1DDoubleSet.java
boolean ordered = true;
boolean ascending = values[0][numSamples -1] > values[0][0];
if (ascending) {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] < values[0][i - 1]) {
ordered = false;
break;
}
}
} else {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] > values[0][i - 1]) {
ordered = false;
break;
}
}
}
Set set = null;
if (ordered) {
ArithProg arithProg = new ArithProg();
if (arithProg.accumulate(values[0])) {
// The domain values form an arithmetic progression (ordered and
// equally spaced) so use a linear set.
set = new Linear1DSet(type, values[0][0], values[0][numSamples - 1],
numSamples);
} else {
// The samples are ordered, so use a gridded set.
set = new Gridded1DDoubleSet(type, values, numSamples);
}
} else {
set = new Irregular1DSet(type, Set.doubleToFloat(values));
}
return set;
}
private static class HeaderInfo {
String name;
Unit unit;
double missingValue = Double.NaN;
String missingString;
String formatString;
String tzString = "GMT";
int isInterval = 0;
double errorEstimate=0;
double scale=1.0;
double offset=0.0;
String fixedValue;
int colspan = 1;
boolean isText = false;
public boolean isParam(String param) {
return name.equals(param) || name.equals(param+"(Text)");
}
public String toString() {
return name;
}
}
/**
* Read in the given file and return the processed data
*
* @param file The file to read in
* @return the data
*/
public static Data processFile(String file) throws Exception {
TextAdapter ta = new TextAdapter(file);
System.out.println(ta.getData().getType());
return ta.getData();
}
// uncomment to test
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Must supply a filename");
System.exit(1);
}
TextAdapter ta = new TextAdapter(args[0]);
System.out.println(ta.getData().getType());
new visad.jmet.DumpType().dumpMathType(ta.getData().getType(),System.out);
new visad.jmet.DumpType().dumpDataType(ta.getData(),System.out);
System.out.println("#### Data = "+ta.getData());
System.out.println("EOF... ");
}
/**
* A cut-and-paste from the IDV Misc method
* Decodes a string representation of a latitude or longitude and
* returns a double version (in degrees). Acceptible formats are:
* <pre>
* +/- ddd:mm, ddd:mm:, ddd:mm:ss, ddd::ss, ddd.fffff ===> [+/-] ddd.fffff
* +/- ddd, ddd:, ddd:: ===> [+/-] ddd
* +/- :mm, :mm:, :mm:ss, ::ss, .fffff ===> [+/-] .fffff
* +/- :, :: ===> 0.0
* Any of the above with N,S,E,W appended
* </pre>
*
* @param latlon string representation of lat or lon
* @return the decoded value in degrees
*/
public static double decodeLatLon(String latlon) {
// first check to see if there is a N,S,E,or W on this
latlon = latlon.trim();
int dirIndex = -1;
int southOrWest = 1;
double value = Double.NaN;
if (latlon.indexOf("S") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("S");
} else if (latlon.indexOf("W") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("W");
} else if (latlon.indexOf("N") > 0) {
dirIndex = latlon.indexOf("N");
} else if (latlon.indexOf("E") > 0) {
dirIndex = latlon.indexOf("E");
}
if (dirIndex > 0) {
latlon = latlon.substring(0, dirIndex).trim();
}
// now see if this is a negative value
if (latlon.indexOf("-") == 0) {
southOrWest *= -1;
latlon = latlon.substring(latlon.indexOf("-") + 1).trim();
}
if (latlon.indexOf(":") >= 0) { //have something like DD:MM:SS, DD::, DD:MM:, etc
int firstIdx = latlon.indexOf(":");
String hours = latlon.substring(0, firstIdx);
String minutes = latlon.substring(firstIdx + 1);
String seconds = "";
if (minutes.indexOf(":") >= 0) {
firstIdx = minutes.indexOf(":");
String temp = minutes.substring(0, firstIdx);
seconds = minutes.substring(firstIdx + 1);
minutes = temp;
}
try {
value = (hours.equals("") == true)
? 0
: Double.parseDouble(hours);
if ( !minutes.equals("")) {
value += Double.parseDouble(minutes) / 60.;
}
if ( !seconds.equals("")) {
value += Double.parseDouble(seconds) / 3600.;
}
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
} else { //have something like DD.ddd
try {
value = Double.parseDouble(latlon);
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
}
return value * southOrWest;
}
public interface StreamProcessor {
public void processValues(Data[] tuple) throws VisADException ;
}
}
| false | true | void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
List<String[]>nameChanges = new ArrayList<String[]>();
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
// squeeze out extra blank spaces
if (hdrDelim.equals(BLANK) || hdrDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
hdr = hdr.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] sthdr = hdr.split(hdrDelim);
// since blanks separate the metadata, if we have a blank
// delimiter, we run into problems. Loop through the header and
// put humpty dumpty back together again
if (hdrDelim.equals(BLANK_DELIM) || hdrDelim.equals(BLANK)) {
List<String> chunks = new ArrayList<String>();
for (int i = 0; i < sthdr.length; i++) {
String subchunk = sthdr[i].trim();
int m = subchunk.indexOf("[");
if (m == -1) {
chunks.add(subchunk);
continue;
}
// have "[", find "]"
int m2 = subchunk.indexOf("]");
while (m2 < 0 && i < sthdr.length) {
i++;
subchunk += " " +sthdr[i].trim();
m2 = subchunk.indexOf("]");
}
chunks.add(subchunk);
}
sthdr = (String[]) chunks.toArray(new String[chunks.size()]);
}
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 0. Remove any spaces around the "=" signs
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
// 0. Remove any spaces around the "=" signs
String cl = name.substring(m+1,m2).trim();
cl = cl.replaceAll(" +=","=");
cl = cl.replaceAll("= +","=");
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit hdrUnit = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
hdrUnitString = hdrUnitString.trim();
try {
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue) {
try {
hdrUnitString = hdrUnitString.replace(' ','_');
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
hdrUnit = null;
}
}
if(hdrUnit!=null) {
//We clone this unit so it has the original unit string, not the SI unit we get from the parser
try {
hdrUnit = hdrUnit.clone(hdrUnitString);
} catch(Exception ignoreThis) {}
}
}
if (debug) System.out.println("#### assigned Unit as u="+hdrUnit);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, hdrUnit, null, infos[i].isInterval);
// System.err.println("rtname:" + rtname + " " + rt);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (debug && hdrUnit != null)
System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
//Make the realType with just the name
rt = RealType.getRealType(rtname);
//Check if the realtype unit works with the unit from the header
if(rt.getDefaultUnit()!=null && hdrUnit!=null) {
if(!Unit.canConvert(rt.getDefaultUnit(), hdrUnit)) {
rt = null;
}
} else if(hdrUnit!=null) {
rt = null;
}
//If the realtype is bad then we make a new one with the unitsuffix and add
//a name change entry so later we change the mathtype string to have the new name
if(rt == null) {
rt = DataUtility.getUniqueRealType(rtname,hdrUnit, null, infos[i].isInterval);
if (rt != null) {
String newName = rt.getName();
nameChanges.add(new String[]{rtname, newName});
infos[i].name = newName;
if(debug)
System.out.println("made new realtype:" + rt + " unit:" + rt.getDefaultUnit());
}
}
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (hdrUnit == null) hdrUnit = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+hdrUnit);
}
infos[i].unit = hdrUnit;
}
for(String[] tuple: nameChanges) {
if(debug) System.err.println ("changing mathtype component from:" + tuple[0] +" to:" + tuple[1]);
maps = maps.replaceAll("(,|\\() *" + tuple[0]+" *(,|\\))", "$1" + tuple[1]+"$2");
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
mte.printStackTrace();
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
//Note, we need to have a reference to the realTypes list somewhere
//after the above call to stringToType so that the list doesn't get gc'ed
//and the realtypes it contains don't get gc'ed
if(realTypes.size()==0) {
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rangeType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
// debug =true;
rangeType = (TupleType) ((FunctionType)mt).getRange();
numRng = rangeType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rangeType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
Real[] prototypeReals = new Real[nhdr];
TupleType tupleType = null;
int index;
int lineCnt = 0;
while (true) {
String line = readLine(bis);
if (debug) System.out.println("read:"+line);
if (line == null) break;
if(skipPattern!=null && skipPattern.matcher(line).find()) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
// squeeze out extra blank spaces
if (dataDelim.equals(BLANK) || dataDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
line = line.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] tokens = line.split(dataDelim);
int n = tokens.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = null;
double [] rValues = null;
Data [] dataArray= null;
if (streamProcessor==null) {
dValues = new double[numDom];
}
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = tokens[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
dataArray = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
if (streamProcessor==null) {
rValues = new double[numRng];
}
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int tokenIdx = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (tokenIdx >= tokens.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = tokens[tokenIdx++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + tokens[tokenIdx++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
if(dValues!=null)
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
int tupleIndex = values_to_index[1][i];
thisMT = rangeType.getComponent(tupleIndex);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=tokenIdx; q < tokens.length; q++) {
String saTmp = tokens[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
tokenIdx++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//tokens[tokenIdx] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
dataArray[tupleIndex] =
new Text((TextType)thisMT, sThisText);
if (debug) System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
// if(true) continue;
double value = getVal(sa,i);
if(rValues!=null)
rValues[tupleIndex] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, value, infos[i].unit);
}
dataArray[tupleIndex] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
e.printStackTrace();
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (dataArray != null) {
if (streamProcessor!=null) {
streamProcessor.processValues(dataArray);
} else {
if(tupleType == null) {
tuple = new Tuple(dataArray);
tupleType = (TupleType)tuple.getType();
} else {
tuple = new Tuple(tupleType, dataArray, false, false);
}
}
}
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(dataArray);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<dataArray.length;i++) {
if(dataArray[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
if (streamProcessor==null) {
if(dValues!=null)
domainValues.add(dValues);
if(rValues!=null)
rangeValues.add(rValues);
if (tuple != null)
tupleValues.add(tuple);
}
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
if (streamProcessor!=null) {
bis.close();
return;
}
int numSamples = rangeValues.size(); // # lines of data
if (numSamples == 0) {
throw new VisADException("No data available to read");
}
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
| void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
List realTypes = new ArrayList();
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
List<String[]>nameChanges = new ArrayList<String[]>();
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+ hdrDelim + "("+
(hdrDelim.getBytes())[0] + ")");
}
// squeeze out extra blank spaces
if (hdrDelim.equals(BLANK) || hdrDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
hdr = hdr.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] sthdr = hdr.split(hdrDelim);
// since blanks separate the metadata, if we have a blank
// delimiter, we run into problems. Loop through the header and
// put humpty dumpty back together again
if (hdrDelim.equals(BLANK_DELIM) || hdrDelim.equals(BLANK)) {
List<String> chunks = new ArrayList<String>();
for (int i = 0; i < sthdr.length; i++) {
String subchunk = sthdr[i].trim();
int m = subchunk.indexOf("[");
if (m == -1) {
chunks.add(subchunk);
continue;
}
// have "[", find "]"
int m2 = subchunk.indexOf("]");
while (m2 < 0 && i < sthdr.length) {
i++;
subchunk += " " +sthdr[i].trim();
m2 = subchunk.indexOf("]");
}
chunks.add(subchunk);
}
sthdr = (String[]) chunks.toArray(new String[chunks.size()]);
}
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 0. Remove any spaces around the "=" signs
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
// 0. Remove any spaces around the "=" signs
String cl = name.substring(m+1,m2).trim();
cl = cl.replaceAll(" +=","=");
cl = cl.replaceAll("= +","=");
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if(properties!=null) {
for(int headerIdx=0;headerIdx<infos.length;headerIdx++) {
String value = (String)properties.get(infos[headerIdx].name+".value");
if(value!=null) infos[headerIdx].fixedValue = value;
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit hdrUnit = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
hdrUnitString = hdrUnitString.trim();
try {
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue) {
try {
hdrUnitString = hdrUnitString.replace(' ','_');
hdrUnit = visad.data.units.Parser.parse(hdrUnitString);
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
hdrUnit = null;
}
}
if(hdrUnit!=null) {
//We clone this unit so it has the original unit string, not the SI unit we get from the parser
try {
hdrUnit = hdrUnit.clone(hdrUnitString);
} catch(Exception ignoreThis) {}
}
}
if (debug) System.out.println("#### assigned Unit as u="+hdrUnit);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, hdrUnit, null, infos[i].isInterval);
// System.err.println("rtname:" + rtname + " " + rt);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (debug && hdrUnit != null)
System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
//Make the realType with just the name
rt = RealType.getRealType(rtname);
//Check if the realtype unit works with the unit from the header
if(rt.getDefaultUnit()!=null && hdrUnit!=null) {
if(!Unit.canConvert(rt.getDefaultUnit(), hdrUnit)) {
rt = null;
}
} else if(hdrUnit!=null) {
rt = null;
}
//If the realtype is bad then we make a new one with the unitsuffix and add
//a name change entry so later we change the mathtype string to have the new name
if(rt == null) {
rt = DataUtility.getUniqueRealType(rtname,hdrUnit, null, infos[i].isInterval);
if (rt != null) {
String newName = rt.getName();
nameChanges.add(new String[]{rtname, newName});
infos[i].name = newName;
if(debug)
System.out.println("made new realtype:" + rt + " unit:" + rt.getDefaultUnit());
}
}
}
//Add the realType here because its possible that it can be GC'ed
//and removed from the global list of realtypes before we
//get back to it. Then the MathType.stringToType(maps) below
//will produce a realtype with no units
realTypes.add(rt);
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (hdrUnit == null) hdrUnit = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+hdrUnit);
}
infos[i].unit = hdrUnit;
}
for(String[] tuple: nameChanges) {
if(debug) System.err.println ("changing mathtype component from:" + tuple[0] +" to:" + tuple[1]);
maps = maps.replaceAll("(,|\\() *" + tuple[0]+" *(,|\\))", "$1" + tuple[1]+"$2");
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
mte.printStackTrace();
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
//Note, we need to have a reference to the realTypes list somewhere
//after the above call to stringToType so that the list doesn't get gc'ed
//and the realtypes it contains don't get gc'ed
if(realTypes.size()==0) {
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rangeType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
// debug =true;
rangeType = (TupleType) ((FunctionType)mt).getRange();
numRng = rangeType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rangeType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
Real[] prototypeReals = new Real[nhdr];
TupleType tupleType = null;
int index;
int lineCnt = 0;
while (true) {
String line = readLine(bis);
if (debug) System.out.println("read:"+line);
if (line == null) break;
if(skipPattern!=null && skipPattern.matcher(line).find()) continue;
if((index=line.indexOf("="))>=0) { // fixed value
String name = line.substring(0,index).trim();
String value = line.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + line);
}
continue;
}
if (dataDelim == null) {
if (line.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (line.indexOf(COMMA) != -1) dataDelim = COMMA;
if (line.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (line.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
((dataDelim == null)
? "null"
: dataDelim + " (" + (dataDelim.getBytes())[0] +")"));
}
// squeeze out extra blank spaces
if (dataDelim.equals(BLANK) || dataDelim.equals(BLANK_DELIM)) {
//System.out.println("line before squeeze: " + line);
line = line.replaceAll("\\s++", " ").trim();
//System.out.println("line after squeeze: " + line);
}
String[] tokens = line.split(dataDelim);
int n = tokens.length;
if (n < 1) continue; // something is wrong if this happens!
lineCnt++;
double [] dValues = null;
double [] rValues = null;
Data [] dataArray= null;
if (streamProcessor==null) {
dValues = new double[numDom];
}
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = tokens[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
dataArray = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
if (streamProcessor==null) {
rValues = new double[numRng];
}
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int tokenIdx = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa=null;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (tokenIdx >= tokens.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = tokens[tokenIdx++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + tokens[tokenIdx++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
if(dValues!=null)
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
int tupleIndex = values_to_index[1][i];
int infosIndex = values_to_index[2][i];
thisMT = rangeType.getComponent(tupleIndex);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=tokenIdx; q < tokens.length; q++) {
String saTmp = tokens[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
tokenIdx++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//tokens[tokenIdx] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
dataArray[tupleIndex] =
new Text((TextType)thisMT, sThisText);
if (debug) System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
// if(true) continue;
double value = getVal(sa,i);
if(rValues!=null)
rValues[tupleIndex] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, value, infos[infosIndex].unit);
}
dataArray[tupleIndex] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("dataArray[" +
tupleIndex + "] = " +
dataArray[tupleIndex]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
e.printStackTrace();
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (dataArray != null) {
if (streamProcessor!=null) {
streamProcessor.processValues(dataArray);
} else {
if(tupleType == null) {
tuple = new Tuple(dataArray);
tupleType = (TupleType)tuple.getType();
} else {
tuple = new Tuple(tupleType, dataArray, false, false);
}
}
}
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(dataArray);
tuple = null;
tryToMakeTuple = false;
} catch(NullPointerException npe) {
for(int i=0;i<dataArray.length;i++) {
if(dataArray[i] == null) {
throw new IllegalArgumentException("An error occurred reading line number:" + lineCnt+" column number:" + (i+1)+"\n" +
line);
}
}
throw npe;
}
}
if (streamProcessor==null) {
if(dValues!=null)
domainValues.add(dValues);
if(rValues!=null)
rangeValues.add(rValues);
if (tuple != null)
tupleValues.add(tuple);
}
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
if (streamProcessor!=null) {
bis.close();
return;
}
int numSamples = rangeValues.size(); // # lines of data
if (numSamples == 0) {
throw new VisADException("No data available to read");
}
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
|
diff --git a/realms/foaf/src/resources/foaf/src/java/org/wyona/yanel/impl/map/FOAFRealm.java b/realms/foaf/src/resources/foaf/src/java/org/wyona/yanel/impl/map/FOAFRealm.java
index 692f3c8..ed21e14 100644
--- a/realms/foaf/src/resources/foaf/src/java/org/wyona/yanel/impl/map/FOAFRealm.java
+++ b/realms/foaf/src/resources/foaf/src/java/org/wyona/yanel/impl/map/FOAFRealm.java
@@ -1,70 +1,70 @@
/*
* Copyright 2007 Wyona
*
* 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.wyona.org/licenses/APACHE-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.wyona.yanel.impl.map;
import org.apache.log4j.Category;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryFactory;
import org.wyona.commons.io.FileUtil;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
/**
*
*/
public class FOAFRealm extends org.wyona.yanel.core.map.Realm {
private Category log = Category.getInstance(FOAFRealm.class);
Repository profilesRepo;
/**
*
*/
public FOAFRealm(String name, String id, String mountPoint, java.io.File configFile) throws Exception {
super(name, id, mountPoint, configFile);
- log.error("DEBUG: Custom FOAF Realm implementation!");
+ log.debug("Custom FOAF Realm implementation!");
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(true);
Configuration config = builder.buildFromFile(configFile);
java.io.File profilesDataRepoConfigFile = new java.io.File(config.getChild("profiles-data").getValue());
- log.error("DEBUG: Profiles Data repo path: " + profilesDataRepoConfigFile);
+ log.debug("Profiles Data repo path: " + profilesDataRepoConfigFile);
if (!profilesDataRepoConfigFile.isAbsolute()) {
profilesDataRepoConfigFile = FileUtil.file(configFile.getParentFile().getAbsolutePath(), profilesDataRepoConfigFile.toString());
}
profilesRepo = new RepositoryFactory().newRepository("profiles", profilesDataRepoConfigFile);
}
/**
*
*/
public Repository getProfilesRepository() {
return profilesRepo;
}
/**
*
*/
public void destroy() throws Exception {
this.destroy();
getProfilesRepository().close();
}
}
| false | true | public FOAFRealm(String name, String id, String mountPoint, java.io.File configFile) throws Exception {
super(name, id, mountPoint, configFile);
log.error("DEBUG: Custom FOAF Realm implementation!");
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(true);
Configuration config = builder.buildFromFile(configFile);
java.io.File profilesDataRepoConfigFile = new java.io.File(config.getChild("profiles-data").getValue());
log.error("DEBUG: Profiles Data repo path: " + profilesDataRepoConfigFile);
if (!profilesDataRepoConfigFile.isAbsolute()) {
profilesDataRepoConfigFile = FileUtil.file(configFile.getParentFile().getAbsolutePath(), profilesDataRepoConfigFile.toString());
}
profilesRepo = new RepositoryFactory().newRepository("profiles", profilesDataRepoConfigFile);
}
| public FOAFRealm(String name, String id, String mountPoint, java.io.File configFile) throws Exception {
super(name, id, mountPoint, configFile);
log.debug("Custom FOAF Realm implementation!");
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(true);
Configuration config = builder.buildFromFile(configFile);
java.io.File profilesDataRepoConfigFile = new java.io.File(config.getChild("profiles-data").getValue());
log.debug("Profiles Data repo path: " + profilesDataRepoConfigFile);
if (!profilesDataRepoConfigFile.isAbsolute()) {
profilesDataRepoConfigFile = FileUtil.file(configFile.getParentFile().getAbsolutePath(), profilesDataRepoConfigFile.toString());
}
profilesRepo = new RepositoryFactory().newRepository("profiles", profilesDataRepoConfigFile);
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/OpenCommitAction.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/OpenCommitAction.java
index 1d5d5db7..50e22d97 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/OpenCommitAction.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/OpenCommitAction.java
@@ -1,40 +1,44 @@
/*******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* 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:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.commit;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;
/**
* Open commit action
*/
public class OpenCommitAction extends ActionDelegate implements
IWorkbenchWindowActionDelegate {
private Shell shell;
@Override
public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
- if (Window.OK == dialog.open())
- for (Object result : dialog.getResult())
- CommitEditor.openQuiet((RepositoryCommit) result);
+ if (Window.OK != dialog.open())
+ return;
+ Object[] results = dialog.getResult();
+ if (results == null || results.length == 0)
+ return;
+ for (Object result : results)
+ CommitEditor.openQuiet((RepositoryCommit) result);
}
public void init(IWorkbenchWindow window) {
shell = window.getShell();
}
}
| true | true | public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK == dialog.open())
for (Object result : dialog.getResult())
CommitEditor.openQuiet((RepositoryCommit) result);
}
| public void run(IAction action) {
CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
if (Window.OK != dialog.open())
return;
Object[] results = dialog.getResult();
if (results == null || results.length == 0)
return;
for (Object result : results)
CommitEditor.openQuiet((RepositoryCommit) result);
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/MethodActionFilter.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/MethodActionFilter.java
index f7de9ec1e..4c77f15b3 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/MethodActionFilter.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/MethodActionFilter.java
@@ -1,39 +1,39 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.ui.IActionFilter;
public class MethodActionFilter implements IActionFilter {
/**
* @see org.eclipse.ui.IActionFilter#testAttribute(Object, String, String)
*/
public boolean testAttribute(Object target, String name, String value) {
if (name.equals("MethodActionFilter") //$NON-NLS-1$
- && value.equals("isNotAbstract")) { //$NON-NLS-1$
+ && value.equals("isAbstract")) { //$NON-NLS-1$
if (target instanceof IMethod) {
IMethod method = (IMethod) target;
try {
- return !Flags.isAbstract(method.getFlags());
+ return Flags.isAbstract(method.getFlags());
} catch (JavaModelException e) {
JDIDebugUIPlugin.log(e);
}
}
}
return false;
}
}
| false | true | public boolean testAttribute(Object target, String name, String value) {
if (name.equals("MethodActionFilter") //$NON-NLS-1$
&& value.equals("isNotAbstract")) { //$NON-NLS-1$
if (target instanceof IMethod) {
IMethod method = (IMethod) target;
try {
return !Flags.isAbstract(method.getFlags());
} catch (JavaModelException e) {
JDIDebugUIPlugin.log(e);
}
}
}
return false;
}
| public boolean testAttribute(Object target, String name, String value) {
if (name.equals("MethodActionFilter") //$NON-NLS-1$
&& value.equals("isAbstract")) { //$NON-NLS-1$
if (target instanceof IMethod) {
IMethod method = (IMethod) target;
try {
return Flags.isAbstract(method.getFlags());
} catch (JavaModelException e) {
JDIDebugUIPlugin.log(e);
}
}
}
return false;
}
|
diff --git a/src/main/java/hudson/scm/subversion/CheckoutUpdater.java b/src/main/java/hudson/scm/subversion/CheckoutUpdater.java
index d6f36c3..5ffc6ca 100755
--- a/src/main/java/hudson/scm/subversion/CheckoutUpdater.java
+++ b/src/main/java/hudson/scm/subversion/CheckoutUpdater.java
@@ -1,135 +1,135 @@
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Fulvio Cavarretta,
* Jean-Baptiste Quenot, Luca Domenico Milanesio, Renaud Bruyeron, Stephen Connolly,
* Tom Huybrechts, Yahoo! Inc., Manufacture Francaise des Pneumatiques Michelin,
* Romain Seguy
*
* 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 hudson.scm.subversion;
import hudson.Extension;
import hudson.Util;
import hudson.scm.SubversionSCM.External;
import hudson.util.IOException2;
import hudson.util.StreamCopyThread;
import org.apache.commons.lang.time.FastDateFormat;
import org.kohsuke.stapler.DataBoundConstructor;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import java.io.File;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
/**
* {@link WorkspaceUpdater} that does a fresh check out.
*
* @author Kohsuke Kawaguchi
*/
public class CheckoutUpdater extends WorkspaceUpdater {
private static final long serialVersionUID = -3502075714024708011L;
private static final FastDateFormat fmt = FastDateFormat.getInstance("''yyyy-MM-dd'T'HH:mm:ss.SSS Z''");
@DataBoundConstructor
public CheckoutUpdater() {}
@Override
public UpdateTask createTask() {
return new UpdateTask() {
private static final long serialVersionUID = 8349986526712487762L;
@Override
public List<External> perform() throws IOException, InterruptedException {
final SVNUpdateClient svnuc = clientManager.getUpdateClient();
final List<External> externals = new ArrayList<External>(); // store discovered externals to here
listener.getLogger().println("Cleaning local Directory " + location.getLocalDir());
Util.deleteContentsRecursive(new File(ws, location.getLocalDir()));
// buffer the output by a separate thread so that the update operation
// won't be blocked by the remoting of the data
PipedOutputStream pos = new PipedOutputStream();
StreamCopyThread sct = new StreamCopyThread("svn log copier", new PipedInputStream(pos), listener.getLogger());
sct.start();
try {
SVNRevision r = getRevision(location);
String revisionName = r.getDate() != null ?
fmt.format(r.getDate()) : r.toString();
listener.getLogger().println("Checking out " + location.remote + " at revision " + revisionName);
File local = new File(ws, location.getLocalDir());
SubversionUpdateEventHandler eventHandler = new SubversionUpdateEventHandler(new PrintStream(pos), externals, local, location.getLocalDir());
svnuc.setEventHandler(eventHandler);
svnuc.setExternalsHandler(eventHandler);
svnuc.setIgnoreExternals(location.isIgnoreExternalsOption());
SVNDepth svnDepth = getSvnDepth(location.getDepthOption());
svnuc.doCheckout(location.getSVNURL(), local.getCanonicalFile(), SVNRevision.HEAD, r, svnDepth, true);
} catch (SVNCancelException e) {
if (isAuthenticationFailedError(e)) {
e.printStackTrace(listener.error("Failed to check out " + location.remote));
return null;
} else {
listener.error("Subversion checkout has been canceled");
throw (InterruptedException)new InterruptedException().initCause(e);
}
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check out " + location.remote));
- return null;
+ throw new IOException("Failed to check out " + location.remote, e) ;
} finally {
try {
pos.close();
} finally {
try {
sct.join(); // wait for all data to be piped.
} catch (InterruptedException e) {
throw new IOException2("interrupted", e);
}
}
}
return externals;
}
};
}
@Extension
public static class DescriptorImpl extends WorkspaceUpdaterDescriptor {
@Override
public String getDisplayName() {
return Messages.CheckoutUpdater_DisplayName();
}
}
}
| true | true | public UpdateTask createTask() {
return new UpdateTask() {
private static final long serialVersionUID = 8349986526712487762L;
@Override
public List<External> perform() throws IOException, InterruptedException {
final SVNUpdateClient svnuc = clientManager.getUpdateClient();
final List<External> externals = new ArrayList<External>(); // store discovered externals to here
listener.getLogger().println("Cleaning local Directory " + location.getLocalDir());
Util.deleteContentsRecursive(new File(ws, location.getLocalDir()));
// buffer the output by a separate thread so that the update operation
// won't be blocked by the remoting of the data
PipedOutputStream pos = new PipedOutputStream();
StreamCopyThread sct = new StreamCopyThread("svn log copier", new PipedInputStream(pos), listener.getLogger());
sct.start();
try {
SVNRevision r = getRevision(location);
String revisionName = r.getDate() != null ?
fmt.format(r.getDate()) : r.toString();
listener.getLogger().println("Checking out " + location.remote + " at revision " + revisionName);
File local = new File(ws, location.getLocalDir());
SubversionUpdateEventHandler eventHandler = new SubversionUpdateEventHandler(new PrintStream(pos), externals, local, location.getLocalDir());
svnuc.setEventHandler(eventHandler);
svnuc.setExternalsHandler(eventHandler);
svnuc.setIgnoreExternals(location.isIgnoreExternalsOption());
SVNDepth svnDepth = getSvnDepth(location.getDepthOption());
svnuc.doCheckout(location.getSVNURL(), local.getCanonicalFile(), SVNRevision.HEAD, r, svnDepth, true);
} catch (SVNCancelException e) {
if (isAuthenticationFailedError(e)) {
e.printStackTrace(listener.error("Failed to check out " + location.remote));
return null;
} else {
listener.error("Subversion checkout has been canceled");
throw (InterruptedException)new InterruptedException().initCause(e);
}
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check out " + location.remote));
return null;
} finally {
try {
pos.close();
} finally {
try {
sct.join(); // wait for all data to be piped.
} catch (InterruptedException e) {
throw new IOException2("interrupted", e);
}
}
}
return externals;
}
};
}
| public UpdateTask createTask() {
return new UpdateTask() {
private static final long serialVersionUID = 8349986526712487762L;
@Override
public List<External> perform() throws IOException, InterruptedException {
final SVNUpdateClient svnuc = clientManager.getUpdateClient();
final List<External> externals = new ArrayList<External>(); // store discovered externals to here
listener.getLogger().println("Cleaning local Directory " + location.getLocalDir());
Util.deleteContentsRecursive(new File(ws, location.getLocalDir()));
// buffer the output by a separate thread so that the update operation
// won't be blocked by the remoting of the data
PipedOutputStream pos = new PipedOutputStream();
StreamCopyThread sct = new StreamCopyThread("svn log copier", new PipedInputStream(pos), listener.getLogger());
sct.start();
try {
SVNRevision r = getRevision(location);
String revisionName = r.getDate() != null ?
fmt.format(r.getDate()) : r.toString();
listener.getLogger().println("Checking out " + location.remote + " at revision " + revisionName);
File local = new File(ws, location.getLocalDir());
SubversionUpdateEventHandler eventHandler = new SubversionUpdateEventHandler(new PrintStream(pos), externals, local, location.getLocalDir());
svnuc.setEventHandler(eventHandler);
svnuc.setExternalsHandler(eventHandler);
svnuc.setIgnoreExternals(location.isIgnoreExternalsOption());
SVNDepth svnDepth = getSvnDepth(location.getDepthOption());
svnuc.doCheckout(location.getSVNURL(), local.getCanonicalFile(), SVNRevision.HEAD, r, svnDepth, true);
} catch (SVNCancelException e) {
if (isAuthenticationFailedError(e)) {
e.printStackTrace(listener.error("Failed to check out " + location.remote));
return null;
} else {
listener.error("Subversion checkout has been canceled");
throw (InterruptedException)new InterruptedException().initCause(e);
}
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check out " + location.remote));
throw new IOException("Failed to check out " + location.remote, e) ;
} finally {
try {
pos.close();
} finally {
try {
sct.join(); // wait for all data to be piped.
} catch (InterruptedException e) {
throw new IOException2("interrupted", e);
}
}
}
return externals;
}
};
}
|
diff --git a/src/Servlets/MailManagementServlet.java b/src/Servlets/MailManagementServlet.java
index d7d03f9..59cad8a 100755
--- a/src/Servlets/MailManagementServlet.java
+++ b/src/Servlets/MailManagementServlet.java
@@ -1,139 +1,139 @@
package Servlets;
import helpers.HTMLHelper;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Accounts.*;
/**
* Servlet implementation class AcctManagementServlet
*/
@WebServlet("/MailManagementServlet")
public class MailManagementServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MailManagementServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MailManager mm = (MailManager) request.getServletContext().getAttribute("mail");
String user = request.getParameter("user");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<head>");
out.println(HTMLHelper.printCSSLink());
out.println("</head>");
out.println(HTMLHelper.printHeader((Account)request.getSession().getAttribute("account")));
out.println("<body>");
AccountManager am = (AccountManager) request.getServletContext().getAttribute("accounts");
if(request.getSession().getAttribute("account") != null) out.println(HTMLHelper.printNewsFeed(am.getAnnouncements()));
out.println(HTMLHelper.contentStart());
if (request.getParameter("index").equals("inbox")) {
TreeMap<Integer, Message> inbox = mm.listInbox(user);
out.println("<table border=\"0\">");
out.println("<tr><th><b>Subject</b></th><th><b>Sender</b></th><th><b>Date</b></th></tr>");
for (int i : inbox.keySet()) {
String boldin = "";
String boldout = "";
if (inbox.get(i).unread) {
boldin = "<b>";
boldout = "</b>";
}
out.println("<tr>");
out.println("<td>"+boldin+"<a href = \"MailManagementServlet?&index="+i+"&user="+user+"\">");
out.println(inbox.get(i).getSubject()) ;
out.println("</a>"+boldout+"</td>");
out.println("<td><a href = \"ProfileServlet?user="+inbox.get(i).getSender()+"\">");
out.println(inbox.get(i).getSender()) ;
out.println("</a></td>");
out.println("<td>");
out.println(new java.util.Date(inbox.get(i).getTimestamp())) ;
out.println("</td>");
}
out.println("</table>");
} else if (request.getParameter("index").equals("outbox")) {
TreeMap<Integer, Message> outbox = mm.listOutbox(user);
//out.println("<ul>");
out.println("<table border=\"0\">");
out.println("<tr><th><b>Subject</b></th><th><b>Recipient</b></th><th><b>Date</b></th></tr>");
for (int i : outbox.keySet()) {
out.println("<tr>");
out.println("<td><a href = \"MailManagementServlet?&index="+i+"&user="+user+"\">");
out.println(outbox.get(i).getSubject()) ;
out.println("</a></td>");
out.println("<td><a href = \"ProfileServlet?user="+outbox.get(i).getRecipient()+"\">");
out.println(outbox.get(i).getRecipient()) ;
out.println("</a></td>");
out.println("<td>");
out.println(new java.util.Date(outbox.get(i).getTimestamp())) ;
out.println("</td>");
}
out.println("</table>");
} else {//print specific message
- int x = 37;
+ int x = 0;
try {
x = Integer.parseInt(request.getParameter("index"));
} catch (NumberFormatException e) {
System.out.println("mail fail");
}
System.out.println(x);
Message m = mm.recieveMessage(x);
out.println("<b>Subject:</b> " + m.getSubject() + "<br>");
out.println("<b>From:</b> " + m.getSender() + " @ " + new java.util.Date(m.getTimestamp())+ "<hr>");
if (m.getChallengeName() != null) {
out.println(m.getSender() + " has challenged you to take: <a href = QuizTitleServlet?id="+m.getChallengeID()+">"+m.getChallengeName()+"</a><br><br>");
}
out.println(m.getBody());
}
out.println(HTMLHelper.contentEnd() + "</body>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sender = request.getParameter("sender");
String recipient = request.getParameter("recipient");
AccountManager am = (AccountManager) request.getServletContext().getAttribute("accounts");
if (!am.accountExists(recipient)) {
String errorURL = "/newMessage.jsp?&to=error&subject="+request.getParameter("subject")+"&quiz=" + request.getParameter("quiz")+"&body="+request.getParameter("body");
request.getRequestDispatcher(errorURL).forward(request, response);
} else {
String subject = request.getParameter("subject");
String body = request.getParameter("body");
int challenge = -1;
try {
challenge = Integer.parseInt(request.getParameter("challenge"));
} catch (NumberFormatException e) {
}
Message m = new Message(sender, recipient, subject, body, 0, challenge, null, true);
MailManager mm = (MailManager) request.getServletContext().getAttribute("mail");
mm.sendMessage(m);
request.getRequestDispatcher("/UserHome.jsp").forward(request, response);
}
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MailManager mm = (MailManager) request.getServletContext().getAttribute("mail");
String user = request.getParameter("user");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<head>");
out.println(HTMLHelper.printCSSLink());
out.println("</head>");
out.println(HTMLHelper.printHeader((Account)request.getSession().getAttribute("account")));
out.println("<body>");
AccountManager am = (AccountManager) request.getServletContext().getAttribute("accounts");
if(request.getSession().getAttribute("account") != null) out.println(HTMLHelper.printNewsFeed(am.getAnnouncements()));
out.println(HTMLHelper.contentStart());
if (request.getParameter("index").equals("inbox")) {
TreeMap<Integer, Message> inbox = mm.listInbox(user);
out.println("<table border=\"0\">");
out.println("<tr><th><b>Subject</b></th><th><b>Sender</b></th><th><b>Date</b></th></tr>");
for (int i : inbox.keySet()) {
String boldin = "";
String boldout = "";
if (inbox.get(i).unread) {
boldin = "<b>";
boldout = "</b>";
}
out.println("<tr>");
out.println("<td>"+boldin+"<a href = \"MailManagementServlet?&index="+i+"&user="+user+"\">");
out.println(inbox.get(i).getSubject()) ;
out.println("</a>"+boldout+"</td>");
out.println("<td><a href = \"ProfileServlet?user="+inbox.get(i).getSender()+"\">");
out.println(inbox.get(i).getSender()) ;
out.println("</a></td>");
out.println("<td>");
out.println(new java.util.Date(inbox.get(i).getTimestamp())) ;
out.println("</td>");
}
out.println("</table>");
} else if (request.getParameter("index").equals("outbox")) {
TreeMap<Integer, Message> outbox = mm.listOutbox(user);
//out.println("<ul>");
out.println("<table border=\"0\">");
out.println("<tr><th><b>Subject</b></th><th><b>Recipient</b></th><th><b>Date</b></th></tr>");
for (int i : outbox.keySet()) {
out.println("<tr>");
out.println("<td><a href = \"MailManagementServlet?&index="+i+"&user="+user+"\">");
out.println(outbox.get(i).getSubject()) ;
out.println("</a></td>");
out.println("<td><a href = \"ProfileServlet?user="+outbox.get(i).getRecipient()+"\">");
out.println(outbox.get(i).getRecipient()) ;
out.println("</a></td>");
out.println("<td>");
out.println(new java.util.Date(outbox.get(i).getTimestamp())) ;
out.println("</td>");
}
out.println("</table>");
} else {//print specific message
int x = 37;
try {
x = Integer.parseInt(request.getParameter("index"));
} catch (NumberFormatException e) {
System.out.println("mail fail");
}
System.out.println(x);
Message m = mm.recieveMessage(x);
out.println("<b>Subject:</b> " + m.getSubject() + "<br>");
out.println("<b>From:</b> " + m.getSender() + " @ " + new java.util.Date(m.getTimestamp())+ "<hr>");
if (m.getChallengeName() != null) {
out.println(m.getSender() + " has challenged you to take: <a href = QuizTitleServlet?id="+m.getChallengeID()+">"+m.getChallengeName()+"</a><br><br>");
}
out.println(m.getBody());
}
out.println(HTMLHelper.contentEnd() + "</body>");
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MailManager mm = (MailManager) request.getServletContext().getAttribute("mail");
String user = request.getParameter("user");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<head>");
out.println(HTMLHelper.printCSSLink());
out.println("</head>");
out.println(HTMLHelper.printHeader((Account)request.getSession().getAttribute("account")));
out.println("<body>");
AccountManager am = (AccountManager) request.getServletContext().getAttribute("accounts");
if(request.getSession().getAttribute("account") != null) out.println(HTMLHelper.printNewsFeed(am.getAnnouncements()));
out.println(HTMLHelper.contentStart());
if (request.getParameter("index").equals("inbox")) {
TreeMap<Integer, Message> inbox = mm.listInbox(user);
out.println("<table border=\"0\">");
out.println("<tr><th><b>Subject</b></th><th><b>Sender</b></th><th><b>Date</b></th></tr>");
for (int i : inbox.keySet()) {
String boldin = "";
String boldout = "";
if (inbox.get(i).unread) {
boldin = "<b>";
boldout = "</b>";
}
out.println("<tr>");
out.println("<td>"+boldin+"<a href = \"MailManagementServlet?&index="+i+"&user="+user+"\">");
out.println(inbox.get(i).getSubject()) ;
out.println("</a>"+boldout+"</td>");
out.println("<td><a href = \"ProfileServlet?user="+inbox.get(i).getSender()+"\">");
out.println(inbox.get(i).getSender()) ;
out.println("</a></td>");
out.println("<td>");
out.println(new java.util.Date(inbox.get(i).getTimestamp())) ;
out.println("</td>");
}
out.println("</table>");
} else if (request.getParameter("index").equals("outbox")) {
TreeMap<Integer, Message> outbox = mm.listOutbox(user);
//out.println("<ul>");
out.println("<table border=\"0\">");
out.println("<tr><th><b>Subject</b></th><th><b>Recipient</b></th><th><b>Date</b></th></tr>");
for (int i : outbox.keySet()) {
out.println("<tr>");
out.println("<td><a href = \"MailManagementServlet?&index="+i+"&user="+user+"\">");
out.println(outbox.get(i).getSubject()) ;
out.println("</a></td>");
out.println("<td><a href = \"ProfileServlet?user="+outbox.get(i).getRecipient()+"\">");
out.println(outbox.get(i).getRecipient()) ;
out.println("</a></td>");
out.println("<td>");
out.println(new java.util.Date(outbox.get(i).getTimestamp())) ;
out.println("</td>");
}
out.println("</table>");
} else {//print specific message
int x = 0;
try {
x = Integer.parseInt(request.getParameter("index"));
} catch (NumberFormatException e) {
System.out.println("mail fail");
}
System.out.println(x);
Message m = mm.recieveMessage(x);
out.println("<b>Subject:</b> " + m.getSubject() + "<br>");
out.println("<b>From:</b> " + m.getSender() + " @ " + new java.util.Date(m.getTimestamp())+ "<hr>");
if (m.getChallengeName() != null) {
out.println(m.getSender() + " has challenged you to take: <a href = QuizTitleServlet?id="+m.getChallengeID()+">"+m.getChallengeName()+"</a><br><br>");
}
out.println(m.getBody());
}
out.println(HTMLHelper.contentEnd() + "</body>");
}
|
diff --git a/src/main/java/com/admob/rocksteady/reactor/Mongodb.java b/src/main/java/com/admob/rocksteady/reactor/Mongodb.java
index 382a186..96af4c2 100644
--- a/src/main/java/com/admob/rocksteady/reactor/Mongodb.java
+++ b/src/main/java/com/admob/rocksteady/reactor/Mongodb.java
@@ -1,122 +1,122 @@
/**
**/
package com.admob.rocksteady.reactor;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.admob.rocksteady.util.MongodbInterface;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.UpdateListener;
import com.espertech.esper.client.PropertyAccessException;
/**
*
* @author Implement Esper UpdateListener to be used when event is triggered.
* This is testing the base form.
*
*/
public class Mongodb implements UpdateListener {
private static final Logger logger = LoggerFactory.getLogger(Mongodb.class);
private String type;
private String tag;
private String cname;
private String suffix;
@Autowired
private MongodbInterface mongodbInterface;
public void setType(String type) {
this.type = type;
}
public void setTag(String tag) {
this.tag = tag;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getTag() {
return tag;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
/**
* Handle the triggered event
*
* @param newEvents the new events in the window
* @param oldEvents the old events in the window
*/
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
if (newEvents == null) {
return;
}
for (EventBean newEvent : newEvents) {
try {
String retention;
String app;
String name;
String colo;
String value;
String hostname;
String timestamp;
retention = newEvent.get("retention").toString();
app = newEvent.get("app").toString();
// get name
if (cname == null) {
name = newEvent.get("name").toString();
} else {
- name = cname;
+ name = new String(cname);
}
if ( (type != null) && (type.equals("uniq_host"))) {
hostname = newEvent.get("hostname").toString();
} else {
hostname = new String("");
}
colo = newEvent.get("colo").toString();
value = newEvent.get("value").toString();
try {
timestamp = newEvent.get("timestamp").toString();
} catch (Exception e) {
timestamp = null;
}
if (retention.isEmpty()) {
retention = new String("");
}
if (suffix == null) {
suffix = new String("");
}
logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + hostname + "." + suffix + " " + value + " ");
// Send the data
mongodbInterface.send(mongodbInterface.mongodbObject(retention, app, name, colo, hostname, suffix, value, timestamp));
} catch (Exception e) {
logger.error("Problem with sending metric to mongodb: " +
e.toString());
}
}
}
}
| true | true | public void update(EventBean[] newEvents, EventBean[] oldEvents) {
if (newEvents == null) {
return;
}
for (EventBean newEvent : newEvents) {
try {
String retention;
String app;
String name;
String colo;
String value;
String hostname;
String timestamp;
retention = newEvent.get("retention").toString();
app = newEvent.get("app").toString();
// get name
if (cname == null) {
name = newEvent.get("name").toString();
} else {
name = cname;
}
if ( (type != null) && (type.equals("uniq_host"))) {
hostname = newEvent.get("hostname").toString();
} else {
hostname = new String("");
}
colo = newEvent.get("colo").toString();
value = newEvent.get("value").toString();
try {
timestamp = newEvent.get("timestamp").toString();
} catch (Exception e) {
timestamp = null;
}
if (retention.isEmpty()) {
retention = new String("");
}
if (suffix == null) {
suffix = new String("");
}
logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + hostname + "." + suffix + " " + value + " ");
// Send the data
mongodbInterface.send(mongodbInterface.mongodbObject(retention, app, name, colo, hostname, suffix, value, timestamp));
} catch (Exception e) {
logger.error("Problem with sending metric to mongodb: " +
e.toString());
}
}
}
| public void update(EventBean[] newEvents, EventBean[] oldEvents) {
if (newEvents == null) {
return;
}
for (EventBean newEvent : newEvents) {
try {
String retention;
String app;
String name;
String colo;
String value;
String hostname;
String timestamp;
retention = newEvent.get("retention").toString();
app = newEvent.get("app").toString();
// get name
if (cname == null) {
name = newEvent.get("name").toString();
} else {
name = new String(cname);
}
if ( (type != null) && (type.equals("uniq_host"))) {
hostname = newEvent.get("hostname").toString();
} else {
hostname = new String("");
}
colo = newEvent.get("colo").toString();
value = newEvent.get("value").toString();
try {
timestamp = newEvent.get("timestamp").toString();
} catch (Exception e) {
timestamp = null;
}
if (retention.isEmpty()) {
retention = new String("");
}
if (suffix == null) {
suffix = new String("");
}
logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + hostname + "." + suffix + " " + value + " ");
// Send the data
mongodbInterface.send(mongodbInterface.mongodbObject(retention, app, name, colo, hostname, suffix, value, timestamp));
} catch (Exception e) {
logger.error("Problem with sending metric to mongodb: " +
e.toString());
}
}
}
|
diff --git a/src/edu/sc/seis/sod/database/network/JDBCNetworkUnifier.java b/src/edu/sc/seis/sod/database/network/JDBCNetworkUnifier.java
index e05b602ef..aeb3fac53 100755
--- a/src/edu/sc/seis/sod/database/network/JDBCNetworkUnifier.java
+++ b/src/edu/sc/seis/sod/database/network/JDBCNetworkUnifier.java
@@ -1,166 +1,180 @@
/**
* JDBCNetworkUnifier.java
*
* allows access to all of the underlying networkDb interfaces from a single
* class
*/
package edu.sc.seis.sod.database.network;
import java.sql.Connection;
import java.sql.SQLException;
import edu.iris.Fissures.Time;
import edu.iris.Fissures.TimeRange;
import edu.iris.Fissures.IfNetwork.Channel;
import edu.iris.Fissures.IfNetwork.NetworkAccess;
import edu.iris.Fissures.IfNetwork.NetworkAttr;
import edu.iris.Fissures.IfNetwork.NetworkId;
import edu.iris.Fissures.IfNetwork.NetworkNotFound;
import edu.iris.Fissures.IfNetwork.Site;
import edu.iris.Fissures.IfNetwork.Station;
import edu.iris.Fissures.model.MicroSecondDate;
import edu.iris.Fissures.network.NetworkIdUtil;
import edu.sc.seis.fissuresUtil.cache.ProxyNetworkAccess;
import edu.sc.seis.fissuresUtil.cache.ProxyNetworkDC;
import edu.sc.seis.fissuresUtil.cache.VestingNetworkDC;
import edu.sc.seis.fissuresUtil.database.ConnMgr;
import edu.sc.seis.fissuresUtil.database.NotFound;
import edu.sc.seis.fissuresUtil.database.network.JDBCChannel;
import edu.sc.seis.fissuresUtil.database.network.JDBCNetwork;
import edu.sc.seis.fissuresUtil.database.network.JDBCSite;
import edu.sc.seis.fissuresUtil.database.network.JDBCStation;
import edu.sc.seis.sod.database.ChannelDbObject;
import edu.sc.seis.sod.database.NetworkDbObject;
import edu.sc.seis.sod.database.SiteDbObject;
import edu.sc.seis.sod.subsetter.network.NetworkEffectiveTimeOverlap;
public class JDBCNetworkUnifier {
public JDBCNetworkUnifier() throws SQLException {
this(ConnMgr.createConnection());
}
public JDBCNetworkUnifier(Connection conn) throws SQLException {
this.chanDb = new JDBCChannel(conn);
this.netDb = chanDb.getNetworkTable();
this.stationDb = chanDb.getStationTable();
this.siteDb = chanDb.getSiteTable();
}
public ChannelDbObject getChannel(int chanDbId) throws NotFound,
SQLException {
return new ChannelDbObject(chanDbId, chanDb.get(chanDbId));
}
public int put(Channel chan) throws SQLException {
return chanDb.put(chan);
}
public SiteDbObject getSite(int siteDbId) throws NotFound, SQLException {
return new SiteDbObject(siteDbId, siteDb.get(siteDbId));
}
public int put(Site site) throws SQLException {
return siteDb.put(site);
}
public Station getStation(int stationDbId) throws NotFound, SQLException {
return stationDb.get(stationDbId);
}
public int put(Station station) throws SQLException {
return stationDb.put(station);
}
public NetworkAttr getNet(int netDbId) throws NotFound, SQLException {
return netDb.get(netDbId);
}
public NetworkDbObject getNet(int netDbId, ProxyNetworkDC ndc)
throws NetworkNotFound, NotFound, SQLException {
NetworkId id = netDb.get(netDbId).get_id();
ProxyNetworkAccess na;
synchronized(ndc) {
try {
- na = (ProxyNetworkAccess)ndc.a_finder().retrieve_by_id(id);
+ return new NetworkDbObject(netDbId, (ProxyNetworkAccess)ndc.a_finder().retrieve_by_id(id));
} catch(NetworkNotFound e) {
// didn't get by id, try by code
logger.debug("Caught exception with retrieve_by_id for "
+ NetworkIdUtil.toString(id) + ", trying by code", e);
NetworkAccess[] netArray = ndc.a_finder()
.retrieve_by_code(id.network_code);
+ if (netArray.length == 0) {
+ throw new NetworkNotFound("Cant retrieve_by_code for "
+ + NetworkIdUtil.toString(id) + " received "
+ + netArray.length + " nets.");
+ }
+ na = (ProxyNetworkAccess)netArray[0];
if(NetworkIdUtil.isTemporary(id)) {
// temp net codes are never reused in the same year, so
// find a network that overlaps the year we have in the id
// and hope it is right
// first make sure format is ok, just to make Charlie happy
MicroSecondDate formatCheck = new MicroSecondDate(id.begin_time);
String netYear = id.begin_time.date_time.substring(0, 4);
TimeRange year = new TimeRange(new Time(netYear
+ "0101T00:00:01.000Z", -1), new Time(netYear
+ "1231T23:59:59.000Z", -1));
NetworkEffectiveTimeOverlap yearOverlap = new NetworkEffectiveTimeOverlap(year);
NetworkAccess found = null;
for(int i = 0; i < netArray.length; i++) {
if(yearOverlap.overlaps(netArray[i].get_attributes().effective_time)) {
if(found != null) {
// two overlap, just give up?
throw new NetworkNotFound("No network matches id="
+ NetworkIdUtil.toString(id)
+ " and more than one overlaps year="
+ netYear);
}
found = netArray[i];
}
}
+ if (found != null) {
+ // found exactly one match so return it
+ return new NetworkDbObject(netDbId, (ProxyNetworkAccess)found);
+ } else {
+ throw new NetworkNotFound("Cant retrieve_by_code for "
+ + NetworkIdUtil.toString(id) + " no year overlaps in "
+ + netArray.length + " nets.");
+ }
} else if(netArray.length != 1) {
throw new NetworkNotFound("Cant retrieve_by_code for "
+ NetworkIdUtil.toString(id) + " received "
+ netArray.length + " nets.");
+ } else {
+ return new NetworkDbObject(netDbId, na);
}
- na = (ProxyNetworkAccess)netArray[0];
}
}
- return new NetworkDbObject(netDbId, na);
}
public int put(NetworkAttr net) throws SQLException {
return netDb.put(net);
}
public NetworkDbObject[] getAllNets(ProxyNetworkDC ndc)
throws SQLException, NotFound, NetworkNotFound {
int[] netIds = netDb.getAllNetworkDBIds();
NetworkDbObject[] out = new NetworkDbObject[netIds.length];
for(int i = 0; i < netIds.length; i++) {
out[i] = getNet(netIds[i], ndc);
}
return out;
}
public JDBCNetwork getNetworkDb() {
return netDb;
}
public JDBCChannel getChannelDb() {
return chanDb;
}
public JDBCSite getSiteDb() {
return siteDb;
}
public JDBCStation getStationDb() {
return stationDb;
}
private JDBCNetwork netDb;
private JDBCChannel chanDb;
private JDBCSite siteDb;
private JDBCStation stationDb;
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(JDBCNetworkUnifier.class);
}
| false | true | public NetworkDbObject getNet(int netDbId, ProxyNetworkDC ndc)
throws NetworkNotFound, NotFound, SQLException {
NetworkId id = netDb.get(netDbId).get_id();
ProxyNetworkAccess na;
synchronized(ndc) {
try {
na = (ProxyNetworkAccess)ndc.a_finder().retrieve_by_id(id);
} catch(NetworkNotFound e) {
// didn't get by id, try by code
logger.debug("Caught exception with retrieve_by_id for "
+ NetworkIdUtil.toString(id) + ", trying by code", e);
NetworkAccess[] netArray = ndc.a_finder()
.retrieve_by_code(id.network_code);
if(NetworkIdUtil.isTemporary(id)) {
// temp net codes are never reused in the same year, so
// find a network that overlaps the year we have in the id
// and hope it is right
// first make sure format is ok, just to make Charlie happy
MicroSecondDate formatCheck = new MicroSecondDate(id.begin_time);
String netYear = id.begin_time.date_time.substring(0, 4);
TimeRange year = new TimeRange(new Time(netYear
+ "0101T00:00:01.000Z", -1), new Time(netYear
+ "1231T23:59:59.000Z", -1));
NetworkEffectiveTimeOverlap yearOverlap = new NetworkEffectiveTimeOverlap(year);
NetworkAccess found = null;
for(int i = 0; i < netArray.length; i++) {
if(yearOverlap.overlaps(netArray[i].get_attributes().effective_time)) {
if(found != null) {
// two overlap, just give up?
throw new NetworkNotFound("No network matches id="
+ NetworkIdUtil.toString(id)
+ " and more than one overlaps year="
+ netYear);
}
found = netArray[i];
}
}
} else if(netArray.length != 1) {
throw new NetworkNotFound("Cant retrieve_by_code for "
+ NetworkIdUtil.toString(id) + " received "
+ netArray.length + " nets.");
}
na = (ProxyNetworkAccess)netArray[0];
}
}
return new NetworkDbObject(netDbId, na);
}
| public NetworkDbObject getNet(int netDbId, ProxyNetworkDC ndc)
throws NetworkNotFound, NotFound, SQLException {
NetworkId id = netDb.get(netDbId).get_id();
ProxyNetworkAccess na;
synchronized(ndc) {
try {
return new NetworkDbObject(netDbId, (ProxyNetworkAccess)ndc.a_finder().retrieve_by_id(id));
} catch(NetworkNotFound e) {
// didn't get by id, try by code
logger.debug("Caught exception with retrieve_by_id for "
+ NetworkIdUtil.toString(id) + ", trying by code", e);
NetworkAccess[] netArray = ndc.a_finder()
.retrieve_by_code(id.network_code);
if (netArray.length == 0) {
throw new NetworkNotFound("Cant retrieve_by_code for "
+ NetworkIdUtil.toString(id) + " received "
+ netArray.length + " nets.");
}
na = (ProxyNetworkAccess)netArray[0];
if(NetworkIdUtil.isTemporary(id)) {
// temp net codes are never reused in the same year, so
// find a network that overlaps the year we have in the id
// and hope it is right
// first make sure format is ok, just to make Charlie happy
MicroSecondDate formatCheck = new MicroSecondDate(id.begin_time);
String netYear = id.begin_time.date_time.substring(0, 4);
TimeRange year = new TimeRange(new Time(netYear
+ "0101T00:00:01.000Z", -1), new Time(netYear
+ "1231T23:59:59.000Z", -1));
NetworkEffectiveTimeOverlap yearOverlap = new NetworkEffectiveTimeOverlap(year);
NetworkAccess found = null;
for(int i = 0; i < netArray.length; i++) {
if(yearOverlap.overlaps(netArray[i].get_attributes().effective_time)) {
if(found != null) {
// two overlap, just give up?
throw new NetworkNotFound("No network matches id="
+ NetworkIdUtil.toString(id)
+ " and more than one overlaps year="
+ netYear);
}
found = netArray[i];
}
}
if (found != null) {
// found exactly one match so return it
return new NetworkDbObject(netDbId, (ProxyNetworkAccess)found);
} else {
throw new NetworkNotFound("Cant retrieve_by_code for "
+ NetworkIdUtil.toString(id) + " no year overlaps in "
+ netArray.length + " nets.");
}
} else if(netArray.length != 1) {
throw new NetworkNotFound("Cant retrieve_by_code for "
+ NetworkIdUtil.toString(id) + " received "
+ netArray.length + " nets.");
} else {
return new NetworkDbObject(netDbId, na);
}
}
}
}
|
diff --git a/grails/test/commons/grails/util/GrailsUtilTests.java b/grails/test/commons/grails/util/GrailsUtilTests.java
index 805808b3e..9c86d2b5b 100644
--- a/grails/test/commons/grails/util/GrailsUtilTests.java
+++ b/grails/test/commons/grails/util/GrailsUtilTests.java
@@ -1,53 +1,53 @@
/* Copyright 2004-2005 Graeme Rocher
*
* 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 grails.util;
import junit.framework.TestCase;
import org.codehaus.groovy.grails.commons.GrailsApplication;
/**
* Tests for the GrailsUtils class
*
* @author Graeme Rocher
* @since 0.4
* <p/>
* Created: Jan 22, 2007
* Time: 6:21:53 PM
*/
public class GrailsUtilTests extends TestCase {
public void testEnvironment() {
System.setProperty(GrailsApplication.ENVIRONMENT, "");
- assertEquals(GrailsApplication.ENV_APPLICATION, GrailsUtil.getEnvironment());
+ assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "prod");
assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "dev");
assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "test");
assertEquals(GrailsApplication.ENV_TEST, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "myenvironment");
assertEquals("myenvironment", GrailsUtil.getEnvironment());
}
protected void tearDown() throws Exception {
System.setProperty(GrailsApplication.ENVIRONMENT, "");
}
}
| true | true | public void testEnvironment() {
System.setProperty(GrailsApplication.ENVIRONMENT, "");
assertEquals(GrailsApplication.ENV_APPLICATION, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "prod");
assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "dev");
assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "test");
assertEquals(GrailsApplication.ENV_TEST, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "myenvironment");
assertEquals("myenvironment", GrailsUtil.getEnvironment());
}
| public void testEnvironment() {
System.setProperty(GrailsApplication.ENVIRONMENT, "");
assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "prod");
assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "dev");
assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "test");
assertEquals(GrailsApplication.ENV_TEST, GrailsUtil.getEnvironment());
System.setProperty(GrailsApplication.ENVIRONMENT, "myenvironment");
assertEquals("myenvironment", GrailsUtil.getEnvironment());
}
|
diff --git a/router/java/src/net/i2p/router/networkdb/HandleDatabaseLookupMessageJob.java b/router/java/src/net/i2p/router/networkdb/HandleDatabaseLookupMessageJob.java
index 3166f7c70..b75374674 100644
--- a/router/java/src/net/i2p/router/networkdb/HandleDatabaseLookupMessageJob.java
+++ b/router/java/src/net/i2p/router/networkdb/HandleDatabaseLookupMessageJob.java
@@ -1,306 +1,306 @@
package net.i2p.router.networkdb;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import net.i2p.data.DataStructure;
import net.i2p.data.Hash;
import net.i2p.data.LeaseSet;
import net.i2p.data.RouterIdentity;
import net.i2p.data.RouterInfo;
import net.i2p.data.TunnelId;
import net.i2p.data.i2np.DatabaseLookupMessage;
import net.i2p.data.i2np.DatabaseSearchReplyMessage;
import net.i2p.data.i2np.DatabaseStoreMessage;
import net.i2p.data.i2np.I2NPMessage;
import net.i2p.data.i2np.TunnelGatewayMessage;
import net.i2p.router.Job;
import net.i2p.router.JobImpl;
import net.i2p.router.Router;
import net.i2p.router.RouterContext;
import net.i2p.router.message.SendMessageDirectJob;
import net.i2p.util.Log;
/**
* Handle a lookup for a key received from a remote peer. Needs to be implemented
* to send back replies, etc
* Unused directly - see kademlia/ for extension
*/
public class HandleDatabaseLookupMessageJob extends JobImpl {
private Log _log;
private DatabaseLookupMessage _message;
private RouterIdentity _from;
private Hash _fromHash;
private final static int MAX_ROUTERS_RETURNED = 3;
private final static int CLOSENESS_THRESHOLD = 8; // FNDF.MAX_TO_FLOOD + 1
private final static int REPLY_TIMEOUT = 60*1000;
private final static int MESSAGE_PRIORITY = 300;
/**
* If a routerInfo structure isn't this recent, don't send it out.
* Equal to KNDF.ROUTER_INFO_EXPIRATION_FLOODFILL.
*/
public final static long EXPIRE_DELAY = 60*60*1000;
public HandleDatabaseLookupMessageJob(RouterContext ctx, DatabaseLookupMessage receivedMessage, RouterIdentity from, Hash fromHash) {
super(ctx);
_log = getContext().logManager().getLog(HandleDatabaseLookupMessageJob.class);
_message = receivedMessage;
_from = from;
_fromHash = fromHash;
}
protected boolean answerAllQueries() { return false; }
public void runJob() {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Handling database lookup message for " + _message.getSearchKey());
Hash fromKey = _message.getFrom();
if (_log.shouldLog(Log.DEBUG)) {
if (_message.getReplyTunnel() != null)
_log.debug("dbLookup received with replies going to " + fromKey
+ " (tunnel " + _message.getReplyTunnel() + ")");
}
// If we are hidden we should not get queries, log and return
if (getContext().router().isHidden()) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Uninvited dbLookup received with replies going to " + fromKey
+ " (tunnel " + _message.getReplyTunnel() + ")");
}
return;
}
LeaseSet ls = getContext().netDb().lookupLeaseSetLocally(_message.getSearchKey());
if (ls != null) {
// We have to be very careful here to decide whether or not to send out the leaseSet,
// to avoid anonymity vulnerabilities.
// As this is complex, lots of comments follow...
boolean isLocal = getContext().clientManager().isLocal(ls.getDestination());
boolean shouldPublishLocal = isLocal && getContext().clientManager().shouldPublishLeaseSet(_message.getSearchKey());
// Only answer a request for a LeaseSet if it has been published
// to us, or, if its local, if we would have published to ourselves
// answerAllQueries: We are floodfill
// getReceivedAsPublished:
// false for local
// false for received over a tunnel
// false for received in response to our lookups
// true for received in a DatabaseStoreMessage unsolicited
if (ls.getReceivedAsPublished()) {
// Answer anything that was stored to us directly
// (i.e. "received as published" - not the result of a query, or received
// over a client tunnel).
// This is probably because we are floodfill, but also perhaps we used to be floodfill,
// so we don't check the answerAllQueries() flag.
// Local leasesets are not handled here
if (_log.shouldLog(Log.INFO))
_log.info("We have the published LS " + _message.getSearchKey().toBase64() + ", answering query");
getContext().statManager().addRateData("netDb.lookupsMatchedReceivedPublished", 1, 0);
sendData(_message.getSearchKey(), ls, fromKey, _message.getReplyTunnel());
} else if (shouldPublishLocal && answerAllQueries()) {
// We are floodfill, and this is our local leaseset, and we publish it.
// Only send it out if it is in our estimated keyspace.
// For this, we do NOT use their dontInclude list as it can't be trusted
// (i.e. it could mess up the closeness calculation)
Set<Hash> closestHashes = getContext().netDb().findNearestRouters(_message.getSearchKey(),
CLOSENESS_THRESHOLD, null);
if (weAreClosest(closestHashes)) {
// It's in our keyspace, so give it to them
if (_log.shouldLog(Log.INFO))
_log.info("We have local LS " + _message.getSearchKey().toBase64() + ", answering query, in our keyspace");
getContext().statManager().addRateData("netDb.lookupsMatchedLocalClosest", 1, 0);
sendData(_message.getSearchKey(), ls, fromKey, _message.getReplyTunnel());
} else {
// Lie, pretend we don't have it
if (_log.shouldLog(Log.INFO))
_log.info("We have local LS " + _message.getSearchKey().toBase64() + ", NOT answering query, out of our keyspace");
getContext().statManager().addRateData("netDb.lookupsMatchedLocalNotClosest", 1, 0);
Set<Hash> routerHashSet = getNearestRouters();
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
} else {
// It was not published to us (we looked it up, for example)
// or it's local and we aren't floodfill,
// or it's local and we don't publish it.
// Lie, pretend we don't have it
if (_log.shouldLog(Log.INFO))
_log.info("We have LS " + _message.getSearchKey().toBase64() +
", NOT answering query - local? " + isLocal + " shouldPublish? " + shouldPublishLocal +
" RAP? " + ls.getReceivedAsPublished() + " RAR? " + ls.getReceivedAsReply());
getContext().statManager().addRateData("netDb.lookupsMatchedRemoteNotClosest", 1, 0);
Set<Hash> routerHashSet = getNearestRouters();
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
} else {
RouterInfo info = getContext().netDb().lookupRouterInfoLocally(_message.getSearchKey());
if ( (info != null) && (info.isCurrent(EXPIRE_DELAY)) ) {
if ( (info.getIdentity().isHidden()) || (isUnreachable(info) && !publishUnreachable()) ) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Not answering a query for a netDb peer who isn't reachable");
- Set us = new HashSet(1);
- us.add(getContext().router().getRouterInfo());
+ Set<Hash> us = new HashSet<Hash>(1);
+ us.add(getContext().router().getRouterInfo().calculateHash());
sendClosest(_message.getSearchKey(), us, fromKey, _message.getReplyTunnel());
//} else if (info.isHidden()) {
// // Don't return hidden nodes
// ERR: we don't want to explicitly reject lookups for hidden nodes, since they
// may have just sent the hidden mode to only us and bundled a lookup with
// a payload targetting some hidden destination (and if we refused to answer,
// yet answered the bundled data message [e.g. HTTP GET], they'd know that
// *we* were hosting that destination). To operate safely,
// perhaps we should refuse to honor lookups bundled down client tunnels?
} else {
// send that routerInfo to the _message.getFromHash peer
if (_log.shouldLog(Log.DEBUG))
_log.debug("We do have key " + _message.getSearchKey().toBase64()
+ " locally as a router info. sending to " + fromKey.toBase64());
sendData(_message.getSearchKey(), info, fromKey, _message.getReplyTunnel());
}
} else {
// not found locally - return closest peer hashes
Set<Hash> routerHashSet = getNearestRouters();
// ERR: see above
// // Remove hidden nodes from set..
// for (Iterator iter = routerInfoSet.iterator(); iter.hasNext();) {
// RouterInfo peer = (RouterInfo)iter.next();
// if (peer.isHidden()) {
// iter.remove();
// }
// }
if (_log.shouldLog(Log.DEBUG))
_log.debug("We do not have key " + _message.getSearchKey().toBase64() +
" locally. sending back " + routerHashSet.size() + " peers to " + fromKey.toBase64());
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
}
}
/**
* Closest to the message's search key,
* honoring the message's dontInclude set.
* Will not include us.
* Side effect - adds us to the message's dontInclude set.
*/
private Set<Hash> getNearestRouters() {
Set<Hash> dontInclude = _message.getDontIncludePeers();
if (dontInclude == null)
dontInclude = new HashSet(1);
dontInclude.add(getContext().routerHash());
// Honor flag to exclude all floodfills
//if (dontInclude.contains(Hash.FAKE_HASH)) {
// This is handled in FloodfillPeerSelector
return getContext().netDb().findNearestRouters(_message.getSearchKey(),
MAX_ROUTERS_RETURNED,
dontInclude);
}
private static boolean isUnreachable(RouterInfo info) {
if (info == null) return true;
String cap = info.getCapabilities();
if (cap == null) return false;
return cap.indexOf(Router.CAPABILITY_REACHABLE) >= 0;
}
public static final String PROP_PUBLISH_UNREACHABLE = "router.publishUnreachableRouters";
public static final boolean DEFAULT_PUBLISH_UNREACHABLE = true;
private boolean publishUnreachable() {
return getContext().getProperty(PROP_PUBLISH_UNREACHABLE, DEFAULT_PUBLISH_UNREACHABLE);
}
private boolean weAreClosest(Set<Hash> routerHashSet) {
return routerHashSet.contains(getContext().routerHash());
}
private void sendData(Hash key, DataStructure data, Hash toPeer, TunnelId replyTunnel) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Sending data matching key " + key.toBase64() + " to peer " + toPeer.toBase64()
+ " tunnel " + replyTunnel);
DatabaseStoreMessage msg = new DatabaseStoreMessage(getContext());
msg.setKey(key);
if (data instanceof LeaseSet) {
msg.setLeaseSet((LeaseSet)data);
msg.setValueType(DatabaseStoreMessage.KEY_TYPE_LEASESET);
getContext().statManager().addRateData("netDb.lookupsMatchedLeaseSet", 1, 0);
} else if (data instanceof RouterInfo) {
msg.setRouterInfo((RouterInfo)data);
msg.setValueType(DatabaseStoreMessage.KEY_TYPE_ROUTERINFO);
}
getContext().statManager().addRateData("netDb.lookupsMatched", 1, 0);
getContext().statManager().addRateData("netDb.lookupsHandled", 1, 0);
sendMessage(msg, toPeer, replyTunnel);
}
protected void sendClosest(Hash key, Set<Hash> routerHashes, Hash toPeer, TunnelId replyTunnel) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Sending closest routers to key " + key.toBase64() + ": # peers = "
+ routerHashes.size() + " tunnel " + replyTunnel);
DatabaseSearchReplyMessage msg = new DatabaseSearchReplyMessage(getContext());
msg.setFromHash(getContext().routerHash());
msg.setSearchKey(key);
int i = 0;
for (Hash h : routerHashes) {
msg.addReply(h);
if (++i >= MAX_ROUTERS_RETURNED)
break;
}
getContext().statManager().addRateData("netDb.lookupsHandled", 1, 0);
sendMessage(msg, toPeer, replyTunnel); // should this go via garlic messages instead?
}
protected void sendMessage(I2NPMessage message, Hash toPeer, TunnelId replyTunnel) {
if (replyTunnel != null) {
sendThroughTunnel(message, toPeer, replyTunnel);
} else {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Sending reply directly to " + toPeer);
Job send = new SendMessageDirectJob(getContext(), message, toPeer, REPLY_TIMEOUT, MESSAGE_PRIORITY);
send.runJob();
//getContext().netDb().lookupRouterInfo(toPeer, send, null, REPLY_TIMEOUT);
}
}
private void sendThroughTunnel(I2NPMessage message, Hash toPeer, TunnelId replyTunnel) {
if (getContext().routerHash().equals(toPeer)) {
// if we are the gateway, act as if we received it
TunnelGatewayMessage m = new TunnelGatewayMessage(getContext());
m.setMessage(message);
m.setTunnelId(replyTunnel);
m.setMessageExpiration(message.getMessageExpiration());
getContext().tunnelDispatcher().dispatch(m);
} else {
// if we aren't the gateway, forward it on
TunnelGatewayMessage m = new TunnelGatewayMessage(getContext());
m.setMessage(message);
m.setMessageExpiration(message.getMessageExpiration());
m.setTunnelId(replyTunnel);
SendMessageDirectJob j = new SendMessageDirectJob(getContext(), m, toPeer, 10*1000, 100);
j.runJob();
//getContext().jobQueue().addJob(j);
}
}
public String getName() { return "Handle Database Lookup Message"; }
@Override
public void dropped() {
getContext().messageHistory().messageProcessingError(_message.getUniqueId(),
_message.getClass().getName(),
"Dropped due to overload");
}
}
| true | true | public void runJob() {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Handling database lookup message for " + _message.getSearchKey());
Hash fromKey = _message.getFrom();
if (_log.shouldLog(Log.DEBUG)) {
if (_message.getReplyTunnel() != null)
_log.debug("dbLookup received with replies going to " + fromKey
+ " (tunnel " + _message.getReplyTunnel() + ")");
}
// If we are hidden we should not get queries, log and return
if (getContext().router().isHidden()) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Uninvited dbLookup received with replies going to " + fromKey
+ " (tunnel " + _message.getReplyTunnel() + ")");
}
return;
}
LeaseSet ls = getContext().netDb().lookupLeaseSetLocally(_message.getSearchKey());
if (ls != null) {
// We have to be very careful here to decide whether or not to send out the leaseSet,
// to avoid anonymity vulnerabilities.
// As this is complex, lots of comments follow...
boolean isLocal = getContext().clientManager().isLocal(ls.getDestination());
boolean shouldPublishLocal = isLocal && getContext().clientManager().shouldPublishLeaseSet(_message.getSearchKey());
// Only answer a request for a LeaseSet if it has been published
// to us, or, if its local, if we would have published to ourselves
// answerAllQueries: We are floodfill
// getReceivedAsPublished:
// false for local
// false for received over a tunnel
// false for received in response to our lookups
// true for received in a DatabaseStoreMessage unsolicited
if (ls.getReceivedAsPublished()) {
// Answer anything that was stored to us directly
// (i.e. "received as published" - not the result of a query, or received
// over a client tunnel).
// This is probably because we are floodfill, but also perhaps we used to be floodfill,
// so we don't check the answerAllQueries() flag.
// Local leasesets are not handled here
if (_log.shouldLog(Log.INFO))
_log.info("We have the published LS " + _message.getSearchKey().toBase64() + ", answering query");
getContext().statManager().addRateData("netDb.lookupsMatchedReceivedPublished", 1, 0);
sendData(_message.getSearchKey(), ls, fromKey, _message.getReplyTunnel());
} else if (shouldPublishLocal && answerAllQueries()) {
// We are floodfill, and this is our local leaseset, and we publish it.
// Only send it out if it is in our estimated keyspace.
// For this, we do NOT use their dontInclude list as it can't be trusted
// (i.e. it could mess up the closeness calculation)
Set<Hash> closestHashes = getContext().netDb().findNearestRouters(_message.getSearchKey(),
CLOSENESS_THRESHOLD, null);
if (weAreClosest(closestHashes)) {
// It's in our keyspace, so give it to them
if (_log.shouldLog(Log.INFO))
_log.info("We have local LS " + _message.getSearchKey().toBase64() + ", answering query, in our keyspace");
getContext().statManager().addRateData("netDb.lookupsMatchedLocalClosest", 1, 0);
sendData(_message.getSearchKey(), ls, fromKey, _message.getReplyTunnel());
} else {
// Lie, pretend we don't have it
if (_log.shouldLog(Log.INFO))
_log.info("We have local LS " + _message.getSearchKey().toBase64() + ", NOT answering query, out of our keyspace");
getContext().statManager().addRateData("netDb.lookupsMatchedLocalNotClosest", 1, 0);
Set<Hash> routerHashSet = getNearestRouters();
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
} else {
// It was not published to us (we looked it up, for example)
// or it's local and we aren't floodfill,
// or it's local and we don't publish it.
// Lie, pretend we don't have it
if (_log.shouldLog(Log.INFO))
_log.info("We have LS " + _message.getSearchKey().toBase64() +
", NOT answering query - local? " + isLocal + " shouldPublish? " + shouldPublishLocal +
" RAP? " + ls.getReceivedAsPublished() + " RAR? " + ls.getReceivedAsReply());
getContext().statManager().addRateData("netDb.lookupsMatchedRemoteNotClosest", 1, 0);
Set<Hash> routerHashSet = getNearestRouters();
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
} else {
RouterInfo info = getContext().netDb().lookupRouterInfoLocally(_message.getSearchKey());
if ( (info != null) && (info.isCurrent(EXPIRE_DELAY)) ) {
if ( (info.getIdentity().isHidden()) || (isUnreachable(info) && !publishUnreachable()) ) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Not answering a query for a netDb peer who isn't reachable");
Set us = new HashSet(1);
us.add(getContext().router().getRouterInfo());
sendClosest(_message.getSearchKey(), us, fromKey, _message.getReplyTunnel());
//} else if (info.isHidden()) {
// // Don't return hidden nodes
// ERR: we don't want to explicitly reject lookups for hidden nodes, since they
// may have just sent the hidden mode to only us and bundled a lookup with
// a payload targetting some hidden destination (and if we refused to answer,
// yet answered the bundled data message [e.g. HTTP GET], they'd know that
// *we* were hosting that destination). To operate safely,
// perhaps we should refuse to honor lookups bundled down client tunnels?
} else {
// send that routerInfo to the _message.getFromHash peer
if (_log.shouldLog(Log.DEBUG))
_log.debug("We do have key " + _message.getSearchKey().toBase64()
+ " locally as a router info. sending to " + fromKey.toBase64());
sendData(_message.getSearchKey(), info, fromKey, _message.getReplyTunnel());
}
} else {
// not found locally - return closest peer hashes
Set<Hash> routerHashSet = getNearestRouters();
// ERR: see above
// // Remove hidden nodes from set..
// for (Iterator iter = routerInfoSet.iterator(); iter.hasNext();) {
// RouterInfo peer = (RouterInfo)iter.next();
// if (peer.isHidden()) {
// iter.remove();
// }
// }
if (_log.shouldLog(Log.DEBUG))
_log.debug("We do not have key " + _message.getSearchKey().toBase64() +
" locally. sending back " + routerHashSet.size() + " peers to " + fromKey.toBase64());
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
}
}
| public void runJob() {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Handling database lookup message for " + _message.getSearchKey());
Hash fromKey = _message.getFrom();
if (_log.shouldLog(Log.DEBUG)) {
if (_message.getReplyTunnel() != null)
_log.debug("dbLookup received with replies going to " + fromKey
+ " (tunnel " + _message.getReplyTunnel() + ")");
}
// If we are hidden we should not get queries, log and return
if (getContext().router().isHidden()) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Uninvited dbLookup received with replies going to " + fromKey
+ " (tunnel " + _message.getReplyTunnel() + ")");
}
return;
}
LeaseSet ls = getContext().netDb().lookupLeaseSetLocally(_message.getSearchKey());
if (ls != null) {
// We have to be very careful here to decide whether or not to send out the leaseSet,
// to avoid anonymity vulnerabilities.
// As this is complex, lots of comments follow...
boolean isLocal = getContext().clientManager().isLocal(ls.getDestination());
boolean shouldPublishLocal = isLocal && getContext().clientManager().shouldPublishLeaseSet(_message.getSearchKey());
// Only answer a request for a LeaseSet if it has been published
// to us, or, if its local, if we would have published to ourselves
// answerAllQueries: We are floodfill
// getReceivedAsPublished:
// false for local
// false for received over a tunnel
// false for received in response to our lookups
// true for received in a DatabaseStoreMessage unsolicited
if (ls.getReceivedAsPublished()) {
// Answer anything that was stored to us directly
// (i.e. "received as published" - not the result of a query, or received
// over a client tunnel).
// This is probably because we are floodfill, but also perhaps we used to be floodfill,
// so we don't check the answerAllQueries() flag.
// Local leasesets are not handled here
if (_log.shouldLog(Log.INFO))
_log.info("We have the published LS " + _message.getSearchKey().toBase64() + ", answering query");
getContext().statManager().addRateData("netDb.lookupsMatchedReceivedPublished", 1, 0);
sendData(_message.getSearchKey(), ls, fromKey, _message.getReplyTunnel());
} else if (shouldPublishLocal && answerAllQueries()) {
// We are floodfill, and this is our local leaseset, and we publish it.
// Only send it out if it is in our estimated keyspace.
// For this, we do NOT use their dontInclude list as it can't be trusted
// (i.e. it could mess up the closeness calculation)
Set<Hash> closestHashes = getContext().netDb().findNearestRouters(_message.getSearchKey(),
CLOSENESS_THRESHOLD, null);
if (weAreClosest(closestHashes)) {
// It's in our keyspace, so give it to them
if (_log.shouldLog(Log.INFO))
_log.info("We have local LS " + _message.getSearchKey().toBase64() + ", answering query, in our keyspace");
getContext().statManager().addRateData("netDb.lookupsMatchedLocalClosest", 1, 0);
sendData(_message.getSearchKey(), ls, fromKey, _message.getReplyTunnel());
} else {
// Lie, pretend we don't have it
if (_log.shouldLog(Log.INFO))
_log.info("We have local LS " + _message.getSearchKey().toBase64() + ", NOT answering query, out of our keyspace");
getContext().statManager().addRateData("netDb.lookupsMatchedLocalNotClosest", 1, 0);
Set<Hash> routerHashSet = getNearestRouters();
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
} else {
// It was not published to us (we looked it up, for example)
// or it's local and we aren't floodfill,
// or it's local and we don't publish it.
// Lie, pretend we don't have it
if (_log.shouldLog(Log.INFO))
_log.info("We have LS " + _message.getSearchKey().toBase64() +
", NOT answering query - local? " + isLocal + " shouldPublish? " + shouldPublishLocal +
" RAP? " + ls.getReceivedAsPublished() + " RAR? " + ls.getReceivedAsReply());
getContext().statManager().addRateData("netDb.lookupsMatchedRemoteNotClosest", 1, 0);
Set<Hash> routerHashSet = getNearestRouters();
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
} else {
RouterInfo info = getContext().netDb().lookupRouterInfoLocally(_message.getSearchKey());
if ( (info != null) && (info.isCurrent(EXPIRE_DELAY)) ) {
if ( (info.getIdentity().isHidden()) || (isUnreachable(info) && !publishUnreachable()) ) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Not answering a query for a netDb peer who isn't reachable");
Set<Hash> us = new HashSet<Hash>(1);
us.add(getContext().router().getRouterInfo().calculateHash());
sendClosest(_message.getSearchKey(), us, fromKey, _message.getReplyTunnel());
//} else if (info.isHidden()) {
// // Don't return hidden nodes
// ERR: we don't want to explicitly reject lookups for hidden nodes, since they
// may have just sent the hidden mode to only us and bundled a lookup with
// a payload targetting some hidden destination (and if we refused to answer,
// yet answered the bundled data message [e.g. HTTP GET], they'd know that
// *we* were hosting that destination). To operate safely,
// perhaps we should refuse to honor lookups bundled down client tunnels?
} else {
// send that routerInfo to the _message.getFromHash peer
if (_log.shouldLog(Log.DEBUG))
_log.debug("We do have key " + _message.getSearchKey().toBase64()
+ " locally as a router info. sending to " + fromKey.toBase64());
sendData(_message.getSearchKey(), info, fromKey, _message.getReplyTunnel());
}
} else {
// not found locally - return closest peer hashes
Set<Hash> routerHashSet = getNearestRouters();
// ERR: see above
// // Remove hidden nodes from set..
// for (Iterator iter = routerInfoSet.iterator(); iter.hasNext();) {
// RouterInfo peer = (RouterInfo)iter.next();
// if (peer.isHidden()) {
// iter.remove();
// }
// }
if (_log.shouldLog(Log.DEBUG))
_log.debug("We do not have key " + _message.getSearchKey().toBase64() +
" locally. sending back " + routerHashSet.size() + " peers to " + fromKey.toBase64());
sendClosest(_message.getSearchKey(), routerHashSet, fromKey, _message.getReplyTunnel());
}
}
}
|
diff --git a/src/main/java/org/mvel2/MacroProcessor.java b/src/main/java/org/mvel2/MacroProcessor.java
index 4eb5d520..7700245d 100644
--- a/src/main/java/org/mvel2/MacroProcessor.java
+++ b/src/main/java/org/mvel2/MacroProcessor.java
@@ -1,120 +1,122 @@
/**
* MVEL 2.0
* Copyright (C) 2007 The Codehaus
* Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor
*
* 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.mvel2;
import org.mvel2.compiler.AbstractParser;
import static org.mvel2.util.ParseTools.isWhitespace;
import static org.mvel2.util.ParseTools.isIdentifierPart;
import org.mvel2.util.StringAppender;
import org.mvel2.util.ParseTools;
import java.util.Map;
/**
* A simple, fast, macro processor. This processor works by simply replacing a matched identifier with a set of code.
*/
public class MacroProcessor extends AbstractParser implements PreProcessor {
private Map<String, Macro> macros;
public MacroProcessor() {
}
public MacroProcessor(Map<String, Macro> macros) {
this.macros = macros;
}
public char[] parse(char[] input) {
setExpression(input);
StringAppender appender = new StringAppender();
int start;
boolean macroArmed = true;
String token;
for (; cursor < length; cursor++) {
start = cursor;
while (cursor < length && isIdentifierPart(expr[cursor])) cursor++;
if (cursor > start) {
if (macros.containsKey(token = new String(expr, start, cursor - start)) && macroArmed) {
appender.append(macros.get(token).doMacro());
}
else {
appender.append(token);
}
}
if (cursor < length) {
switch (expr[cursor]) {
case '\\':
cursor++;
break;
case '/':
start = cursor;
if (skipCommentBlock() == OP_CONTINUE) {
if (cursor < length) cursor++;
}
appender.append(new String(expr, start, cursor - start));
if (cursor < length) cursor--;
break;
case '"':
case '\'':
start = cursor;
cursor = ParseTools.captureStringLiteral(expr[cursor], expr, cursor, length);
appender.append(new String(expr, start, cursor - start));
if (cursor >= length) break;
else if (isIdentifierPart(expr[cursor])) cursor--;
default:
switch (expr[cursor]) {
case '.':
macroArmed = false;
break;
case ';':
+ case '{':
+ case '(':
macroArmed = true;
break;
}
appender.append(expr[cursor]);
}
}
}
return appender.toChars();
}
public String parse(String input) {
return new String(parse(input.toCharArray()));
}
public Map<String, Macro> getMacros() {
return macros;
}
public void setMacros(Map<String, Macro> macros) {
this.macros = macros;
}
public void captureToWhitespace() {
while (cursor < length && !isWhitespace(expr[cursor])) cursor++;
}
}
| true | true | public char[] parse(char[] input) {
setExpression(input);
StringAppender appender = new StringAppender();
int start;
boolean macroArmed = true;
String token;
for (; cursor < length; cursor++) {
start = cursor;
while (cursor < length && isIdentifierPart(expr[cursor])) cursor++;
if (cursor > start) {
if (macros.containsKey(token = new String(expr, start, cursor - start)) && macroArmed) {
appender.append(macros.get(token).doMacro());
}
else {
appender.append(token);
}
}
if (cursor < length) {
switch (expr[cursor]) {
case '\\':
cursor++;
break;
case '/':
start = cursor;
if (skipCommentBlock() == OP_CONTINUE) {
if (cursor < length) cursor++;
}
appender.append(new String(expr, start, cursor - start));
if (cursor < length) cursor--;
break;
case '"':
case '\'':
start = cursor;
cursor = ParseTools.captureStringLiteral(expr[cursor], expr, cursor, length);
appender.append(new String(expr, start, cursor - start));
if (cursor >= length) break;
else if (isIdentifierPart(expr[cursor])) cursor--;
default:
switch (expr[cursor]) {
case '.':
macroArmed = false;
break;
case ';':
macroArmed = true;
break;
}
appender.append(expr[cursor]);
}
}
}
return appender.toChars();
}
| public char[] parse(char[] input) {
setExpression(input);
StringAppender appender = new StringAppender();
int start;
boolean macroArmed = true;
String token;
for (; cursor < length; cursor++) {
start = cursor;
while (cursor < length && isIdentifierPart(expr[cursor])) cursor++;
if (cursor > start) {
if (macros.containsKey(token = new String(expr, start, cursor - start)) && macroArmed) {
appender.append(macros.get(token).doMacro());
}
else {
appender.append(token);
}
}
if (cursor < length) {
switch (expr[cursor]) {
case '\\':
cursor++;
break;
case '/':
start = cursor;
if (skipCommentBlock() == OP_CONTINUE) {
if (cursor < length) cursor++;
}
appender.append(new String(expr, start, cursor - start));
if (cursor < length) cursor--;
break;
case '"':
case '\'':
start = cursor;
cursor = ParseTools.captureStringLiteral(expr[cursor], expr, cursor, length);
appender.append(new String(expr, start, cursor - start));
if (cursor >= length) break;
else if (isIdentifierPart(expr[cursor])) cursor--;
default:
switch (expr[cursor]) {
case '.':
macroArmed = false;
break;
case ';':
case '{':
case '(':
macroArmed = true;
break;
}
appender.append(expr[cursor]);
}
}
}
return appender.toChars();
}
|
diff --git a/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java b/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java
index fb539815bd..66c591ded9 100644
--- a/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java
+++ b/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java
@@ -1,118 +1,121 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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 (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 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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.maven;
import static org.apache.commons.io.FileUtils.copyFile;
import java.io.File;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
/**
* @goal copy
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class CopyMojo extends AbstractMojo {
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* @parameter
*/
private Copy[] files;
public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
if ( files == null ) {
log.debug( "No files configured." );
return;
}
File basedir = project.getBasedir();
for ( Copy copy : files ) {
log.info( "Copy " + copy.from + " to " + copy.to );
File from = new File( basedir, copy.from );
File to = new File( basedir, copy.to );
- to.getParentFile().mkdirs();
+ if ( !to.getParentFile().mkdirs() ) {
+ log.warn( "Could not create parent directories for " + to + "." );
+ continue;
+ }
try {
copyFile( from, to );
} catch ( IOException e ) {
log.warn( "Could not copy " + copy.from + " to " + copy.to + ": " + e.getLocalizedMessage() );
log.debug( e );
}
}
}
/**
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public static class Copy {
/**
* @parameter
*/
String from;
/**
* @parameter
*/
String to;
@Override
public String toString() {
return from + " -> " + to;
}
}
}
| true | true | public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
if ( files == null ) {
log.debug( "No files configured." );
return;
}
File basedir = project.getBasedir();
for ( Copy copy : files ) {
log.info( "Copy " + copy.from + " to " + copy.to );
File from = new File( basedir, copy.from );
File to = new File( basedir, copy.to );
to.getParentFile().mkdirs();
try {
copyFile( from, to );
} catch ( IOException e ) {
log.warn( "Could not copy " + copy.from + " to " + copy.to + ": " + e.getLocalizedMessage() );
log.debug( e );
}
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
if ( files == null ) {
log.debug( "No files configured." );
return;
}
File basedir = project.getBasedir();
for ( Copy copy : files ) {
log.info( "Copy " + copy.from + " to " + copy.to );
File from = new File( basedir, copy.from );
File to = new File( basedir, copy.to );
if ( !to.getParentFile().mkdirs() ) {
log.warn( "Could not create parent directories for " + to + "." );
continue;
}
try {
copyFile( from, to );
} catch ( IOException e ) {
log.warn( "Could not copy " + copy.from + " to " + copy.to + ": " + e.getLocalizedMessage() );
log.debug( e );
}
}
}
|
diff --git a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/JFlexLexer.java b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/JFlexLexer.java
index 41c31102..8a7716b8 100644
--- a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/JFlexLexer.java
+++ b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/JFlexLexer.java
@@ -1,529 +1,534 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* 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 (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.parser.jflex;
import java.util.Stack;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.Environment;
import org.jamwiki.parser.ParserOutput;
import org.jamwiki.parser.ParserInput;
import org.jamwiki.utils.WikiLogger;
/**
* Abstract class that is extended by the JFlex lexers. This class primarily
* contains utility methods useful during parsing.
*/
public abstract class JFlexLexer {
private static final WikiLogger logger = WikiLogger.getLogger(JFlexLexer.class.getName());
/** Member variable used to keep track of the state history for the lexer. */
protected Stack<Integer> states = new Stack<Integer>();
/** Parser configuration information. */
protected ParserInput parserInput = null;
/** Parser parsing results. */
protected ParserOutput parserOutput = null;
/** Parser mode, which provides input to the parser about what steps to take. */
protected int mode = JFlexParser.MODE_POSTPROCESS;
/** Stack of currently parsed tag content. */
private Stack<JFlexTagItem> tagStack = new Stack<JFlexTagItem>();
/**
* Utility method used to indicate whether HTML tags are allowed in wiki syntax
* or not.
*/
protected boolean allowHTML() {
return Environment.getBooleanValue(Environment.PROP_PARSER_ALLOW_HTML);
}
/**
* Utility method used to indicate whether Javascript is allowed in wiki syntax
* or not.
*/
protected boolean allowJavascript() {
return Environment.getBooleanValue(Environment.PROP_PARSER_ALLOW_JAVASCRIPT);
}
/**
* Utility method used to indicate whether templates are allowed in wiki syntax
* or not.
*/
protected boolean allowTemplates() {
return Environment.getBooleanValue(Environment.PROP_PARSER_ALLOW_TEMPLATES);
}
/**
* Append content to the current tag in the tag stack.
*/
protected void append(String content) {
JFlexTagItem currentTag = this.tagStack.peek();
currentTag.getTagContent().append(content);
}
/**
* Begin a new parser state and store the old state onto the stack.
*
* @param state The new parsing state that is being entered.
*/
protected void beginState(int state) {
// store current state
states.push(yystate());
// switch to new state
yybegin(state);
}
/**
* End processing of a parser state and switch to the previous parser state.
*/
protected void endState() {
// revert to previous state
if (states.empty()) {
logger.warning("Attempt to call endState for an empty stack with text: " + yytext());
return;
}
int next = states.pop();
yybegin(next);
}
/**
* This method is used to set the ParserOutput field, which is used to retrieve
* parsed information from the parser.
*
* @return Parsed information generated by the parser
*/
public ParserOutput getParserOutput() {
return this.parserOutput;
}
/**
* Initialize the parser settings. This functionality should be done
* from the constructor, but since JFlex generates code it is not possible
* to modify the constructor parameters.
*
* @param parserInput The ParserInput object containing parser parameters
* required for successful parsing.
* @param parserOutput The current parsed document. When parsing is done
* in multiple stages that output values are also built in stages.
* @param mode The parser mode to use when parsing. Mode affects what
* type of parsing actions are taken when processing raw text.
*/
public final void init(ParserInput parserInput, ParserOutput parserOutput, int mode) {
this.parserInput = parserInput;
this.parserOutput = parserOutput;
this.mode = mode;
this.tagStack.push(new JFlexTagItem(JFlexTagItem.ROOT_TAG));
}
/**
* Peek at the current tag from the lexer stack and see if it matches
* the given tag type.
*/
protected JFlexTagItem peekTag() {
return (JFlexTagItem)this.tagStack.peek();
}
/**
* Pop the most recent HTML tag from the lexer stack.
*/
protected JFlexTagItem popTag(String tagType) {
if (this.tagStack.size() <= 1) {
logger.warning("popTag called on an empty tag stack or on the root stack element. Please report this error on jamwiki.org, and provide the wiki syntax for the topic being parsed.");
}
// verify that the tag being closed is the tag that is currently open. if not
// there are two options - first is that the user entered unbalanced HTML such
// as "<u><strong>text</u></strong>" and it should be re-balanced, and second
// is that this is just a random close tag such as "<div>text</div></div>" and
// it should be escaped without modifying the tag stack.
if (!this.peekTag().getTagType().equals(tagType)) {
// check to see if a close tag override was previously set, which happens
// from the inner tag of unbalanced HTML. Example: "<u><strong>text</u></strong>"
// would set a close tag override when the "</u>" is parsed to indicate that
// the "</strong>" should actually be parsed as a "</u>".
if (StringUtils.equals(this.peekTag().getTagType(), this.peekTag().getCloseTagOverride())) {
return this.popTag(this.peekTag().getCloseTagOverride());
}
// check to see if the parent tag matches the current close tag. if so then
// this is unbalanced HTML of the form "<u><strong>text</u></strong>" and
// it should be parsed as "<u><strong>text</strong></u>".
JFlexTagItem parent = null;
if (this.tagStack.size() > 2) {
parent = this.tagStack.get(this.tagStack.size() - 2);
}
if (parent != null && parent.getTagType().equals(tagType)) {
parent.setCloseTagOverride(tagType);
return this.popTag(this.peekTag().getTagType());
}
// if the above checks fail then this is an attempt to pop a tag that is not
// currently open, so append the escaped close tag to the current tag
// content without modifying the tag stack.
JFlexTagItem currentTag = this.tagStack.peek();
currentTag.getTagContent().append("</" + tagType + ">");
return null;
}
JFlexTagItem currentTag = this.tagStack.peek();
if (this.tagStack.size() > 1) {
// only pop if not the root tag
currentTag = this.tagStack.pop();
}
JFlexTagItem previousTag = this.tagStack.peek();
if (!JFlexParserUtil.isInlineTag(currentTag.getTagType()) || currentTag.getTagType().equals("pre")) {
// if the current tag is not an inline tag, make sure it is on its own lines
String trimmedContent = StringUtils.stripEnd(previousTag.getTagContent().toString(), null);
previousTag.getTagContent().replace(0, previousTag.getTagContent().length(), trimmedContent);
previousTag.getTagContent().append('\n');
previousTag.getTagContent().append(currentTag.toHtml());
previousTag.getTagContent().append('\n');
} else {
previousTag.getTagContent().append(currentTag.toHtml());
}
return currentTag;
}
/**
* Pop all tags off of the stack and return a string representation.
*/
protected String popAllTags() {
// pop the stack down to (but not including) the root tag
while (this.tagStack.size() > 1) {
JFlexTagItem currentTag = this.tagStack.peek();
this.popTag(currentTag.getTagType());
}
// now pop the root tag
JFlexTagItem currentTag = this.tagStack.pop();
return (this.mode >= JFlexParser.MODE_LAYOUT) ? currentTag.toHtml().trim() : currentTag.toHtml();
}
/**
* Push a new HTML tag onto the lexer stack.
*/
protected void pushTag(String tagType, String tagAttributes) {
JFlexTagItem tag = new JFlexTagItem(tagType);
tag.setTagAttributes(tagAttributes);
// many HTML tags cannot nest (ie "<li><li></li></li>" is invalid), so if a non-nesting
// tag is being added and the previous tag is of the same type, close the previous tag
if (JFlexParserUtil.isNonNestingTag(tagType) && this.peekTag().getTagType().equals(tagType)) {
this.popTag(tagType);
}
this.tagStack.push(tag);
}
/**
* Utility method used when parsing list tags to determine the current
* list nesting level.
*/
protected int currentListDepth() {
int depth = 0;
int currentPos = this.tagStack.size() - 1;
while (currentPos >= 0) {
JFlexTagItem tag = this.tagStack.get(currentPos);
if (!StringUtils.equals(tag.getTagType(), "li") && !StringUtils.equals(tag.getTagType(), "dd") && !StringUtils.equals(tag.getTagType(), "dt")) {
break;
}
// move back in the stack two since each list item has a parent list type
currentPos -= 2;
depth++;
}
return depth;
}
/**
*
*/
protected String calculateListItemType(char wikiSyntax) {
if (wikiSyntax == '*' || wikiSyntax == '#') {
return "li";
}
if (wikiSyntax == ';') {
return "dt";
}
if (wikiSyntax == ':') {
return "dd";
}
throw new IllegalArgumentException("Unrecognized wiki syntax: " + wikiSyntax);
}
/**
*
*/
protected String calculateListType(char wikiSyntax) {
if (wikiSyntax == ';' || wikiSyntax == ':') {
return "dl";
}
if (wikiSyntax == '#') {
return "ol";
}
if (wikiSyntax == '*') {
return "ul";
}
throw new IllegalArgumentException("Unrecognized wiki syntax: " + wikiSyntax);
}
/**
*
*/
protected void processListStack(String wikiSyntax) {
+ // before adding to a list, first make sure that any open inline tags or paragraph tags
+ // have been closed (example: "<i><ul>" is invalid. close the <i> first).
+ while (!JFlexParserUtil.isRootTag(this.peekTag().getTagType()) && (this.peekTag().getTagType().equals("p") || JFlexParserUtil.isInlineTag(this.peekTag().getTagType()))) {
+ this.popTag(this.peekTag().getTagType());
+ }
int previousDepth = this.currentListDepth();
int currentDepth = wikiSyntax.length();
String tagType;
// if list was previously open to a greater depth, close the old list down to the
// current depth.
int tagsToPop = (previousDepth - currentDepth);
if (tagsToPop > 0) {
this.popListTags(tagsToPop);
previousDepth -= tagsToPop;
}
// now look for differences in the current list stacks. for example, if
// the previous list was "::;" and the current list is "###" then there are
// some lists that must be closed.
for (int i=0; i < previousDepth; i++) {
// get the tagType for the root list ("ul", "dl", etc, NOT "li")
int tagPos = this.tagStack.size() - ((previousDepth - i) * 2);
tagType = (this.tagStack.get(tagPos)).getTagType();
if (tagType.equals(this.calculateListType(wikiSyntax.charAt(i)))) {
continue;
}
// if the above test did not match, then the stack needs to be popped
// to this point.
tagsToPop = (previousDepth - i);
this.popListTags(tagsToPop);
previousDepth -= tagsToPop;
break;
}
if (previousDepth == 0) {
// if no list is open, open one
this.pushTag(this.calculateListType(wikiSyntax.charAt(0)), null);
// add the new list item to the stack
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(0)), null);
} else if (previousDepth == currentDepth) {
// pop the previous list item
tagType = (this.tagStack.peek()).getTagType();
popTag(tagType);
// add the new list item to the stack
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(previousDepth - 1)), null);
}
// if the new list has additional elements, push them onto the stack
int counterStart = (previousDepth > 1) ? previousDepth : 1;
for (int i=counterStart; i < wikiSyntax.length(); i++) {
String previousTagType = (this.tagStack.peek()).getTagType();
// handle a weird corner case. if a "dt" is open and there are
// sub-lists, close the dt and open a "dd" for the sub-list
if (previousTagType.equals("dt")) {
this.popTag("dt");
if (!this.calculateListType(wikiSyntax.charAt(i)).equals("dl")) {
this.popTag("dl");
this.pushTag("dl", null);
}
this.pushTag("dd", null);
}
this.pushTag(this.calculateListType(wikiSyntax.charAt(i)), null);
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(i)), null);
}
}
/**
*
*/
protected void popListTags(int depth) {
if (depth < 0) {
throw new IllegalArgumentException("Cannot pop a negative number: " + depth);
}
String tagType;
for (int i=0; i < depth; i++) {
// pop twice since lists have a list tag and a list item tag ("<ul><li></li></ul>")
tagType = (this.tagStack.peek()).getTagType();
popTag(tagType);
tagType = (this.tagStack.peek()).getTagType();
popTag(tagType);
}
}
/**
* Take Wiki text of the form "|" or "| style='foo' |" and convert to
* and HTML <td> or <th> tag.
*
* @param text The text to be parsed.
* @param tagType The HTML tag type, either "td" or "th".
* @param markup The Wiki markup for the tag, either "|", "|+" or "!"
*/
protected void parseTableCell(String text, String tagType, String markup) {
if (text == null) {
throw new IllegalArgumentException("No text specified while parsing table cell");
}
text = text.trim();
String tagAttributes = null;
int pos = StringUtils.indexOfAnyBut(text, markup);
if (pos != -1) {
text = text.substring(pos);
pos = text.indexOf('|');
if (pos != -1) {
text = text.substring(0, pos);
}
tagAttributes = JFlexParserUtil.validateHtmlTagAttributes(text.trim());
}
this.pushTag(tagType, tagAttributes);
}
/**
* Make sure any open table tags that need to be closed are closed.
*/
protected void processTableStack() {
String previousTagType = this.peekTag().getTagType();
if (!previousTagType.equals("caption") && !previousTagType.equals("th") && !previousTagType.equals("td")) {
// no table cell was open, so nothing to close
return;
}
// pop the previous tag
this.popTag(previousTagType);
}
/**
* Handle parsing of bold, italic, and bolditalic tags.
*
* @param tagType The tag type being parsed - either "i", "b", or <code>null</code>
* if a bolditalic tag is being parsed.
*/
protected void processBoldItalic(String tagType) {
if (tagType == null) {
// bold-italic
if (this.peekTag().getTagType().equals("i")) {
// italic tag already opened
this.processBoldItalic("i");
this.processBoldItalic("b");
} else {
// standard bold-italic processing
this.processBoldItalic("b");
this.processBoldItalic("i");
}
return;
}
// bold or italic
if (this.peekTag().getTagType().equals(tagType)) {
// tag was open, close it
this.popTag(tagType);
return;
}
// TODO - make this more generic and implement it globally
if (tagType.equals("b") && this.peekTag().getTagType().equals("i")) {
// since Mediawiki syntax unfortunately chose to use the same character
// for bold and italic ('' and '''), see if the syntax is of the form
// '''''bold''' then italic'', in which case the current stack contains
// "b" followed by "i" when it should be the reverse.
int stackLength = this.tagStack.size();
if (stackLength > 2) {
JFlexTagItem grandparent = this.tagStack.get(stackLength - 2);
if (grandparent.getTagType().equals("b")) {
// swap the tag types and close the current tag
grandparent.changeTagType("i");
this.peekTag().changeTagType("b");
this.popTag(tagType);
return;
}
}
}
// push the new tag onto the stack
this.pushTag(tagType, null);
}
/**
*
*/
protected void parseParagraphEnd(String raw) {
if (this.mode >= JFlexParser.MODE_LAYOUT && this.peekTag().getTagType().equals("p")) {
// only perform processing if a paragraph is open - tag may have been already been
// closed explicitly with a "</p>".
this.popTag("p");
}
// push back everything except for any opening newline that was matched
int pushback = raw.length();
int pos = raw.indexOf('\n');
if (pos != -1 && pos < raw.length()) {
pushback = raw.substring(pos + 1).length();
}
yypushback(pushback);
}
/**
*
*/
protected void parseParagraphStart(String raw) {
int pushback = raw.length();
if (this.mode >= JFlexParser.MODE_LAYOUT) {
this.pushTag("p", null);
int newlineCount = StringUtils.countMatches(raw, "\n");
if (newlineCount > 0) {
pushback = StringUtils.stripStart(raw, " \n\r\t").length();
}
if (newlineCount == 2) {
// if the pattern matched two opening newlines then start the paragraph with a <br /> tag
this.append("<br />\n");
}
}
yypushback(pushback);
}
/**
*
*/
protected void parseParagraphEmpty(String raw) {
// push back everything up to the last of the opening newlines that were matched
yypushback(StringUtils.stripStart(raw, " \n\r\t").length() + 1);
if (this.mode < JFlexParser.MODE_LAYOUT) {
return;
}
int newlineCount = 0;
for (int i = 0; i < raw.length(); i++) {
if (raw.charAt(i) != '\n') {
// only count newlines for paragraph creation
continue;
}
newlineCount++;
if (newlineCount % 2 != 0) {
// two newlines are required to create a paragraph
continue;
}
this.pushTag("p", null);
this.append("<br />\n");
this.popTag("p");
}
}
/**
* JFlex internal method used to change the lexer state values.
*/
public abstract void yybegin(int newState);
/**
* JFlex internal method used to parse the next token.
*/
public abstract String yylex() throws Exception;
/**
* JFlex internal method used to push text back onto the parser stack.
*/
public abstract void yypushback(int number);
/**
* JFlex internal method used to retrieve the current lexer state value.
*/
public abstract int yystate();
/**
* JFlex internal method used to retrieve the current text matched by the
* yylex() method.
*/
public abstract String yytext();
}
| true | true | protected void processListStack(String wikiSyntax) {
int previousDepth = this.currentListDepth();
int currentDepth = wikiSyntax.length();
String tagType;
// if list was previously open to a greater depth, close the old list down to the
// current depth.
int tagsToPop = (previousDepth - currentDepth);
if (tagsToPop > 0) {
this.popListTags(tagsToPop);
previousDepth -= tagsToPop;
}
// now look for differences in the current list stacks. for example, if
// the previous list was "::;" and the current list is "###" then there are
// some lists that must be closed.
for (int i=0; i < previousDepth; i++) {
// get the tagType for the root list ("ul", "dl", etc, NOT "li")
int tagPos = this.tagStack.size() - ((previousDepth - i) * 2);
tagType = (this.tagStack.get(tagPos)).getTagType();
if (tagType.equals(this.calculateListType(wikiSyntax.charAt(i)))) {
continue;
}
// if the above test did not match, then the stack needs to be popped
// to this point.
tagsToPop = (previousDepth - i);
this.popListTags(tagsToPop);
previousDepth -= tagsToPop;
break;
}
if (previousDepth == 0) {
// if no list is open, open one
this.pushTag(this.calculateListType(wikiSyntax.charAt(0)), null);
// add the new list item to the stack
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(0)), null);
} else if (previousDepth == currentDepth) {
// pop the previous list item
tagType = (this.tagStack.peek()).getTagType();
popTag(tagType);
// add the new list item to the stack
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(previousDepth - 1)), null);
}
// if the new list has additional elements, push them onto the stack
int counterStart = (previousDepth > 1) ? previousDepth : 1;
for (int i=counterStart; i < wikiSyntax.length(); i++) {
String previousTagType = (this.tagStack.peek()).getTagType();
// handle a weird corner case. if a "dt" is open and there are
// sub-lists, close the dt and open a "dd" for the sub-list
if (previousTagType.equals("dt")) {
this.popTag("dt");
if (!this.calculateListType(wikiSyntax.charAt(i)).equals("dl")) {
this.popTag("dl");
this.pushTag("dl", null);
}
this.pushTag("dd", null);
}
this.pushTag(this.calculateListType(wikiSyntax.charAt(i)), null);
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(i)), null);
}
}
| protected void processListStack(String wikiSyntax) {
// before adding to a list, first make sure that any open inline tags or paragraph tags
// have been closed (example: "<i><ul>" is invalid. close the <i> first).
while (!JFlexParserUtil.isRootTag(this.peekTag().getTagType()) && (this.peekTag().getTagType().equals("p") || JFlexParserUtil.isInlineTag(this.peekTag().getTagType()))) {
this.popTag(this.peekTag().getTagType());
}
int previousDepth = this.currentListDepth();
int currentDepth = wikiSyntax.length();
String tagType;
// if list was previously open to a greater depth, close the old list down to the
// current depth.
int tagsToPop = (previousDepth - currentDepth);
if (tagsToPop > 0) {
this.popListTags(tagsToPop);
previousDepth -= tagsToPop;
}
// now look for differences in the current list stacks. for example, if
// the previous list was "::;" and the current list is "###" then there are
// some lists that must be closed.
for (int i=0; i < previousDepth; i++) {
// get the tagType for the root list ("ul", "dl", etc, NOT "li")
int tagPos = this.tagStack.size() - ((previousDepth - i) * 2);
tagType = (this.tagStack.get(tagPos)).getTagType();
if (tagType.equals(this.calculateListType(wikiSyntax.charAt(i)))) {
continue;
}
// if the above test did not match, then the stack needs to be popped
// to this point.
tagsToPop = (previousDepth - i);
this.popListTags(tagsToPop);
previousDepth -= tagsToPop;
break;
}
if (previousDepth == 0) {
// if no list is open, open one
this.pushTag(this.calculateListType(wikiSyntax.charAt(0)), null);
// add the new list item to the stack
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(0)), null);
} else if (previousDepth == currentDepth) {
// pop the previous list item
tagType = (this.tagStack.peek()).getTagType();
popTag(tagType);
// add the new list item to the stack
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(previousDepth - 1)), null);
}
// if the new list has additional elements, push them onto the stack
int counterStart = (previousDepth > 1) ? previousDepth : 1;
for (int i=counterStart; i < wikiSyntax.length(); i++) {
String previousTagType = (this.tagStack.peek()).getTagType();
// handle a weird corner case. if a "dt" is open and there are
// sub-lists, close the dt and open a "dd" for the sub-list
if (previousTagType.equals("dt")) {
this.popTag("dt");
if (!this.calculateListType(wikiSyntax.charAt(i)).equals("dl")) {
this.popTag("dl");
this.pushTag("dl", null);
}
this.pushTag("dd", null);
}
this.pushTag(this.calculateListType(wikiSyntax.charAt(i)), null);
this.pushTag(this.calculateListItemType(wikiSyntax.charAt(i)), null);
}
}
|
diff --git a/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java b/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java
index cd73b5e6646..90c3359ac5d 100644
--- a/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java
+++ b/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java
@@ -1,853 +1,853 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.discovery.zen;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalStateException;
import org.elasticsearch.cluster.*;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeService;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.UUID;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.component.Lifecycle;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.internal.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.InitialStateDiscoveryListener;
import org.elasticsearch.discovery.zen.elect.ElectMasterService;
import org.elasticsearch.discovery.zen.fd.MasterFaultDetection;
import org.elasticsearch.discovery.zen.fd.NodesFaultDetection;
import org.elasticsearch.discovery.zen.membership.MembershipAction;
import org.elasticsearch.discovery.zen.ping.ZenPing;
import org.elasticsearch.discovery.zen.ping.ZenPingService;
import org.elasticsearch.discovery.zen.publish.PublishClusterStateAction;
import org.elasticsearch.gateway.GatewayService;
import org.elasticsearch.node.service.NodeService;
import org.elasticsearch.node.settings.NodeSettingsService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.google.common.collect.Lists.newArrayList;
import static org.elasticsearch.cluster.ClusterState.newClusterStateBuilder;
import static org.elasticsearch.cluster.node.DiscoveryNodes.newNodesBuilder;
import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds;
/**
*
*/
public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implements Discovery, DiscoveryNodesProvider {
private final ThreadPool threadPool;
private final TransportService transportService;
private final ClusterService clusterService;
private AllocationService allocationService;
private final ClusterName clusterName;
private final DiscoveryNodeService discoveryNodeService;
private final ZenPingService pingService;
private final MasterFaultDetection masterFD;
private final NodesFaultDetection nodesFD;
private final PublishClusterStateAction publishClusterState;
private final MembershipAction membership;
private final TimeValue pingTimeout;
// a flag that should be used only for testing
private final boolean sendLeaveRequest;
private final ElectMasterService electMaster;
private final boolean masterElectionFilterClientNodes;
private final boolean masterElectionFilterDataNodes;
private DiscoveryNode localNode;
private final CopyOnWriteArrayList<InitialStateDiscoveryListener> initialStateListeners = new CopyOnWriteArrayList<InitialStateDiscoveryListener>();
private volatile boolean master = false;
private volatile DiscoveryNodes latestDiscoNodes;
private volatile Thread currentJoinThread;
private final AtomicBoolean initialStateSent = new AtomicBoolean();
@Nullable
private NodeService nodeService;
@Inject
public ZenDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool,
TransportService transportService, ClusterService clusterService, NodeSettingsService nodeSettingsService,
DiscoveryNodeService discoveryNodeService, ZenPingService pingService) {
super(settings);
this.clusterName = clusterName;
this.threadPool = threadPool;
this.clusterService = clusterService;
this.transportService = transportService;
this.discoveryNodeService = discoveryNodeService;
this.pingService = pingService;
// also support direct discovery.zen settings, for cases when it gets extended
this.pingTimeout = settings.getAsTime("discovery.zen.ping.timeout", settings.getAsTime("discovery.zen.ping_timeout", componentSettings.getAsTime("ping_timeout", componentSettings.getAsTime("initial_ping_timeout", timeValueSeconds(3)))));
this.sendLeaveRequest = componentSettings.getAsBoolean("send_leave_request", true);
this.masterElectionFilterClientNodes = settings.getAsBoolean("discovery.zen.master_election.filter_client", true);
this.masterElectionFilterDataNodes = settings.getAsBoolean("discovery.zen.master_election.filter_data", false);
logger.debug("using ping.timeout [{}], master_election.filter_client [{}], master_election.filter_data [{}]", pingTimeout, masterElectionFilterClientNodes, masterElectionFilterDataNodes);
this.electMaster = new ElectMasterService(settings);
nodeSettingsService.addListener(new ApplySettings());
this.masterFD = new MasterFaultDetection(settings, threadPool, transportService, this);
this.masterFD.addListener(new MasterNodeFailureListener());
this.nodesFD = new NodesFaultDetection(settings, threadPool, transportService);
this.nodesFD.addListener(new NodeFailureListener());
this.publishClusterState = new PublishClusterStateAction(settings, transportService, this, new NewClusterStateListener());
this.pingService.setNodesProvider(this);
this.membership = new MembershipAction(settings, transportService, this, new MembershipListener());
transportService.registerHandler(RejoinClusterRequestHandler.ACTION, new RejoinClusterRequestHandler());
}
@Override
public void setNodeService(@Nullable NodeService nodeService) {
this.nodeService = nodeService;
}
@Override
public void setAllocationService(AllocationService allocationService) {
this.allocationService = allocationService;
}
@Override
protected void doStart() throws ElasticSearchException {
Map<String, String> nodeAttributes = discoveryNodeService.buildAttributes();
// note, we rely on the fact that its a new id each time we start, see FD and "kill -9" handling
String nodeId = UUID.randomBase64UUID();
localNode = new DiscoveryNode(settings.get("name"), nodeId, transportService.boundAddress().publishAddress(), nodeAttributes);
latestDiscoNodes = new DiscoveryNodes.Builder().put(localNode).localNodeId(localNode.id()).build();
nodesFD.updateNodes(latestDiscoNodes);
pingService.start();
// do the join on a different thread, the DiscoveryService waits for 30s anyhow till it is discovered
asyncJoinCluster();
}
@Override
protected void doStop() throws ElasticSearchException {
pingService.stop();
masterFD.stop("zen disco stop");
nodesFD.stop();
initialStateSent.set(false);
if (sendLeaveRequest) {
if (!master && latestDiscoNodes.masterNode() != null) {
try {
membership.sendLeaveRequestBlocking(latestDiscoNodes.masterNode(), localNode, TimeValue.timeValueSeconds(1));
} catch (Exception e) {
logger.debug("failed to send leave request to master [{}]", e, latestDiscoNodes.masterNode());
}
} else {
DiscoveryNode[] possibleMasters = electMaster.nextPossibleMasters(latestDiscoNodes.nodes().values(), 5);
for (DiscoveryNode possibleMaster : possibleMasters) {
if (localNode.equals(possibleMaster)) {
continue;
}
try {
membership.sendLeaveRequest(latestDiscoNodes.masterNode(), possibleMaster);
} catch (Exception e) {
logger.debug("failed to send leave request from master [{}] to possible master [{}]", e, latestDiscoNodes.masterNode(), possibleMaster);
}
}
}
}
master = false;
if (currentJoinThread != null) {
try {
currentJoinThread.interrupt();
} catch (Exception e) {
// ignore
}
}
}
@Override
protected void doClose() throws ElasticSearchException {
masterFD.close();
nodesFD.close();
publishClusterState.close();
membership.close();
pingService.close();
}
@Override
public DiscoveryNode localNode() {
return localNode;
}
@Override
public void addListener(InitialStateDiscoveryListener listener) {
this.initialStateListeners.add(listener);
}
@Override
public void removeListener(InitialStateDiscoveryListener listener) {
this.initialStateListeners.remove(listener);
}
@Override
public String nodeDescription() {
return clusterName.value() + "/" + localNode.id();
}
@Override
public DiscoveryNodes nodes() {
DiscoveryNodes latestNodes = this.latestDiscoNodes;
if (latestNodes != null) {
return latestNodes;
}
// have not decided yet, just send the local node
return newNodesBuilder().put(localNode).localNodeId(localNode.id()).build();
}
@Override
public NodeService nodeService() {
return this.nodeService;
}
@Override
public void publish(ClusterState clusterState) {
if (!master) {
throw new ElasticSearchIllegalStateException("Shouldn't publish state when not master");
}
latestDiscoNodes = clusterState.nodes();
nodesFD.updateNodes(clusterState.nodes());
publishClusterState.publish(clusterState);
}
private void asyncJoinCluster() {
if (currentJoinThread != null) {
// we are already joining, ignore...
logger.trace("a join thread already running");
return;
}
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
currentJoinThread = Thread.currentThread();
try {
innterJoinCluster();
} finally {
currentJoinThread = null;
}
}
});
}
private void innterJoinCluster() {
boolean retry = true;
while (retry) {
if (lifecycle.stoppedOrClosed()) {
return;
}
retry = false;
DiscoveryNode masterNode = findMaster();
if (masterNode == null) {
logger.trace("no masterNode returned");
retry = true;
continue;
}
if (localNode.equals(masterNode)) {
this.master = true;
nodesFD.start(); // start the nodes FD
clusterService.submitStateUpdateTask("zen-disco-join (elected_as_master)", new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
.localNodeId(localNode.id())
.masterNodeId(localNode.id())
// put our local node
.put(localNode);
// update the fact that we are the master...
latestDiscoNodes = builder.build();
ClusterBlocks clusterBlocks = ClusterBlocks.builder().blocks(currentState.blocks()).removeGlobalBlock(NO_MASTER_BLOCK).build();
return newClusterStateBuilder().state(currentState).nodes(builder).blocks(clusterBlocks).build();
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
} else {
this.master = false;
try {
// first, make sure we can connect to the master
transportService.connectToNode(masterNode);
} catch (Exception e) {
logger.warn("failed to connect to master [{}], retrying...", e, masterNode);
retry = true;
continue;
}
// send join request
ClusterState joinClusterStateX;
try {
joinClusterStateX = membership.sendJoinRequestBlocking(masterNode, localNode, pingTimeout);
} catch (Exception e) {
if (e instanceof ElasticSearchException) {
logger.info("failed to send join request to master [{}], reason [{}]", masterNode, ((ElasticSearchException) e).getDetailedMessage());
} else {
logger.info("failed to send join request to master [{}], reason [{}]", masterNode, e.getMessage());
}
if (logger.isTraceEnabled()) {
logger.trace("detailed failed reason", e);
}
// failed to send the join request, retry
retry = true;
continue;
}
masterFD.start(masterNode, "initial_join");
// no need to submit the received cluster state, we will get it from the master when it publishes
// the fact that we joined
}
}
}
private void handleLeaveRequest(final DiscoveryNode node) {
if (lifecycleState() != Lifecycle.State.STARTED) {
// not started, ignore a node failure
return;
}
if (master) {
clusterService.submitStateUpdateTask("zen-disco-node_left(" + node + ")", Priority.HIGH, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
.putAll(currentState.nodes())
.remove(node.id());
latestDiscoNodes = builder.build();
currentState = newClusterStateBuilder().state(currentState).nodes(latestDiscoNodes).build();
// check if we have enough master nodes, if not, we need to move into joining the cluster again
if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) {
return rejoin(currentState, "not enough master nodes");
}
// eagerly run reroute to remove dead nodes from routing table
RoutingAllocation.Result routingResult = allocationService.reroute(newClusterStateBuilder().state(currentState).build());
return newClusterStateBuilder().state(currentState).routingResult(routingResult).build();
}
});
} else {
handleMasterGone(node, "shut_down");
}
}
private void handleNodeFailure(final DiscoveryNode node, String reason) {
if (lifecycleState() != Lifecycle.State.STARTED) {
// not started, ignore a node failure
return;
}
if (!master) {
// nothing to do here...
return;
}
clusterService.submitStateUpdateTask("zen-disco-node_failed(" + node + "), reason " + reason, new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder()
.putAll(currentState.nodes())
.remove(node.id());
latestDiscoNodes = builder.build();
currentState = newClusterStateBuilder().state(currentState).nodes(latestDiscoNodes).build();
// check if we have enough master nodes, if not, we need to move into joining the cluster again
if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) {
return rejoin(currentState, "not enough master nodes");
}
// eagerly run reroute to remove dead nodes from routing table
RoutingAllocation.Result routingResult = allocationService.reroute(newClusterStateBuilder().state(currentState).build());
return newClusterStateBuilder().state(currentState).routingResult(routingResult).build();
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
}
private void handleMinimumMasterNodesChanged(final int minimumMasterNodes) {
if (lifecycleState() != Lifecycle.State.STARTED) {
// not started, ignore a node failure
return;
}
if (!master) {
// nothing to do here...
return;
}
clusterService.submitStateUpdateTask("zen-disco-minimum_master_nodes_changed", new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
final int prevMinimumMasterNode = ZenDiscovery.this.electMaster.minimumMasterNodes();
ZenDiscovery.this.electMaster.minimumMasterNodes(minimumMasterNodes);
// check if we have enough master nodes, if not, we need to move into joining the cluster again
if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) {
return rejoin(currentState, "not enough master nodes on change of minimum_master_nodes from [" + prevMinimumMasterNode + "] to [" + minimumMasterNodes + "]");
}
return currentState;
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
}
private void handleMasterGone(final DiscoveryNode masterNode, final String reason) {
if (lifecycleState() != Lifecycle.State.STARTED) {
// not started, ignore a master failure
return;
}
if (master) {
// we might get this on both a master telling us shutting down, and then the disconnect failure
return;
}
logger.info("master_left [{}], reason [{}]", masterNode, reason);
clusterService.submitStateUpdateTask("zen-disco-master_failed (" + masterNode + ")", Priority.HIGH, new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (!masterNode.id().equals(currentState.nodes().masterNodeId())) {
// master got switched on us, no need to send anything
return currentState;
}
DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.newNodesBuilder()
.putAll(currentState.nodes())
// make sure the old master node, which has failed, is not part of the nodes we publish
.remove(masterNode.id())
.masterNodeId(null);
if (!electMaster.hasEnoughMasterNodes(nodesBuilder.build())) {
return rejoin(ClusterState.builder().state(currentState).nodes(nodesBuilder).build(), "not enough master nodes after master left (reason = " + reason + ")");
}
final DiscoveryNode electedMaster = electMaster.electMaster(nodesBuilder.build()); // elect master
if (localNode.equals(electedMaster)) {
master = true;
masterFD.stop("got elected as new master since master left (reason = " + reason + ")");
nodesFD.start();
nodesBuilder.masterNodeId(localNode.id());
latestDiscoNodes = nodesBuilder.build();
return newClusterStateBuilder().state(currentState).nodes(latestDiscoNodes).build();
} else {
nodesFD.stop();
if (electedMaster != null) {
nodesBuilder.masterNodeId(electedMaster.id());
masterFD.restart(electedMaster, "possible elected master since master left (reason = " + reason + ")");
latestDiscoNodes = nodesBuilder.build();
return newClusterStateBuilder().state(currentState)
.nodes(latestDiscoNodes)
.build();
} else {
return rejoin(newClusterStateBuilder().state(currentState).nodes(nodesBuilder.build()).build(), "master_left and no other node elected to become master");
}
}
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
}
void handleNewClusterStateFromMaster(final ClusterState newState) {
if (master) {
clusterService.submitStateUpdateTask("zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (newState.version() > currentState.version()) {
logger.warn("received cluster state from [{}] which is also master but with a newer cluster_state, rejoining to cluster...", newState.nodes().masterNode());
return rejoin(currentState, "zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]");
} else {
logger.warn("received cluster state from [{}] which is also master but with an older cluster_state, telling [{}] to rejoin the cluster", newState.nodes().masterNode(), newState.nodes().masterNode());
transportService.sendRequest(newState.nodes().masterNode(), RejoinClusterRequestHandler.ACTION, new RejoinClusterRequest(currentState.nodes().localNodeId()), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send rejoin request to [{}]", exp, newState.nodes().masterNode());
}
});
return currentState;
}
}
});
} else {
if (newState.nodes().localNode() == null) {
logger.warn("received a cluster state from [{}] and not part of the cluster, should not happen", newState.nodes().masterNode());
} else {
if (currentJoinThread != null) {
logger.debug("got a new state from master node, though we are already trying to rejoin the cluster");
}
clusterService.submitStateUpdateTask("zen-disco-receive(from master [" + newState.nodes().masterNode() + "])", new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
// we don't need to do this, since we ping the master, and get notified when it has moved from being a master
// because it doesn't have enough master nodes...
//if (!electMaster.hasEnoughMasterNodes(newState.nodes())) {
// return disconnectFromCluster(newState, "not enough master nodes on new cluster state received from [" + newState.nodes().masterNode() + "]");
//}
latestDiscoNodes = newState.nodes();
// check to see that we monitor the correct master of the cluster
if (masterFD.masterNode() == null || !masterFD.masterNode().equals(latestDiscoNodes.masterNode())) {
- masterFD.restart(latestDiscoNodes.masterNode(), "new cluster stare received and we monitor the wrong master [" + masterFD.masterNode() + "]");
+ masterFD.restart(latestDiscoNodes.masterNode(), "new cluster state received and we are monitoring the wrong master [" + masterFD.masterNode() + "]");
}
ClusterState.Builder builder = ClusterState.builder().state(newState);
// if the routing table did not change, use the original one
if (newState.routingTable().version() == currentState.routingTable().version()) {
builder.routingTable(currentState.routingTable());
}
// same for metadata
if (newState.metaData().version() == currentState.metaData().version()) {
builder.metaData(currentState.metaData());
} else {
// if its not the same version, only copy over new indices or ones that changed the version
MetaData.Builder metaDataBuilder = MetaData.builder().metaData(newState.metaData()).removeAllIndices();
for (IndexMetaData indexMetaData : newState.metaData()) {
IndexMetaData currentIndexMetaData = currentState.metaData().index(indexMetaData.index());
if (currentIndexMetaData == null || currentIndexMetaData.version() != indexMetaData.version()) {
metaDataBuilder.put(indexMetaData, false);
} else {
metaDataBuilder.put(currentIndexMetaData, false);
}
}
builder.metaData(metaDataBuilder);
}
return builder.build();
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
}
}
}
private ClusterState handleJoinRequest(final DiscoveryNode node) {
if (!master) {
throw new ElasticSearchIllegalStateException("Node [" + localNode + "] not master for join request from [" + node + "]");
}
ClusterState state = clusterService.state();
if (!transportService.addressSupported(node.address().getClass())) {
// TODO, what should we do now? Maybe inform that node that its crap?
logger.warn("received a wrong address type from [{}], ignoring...", node);
} else {
// try and connect to the node, if it fails, we can raise an exception back to the client...
transportService.connectToNode(node);
state = clusterService.state();
// validate the join request, will throw a failure if it fails, which will get back to the
// node calling the join request
membership.sendValidateJoinRequestBlocking(node, state, pingTimeout);
clusterService.submitStateUpdateTask("zen-disco-receive(join from node[" + node + "])", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (currentState.nodes().nodeExists(node.id())) {
// the node already exists in the cluster
logger.warn("received a join request for an existing node [{}]", node);
// still send a new cluster state, so it will be re published and possibly update the other node
return ClusterState.builder().state(currentState).build();
}
return newClusterStateBuilder().state(currentState).nodes(currentState.nodes().newNode(node)).build();
}
});
}
return state;
}
private DiscoveryNode findMaster() {
ZenPing.PingResponse[] fullPingResponses = pingService.pingAndWait(pingTimeout);
if (fullPingResponses == null) {
logger.trace("No full ping responses");
return null;
}
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("full ping responses:");
if (fullPingResponses.length == 0) {
sb.append(" {none}");
} else {
for (ZenPing.PingResponse pingResponse : fullPingResponses) {
sb.append("\n\t--> ").append("target [").append(pingResponse.target()).append("], master [").append(pingResponse.master()).append("]");
}
}
logger.trace(sb.toString());
}
// filter responses
List<ZenPing.PingResponse> pingResponses = Lists.newArrayList();
for (ZenPing.PingResponse pingResponse : fullPingResponses) {
DiscoveryNode node = pingResponse.target();
if (masterElectionFilterClientNodes && (node.clientNode() || (!node.masterNode() && !node.dataNode()))) {
// filter out the client node, which is a client node, or also one that is not data and not master (effectively, client)
} else if (masterElectionFilterDataNodes && (!node.masterNode() && node.dataNode())) {
// filter out data node that is not also master
} else {
pingResponses.add(pingResponse);
}
}
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("filtered ping responses: (filter_client[").append(masterElectionFilterClientNodes).append("], filter_data[").append(masterElectionFilterDataNodes).append("])");
if (pingResponses.isEmpty()) {
sb.append(" {none}");
} else {
for (ZenPing.PingResponse pingResponse : pingResponses) {
sb.append("\n\t--> ").append("target [").append(pingResponse.target()).append("], master [").append(pingResponse.master()).append("]");
}
}
logger.debug(sb.toString());
}
List<DiscoveryNode> pingMasters = newArrayList();
for (ZenPing.PingResponse pingResponse : pingResponses) {
if (pingResponse.master() != null) {
pingMasters.add(pingResponse.master());
}
}
Set<DiscoveryNode> possibleMasterNodes = Sets.newHashSet();
possibleMasterNodes.add(localNode);
for (ZenPing.PingResponse pingResponse : pingResponses) {
possibleMasterNodes.add(pingResponse.target());
}
// if we don't have enough master nodes, we bail, even if we get a response that indicates
// there is a master by other node, we don't see enough...
if (!electMaster.hasEnoughMasterNodes(possibleMasterNodes)) {
return null;
}
if (pingMasters.isEmpty()) {
// lets tie break between discovered nodes
DiscoveryNode electedMaster = electMaster.electMaster(possibleMasterNodes);
if (localNode.equals(electedMaster)) {
return localNode;
}
} else {
DiscoveryNode electedMaster = electMaster.electMaster(pingMasters);
if (electedMaster != null) {
return electedMaster;
}
}
return null;
}
private ClusterState rejoin(ClusterState clusterState, String reason) {
logger.warn(reason + ", current nodes: {}", clusterState.nodes());
nodesFD.stop();
masterFD.stop(reason);
master = false;
ClusterBlocks clusterBlocks = ClusterBlocks.builder().blocks(clusterState.blocks())
.addGlobalBlock(NO_MASTER_BLOCK)
.addGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)
.build();
// clear the routing table, we have no master, so we need to recreate the routing when we reform the cluster
RoutingTable routingTable = RoutingTable.builder().build();
// we also clean the metadata, since we are going to recover it if we become master
MetaData metaData = MetaData.builder().build();
// clean the nodes, we are now not connected to anybody, since we try and reform the cluster
latestDiscoNodes = new DiscoveryNodes.Builder().put(localNode).localNodeId(localNode.id()).build();
asyncJoinCluster();
return newClusterStateBuilder().state(clusterState)
.blocks(clusterBlocks)
.nodes(latestDiscoNodes)
.routingTable(routingTable)
.metaData(metaData)
.build();
}
private void sendInitialStateEventIfNeeded() {
if (initialStateSent.compareAndSet(false, true)) {
for (InitialStateDiscoveryListener listener : initialStateListeners) {
listener.initialStateProcessed();
}
}
}
private class NewClusterStateListener implements PublishClusterStateAction.NewClusterStateListener {
@Override
public void onNewClusterState(ClusterState clusterState) {
handleNewClusterStateFromMaster(clusterState);
}
}
private class MembershipListener implements MembershipAction.MembershipListener {
@Override
public ClusterState onJoin(DiscoveryNode node) {
return handleJoinRequest(node);
}
@Override
public void onLeave(DiscoveryNode node) {
handleLeaveRequest(node);
}
}
private class NodeFailureListener implements NodesFaultDetection.Listener {
@Override
public void onNodeFailure(DiscoveryNode node, String reason) {
handleNodeFailure(node, reason);
}
}
private class MasterNodeFailureListener implements MasterFaultDetection.Listener {
@Override
public void onMasterFailure(DiscoveryNode masterNode, String reason) {
handleMasterGone(masterNode, reason);
}
@Override
public void onDisconnectedFromMaster() {
// got disconnected from the master, send a join request
DiscoveryNode masterNode = latestDiscoNodes.masterNode();
try {
membership.sendJoinRequest(masterNode, localNode);
} catch (Exception e) {
logger.warn("failed to send join request on disconnection from master [{}]", masterNode);
}
}
}
static class RejoinClusterRequest extends TransportRequest {
private String fromNodeId;
RejoinClusterRequest(String fromNodeId) {
this.fromNodeId = fromNodeId;
}
RejoinClusterRequest() {
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
fromNodeId = in.readOptionalString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalString(fromNodeId);
}
}
class RejoinClusterRequestHandler extends BaseTransportRequestHandler<RejoinClusterRequest> {
static final String ACTION = "discovery/zen/rejoin";
@Override
public RejoinClusterRequest newInstance() {
return new RejoinClusterRequest();
}
@Override
public void messageReceived(final RejoinClusterRequest request, final TransportChannel channel) throws Exception {
clusterService.submitStateUpdateTask("received a request to rejoin the cluster from [" + request.fromNodeId + "]", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
try {
channel.sendResponse(TransportResponse.Empty.INSTANCE);
} catch (Exception e) {
logger.warn("failed to send response on rejoin cluster request handling", e);
}
return rejoin(currentState, "received a request to rejoin the cluster from [" + request.fromNodeId + "]");
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
int minimumMasterNodes = settings.getAsInt("discovery.zen.minimum_master_nodes", ZenDiscovery.this.electMaster.minimumMasterNodes());
if (minimumMasterNodes != ZenDiscovery.this.electMaster.minimumMasterNodes()) {
logger.info("updating discovery.zen.minimum_master_nodes from [{}] to [{}]", ZenDiscovery.this.electMaster.minimumMasterNodes(), minimumMasterNodes);
handleMinimumMasterNodesChanged(minimumMasterNodes);
}
}
}
}
| true | true | void handleNewClusterStateFromMaster(final ClusterState newState) {
if (master) {
clusterService.submitStateUpdateTask("zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (newState.version() > currentState.version()) {
logger.warn("received cluster state from [{}] which is also master but with a newer cluster_state, rejoining to cluster...", newState.nodes().masterNode());
return rejoin(currentState, "zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]");
} else {
logger.warn("received cluster state from [{}] which is also master but with an older cluster_state, telling [{}] to rejoin the cluster", newState.nodes().masterNode(), newState.nodes().masterNode());
transportService.sendRequest(newState.nodes().masterNode(), RejoinClusterRequestHandler.ACTION, new RejoinClusterRequest(currentState.nodes().localNodeId()), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send rejoin request to [{}]", exp, newState.nodes().masterNode());
}
});
return currentState;
}
}
});
} else {
if (newState.nodes().localNode() == null) {
logger.warn("received a cluster state from [{}] and not part of the cluster, should not happen", newState.nodes().masterNode());
} else {
if (currentJoinThread != null) {
logger.debug("got a new state from master node, though we are already trying to rejoin the cluster");
}
clusterService.submitStateUpdateTask("zen-disco-receive(from master [" + newState.nodes().masterNode() + "])", new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
// we don't need to do this, since we ping the master, and get notified when it has moved from being a master
// because it doesn't have enough master nodes...
//if (!electMaster.hasEnoughMasterNodes(newState.nodes())) {
// return disconnectFromCluster(newState, "not enough master nodes on new cluster state received from [" + newState.nodes().masterNode() + "]");
//}
latestDiscoNodes = newState.nodes();
// check to see that we monitor the correct master of the cluster
if (masterFD.masterNode() == null || !masterFD.masterNode().equals(latestDiscoNodes.masterNode())) {
masterFD.restart(latestDiscoNodes.masterNode(), "new cluster stare received and we monitor the wrong master [" + masterFD.masterNode() + "]");
}
ClusterState.Builder builder = ClusterState.builder().state(newState);
// if the routing table did not change, use the original one
if (newState.routingTable().version() == currentState.routingTable().version()) {
builder.routingTable(currentState.routingTable());
}
// same for metadata
if (newState.metaData().version() == currentState.metaData().version()) {
builder.metaData(currentState.metaData());
} else {
// if its not the same version, only copy over new indices or ones that changed the version
MetaData.Builder metaDataBuilder = MetaData.builder().metaData(newState.metaData()).removeAllIndices();
for (IndexMetaData indexMetaData : newState.metaData()) {
IndexMetaData currentIndexMetaData = currentState.metaData().index(indexMetaData.index());
if (currentIndexMetaData == null || currentIndexMetaData.version() != indexMetaData.version()) {
metaDataBuilder.put(indexMetaData, false);
} else {
metaDataBuilder.put(currentIndexMetaData, false);
}
}
builder.metaData(metaDataBuilder);
}
return builder.build();
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
}
}
}
| void handleNewClusterStateFromMaster(final ClusterState newState) {
if (master) {
clusterService.submitStateUpdateTask("zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (newState.version() > currentState.version()) {
logger.warn("received cluster state from [{}] which is also master but with a newer cluster_state, rejoining to cluster...", newState.nodes().masterNode());
return rejoin(currentState, "zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]");
} else {
logger.warn("received cluster state from [{}] which is also master but with an older cluster_state, telling [{}] to rejoin the cluster", newState.nodes().masterNode(), newState.nodes().masterNode());
transportService.sendRequest(newState.nodes().masterNode(), RejoinClusterRequestHandler.ACTION, new RejoinClusterRequest(currentState.nodes().localNodeId()), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send rejoin request to [{}]", exp, newState.nodes().masterNode());
}
});
return currentState;
}
}
});
} else {
if (newState.nodes().localNode() == null) {
logger.warn("received a cluster state from [{}] and not part of the cluster, should not happen", newState.nodes().masterNode());
} else {
if (currentJoinThread != null) {
logger.debug("got a new state from master node, though we are already trying to rejoin the cluster");
}
clusterService.submitStateUpdateTask("zen-disco-receive(from master [" + newState.nodes().masterNode() + "])", new ProcessedClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
// we don't need to do this, since we ping the master, and get notified when it has moved from being a master
// because it doesn't have enough master nodes...
//if (!electMaster.hasEnoughMasterNodes(newState.nodes())) {
// return disconnectFromCluster(newState, "not enough master nodes on new cluster state received from [" + newState.nodes().masterNode() + "]");
//}
latestDiscoNodes = newState.nodes();
// check to see that we monitor the correct master of the cluster
if (masterFD.masterNode() == null || !masterFD.masterNode().equals(latestDiscoNodes.masterNode())) {
masterFD.restart(latestDiscoNodes.masterNode(), "new cluster state received and we are monitoring the wrong master [" + masterFD.masterNode() + "]");
}
ClusterState.Builder builder = ClusterState.builder().state(newState);
// if the routing table did not change, use the original one
if (newState.routingTable().version() == currentState.routingTable().version()) {
builder.routingTable(currentState.routingTable());
}
// same for metadata
if (newState.metaData().version() == currentState.metaData().version()) {
builder.metaData(currentState.metaData());
} else {
// if its not the same version, only copy over new indices or ones that changed the version
MetaData.Builder metaDataBuilder = MetaData.builder().metaData(newState.metaData()).removeAllIndices();
for (IndexMetaData indexMetaData : newState.metaData()) {
IndexMetaData currentIndexMetaData = currentState.metaData().index(indexMetaData.index());
if (currentIndexMetaData == null || currentIndexMetaData.version() != indexMetaData.version()) {
metaDataBuilder.put(indexMetaData, false);
} else {
metaDataBuilder.put(currentIndexMetaData, false);
}
}
builder.metaData(metaDataBuilder);
}
return builder.build();
}
@Override
public void clusterStateProcessed(ClusterState clusterState) {
sendInitialStateEventIfNeeded();
}
});
}
}
}
|
diff --git a/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java b/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java
index f8671e1d84a..7c7f57843f2 100644
--- a/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java
+++ b/src/main/java/org/elasticsearch/indices/store/TransportNodesListShardStoreMetaData.java
@@ -1,427 +1,427 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.indices.store;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.FailedNodeException;
import org.elasticsearch.action.support.nodes.*;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.service.InternalIndexShard;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreFileMetaData;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
*
*/
public class TransportNodesListShardStoreMetaData extends TransportNodesOperationAction<TransportNodesListShardStoreMetaData.Request, TransportNodesListShardStoreMetaData.NodesStoreFilesMetaData, TransportNodesListShardStoreMetaData.NodeRequest, TransportNodesListShardStoreMetaData.NodeStoreFilesMetaData> {
private final IndicesService indicesService;
private final NodeEnvironment nodeEnv;
@Inject
public TransportNodesListShardStoreMetaData(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
IndicesService indicesService, NodeEnvironment nodeEnv) {
super(settings, clusterName, threadPool, clusterService, transportService);
this.indicesService = indicesService;
this.nodeEnv = nodeEnv;
}
public ActionFuture<NodesStoreFilesMetaData> list(ShardId shardId, boolean onlyUnallocated, Set<String> nodesIds, @Nullable TimeValue timeout) {
return execute(new Request(shardId, onlyUnallocated, nodesIds).timeout(timeout));
}
@Override
protected String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
protected String transportAction() {
return "/cluster/nodes/indices/shard/store";
}
@Override
protected Request newRequest() {
return new Request();
}
@Override
protected NodeRequest newNodeRequest() {
return new NodeRequest();
}
@Override
protected NodeRequest newNodeRequest(String nodeId, Request request) {
return new NodeRequest(nodeId, request);
}
@Override
protected NodeStoreFilesMetaData newNodeResponse() {
return new NodeStoreFilesMetaData();
}
@Override
protected NodesStoreFilesMetaData newResponse(Request request, AtomicReferenceArray responses) {
final List<NodeStoreFilesMetaData> nodeStoreFilesMetaDatas = Lists.newArrayList();
final List<FailedNodeException> failures = Lists.newArrayList();
for (int i = 0; i < responses.length(); i++) {
Object resp = responses.get(i);
if (resp instanceof NodeStoreFilesMetaData) { // will also filter out null response for unallocated ones
nodeStoreFilesMetaDatas.add((NodeStoreFilesMetaData) resp);
} else if (resp instanceof FailedNodeException) {
failures.add((FailedNodeException) resp);
}
}
return new NodesStoreFilesMetaData(clusterName, nodeStoreFilesMetaDatas.toArray(new NodeStoreFilesMetaData[nodeStoreFilesMetaDatas.size()]),
failures.toArray(new FailedNodeException[failures.size()]));
}
@Override
protected NodeStoreFilesMetaData nodeOperation(NodeRequest request) throws ElasticSearchException {
if (request.unallocated) {
IndexService indexService = indicesService.indexService(request.shardId.index().name());
if (indexService == null) {
return new NodeStoreFilesMetaData(clusterService.state().nodes().localNode(), null);
}
if (!indexService.hasShard(request.shardId.id())) {
return new NodeStoreFilesMetaData(clusterService.state().nodes().localNode(), null);
}
}
IndexMetaData metaData = clusterService.state().metaData().index(request.shardId.index().name());
if (metaData == null) {
return new NodeStoreFilesMetaData(clusterService.state().nodes().localNode(), null);
}
try {
return new NodeStoreFilesMetaData(clusterService.state().nodes().localNode(), listStoreMetaData(request.shardId));
} catch (IOException e) {
throw new ElasticSearchException("Failed to list store metadata for shard [" + request.shardId + "]", e);
}
}
private StoreFilesMetaData listStoreMetaData(ShardId shardId) throws IOException {
IndexService indexService = indicesService.indexService(shardId.index().name());
if (indexService != null) {
InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId.id());
if (indexShard != null) {
return new StoreFilesMetaData(true, shardId, indexShard.store().list());
}
}
// try and see if we an list unallocated
IndexMetaData metaData = clusterService.state().metaData().index(shardId.index().name());
if (metaData == null) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
String storeType = metaData.settings().get("index.store.type", "fs");
if (!storeType.contains("fs")) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
File[] shardLocations = nodeEnv.shardLocations(shardId);
File[] shardIndexLocations = new File[shardLocations.length];
for (int i = 0; i < shardLocations.length; i++) {
shardIndexLocations[i] = new File(shardLocations[i], "index");
}
boolean exists = false;
for (File shardIndexLocation : shardIndexLocations) {
if (shardIndexLocation.exists()) {
exists = true;
break;
}
}
if (!exists) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
Map<String, String> checksums = Store.readChecksums(shardIndexLocations);
if (checksums == null) {
checksums = ImmutableMap.of();
}
Map<String, StoreFileMetaData> files = Maps.newHashMap();
for (File shardIndexLocation : shardIndexLocations) {
File[] listedFiles = shardIndexLocation.listFiles();
if (listedFiles == null) {
continue;
}
for (File file : listedFiles) {
// BACKWARD CKS SUPPORT
if (file.getName().endsWith(".cks")) {
continue;
}
if (Store.isChecksum(file.getName())) {
continue;
}
- files.put(file.getName(), new StoreFileMetaData(file.getName(), file.length(), file.lastModified(), checksums.get(file.getName())));
+ files.put(file.getName(), new StoreFileMetaData(file.getName(), file.length(), checksums.get(file.getName())));
}
}
return new StoreFilesMetaData(false, shardId, files);
}
@Override
protected boolean accumulateExceptions() {
return true;
}
public static class StoreFilesMetaData implements Iterable<StoreFileMetaData>, Streamable {
private boolean allocated;
private ShardId shardId;
private Map<String, StoreFileMetaData> files;
StoreFilesMetaData() {
}
public StoreFilesMetaData(boolean allocated, ShardId shardId, Map<String, StoreFileMetaData> files) {
this.allocated = allocated;
this.shardId = shardId;
this.files = files;
}
public boolean allocated() {
return allocated;
}
public ShardId shardId() {
return this.shardId;
}
public long totalSizeInBytes() {
long totalSizeInBytes = 0;
for (StoreFileMetaData file : this) {
totalSizeInBytes += file.length();
}
return totalSizeInBytes;
}
@Override
public Iterator<StoreFileMetaData> iterator() {
return files.values().iterator();
}
public boolean fileExists(String name) {
return files.containsKey(name);
}
public StoreFileMetaData file(String name) {
return files.get(name);
}
public static StoreFilesMetaData readStoreFilesMetaData(StreamInput in) throws IOException {
StoreFilesMetaData md = new StoreFilesMetaData();
md.readFrom(in);
return md;
}
@Override
public void readFrom(StreamInput in) throws IOException {
allocated = in.readBoolean();
shardId = ShardId.readShardId(in);
int size = in.readVInt();
files = Maps.newHashMapWithExpectedSize(size);
for (int i = 0; i < size; i++) {
StoreFileMetaData md = StoreFileMetaData.readStoreFileMetaData(in);
files.put(md.name(), md);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeBoolean(allocated);
shardId.writeTo(out);
out.writeVInt(files.size());
for (StoreFileMetaData md : files.values()) {
md.writeTo(out);
}
}
}
static class Request extends NodesOperationRequest<Request> {
private ShardId shardId;
private boolean unallocated;
public Request() {
}
public Request(ShardId shardId, boolean unallocated, Set<String> nodesIds) {
super(nodesIds.toArray(new String[nodesIds.size()]));
this.shardId = shardId;
this.unallocated = unallocated;
}
public Request(ShardId shardId, boolean unallocated, String... nodesIds) {
super(nodesIds);
this.shardId = shardId;
this.unallocated = unallocated;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardId = ShardId.readShardId(in);
unallocated = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardId.writeTo(out);
out.writeBoolean(unallocated);
}
}
public static class NodesStoreFilesMetaData extends NodesOperationResponse<NodeStoreFilesMetaData> {
private FailedNodeException[] failures;
NodesStoreFilesMetaData() {
}
public NodesStoreFilesMetaData(ClusterName clusterName, NodeStoreFilesMetaData[] nodes, FailedNodeException[] failures) {
super(clusterName, nodes);
this.failures = failures;
}
public FailedNodeException[] failures() {
return failures;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
nodes = new NodeStoreFilesMetaData[in.readVInt()];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = NodeStoreFilesMetaData.readListShardStoreNodeOperationResponse(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(nodes.length);
for (NodeStoreFilesMetaData response : nodes) {
response.writeTo(out);
}
}
}
static class NodeRequest extends NodeOperationRequest {
private ShardId shardId;
private boolean unallocated;
NodeRequest() {
}
NodeRequest(String nodeId, TransportNodesListShardStoreMetaData.Request request) {
super(request, nodeId);
this.shardId = request.shardId;
this.unallocated = request.unallocated;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardId = ShardId.readShardId(in);
unallocated = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardId.writeTo(out);
out.writeBoolean(unallocated);
}
}
public static class NodeStoreFilesMetaData extends NodeOperationResponse {
private StoreFilesMetaData storeFilesMetaData;
NodeStoreFilesMetaData() {
}
public NodeStoreFilesMetaData(DiscoveryNode node, StoreFilesMetaData storeFilesMetaData) {
super(node);
this.storeFilesMetaData = storeFilesMetaData;
}
public StoreFilesMetaData storeFilesMetaData() {
return storeFilesMetaData;
}
public static NodeStoreFilesMetaData readListShardStoreNodeOperationResponse(StreamInput in) throws IOException {
NodeStoreFilesMetaData resp = new NodeStoreFilesMetaData();
resp.readFrom(in);
return resp;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
if (in.readBoolean()) {
storeFilesMetaData = StoreFilesMetaData.readStoreFilesMetaData(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
if (storeFilesMetaData == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
storeFilesMetaData.writeTo(out);
}
}
}
}
| true | true | private StoreFilesMetaData listStoreMetaData(ShardId shardId) throws IOException {
IndexService indexService = indicesService.indexService(shardId.index().name());
if (indexService != null) {
InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId.id());
if (indexShard != null) {
return new StoreFilesMetaData(true, shardId, indexShard.store().list());
}
}
// try and see if we an list unallocated
IndexMetaData metaData = clusterService.state().metaData().index(shardId.index().name());
if (metaData == null) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
String storeType = metaData.settings().get("index.store.type", "fs");
if (!storeType.contains("fs")) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
File[] shardLocations = nodeEnv.shardLocations(shardId);
File[] shardIndexLocations = new File[shardLocations.length];
for (int i = 0; i < shardLocations.length; i++) {
shardIndexLocations[i] = new File(shardLocations[i], "index");
}
boolean exists = false;
for (File shardIndexLocation : shardIndexLocations) {
if (shardIndexLocation.exists()) {
exists = true;
break;
}
}
if (!exists) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
Map<String, String> checksums = Store.readChecksums(shardIndexLocations);
if (checksums == null) {
checksums = ImmutableMap.of();
}
Map<String, StoreFileMetaData> files = Maps.newHashMap();
for (File shardIndexLocation : shardIndexLocations) {
File[] listedFiles = shardIndexLocation.listFiles();
if (listedFiles == null) {
continue;
}
for (File file : listedFiles) {
// BACKWARD CKS SUPPORT
if (file.getName().endsWith(".cks")) {
continue;
}
if (Store.isChecksum(file.getName())) {
continue;
}
files.put(file.getName(), new StoreFileMetaData(file.getName(), file.length(), file.lastModified(), checksums.get(file.getName())));
}
}
return new StoreFilesMetaData(false, shardId, files);
}
| private StoreFilesMetaData listStoreMetaData(ShardId shardId) throws IOException {
IndexService indexService = indicesService.indexService(shardId.index().name());
if (indexService != null) {
InternalIndexShard indexShard = (InternalIndexShard) indexService.shard(shardId.id());
if (indexShard != null) {
return new StoreFilesMetaData(true, shardId, indexShard.store().list());
}
}
// try and see if we an list unallocated
IndexMetaData metaData = clusterService.state().metaData().index(shardId.index().name());
if (metaData == null) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
String storeType = metaData.settings().get("index.store.type", "fs");
if (!storeType.contains("fs")) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
File[] shardLocations = nodeEnv.shardLocations(shardId);
File[] shardIndexLocations = new File[shardLocations.length];
for (int i = 0; i < shardLocations.length; i++) {
shardIndexLocations[i] = new File(shardLocations[i], "index");
}
boolean exists = false;
for (File shardIndexLocation : shardIndexLocations) {
if (shardIndexLocation.exists()) {
exists = true;
break;
}
}
if (!exists) {
return new StoreFilesMetaData(false, shardId, ImmutableMap.<String, StoreFileMetaData>of());
}
Map<String, String> checksums = Store.readChecksums(shardIndexLocations);
if (checksums == null) {
checksums = ImmutableMap.of();
}
Map<String, StoreFileMetaData> files = Maps.newHashMap();
for (File shardIndexLocation : shardIndexLocations) {
File[] listedFiles = shardIndexLocation.listFiles();
if (listedFiles == null) {
continue;
}
for (File file : listedFiles) {
// BACKWARD CKS SUPPORT
if (file.getName().endsWith(".cks")) {
continue;
}
if (Store.isChecksum(file.getName())) {
continue;
}
files.put(file.getName(), new StoreFileMetaData(file.getName(), file.length(), checksums.get(file.getName())));
}
}
return new StoreFilesMetaData(false, shardId, files);
}
|
diff --git a/src/test/java/ch/bergturbenthal/hs485/frontend/gwtfrontend/client/EventBuilderTest.java b/src/test/java/ch/bergturbenthal/hs485/frontend/gwtfrontend/client/EventBuilderTest.java
index 9f02d63..2486ad9 100644
--- a/src/test/java/ch/bergturbenthal/hs485/frontend/gwtfrontend/client/EventBuilderTest.java
+++ b/src/test/java/ch/bergturbenthal/hs485/frontend/gwtfrontend/client/EventBuilderTest.java
@@ -1,42 +1,42 @@
package ch.bergturbenthal.hs485.frontend.gwtfrontend.client;
import java.util.Collection;
import junit.framework.Assert;
import org.junit.Test;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.client.editor.event.EventSourceManager;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.client.editor.event.EventTypeManager;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.client.editor.event.LabelGenerator;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.shared.db.InputConnector;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.shared.db.OutputDevice;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.shared.db.handler.EventSource;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.shared.event.KeyEvent;
import ch.bergturbenthal.hs485.frontend.gwtfrontend.shared.event.ValueEvent;
public class EventBuilderTest {
@Test
public void testBuilder() {
final EventTypeManager panelBuilder = new EventTypeManager(new LabelGenerator() {
@Override
public String makeLabelForInputConnector(final InputConnector inputConnector) {
// TODO Auto-generated method stub
return "";
}
@Override
public String makeLabelForOutputDevice(final OutputDevice outputDevice) {
return "";
}
});
final Collection<EventSourceManager<ValueEvent, EventSource<ValueEvent>>> valueBuilders = panelBuilder.listInputPanelsForEvent(ValueEvent.class
.getName());
Assert.assertEquals(0, valueBuilders.size());
final Collection<EventSourceManager<KeyEvent, EventSource<KeyEvent>>> keyBuilders = panelBuilder
.listInputPanelsForEvent(KeyEvent.class.getName());
- Assert.assertEquals(2, keyBuilders.size());
+ Assert.assertEquals(3, keyBuilders.size());
}
}
| true | true | public void testBuilder() {
final EventTypeManager panelBuilder = new EventTypeManager(new LabelGenerator() {
@Override
public String makeLabelForInputConnector(final InputConnector inputConnector) {
// TODO Auto-generated method stub
return "";
}
@Override
public String makeLabelForOutputDevice(final OutputDevice outputDevice) {
return "";
}
});
final Collection<EventSourceManager<ValueEvent, EventSource<ValueEvent>>> valueBuilders = panelBuilder.listInputPanelsForEvent(ValueEvent.class
.getName());
Assert.assertEquals(0, valueBuilders.size());
final Collection<EventSourceManager<KeyEvent, EventSource<KeyEvent>>> keyBuilders = panelBuilder
.listInputPanelsForEvent(KeyEvent.class.getName());
Assert.assertEquals(2, keyBuilders.size());
}
| public void testBuilder() {
final EventTypeManager panelBuilder = new EventTypeManager(new LabelGenerator() {
@Override
public String makeLabelForInputConnector(final InputConnector inputConnector) {
// TODO Auto-generated method stub
return "";
}
@Override
public String makeLabelForOutputDevice(final OutputDevice outputDevice) {
return "";
}
});
final Collection<EventSourceManager<ValueEvent, EventSource<ValueEvent>>> valueBuilders = panelBuilder.listInputPanelsForEvent(ValueEvent.class
.getName());
Assert.assertEquals(0, valueBuilders.size());
final Collection<EventSourceManager<KeyEvent, EventSource<KeyEvent>>> keyBuilders = panelBuilder
.listInputPanelsForEvent(KeyEvent.class.getName());
Assert.assertEquals(3, keyBuilders.size());
}
|
diff --git a/src/test/java/com/rightmove/es/service/PropertySearchServiceTest.java b/src/test/java/com/rightmove/es/service/PropertySearchServiceTest.java
index 12e1ed1..d551ee9 100644
--- a/src/test/java/com/rightmove/es/service/PropertySearchServiceTest.java
+++ b/src/test/java/com/rightmove/es/service/PropertySearchServiceTest.java
@@ -1,90 +1,90 @@
package com.rightmove.es.service;
import com.rightmove.es.domain.Property;
import com.rightmove.es.domain.PropertyFilter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.FacetedPage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/applicationContext.xml")
public class PropertySearchServiceTest {
@Autowired
private PropertySearchService propertySearchService;
@Autowired
private PropertyService propertyService;
@Autowired
private ElasticsearchTemplate esTemplate;
@Test
public void getSearchResultFilteredWithFacets() {
- indexProperty(1L, "London", "NW1");
- indexProperty(2L, "London", "NW1");
- indexProperty(3L, "London", "NW2");
- indexProperty(4L, "London", "NW3");
- indexProperty(5L, "London", "NW4");
+ indexProperty(1L, "London", "NW1", "AB1", "summary test", null);
+ indexProperty(2L, "London", "NW1", "AB2", "summary test", null);
+ indexProperty(3L, "London", "NW2", "AB3", "summary test", null);
+ indexProperty(4L, "London", "NW3", "AB4", "summary test", null);
+ indexProperty(5L, "London", "NW4", "AB5", "summary test", null);
PropertyFilter propertyFilter = new PropertyFilter();
propertyFilter.addFilter("nw1","outcode");
FacetedPage<Property> results = propertySearchService.search("summary test", propertyFilter).getProperties();
assertEquals(2, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
System.out.println();
propertyFilter.addFilter("nw2","outcode");
results = propertySearchService.search("summary test", propertyFilter).getProperties();
assertEquals(3, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
assertEquals(1, results.getFacets().size());
}
@Test
public void weight() {
indexProperty(1L, "Milton Keynes", "AB1", "DE2", "summary test", null);
indexProperty(2L, "Milton Keynes", "AB1", "DE3", "this property has 2 staircases", Arrays.asList("walls"));
indexProperty(3L, "NW1", "NW2");
indexProperty(4L, "NW1", "NW1");
indexProperty(5L, "London", "NW3");
FacetedPage<Property> results = propertySearchService.search("AB1 walls").getProperties();
//assertEquals(2, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
}
public void indexProperty(Long id, String city, String incode) {
indexProperty(id, city, "OUT", incode, "summary test", null);
}
public void indexProperty(Long id, String city, String outcode, String incode, String summary, List<String> features) {
Property property = new Property();
property.setId(id);
property.setIncode(incode);
property.setOutcode(outcode);
property.setCity(city);
property.setSummary(summary);
property.setFeatures(features);
propertyService.indexProperty(property);
}
}
| true | true | public void getSearchResultFilteredWithFacets() {
indexProperty(1L, "London", "NW1");
indexProperty(2L, "London", "NW1");
indexProperty(3L, "London", "NW2");
indexProperty(4L, "London", "NW3");
indexProperty(5L, "London", "NW4");
PropertyFilter propertyFilter = new PropertyFilter();
propertyFilter.addFilter("nw1","outcode");
FacetedPage<Property> results = propertySearchService.search("summary test", propertyFilter).getProperties();
assertEquals(2, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
System.out.println();
propertyFilter.addFilter("nw2","outcode");
results = propertySearchService.search("summary test", propertyFilter).getProperties();
assertEquals(3, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
assertEquals(1, results.getFacets().size());
}
| public void getSearchResultFilteredWithFacets() {
indexProperty(1L, "London", "NW1", "AB1", "summary test", null);
indexProperty(2L, "London", "NW1", "AB2", "summary test", null);
indexProperty(3L, "London", "NW2", "AB3", "summary test", null);
indexProperty(4L, "London", "NW3", "AB4", "summary test", null);
indexProperty(5L, "London", "NW4", "AB5", "summary test", null);
PropertyFilter propertyFilter = new PropertyFilter();
propertyFilter.addFilter("nw1","outcode");
FacetedPage<Property> results = propertySearchService.search("summary test", propertyFilter).getProperties();
assertEquals(2, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
System.out.println();
propertyFilter.addFilter("nw2","outcode");
results = propertySearchService.search("summary test", propertyFilter).getProperties();
assertEquals(3, results.getNumberOfElements());
for (Property property : results) {
System.out.println(property);
}
assertEquals(1, results.getFacets().size());
}
|
diff --git a/src/de/schildbach/pte/AbstractHafasProvider.java b/src/de/schildbach/pte/AbstractHafasProvider.java
index 9836e97..3413a93 100644
--- a/src/de/schildbach/pte/AbstractHafasProvider.java
+++ b/src/de/schildbach/pte/AbstractHafasProvider.java
@@ -1,888 +1,890 @@
/*
* Copyright 2010 the original author or authors.
*
* 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 de.schildbach.pte;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import de.schildbach.pte.dto.Connection;
import de.schildbach.pte.dto.GetConnectionDetailsResult;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.QueryConnectionsResult;
import de.schildbach.pte.dto.Station;
import de.schildbach.pte.util.Color;
import de.schildbach.pte.util.ParserUtils;
import de.schildbach.pte.util.XmlPullUtil;
/**
* @author Andreas Schildbach
*/
public abstract class AbstractHafasProvider implements NetworkProvider
{
private static final String DEFAULT_ENCODING = "ISO-8859-1";
private final String apiUri;
private static final String prod = "hafas";
private final String accessId;
public AbstractHafasProvider(final String apiUri, final String accessId)
{
this.apiUri = apiUri;
this.accessId = accessId;
}
private final String wrap(final String request)
{
return "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" //
+ "<ReqC ver=\"1.1\" prod=\"" + prod + "\" lang=\"DE\"" + (accessId != null ? " accessId=\"" + accessId + "\"" : "") + ">" //
+ request //
+ "</ReqC>";
}
private static final Location parseStation(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Station".equals(type))
{
final String name = pp.getAttributeValue(null, "name").trim();
final int id = Integer.parseInt(pp.getAttributeValue(null, "externalStationNr"));
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.STATION, id, y, x, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parsePoi(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Poi".equals(type))
{
String name = pp.getAttributeValue(null, "name").trim();
if (name.equals("unknown"))
name = null;
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.POI, 0, y, x, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parseAddress(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Address".equals(type))
{
String name = pp.getAttributeValue(null, "name").trim();
if (name.equals("unknown"))
name = null;
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.ADDRESS, 0, y, x, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parseReqLoc(final XmlPullParser pp)
{
final String type = pp.getName();
if ("ReqLoc".equals(type))
{
XmlPullUtil.requireAttr(pp, "type", "ADR");
final String name = pp.getAttributeValue(null, "output").trim();
return new Location(LocationType.ADDRESS, 0, 0, 0, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
public List<Location> autocompleteStations(final CharSequence constraint) throws IOException
{
final String request = "<LocValReq id=\"req\" maxNr=\"20\"><ReqLoc match=\"" + constraint + "\" type=\"ALLTYPE\"/></LocValReq>";
// System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request));
final List<Location> results = new ArrayList<Location>();
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "LocValRes");
XmlPullUtil.requireAttr(pp, "id", "req");
XmlPullUtil.enter(pp);
while (pp.getEventType() == XmlPullParser.START_TAG)
{
final String tag = pp.getName();
if ("Station".equals(tag))
results.add(parseStation(pp));
else if ("Poi".equals(tag))
results.add(parsePoi(pp));
else if ("Address".equals(tag))
results.add(parseAddress(pp));
else if ("ReqLoc".equals(tag))
/* results.add(parseReqLoc(pp)) */;
else
System.out.println("cannot handle tag: " + tag);
XmlPullUtil.next(pp);
}
XmlPullUtil.exit(pp);
return results;
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final SocketTimeoutException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed) throws IOException
{
if (from.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(from.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(autocompletes, null, null);
from = autocompletes.get(0);
}
if (via != null && via.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(via.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, autocompletes, null);
via = autocompletes.get(0);
}
if (to.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(to.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, null, autocompletes);
to = autocompletes.get(0);
}
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final String request = "<ConReq>" //
+ "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" //
+ (via != null ? "<Via>" + location(via) + "</Via>" : "") //
+ "<Dest>" + location(to) + "</Dest>" //
+ "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" //
+ "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" //
+ "</ConReq>";
// System.out.println(request);
// System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request));
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "ConRes");
XmlPullUtil.enter(pp);
if (pp.getName().equals("Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380"))
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String sessionId = XmlPullUtil.text(pp);
XmlPullUtil.require(pp, "ConnectionList");
XmlPullUtil.enter(pp);
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Overview");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.exit(pp);
XmlPullUtil.require(pp, "ConSectionList");
XmlPullUtil.enter(pp);
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.require(pp, "Departure");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "BasicStop");
XmlPullUtil.enter(pp);
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
Location departure;
if (pp.getName().equals("Station"))
departure = parseStation(pp);
else if (pp.getName().equals("Poi"))
departure = parsePoi(pp);
+ else if (pp.getName().equals("Address"))
+ departure = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Dep");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.require(pp, "Platform");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
String direction = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "JourneyAttributeList");
XmlPullUtil.enter(pp);
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Attribute");
final String attrName = XmlPullUtil.attr(pp, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
direction = attributeVariants.get("NORMAL");
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Duration");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.require(pp, "Arrival");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "BasicStop");
XmlPullUtil.enter(pp);
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
Location arrival;
if (pp.getName().equals("Station"))
arrival = parseStation(pp);
else if (pp.getName().equals("Poi"))
arrival = parsePoi(pp);
else if (pp.getName().equals("Address"))
arrival = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Arr");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.require(pp, "Platform");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id,
departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id,
arrival.name));
}
else
{
parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, null, null, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final SocketTimeoutException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
private final Map<String, String> parseAttributeVariants(final XmlPullParser pp) throws XmlPullParserException, IOException
{
final Map<String, String> attributeVariants = new HashMap<String, String>();
while (XmlPullUtil.test(pp, "AttributeVariant"))
{
final String type = XmlPullUtil.attr(pp, "type");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
final String value = XmlPullUtil.text(pp).trim();
XmlPullUtil.exit(pp);
attributeVariants.put(type, value);
}
return attributeVariants;
}
private static final Pattern P_TIME = Pattern.compile("(\\d+)d(\\d+):(\\d{2}):(\\d{2})");
private Date parseTime(final Calendar currentDate, final String str)
{
final Matcher m = P_TIME.matcher(str);
if (m.matches())
{
final Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, currentDate.get(Calendar.YEAR));
c.set(Calendar.MONTH, currentDate.get(Calendar.MONTH));
c.set(Calendar.DAY_OF_MONTH, currentDate.get(Calendar.DAY_OF_MONTH));
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(2)));
c.set(Calendar.MINUTE, Integer.parseInt(m.group(3)));
c.set(Calendar.SECOND, Integer.parseInt(m.group(4)));
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(1)));
return c.getTime();
}
else
{
throw new IllegalArgumentException("cannot parse duration: " + str);
}
}
private static final Pattern P_DURATION = Pattern.compile("(\\d+):(\\d{2})");
private final int parseDuration(final String str)
{
final Matcher m = P_DURATION.matcher(str);
if (m.matches())
return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));
else
throw new IllegalArgumentException("cannot parse duration: " + str);
}
private final String location(final Location location)
{
if (location.type == LocationType.STATION && location.id != 0)
return "<Station externalId=\"" + location.id + "\" />";
if (location.type == LocationType.POI && (location.lat != 0 || location.lon != 0))
return "<Poi type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />";
if (location.type == LocationType.ADDRESS && (location.lat != 0 || location.lon != 0))
return "<Address type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />";
throw new IllegalArgumentException("cannot handle: " + location.toDebugString());
}
private static final Pattern P_LINE_S = Pattern.compile("S\\d+");
private final String _normalizeLine(final String type, final String name, final String longCategory)
{
final String normalizedType = type.split(" ", 2)[0];
final String normalizedName = normalizeWhitespace(name);
if ("EN".equals(normalizedType)) // EuroNight
return "I" + normalizedName;
if ("EC".equals(normalizedType)) // EuroCity
return "I" + normalizedName;
if ("ICE".equals(normalizedType)) // InterCityExpress
return "I" + normalizedName;
if ("IC".equals(normalizedType)) // InterCity
return "I" + normalizedName;
if ("ICN".equals(normalizedType)) // IC-Neigezug
return "I" + normalizedName;
if ("CNL".equals(normalizedType)) // CityNightLine
return "I" + normalizedName;
if ("OEC".equals(normalizedType)) // ÖBB EuroCity
return "I" + normalizedName;
if ("OIC".equals(normalizedType)) // ÖBB InterCity
return "I" + normalizedName;
if ("TGV".equals(normalizedType)) // Train à grande vit.
return "I" + normalizedName;
if ("THA".equals(normalizedType)) // Thalys
return "I" + normalizedName;
// if ("THALYS".equals(normalizedType))
// return "I" + normalizedName;
if ("ES".equals(normalizedType)) // Eurostar Italia
return "I" + normalizedName;
if ("EST".equals(normalizedType)) // Eurostar
return "I" + normalizedName;
if ("X2".equals(normalizedType)) // X2000 Neigezug, Schweden
return "I" + normalizedName;
if ("RJ".equals(normalizedType)) // Railjet
return "I" + normalizedName;
if ("AVE".equals(normalizedType)) // Alta Velocidad ES
return "I" + normalizedName;
if ("ARC".equals(normalizedType)) // Arco, Spanien
return "I" + normalizedName;
if ("ALS".equals(normalizedType)) // Alaris, Spanien
return "I" + normalizedName;
if ("NZ".equals(normalizedType)) // Nacht-Zug
return "I" + normalizedName;
if ("R".equals(normalizedType)) // Regio
return "R" + normalizedName;
if ("D".equals(normalizedType)) // Schnellzug
return "R" + normalizedName;
if ("E".equals(normalizedType)) // Eilzug
return "R" + normalizedName;
if ("RE".equals(normalizedType)) // RegioExpress
return "R" + normalizedName;
if ("IR".equals(normalizedType)) // InterRegio
return "R" + normalizedName;
if ("IRE".equals(normalizedType)) // InterRegioExpress
return "R" + normalizedName;
if ("ATZ".equals(normalizedType)) // Autotunnelzug
return "R" + normalizedName;
if ("S".equals(normalizedType)) // S-Bahn
return "S" + normalizedName;
if (P_LINE_S.matcher(normalizedType).matches()) // diverse S-Bahnen
return "S" + normalizedType;
if ("Met".equals(normalizedType)) // Metro
return "U" + normalizedName;
if ("M".equals(normalizedType)) // Metro
return "U" + normalizedName;
if ("Métro".equals(normalizedType))
return "U" + normalizedName;
if ("Tram".equals(normalizedType)) // Tram
return "T" + normalizedName;
if ("Tramway".equals(normalizedType))
return "T" + normalizedName;
if ("BUS".equals(normalizedType)) // Bus
return "B" + normalizedName;
if ("Bus".equals(normalizedType)) // Niederflurbus
return "B" + normalizedName;
if ("NFB".equals(normalizedType)) // Niederflur-Bus
return "B" + normalizedName;
if ("Tro".equals(normalizedType)) // Trolleybus
return "B" + normalizedName;
if ("Taxi".equals(normalizedType)) // Taxi
return "B" + normalizedName;
if ("TX".equals(normalizedType)) // Taxi
return "B" + normalizedName;
if ("BAT".equals(normalizedType)) // Schiff
return "F" + normalizedName;
if ("LB".equals(normalizedType)) // Luftseilbahn
return "C" + normalizedName;
if ("FUN".equals(normalizedType)) // Standseilbahn
return "C" + normalizedName;
if ("Fun".equals(normalizedType)) // Funiculaire
return "C" + normalizedName;
if ("L".equals(normalizedType))
return "?" + normalizedName;
if ("P".equals(normalizedType))
return "?" + normalizedName;
if ("CR".equals(normalizedType))
return "?" + normalizedName;
if ("TRN".equals(normalizedType))
return "?" + normalizedName;
throw new IllegalStateException("cannot normalize type '" + normalizedType + "' (" + type + ") name '" + normalizedName + "' longCategory '"
+ longCategory + "'");
}
private final static Pattern P_WHITESPACE = Pattern.compile("\\s+");
private final String normalizeWhitespace(final String str)
{
return P_WHITESPACE.matcher(str).replaceAll("");
}
public QueryConnectionsResult queryMoreConnections(String uri) throws IOException
{
throw new UnsupportedOperationException();
}
public GetConnectionDetailsResult getConnectionDetails(String connectionUri) throws IOException
{
throw new UnsupportedOperationException();
}
private final static Pattern P_NEARBY_COARSE = Pattern.compile("<tr class=\"(zebra[^\"]*)\">(.*?)</tr>", Pattern.DOTALL);
private final static Pattern P_NEARBY_FINE_COORDS = Pattern
.compile("&REQMapRoute0\\.Location0\\.X=(-?\\d+)&REQMapRoute0\\.Location0\\.Y=(-?\\d+)&");
private final static Pattern P_NEARBY_FINE_LOCATION = Pattern.compile("[\\?&]input=(\\d+)&[^\"]*\">([^<]*)<");
protected abstract String nearbyStationUri(String stationId);
public NearbyStationsResult nearbyStations(final String stationId, final int lat, final int lon, final int maxDistance, final int maxStations)
throws IOException
{
if (stationId == null)
throw new IllegalArgumentException("stationId must be given");
final List<Station> stations = new ArrayList<Station>();
final String uri = nearbyStationUri(stationId);
final CharSequence page = ParserUtils.scrape(uri);
String oldZebra = null;
final Matcher mCoarse = P_NEARBY_COARSE.matcher(page);
while (mCoarse.find())
{
final String zebra = mCoarse.group(1);
if (oldZebra != null && zebra.equals(oldZebra))
throw new IllegalArgumentException("missed row? last:" + zebra);
else
oldZebra = zebra;
final Matcher mFineLocation = P_NEARBY_FINE_LOCATION.matcher(mCoarse.group(2));
if (mFineLocation.find())
{
int parsedLon = 0;
int parsedLat = 0;
final int parsedId = Integer.parseInt(mFineLocation.group(1));
final String parsedName = ParserUtils.resolveEntities(mFineLocation.group(2));
final Matcher mFineCoords = P_NEARBY_FINE_COORDS.matcher(mCoarse.group(2));
if (mFineCoords.find())
{
parsedLon = Integer.parseInt(mFineCoords.group(1));
parsedLat = Integer.parseInt(mFineCoords.group(2));
}
stations.add(new Station(parsedId, parsedName, parsedLat, parsedLon, 0, null, null));
}
else
{
throw new IllegalArgumentException("cannot parse '" + mCoarse.group(2) + "' on " + uri);
}
}
if (maxStations == 0 || maxStations >= stations.size())
return new NearbyStationsResult(uri, stations);
else
return new NearbyStationsResult(uri, stations.subList(0, maxStations));
}
protected static final Pattern P_NORMALIZE_LINE = Pattern.compile("([A-Za-zÄÖÜäöüßáàâéèêíìîóòôúùû/-]+)[\\s-]*(.*)");
protected final String normalizeLine(final String type, final String line)
{
final Matcher m = P_NORMALIZE_LINE.matcher(line);
final String strippedLine = m.matches() ? m.group(1) + m.group(2) : line;
final char normalizedType = normalizeType(type);
if (normalizedType != 0)
return normalizedType + strippedLine;
throw new IllegalStateException("cannot normalize type '" + type + "' line '" + line + "'");
}
protected abstract char normalizeType(String type);
protected final char normalizeCommonTypes(final String ucType)
{
// Intercity
if (ucType.equals("EC")) // EuroCity
return 'I';
if (ucType.equals("EN")) // EuroNight
return 'I';
if (ucType.equals("ICE")) // InterCityExpress
return 'I';
if (ucType.equals("IC")) // InterCity
return 'I';
if (ucType.equals("EN")) // EuroNight
return 'I';
if (ucType.equals("CNL")) // CityNightLine
return 'I';
if (ucType.equals("OEC")) // ÖBB-EuroCity
return 'I';
if (ucType.equals("OIC")) // ÖBB-InterCity
return 'I';
if (ucType.equals("RJ")) // RailJet, Österreichische Bundesbahnen
return 'I';
if (ucType.equals("THA")) // Thalys
return 'I';
if (ucType.equals("TGV")) // Train à Grande Vitesse
return 'I';
if (ucType.equals("DNZ")) // Berlin-Saratov, Berlin-Moskva, Connections only?
return 'I';
if (ucType.equals("AIR")) // Generic Flight
return 'I';
if (ucType.equals("ECB")) // EC, Verona-München
return 'I';
if (ucType.equals("INZ")) // Nacht
return 'I';
if (ucType.equals("RHI")) // ICE
return 'I';
if (ucType.equals("RHT")) // TGV
return 'I';
if (ucType.equals("TGD")) // TGV
return 'I';
if (ucType.equals("IRX")) // IC
return 'I';
// Regional Germany
if (ucType.equals("ZUG")) // Generic Train
return 'R';
if (ucType.equals("R")) // Generic Regional Train
return 'R';
if (ucType.equals("DPN")) // Dritter Personen Nahverkehr
return 'R';
if (ucType.equals("RB")) // RegionalBahn
return 'R';
if (ucType.equals("RE")) // RegionalExpress
return 'R';
if (ucType.equals("IR")) // Interregio
return 'R';
if (ucType.equals("IRE")) // Interregio Express
return 'R';
if (ucType.equals("HEX")) // Harz-Berlin-Express, Veolia
return 'R';
if (ucType.equals("WFB")) // Westfalenbahn
return 'R';
if (ucType.equals("RT")) // RegioTram
return 'R';
if (ucType.equals("REX")) // RegionalExpress, Österreich
return 'R';
// Regional Poland
if (ucType.equals("OS")) // Chop-Cierna nas Tisou
return 'R';
if (ucType.equals("SP")) // Polen
return 'R';
// Suburban Trains
if (ucType.equals("S")) // Generic S-Bahn
return 'S';
// Subway
if (ucType.equals("U")) // Generic U-Bahn
return 'U';
// Tram
if (ucType.equals("STR")) // Generic Tram
return 'T';
// Bus
if (ucType.equals("BUS")) // Generic Bus
return 'B';
if (ucType.equals("AST")) // Anruf-Sammel-Taxi
return 'B';
if (ucType.equals("SEV")) // Schienen-Ersatz-Verkehr
return 'B';
if (ucType.equals("BUSSEV")) // Schienen-Ersatz-Verkehr
return 'B';
if (ucType.equals("FB")) // Luxemburg-Saarbrücken
return 'B';
// Ferry
if (ucType.equals("AS")) // SyltShuttle, eigentlich Autoreisezug
return 'F';
return 0;
}
private static final Pattern P_CONNECTION_ID = Pattern.compile("co=(C\\d+-\\d+)&");
protected static String extractConnectionId(final String link)
{
final Matcher m = P_CONNECTION_ID.matcher(link);
if (m.find())
return m.group(1);
else
throw new IllegalArgumentException("cannot extract id from " + link);
}
private static final Map<Character, int[]> LINES = new HashMap<Character, int[]>();
static
{
LINES.put('I', new int[] { Color.WHITE, Color.RED, Color.RED });
LINES.put('R', new int[] { Color.GRAY, Color.WHITE });
LINES.put('S', new int[] { Color.parseColor("#006e34"), Color.WHITE });
LINES.put('U', new int[] { Color.parseColor("#003090"), Color.WHITE });
LINES.put('T', new int[] { Color.parseColor("#cc0000"), Color.WHITE });
LINES.put('B', new int[] { Color.parseColor("#993399"), Color.WHITE });
LINES.put('F', new int[] { Color.BLUE, Color.WHITE });
LINES.put('?', new int[] { Color.DKGRAY, Color.WHITE });
}
public final int[] lineColors(final String line)
{
return LINES.get(line.charAt(0));
}
private void assertResC(final XmlPullParser pp) throws XmlPullParserException, IOException
{
if (!XmlPullUtil.jumpToStartTag(pp, null, "ResC"))
throw new IOException("cannot find <ResC />");
}
}
| true | true | public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed) throws IOException
{
if (from.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(from.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(autocompletes, null, null);
from = autocompletes.get(0);
}
if (via != null && via.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(via.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, autocompletes, null);
via = autocompletes.get(0);
}
if (to.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(to.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, null, autocompletes);
to = autocompletes.get(0);
}
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final String request = "<ConReq>" //
+ "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" //
+ (via != null ? "<Via>" + location(via) + "</Via>" : "") //
+ "<Dest>" + location(to) + "</Dest>" //
+ "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" //
+ "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" //
+ "</ConReq>";
// System.out.println(request);
// System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request));
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "ConRes");
XmlPullUtil.enter(pp);
if (pp.getName().equals("Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380"))
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String sessionId = XmlPullUtil.text(pp);
XmlPullUtil.require(pp, "ConnectionList");
XmlPullUtil.enter(pp);
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Overview");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.exit(pp);
XmlPullUtil.require(pp, "ConSectionList");
XmlPullUtil.enter(pp);
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.require(pp, "Departure");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "BasicStop");
XmlPullUtil.enter(pp);
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
Location departure;
if (pp.getName().equals("Station"))
departure = parseStation(pp);
else if (pp.getName().equals("Poi"))
departure = parsePoi(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Dep");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.require(pp, "Platform");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
String direction = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "JourneyAttributeList");
XmlPullUtil.enter(pp);
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Attribute");
final String attrName = XmlPullUtil.attr(pp, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
direction = attributeVariants.get("NORMAL");
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Duration");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.require(pp, "Arrival");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "BasicStop");
XmlPullUtil.enter(pp);
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
Location arrival;
if (pp.getName().equals("Station"))
arrival = parseStation(pp);
else if (pp.getName().equals("Poi"))
arrival = parsePoi(pp);
else if (pp.getName().equals("Address"))
arrival = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Arr");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.require(pp, "Platform");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id,
departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id,
arrival.name));
}
else
{
parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, null, null, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final SocketTimeoutException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
| public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed) throws IOException
{
if (from.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(from.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(autocompletes, null, null);
from = autocompletes.get(0);
}
if (via != null && via.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(via.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, autocompletes, null);
via = autocompletes.get(0);
}
if (to.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(to.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, null, autocompletes);
to = autocompletes.get(0);
}
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final String request = "<ConReq>" //
+ "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" //
+ (via != null ? "<Via>" + location(via) + "</Via>" : "") //
+ "<Dest>" + location(to) + "</Dest>" //
+ "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" //
+ "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" //
+ "</ConReq>";
// System.out.println(request);
// System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request));
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "ConRes");
XmlPullUtil.enter(pp);
if (pp.getName().equals("Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380"))
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String sessionId = XmlPullUtil.text(pp);
XmlPullUtil.require(pp, "ConnectionList");
XmlPullUtil.enter(pp);
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Overview");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.exit(pp);
XmlPullUtil.require(pp, "ConSectionList");
XmlPullUtil.enter(pp);
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.require(pp, "Departure");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "BasicStop");
XmlPullUtil.enter(pp);
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
Location departure;
if (pp.getName().equals("Station"))
departure = parseStation(pp);
else if (pp.getName().equals("Poi"))
departure = parsePoi(pp);
else if (pp.getName().equals("Address"))
departure = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Dep");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.require(pp, "Platform");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
String direction = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "JourneyAttributeList");
XmlPullUtil.enter(pp);
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Attribute");
final String attrName = XmlPullUtil.attr(pp, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
direction = attributeVariants.get("NORMAL");
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Duration");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.require(pp, "Arrival");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "BasicStop");
XmlPullUtil.enter(pp);
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
Location arrival;
if (pp.getName().equals("Station"))
arrival = parseStation(pp);
else if (pp.getName().equals("Poi"))
arrival = parsePoi(pp);
else if (pp.getName().equals("Address"))
arrival = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
XmlPullUtil.require(pp, "Arr");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.require(pp, "Platform");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id,
departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id,
arrival.name));
}
else
{
parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, null, null, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final SocketTimeoutException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
|
diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java
index c4d5845ba..2766f82a7 100644
--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java
+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java
@@ -1,166 +1,165 @@
/*
* 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.solr.handler.dataimport;
import org.junit.Ignore;
import org.junit.Test;
import org.apache.solr.util.DateMathParser;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* <p>
* Test for VariableResolver
* </p>
*
*
* @since solr 1.3
*/
public class TestVariableResolver extends AbstractDataImportHandlerTestCase {
@Test
public void testSimpleNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
assertEquals("WORLD", vri.resolve("hello.world"));
}
@Test
public void testDefaults() {
// System.out.println(System.setProperty(TestVariableResolver.class.getName(),"hello"));
System.setProperty(TestVariableResolver.class.getName(), "hello");
// System.out.println("s.gP()"+
// System.getProperty(TestVariableResolver.class.getName()));
Properties p = new Properties();
p.put("hello", "world");
VariableResolver vri = new VariableResolver(p);
Object val = vri.resolve(TestVariableResolver.class.getName());
// System.out.println("val = " + val);
assertEquals("hello", val);
assertEquals("world", vri.resolve("hello"));
}
@Test
public void testNestedNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
ns = new HashMap<String,Object>();
ns.put("world1", "WORLD1");
vri.addNamespace("hello.my", ns);
assertEquals("WORLD1", vri.resolve("hello.my.world1"));
}
@Test
public void test3LevelNestedNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
ns = new HashMap<String,Object>();
ns.put("world1", "WORLD1");
vri.addNamespace("hello.my.new", ns);
assertEquals("WORLD1", vri.resolve("hello.my.new.world1"));
}
@Test
public void dateNamespaceWithValue() {
VariableResolver vri = new VariableResolver();
vri.setEvaluators(new DataImporter().getEvaluators(Collections
.<Map<String,String>> emptyList()));
Map<String,Object> ns = new HashMap<String,Object>();
Date d = new Date();
ns.put("dt", d);
vri.addNamespace("A", ns);
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT).format(d),
vri.replaceTokens("${dataimporter.functions.formatDate(A.dt,'yyyy-MM-dd HH:mm:ss')}"));
}
@Test
public void dateNamespaceWithExpr() throws Exception {
VariableResolver vri = new VariableResolver();
vri.setEvaluators(new DataImporter().getEvaluators(Collections
.<Map<String,String>> emptyList()));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
DateMathParser dmp = new DateMathParser(TimeZone.getDefault(), Locale.ROOT);
String s = vri
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
}
@Test
public void testDefaultNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace(null, ns);
assertEquals("WORLD", vri.resolve("world"));
}
@Test
public void testDefaultNamespace1() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace(null, ns);
assertEquals("WORLD", vri.resolve("world"));
}
@Test
public void testFunctionNamespace1() throws Exception {
VariableResolver resolver = new VariableResolver();
final List<Map<String,String>> l = new ArrayList<Map<String,String>>();
Map<String,String> m = new HashMap<String,String>();
m.put("name", "test");
m.put("class", E.class.getName());
l.add(m);
resolver.setEvaluators(new DataImporter().getEvaluators(l));
ContextImpl context = new ContextImpl(null, resolver, null,
Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
- DateMathParser dmp = new DateMathParser(TimeZone.getDefault(),
- Locale.getDefault());
+ DateMathParser dmp = new DateMathParser(TimeZone.getDefault(), Locale.ROOT);
String s = resolver
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
assertEquals("Hello World",
resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}
public static class E extends Evaluator {
@Override
public String evaluate(String expression, Context context) {
return "Hello World";
}
}
}
| true | true | public void testFunctionNamespace1() throws Exception {
VariableResolver resolver = new VariableResolver();
final List<Map<String,String>> l = new ArrayList<Map<String,String>>();
Map<String,String> m = new HashMap<String,String>();
m.put("name", "test");
m.put("class", E.class.getName());
l.add(m);
resolver.setEvaluators(new DataImporter().getEvaluators(l));
ContextImpl context = new ContextImpl(null, resolver, null,
Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
DateMathParser dmp = new DateMathParser(TimeZone.getDefault(),
Locale.getDefault());
String s = resolver
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
assertEquals("Hello World",
resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}
| public void testFunctionNamespace1() throws Exception {
VariableResolver resolver = new VariableResolver();
final List<Map<String,String>> l = new ArrayList<Map<String,String>>();
Map<String,String> m = new HashMap<String,String>();
m.put("name", "test");
m.put("class", E.class.getName());
l.add(m);
resolver.setEvaluators(new DataImporter().getEvaluators(l));
ContextImpl context = new ContextImpl(null, resolver, null,
Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
DateMathParser dmp = new DateMathParser(TimeZone.getDefault(), Locale.ROOT);
String s = resolver
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
assertEquals("Hello World",
resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}
|
diff --git a/src/nodebox/client/FileUtils.java b/src/nodebox/client/FileUtils.java
index 76c5aac1..5beb3d4a 100644
--- a/src/nodebox/client/FileUtils.java
+++ b/src/nodebox/client/FileUtils.java
@@ -1,172 +1,173 @@
package nodebox.client;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.*;
import java.util.Locale;
import java.util.StringTokenizer;
public class FileUtils {
/**
* Gets the extension of a file.
*
* @param f the file
* @return the extension of the file.
*/
public static String getExtension(File f) {
return getExtension(f.getName());
}
/**
* Gets the extension of a file.
*
* @param fileName the file name
* @return the extension of the file.
*/
public static String getExtension(String fileName) {
String ext = null;
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
ext = fileName.substring(i + 1).toLowerCase(Locale.US);
}
return ext;
}
public static File showOpenDialog(Frame owner, String pathName, String extensions, String description) {
return showFileDialog(owner, pathName, extensions, description, FileDialog.LOAD);
}
public static File showSaveDialog(Frame owner, String pathName, String extensions, String description) {
return showFileDialog(owner, pathName, extensions, description, FileDialog.SAVE);
}
private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) {
FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType);
if (pathName == null || pathName.trim().length() == 0) {
NodeBoxDocument document = NodeBoxDocument.getCurrentDocument();
if (document != null) {
File documentFile = document.getDocumentFile();
if (documentFile != null) {
- fileDialog.setFile(documentFile.getParentFile().getPath());
+ fileDialog.setDirectory(documentFile.getParentFile().getPath());
}
}
} else {
File f = new File(pathName);
if (f.isDirectory()) {
fileDialog.setDirectory(pathName);
} else {
- fileDialog.setFile(pathName);
+ fileDialog.setDirectory(f.getParentFile().getPath());
+ fileDialog.setFile(f.getName());
}
}
fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description));
fileDialog.setVisible(true);
String chosenFile = fileDialog.getFile();
String dir = fileDialog.getDirectory();
if (chosenFile != null) {
return new File(dir + chosenFile);
} else {
return null;
}
}
public static String[] parseExtensions(String extensions) {
StringTokenizer st = new StringTokenizer(extensions, ",");
String[] ext = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
ext[i++] = st.nextToken();
}
return ext;
}
public static class FileExtensionFilter extends FileFilter implements FilenameFilter {
String[] extensions;
String description;
public FileExtensionFilter(String extensions, String description) {
this.extensions = parseExtensions(extensions);
this.description = description;
}
public boolean accept(File f) {
return f.isDirectory() || accept(null, f.getName());
}
public boolean accept(File f, String s) {
String extension = FileUtils.getExtension(s);
if (extension != null) {
for (String extension1 : extensions) {
if (extension1.equals("*") || extension1.equalsIgnoreCase(extension)) {
return true;
}
}
}
return false;
}
public String getDescription() {
return description;
}
}
public static String readFile(File file) {
StringBuffer contents = new StringBuffer();
try {
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
contents.append(line);
contents.append("\n");
}
in.close();
} catch (IOException e) {
throw new RuntimeException("Could not read file " + file, e);
}
return contents.toString();
}
public static void writeFile(File file, String s) {
try {
Writer out = new BufferedWriter(new FileWriter(file));
out.write(s);
out.close();
} catch (IOException e) {
throw new RuntimeException("Could not write file " + file, e);
}
}
public static File createTemporaryDirectory(String prefix) {
File tempDir = null;
try {
tempDir = File.createTempFile(prefix, "");
} catch (IOException e) {
throw new RuntimeException("Could not create temporary file " + prefix);
}
boolean success = tempDir.delete();
if (!success) throw new RuntimeException("Could not delete temporary file " + tempDir);
success = tempDir.mkdir();
if (!success) throw new RuntimeException("Could not create temporary directory " + tempDir);
return tempDir;
}
public static boolean deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
}
return (directory.delete());
}
}
| false | true | private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) {
FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType);
if (pathName == null || pathName.trim().length() == 0) {
NodeBoxDocument document = NodeBoxDocument.getCurrentDocument();
if (document != null) {
File documentFile = document.getDocumentFile();
if (documentFile != null) {
fileDialog.setFile(documentFile.getParentFile().getPath());
}
}
} else {
File f = new File(pathName);
if (f.isDirectory()) {
fileDialog.setDirectory(pathName);
} else {
fileDialog.setFile(pathName);
}
}
fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description));
fileDialog.setVisible(true);
String chosenFile = fileDialog.getFile();
String dir = fileDialog.getDirectory();
if (chosenFile != null) {
return new File(dir + chosenFile);
} else {
return null;
}
}
| private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) {
FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType);
if (pathName == null || pathName.trim().length() == 0) {
NodeBoxDocument document = NodeBoxDocument.getCurrentDocument();
if (document != null) {
File documentFile = document.getDocumentFile();
if (documentFile != null) {
fileDialog.setDirectory(documentFile.getParentFile().getPath());
}
}
} else {
File f = new File(pathName);
if (f.isDirectory()) {
fileDialog.setDirectory(pathName);
} else {
fileDialog.setDirectory(f.getParentFile().getPath());
fileDialog.setFile(f.getName());
}
}
fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description));
fileDialog.setVisible(true);
String chosenFile = fileDialog.getFile();
String dir = fileDialog.getDirectory();
if (chosenFile != null) {
return new File(dir + chosenFile);
} else {
return null;
}
}
|
diff --git a/src/edu/jas/application/ReductionTest.java b/src/edu/jas/application/ReductionTest.java
index 8305d828..1abeb39f 100644
--- a/src/edu/jas/application/ReductionTest.java
+++ b/src/edu/jas/application/ReductionTest.java
@@ -1,300 +1,300 @@
/*
* $Id$
*/
package edu.jas.application;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.log4j.BasicConfigurator;
import edu.jas.structure.Product;
import edu.jas.structure.ProductRing;
import edu.jas.structure.RingFactory;
import edu.jas.arith.BigInteger;
import edu.jas.arith.BigRational;
import edu.jas.arith.BigComplex;
import edu.jas.poly.ExpVector;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.ColorPolynomial;
import edu.jas.poly.GenPolynomialRing;
import edu.jas.poly.PolynomialList;
//import edu.jas.application.Ideal;
/**
* Reduction tests with JUnit.
* @author Heinz Kredel.
*/
public class ReductionTest extends TestCase {
/**
* main
*/
public static void main (String[] args) {
BasicConfigurator.configure();
junit.textui.TestRunner.run( suite() );
}
/**
* Constructs a <CODE>ReductionTest</CODE> object.
* @param name String
*/
public ReductionTest(String name) {
super(name);
}
/**
* suite.
* @return a test suite.
*/
public static Test suite() {
TestSuite suite= new TestSuite(ReductionTest.class);
return suite;
}
//private final static int bitlen = 100;
GenPolynomialRing<BigRational> fac;
GenPolynomial<BigRational> a;
GenPolynomial<BigRational> b;
GenPolynomial<BigRational> c;
GenPolynomial<BigRational> d;
GenPolynomial<BigRational> e;
List<GenPolynomial<BigRational>> L;
PolynomialList<BigRational> F;
PolynomialList<BigRational> G;
//ReductionSeq<BigRational> red;
//Reduction<BigRational> redpar;
int rl = 2;
int kl = 2;
int ll = 3;
int el = 3;
float q = 0.4f;
protected void setUp() {
a = b = c = d = e = null;
fac = new GenPolynomialRing<BigRational>( new BigRational(0), rl );
//red = new ReductionSeq<BigRational>();
//redpar = new ReductionPar<BigRational>();
}
protected void tearDown() {
a = b = c = d = e = null;
fac = null;
//red = null;
//redpar = null;
}
/**
* Test dummy.
*
*/
public void testDummy() {
}
/**
* Test rational coefficient polynomial parametric reduction.
*
*/
public void xtestRatPolReduction() {
RingFactory<BigRational> bi = new BigRational(0);
GenPolynomialRing<BigRational> pr
= new GenPolynomialRing<BigRational>(bi,2, new String[] { "a", "b" } );
GenPolynomialRing<GenPolynomial<BigRational>> fac
= new GenPolynomialRing<GenPolynomial<BigRational>>(pr,rl);
CReductionSeq<BigRational> cred
- = new CReductionSeq<BigRational>();
+ = new CReductionSeq<BigRational>( bi );
GenPolynomial<GenPolynomial<BigRational>> a = fac.random(kl, ll, el, q );
while ( a.isZERO() ) {
a = fac.random(kl, ll, el, q );
}
GenPolynomial<GenPolynomial<BigRational>> b = fac.random(kl, ll, el, q );
while ( b.isZERO() ) {
b = fac.random(kl, ll, el, q );
}
GenPolynomial<GenPolynomial<BigRational>> g = fac.getZERO();
Map.Entry<ExpVector,GenPolynomial<BigRational>> m = a.leadingMonomial();
ExpVector e = m.getKey();
GenPolynomial<BigRational> c = m.getValue();
GenPolynomial<GenPolynomial<BigRational>> r = fac.getZERO();
r = r.sum(c,e);
GenPolynomial<GenPolynomial<BigRational>> w = a.reductum();
ColorPolynomial<BigRational> p
= new ColorPolynomial<BigRational>(g,r,w);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(r,g,w);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
if ( !w.isZERO() ) {
assertFalse("deter(p) ", p.isDetermined());
}
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(r,w,g);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(w,g,r);
//System.out.println("p = " + p);
if ( !w.isZERO() ) {
assertFalse("check(p) ", p.checkInvariant());
}
assertFalse("deter(p) ", p.isDetermined());
assertFalse("p == 0 ", p.isZERO());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(w,g,g);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
assertTrue("p == 0 ", p.isZERO());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
List<GenPolynomial<BigRational>> i
= new ArrayList<GenPolynomial<BigRational>>();
Ideal<BigRational> id = new Ideal<BigRational>(pr,i);
List<ColorPolynomial<BigRational>> cp
= new ArrayList<ColorPolynomial<BigRational>>();
Condition<BigRational> cond = new Condition<BigRational>(id);
ColoredSystem<BigRational> s
= new ColoredSystem<BigRational>(cond,cp);
//System.out.println("s = " + s);
assertTrue("isDetermined ", s.isDetermined());
assertTrue("checkInvariant ", s.checkInvariant());
List<ColoredSystem<BigRational>> CS
= new ArrayList<ColoredSystem<BigRational>>();
CS.add(s);
//System.out.println("CS = " + CS);
List<ColoredSystem<BigRational>> CSp = CS;
//System.out.println("\na = " + a);
//System.out.println("b = " + b + "\n");
CS = cred.determine(s,p);
//System.out.println("CS = " + CS);
for ( ColoredSystem<BigRational> x : CS ) {
assertTrue("isDetermined ", x.isDetermined());
assertTrue("checkInvariant ", x.checkInvariant());
}
List<GenPolynomial<GenPolynomial<BigRational>>> L;
L = new ArrayList<GenPolynomial<GenPolynomial<BigRational>>>();
L.add(a);
L.add(b);
//System.out.println("\na = " + a);
//System.out.println("b = " + b + "\n");
List<Condition<BigRational>> Ccond;
//System.out.println("caseDistinction ----------------------------------");
Ccond = cred.caseDistinction(L);
//System.out.println("Ccond ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
//for ( Condition<BigRational> cnd : Ccond ) {
// System.out.println("" + cnd);
//}
//System.out.println("determine ---------------------------------");
CSp = cred.determine(L);
//System.out.println("CSp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + CSp);
//System.out.println("++++++++++++++++++++++++++++++++++++++");
for ( ColoredSystem<BigRational> x : CSp ) {
assertTrue("isDetermined ", x.isDetermined());
assertTrue("checkInvariant ", x.checkInvariant());
//System.out.println("condition == 0: " + x.getConditionZero());
//System.out.println("condition != 0: " + x.getConditionNonZero());
//System.out.println("polynomial list: " + x.getPolynomialList());
//System.out.println("++++++++++++++++++++++++++++++++++++++");
}
ColorPolynomial<BigRational> q, h;
List<ColoredSystem<BigRational>> NCS;
for ( ColoredSystem<BigRational> x : CSp ) {
int k = x.list.size();
for ( int j = 0; j < k; j++ ) {
p = x.list.get(j);
for ( int l = j+1; l < k; l++ ) {
q = x.list.get(l);
h = cred.SPolynomial(p,q);
//System.out.println("spol(a,b) = " + h);
boolean t = cred.isNormalform( x.list, h );
//System.out.println("isNF(spol(a,b)) = " + t);
- h = cred.normalform( x.list, h );
+ h = cred.normalform( x.condition, x.list, h );
//System.out.println("NF(spol(a,b)) = " + h);
t = cred.isNormalform( x.list, h );
//System.out.println("isNF(NF(spol(a,b))) = " + t);
assertTrue("isNF(NF(spol(a,b))) ", t);
NCS = cred.determine( x, h );
for ( ColoredSystem<BigRational> cpp : NCS ) {
assertTrue("isDetermined( cpp ) ", cpp.isDetermined() );
assertTrue("checkInvariant ", cpp.checkInvariant());
}
}
}
}
if ( false ) {
return;
}
ComprehensiveGroebnerBaseSeq<BigRational> cgb =
new ComprehensiveGroebnerBaseSeq<BigRational>(cred,bi);
System.out.println("isGB(L) = " + cgb.isGB(L) );
if ( true ) {
List<ColoredSystem<BigRational>> Gsys = cgb.GBsys( L );
//System.out.println("GBsys(L) = " + Gsys );
//System.out.println("isGBsys(G) = " + cgb.isGBsys(Gsys) );
assertTrue("isGBsys( GBsys(G) ) ", cgb.isGBsys(Gsys) );
}
if ( true ) {
List<GenPolynomial<GenPolynomial<BigRational>>> G;
G = cgb.GB(L);
//System.out.println("GB(L) = " + G );
//System.out.println("isGB(G) = " + cgb.isGB(G) );
assertTrue("isGB( GB(G) ) ", cgb.isGB(G) );
}
}
}
| false | true | public void xtestRatPolReduction() {
RingFactory<BigRational> bi = new BigRational(0);
GenPolynomialRing<BigRational> pr
= new GenPolynomialRing<BigRational>(bi,2, new String[] { "a", "b" } );
GenPolynomialRing<GenPolynomial<BigRational>> fac
= new GenPolynomialRing<GenPolynomial<BigRational>>(pr,rl);
CReductionSeq<BigRational> cred
= new CReductionSeq<BigRational>();
GenPolynomial<GenPolynomial<BigRational>> a = fac.random(kl, ll, el, q );
while ( a.isZERO() ) {
a = fac.random(kl, ll, el, q );
}
GenPolynomial<GenPolynomial<BigRational>> b = fac.random(kl, ll, el, q );
while ( b.isZERO() ) {
b = fac.random(kl, ll, el, q );
}
GenPolynomial<GenPolynomial<BigRational>> g = fac.getZERO();
Map.Entry<ExpVector,GenPolynomial<BigRational>> m = a.leadingMonomial();
ExpVector e = m.getKey();
GenPolynomial<BigRational> c = m.getValue();
GenPolynomial<GenPolynomial<BigRational>> r = fac.getZERO();
r = r.sum(c,e);
GenPolynomial<GenPolynomial<BigRational>> w = a.reductum();
ColorPolynomial<BigRational> p
= new ColorPolynomial<BigRational>(g,r,w);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(r,g,w);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
if ( !w.isZERO() ) {
assertFalse("deter(p) ", p.isDetermined());
}
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(r,w,g);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(w,g,r);
//System.out.println("p = " + p);
if ( !w.isZERO() ) {
assertFalse("check(p) ", p.checkInvariant());
}
assertFalse("deter(p) ", p.isDetermined());
assertFalse("p == 0 ", p.isZERO());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(w,g,g);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
assertTrue("p == 0 ", p.isZERO());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
List<GenPolynomial<BigRational>> i
= new ArrayList<GenPolynomial<BigRational>>();
Ideal<BigRational> id = new Ideal<BigRational>(pr,i);
List<ColorPolynomial<BigRational>> cp
= new ArrayList<ColorPolynomial<BigRational>>();
Condition<BigRational> cond = new Condition<BigRational>(id);
ColoredSystem<BigRational> s
= new ColoredSystem<BigRational>(cond,cp);
//System.out.println("s = " + s);
assertTrue("isDetermined ", s.isDetermined());
assertTrue("checkInvariant ", s.checkInvariant());
List<ColoredSystem<BigRational>> CS
= new ArrayList<ColoredSystem<BigRational>>();
CS.add(s);
//System.out.println("CS = " + CS);
List<ColoredSystem<BigRational>> CSp = CS;
//System.out.println("\na = " + a);
//System.out.println("b = " + b + "\n");
CS = cred.determine(s,p);
//System.out.println("CS = " + CS);
for ( ColoredSystem<BigRational> x : CS ) {
assertTrue("isDetermined ", x.isDetermined());
assertTrue("checkInvariant ", x.checkInvariant());
}
List<GenPolynomial<GenPolynomial<BigRational>>> L;
L = new ArrayList<GenPolynomial<GenPolynomial<BigRational>>>();
L.add(a);
L.add(b);
//System.out.println("\na = " + a);
//System.out.println("b = " + b + "\n");
List<Condition<BigRational>> Ccond;
//System.out.println("caseDistinction ----------------------------------");
Ccond = cred.caseDistinction(L);
//System.out.println("Ccond ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
//for ( Condition<BigRational> cnd : Ccond ) {
// System.out.println("" + cnd);
//}
//System.out.println("determine ---------------------------------");
CSp = cred.determine(L);
//System.out.println("CSp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + CSp);
//System.out.println("++++++++++++++++++++++++++++++++++++++");
for ( ColoredSystem<BigRational> x : CSp ) {
assertTrue("isDetermined ", x.isDetermined());
assertTrue("checkInvariant ", x.checkInvariant());
//System.out.println("condition == 0: " + x.getConditionZero());
//System.out.println("condition != 0: " + x.getConditionNonZero());
//System.out.println("polynomial list: " + x.getPolynomialList());
//System.out.println("++++++++++++++++++++++++++++++++++++++");
}
ColorPolynomial<BigRational> q, h;
List<ColoredSystem<BigRational>> NCS;
for ( ColoredSystem<BigRational> x : CSp ) {
int k = x.list.size();
for ( int j = 0; j < k; j++ ) {
p = x.list.get(j);
for ( int l = j+1; l < k; l++ ) {
q = x.list.get(l);
h = cred.SPolynomial(p,q);
//System.out.println("spol(a,b) = " + h);
boolean t = cred.isNormalform( x.list, h );
//System.out.println("isNF(spol(a,b)) = " + t);
h = cred.normalform( x.list, h );
//System.out.println("NF(spol(a,b)) = " + h);
t = cred.isNormalform( x.list, h );
//System.out.println("isNF(NF(spol(a,b))) = " + t);
assertTrue("isNF(NF(spol(a,b))) ", t);
NCS = cred.determine( x, h );
for ( ColoredSystem<BigRational> cpp : NCS ) {
assertTrue("isDetermined( cpp ) ", cpp.isDetermined() );
assertTrue("checkInvariant ", cpp.checkInvariant());
}
}
}
}
if ( false ) {
return;
}
ComprehensiveGroebnerBaseSeq<BigRational> cgb =
new ComprehensiveGroebnerBaseSeq<BigRational>(cred,bi);
System.out.println("isGB(L) = " + cgb.isGB(L) );
if ( true ) {
List<ColoredSystem<BigRational>> Gsys = cgb.GBsys( L );
//System.out.println("GBsys(L) = " + Gsys );
//System.out.println("isGBsys(G) = " + cgb.isGBsys(Gsys) );
assertTrue("isGBsys( GBsys(G) ) ", cgb.isGBsys(Gsys) );
}
if ( true ) {
List<GenPolynomial<GenPolynomial<BigRational>>> G;
G = cgb.GB(L);
//System.out.println("GB(L) = " + G );
//System.out.println("isGB(G) = " + cgb.isGB(G) );
assertTrue("isGB( GB(G) ) ", cgb.isGB(G) );
}
}
| public void xtestRatPolReduction() {
RingFactory<BigRational> bi = new BigRational(0);
GenPolynomialRing<BigRational> pr
= new GenPolynomialRing<BigRational>(bi,2, new String[] { "a", "b" } );
GenPolynomialRing<GenPolynomial<BigRational>> fac
= new GenPolynomialRing<GenPolynomial<BigRational>>(pr,rl);
CReductionSeq<BigRational> cred
= new CReductionSeq<BigRational>( bi );
GenPolynomial<GenPolynomial<BigRational>> a = fac.random(kl, ll, el, q );
while ( a.isZERO() ) {
a = fac.random(kl, ll, el, q );
}
GenPolynomial<GenPolynomial<BigRational>> b = fac.random(kl, ll, el, q );
while ( b.isZERO() ) {
b = fac.random(kl, ll, el, q );
}
GenPolynomial<GenPolynomial<BigRational>> g = fac.getZERO();
Map.Entry<ExpVector,GenPolynomial<BigRational>> m = a.leadingMonomial();
ExpVector e = m.getKey();
GenPolynomial<BigRational> c = m.getValue();
GenPolynomial<GenPolynomial<BigRational>> r = fac.getZERO();
r = r.sum(c,e);
GenPolynomial<GenPolynomial<BigRational>> w = a.reductum();
ColorPolynomial<BigRational> p
= new ColorPolynomial<BigRational>(g,r,w);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(r,g,w);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
if ( !w.isZERO() ) {
assertFalse("deter(p) ", p.isDetermined());
}
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(r,w,g);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(w,g,r);
//System.out.println("p = " + p);
if ( !w.isZERO() ) {
assertFalse("check(p) ", p.checkInvariant());
}
assertFalse("deter(p) ", p.isDetermined());
assertFalse("p == 0 ", p.isZERO());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
p = new ColorPolynomial<BigRational>(w,g,g);
//System.out.println("p = " + p);
assertTrue("check(p) ", p.checkInvariant());
assertTrue("deter(p) ", p.isDetermined());
assertTrue("p == 0 ", p.isZERO());
//System.out.println("cond != 0: " + p.getConditionNonZero());
//System.out.println("cond == 0: " + p.getConditionZero());
List<GenPolynomial<BigRational>> i
= new ArrayList<GenPolynomial<BigRational>>();
Ideal<BigRational> id = new Ideal<BigRational>(pr,i);
List<ColorPolynomial<BigRational>> cp
= new ArrayList<ColorPolynomial<BigRational>>();
Condition<BigRational> cond = new Condition<BigRational>(id);
ColoredSystem<BigRational> s
= new ColoredSystem<BigRational>(cond,cp);
//System.out.println("s = " + s);
assertTrue("isDetermined ", s.isDetermined());
assertTrue("checkInvariant ", s.checkInvariant());
List<ColoredSystem<BigRational>> CS
= new ArrayList<ColoredSystem<BigRational>>();
CS.add(s);
//System.out.println("CS = " + CS);
List<ColoredSystem<BigRational>> CSp = CS;
//System.out.println("\na = " + a);
//System.out.println("b = " + b + "\n");
CS = cred.determine(s,p);
//System.out.println("CS = " + CS);
for ( ColoredSystem<BigRational> x : CS ) {
assertTrue("isDetermined ", x.isDetermined());
assertTrue("checkInvariant ", x.checkInvariant());
}
List<GenPolynomial<GenPolynomial<BigRational>>> L;
L = new ArrayList<GenPolynomial<GenPolynomial<BigRational>>>();
L.add(a);
L.add(b);
//System.out.println("\na = " + a);
//System.out.println("b = " + b + "\n");
List<Condition<BigRational>> Ccond;
//System.out.println("caseDistinction ----------------------------------");
Ccond = cred.caseDistinction(L);
//System.out.println("Ccond ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
//for ( Condition<BigRational> cnd : Ccond ) {
// System.out.println("" + cnd);
//}
//System.out.println("determine ---------------------------------");
CSp = cred.determine(L);
//System.out.println("CSp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + CSp);
//System.out.println("++++++++++++++++++++++++++++++++++++++");
for ( ColoredSystem<BigRational> x : CSp ) {
assertTrue("isDetermined ", x.isDetermined());
assertTrue("checkInvariant ", x.checkInvariant());
//System.out.println("condition == 0: " + x.getConditionZero());
//System.out.println("condition != 0: " + x.getConditionNonZero());
//System.out.println("polynomial list: " + x.getPolynomialList());
//System.out.println("++++++++++++++++++++++++++++++++++++++");
}
ColorPolynomial<BigRational> q, h;
List<ColoredSystem<BigRational>> NCS;
for ( ColoredSystem<BigRational> x : CSp ) {
int k = x.list.size();
for ( int j = 0; j < k; j++ ) {
p = x.list.get(j);
for ( int l = j+1; l < k; l++ ) {
q = x.list.get(l);
h = cred.SPolynomial(p,q);
//System.out.println("spol(a,b) = " + h);
boolean t = cred.isNormalform( x.list, h );
//System.out.println("isNF(spol(a,b)) = " + t);
h = cred.normalform( x.condition, x.list, h );
//System.out.println("NF(spol(a,b)) = " + h);
t = cred.isNormalform( x.list, h );
//System.out.println("isNF(NF(spol(a,b))) = " + t);
assertTrue("isNF(NF(spol(a,b))) ", t);
NCS = cred.determine( x, h );
for ( ColoredSystem<BigRational> cpp : NCS ) {
assertTrue("isDetermined( cpp ) ", cpp.isDetermined() );
assertTrue("checkInvariant ", cpp.checkInvariant());
}
}
}
}
if ( false ) {
return;
}
ComprehensiveGroebnerBaseSeq<BigRational> cgb =
new ComprehensiveGroebnerBaseSeq<BigRational>(cred,bi);
System.out.println("isGB(L) = " + cgb.isGB(L) );
if ( true ) {
List<ColoredSystem<BigRational>> Gsys = cgb.GBsys( L );
//System.out.println("GBsys(L) = " + Gsys );
//System.out.println("isGBsys(G) = " + cgb.isGBsys(Gsys) );
assertTrue("isGBsys( GBsys(G) ) ", cgb.isGBsys(Gsys) );
}
if ( true ) {
List<GenPolynomial<GenPolynomial<BigRational>>> G;
G = cgb.GB(L);
//System.out.println("GB(L) = " + G );
//System.out.println("isGB(G) = " + cgb.isGB(G) );
assertTrue("isGB( GB(G) ) ", cgb.isGB(G) );
}
}
|
diff --git a/src/edu/sru/andgate/bitbot/graphics/NickGameActivity.java b/src/edu/sru/andgate/bitbot/graphics/NickGameActivity.java
index 7d4d90e..0a2d065 100644
--- a/src/edu/sru/andgate/bitbot/graphics/NickGameActivity.java
+++ b/src/edu/sru/andgate/bitbot/graphics/NickGameActivity.java
@@ -1,429 +1,429 @@
//File: GameGraphics.java
//Purpose: Test graphics rendering class, as well as imitate a game engine.
//Note: This class will just be renamed GameEngine at this point.
package edu.sru.andgate.bitbot.graphics;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.media.MediaPlayer;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.TextView;
import edu.sru.andgate.bitbot.Bot;
import edu.sru.andgate.bitbot.R;
import edu.sru.andgate.bitbot.gametypes.BotVsBot;
import edu.sru.andgate.bitbot.gametypes.DungeonCrawl;
import edu.sru.andgate.bitbot.gametypes.GameTypes;
import edu.sru.andgate.bitbot.gametypes.TutorialTesting;
import edu.sru.andgate.bitbot.interpreter.InstructionLimitedVirtualMachine;
public class NickGameActivity extends Activity
{
private GameView glSurfaceView;
private Timer t;
private GlRenderer gameRenderer;
private DrawableParticleEmitter particleEmitter;
private MediaPlayer mp;
private int[][] drawList;
private int drawListPointer = 0;
private boolean gameLoop = true;
private String botFile, mapFile;
private float touchX = 0;
private float touchY = 0;
private float previousTouchX = 0;
private float previousTouchY = 0;
private ArrayList<DrawableBot> notifyOnTouchList;
private GameTypes gameType;
public int numShotsFired, numBulletsContact, kills;
private int MAX_OBJECTS = 250;
private final int TYPE_BOT = 0;
private final int TYPE_GUN = 1;
public String missionType;
private int viewType = 0;
//TileMap testMap;
private CollisionManager collisionManager;
private TextView codeTxt;
private ScrollView codeScroll;
private InstructionLimitedVirtualMachine ilvm = new InstructionLimitedVirtualMachine();
// Used to globably access the current game.
public static NickGameActivity currentGame = null;
public NickGameActivity()
{
currentGame = this;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
kills = 0;
numBulletsContact = 0;
numShotsFired = 0;
//figure out what type of Game this is
missionType = getIntent().getExtras().getString("GameType");
botFile = getIntent().getExtras().getString("Bot");
mapFile = getIntent().getExtras().getString("MapFile");
viewType = getIntent().getExtras().getInt("ViewType", 0);
if(missionType.equalsIgnoreCase("BOT versus BOT")){
gameType = new BotVsBot(this,mapFile, botFile);
}else if(missionType.equalsIgnoreCase("Dungeon Crawl")){
gameType = new DungeonCrawl(this, mapFile, botFile);
}else if(missionType.equalsIgnoreCase("Tutorial")){
int numOfBots = getIntent().getExtras().getInt("BotNum");
gameType = new TutorialTesting(this, numOfBots, botFile);
}
gameType.Initialize(this);
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Keep screen from shutting off
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// requesting to turn the title OFF
requestWindowFeature(Window.FEATURE_NO_TITLE);
mp = MediaPlayer.create(this.getBaseContext(), R.raw.neverland);
mp.start();
mp.setLooping(true);
notifyOnTouchList = new ArrayList<DrawableBot>(MAX_OBJECTS);
if(viewType == 0)
{
setContentView(R.layout.game_activity);
glSurfaceView = (GameView) findViewById(R.id.game_view);
}
else if(viewType == 1)
{
setContentView(R.layout.game_activity_scrollview);
glSurfaceView = (GameView) findViewById(R.id.game_view);
codeTxt = (TextView) findViewById(R.id.code_txt);
codeScroll = (ScrollView) findViewById(R.id.code_scroll);
gameType.getBot().getInterpreter().setOutputTextView(codeTxt);
codeTxt.setText(gameType.getBot().getInterpreter().getBotLog());
}
notifyOnTouchList.add(gameType.getBot().getDrawableBot());
//Declare Collision Manager
collisionManager = new CollisionManager(gameType.getMap());
//Declare Particle Emitter
particleEmitter = new DrawableParticleEmitter();
//Attach emitter to CollisionManager
collisionManager.setParticleEmitter(particleEmitter);
//Declare Draw List
drawList = new int[2][MAX_OBJECTS];
gameRenderer = new GlRenderer(this);
ilvm.addInterpreter(gameType.getBot().getInterpreter());
// // Run the vm every second.
// t = new Timer();
// t.schedule(new TimerTask()
// {
// @Override
// public void run()
// {
// ilvm.resume(4);
// }
// }, 50, 50);
//Set renderer to be the main renderer with the current activity context
glSurfaceView.setEGLConfigChooser(false);
glSurfaceView.setRenderer(gameRenderer);
glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
gameRenderer.setTileMap(gameType.getMap());
//Nick
for(int i = 0; i < gameType.getBots().length; i++){
addBotToWorld(gameType.getBots()[i]);
}
addBotToWorld(gameType.getBot());
//Tell camera to continuously update so it can follow user bot
gameRenderer.continuousCameraUpdate = true;
gameRenderer.setParticleEmitter(particleEmitter);
preloadTextures(); //Should always be called before game starts
gameRenderer.startSimulation();
startGameLoop();
}
public void addBotToWorld(Bot bot)
{
gameRenderer.addObjectToWorld(bot);
collisionManager.addCollisionDetector(bot);
}
public void preloadTextures()
{
gameRenderer.setPreloadTextureFlag(true);
glSurfaceView.requestRender();
}
public void addToDrawList(int type, int objectID)
{
drawList[0][drawListPointer] = type; //Set Object Type
drawList[1][drawListPointer] = objectID; //Set Object ID
drawListPointer++; //Increment Draw List Pointer / (Size-1)
}
public void addToDrawList(Bot bot)
{
drawList[0][drawListPointer] = TYPE_BOT;
drawList[1][drawListPointer] = bot.getDrawableBot().ID;
drawListPointer++;
drawList[0][drawListPointer] = TYPE_BOT;
drawList[1][drawListPointer] = bot.getBotLayer().ID;
drawListPointer++;
drawList[0][drawListPointer] = TYPE_GUN;
drawList[1][drawListPointer] = bot.getDrawableGun().ID;
drawListPointer++;
}
public void startGameLoop()
{
Runnable gR = new Runnable()
{
//Proof of concept variables
int shotCount = 0;
boolean thisFrameDrawn = false;
//Testing FPS Only
long startTime = 0;
long endTime = 0;
long timeCount = 0;
int frameCount = 0;
//Game Loop
public void run()
{
while(gameLoop)
{
startTime = System.currentTimeMillis();
//IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION
thisFrameDrawn = false;
//Handle touch events
HandleTouchEvents();
//check victory conditions
gameType.Update();
//gameType.getBot().getDrawableBot().moveByTouch(0.1f);
gameType.getBot().getDrawableBot().move();
//gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90);
// Run Interpreter
// ilvm.resume(30);
- ilvm.resume(4);
//update players bot's gun
if(gameType.getBot().getDrawableBot().isAlive)
{
gameType.getBot().getDrawableGun().update();
}
//update all other bot's gun's
for(int i = 0; i < gameType.getBots().length; i++)
{
if(gameType.getBots()[i].getDrawableBot().isAlive)
{
gameType.getBots()[i].getDrawableGun().update();
}
}
+ ilvm.resume(4);
// //no?
// if(shotCount >= 10)
// {
// if(gameType.getBot().getDrawableBot().isAlive)
// {
// gameType.getBot().getDrawableGun().fire();
// }
// for(int i = 0; i < gameType.getBots().length; i++)
// {
// if(gameType.getBots()[i].getDrawableBot().isAlive)
// {
// gameType.getBots()[i].getDrawableGun().fire();
// }
// }
// numShotsFired++;
// shotCount = 0;
// }
// shotCount++;
//Collision Detection Updater
collisionManager.update();
//Particle Emitter Updater
particleEmitter.update();
//Camera Stuff
gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0];
gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1];
// Add bots to the drawlist if they are alive
for (int i = 0; i < gameType.getBots().length; i++)
if(gameType.getBots()[i].getDrawableBot().isAlive)
addToDrawList(gameType.getBots()[i]);
// Add the player to the drawlist if he is alive.
if (gameType.getBot().getDrawableBot().isAlive)
addToDrawList(gameType.getBot());
//Renderer Synchronization / Draw Frame Request
while (!thisFrameDrawn && gameLoop)
{
if(gameRenderer.getFrameDrawn())
{
gameRenderer.drawListSize = drawListPointer;
for(int i=0;i<2;i++)
for(int j=0;j<drawListPointer;j++)
gameRenderer.drawList[i][j] = drawList[i][j];
//gameRenderer.setFrameDrawn(false);
gameRenderer.frameDrawn = false;
glSurfaceView.requestRender();
thisFrameDrawn = true;
drawListPointer = 0;
}
// If we're waiting on the gameRenderer, should the thread pause
// to let other stuff happen?
// try {Thread.sleep(1);}
// catch (InterruptedException e) {}
}
// Count up the number of frames and every second print that number
// out and reset the count.
endTime = System.currentTimeMillis();
timeCount += (endTime-startTime);
frameCount++;
if(timeCount >= 1000.0)
{
Log.v("bitbot", "FPS: " + frameCount);
frameCount = 0;
timeCount = 0;
}
}
}
};
Thread gT = new Thread(gR);
gT.setName("Game Thread: " + gT.getName());
gT.start();
}
/**
* This method is called once every frame and handles touch events (obviously)
*/
private void HandleTouchEvents()
{
if (glSurfaceView.touchNeedsToBeHandled)
{
//Touch Event Vars
float xWaypoint = 0.0f;
float yWaypoint = 0.0f;
float xPercentage = 0.0f;
float yPercentage = 0.0f;
touchX = glSurfaceView.touchX;
touchY = glSurfaceView.touchY;
if(true || touchX != previousTouchX || touchY != previousTouchY)
{
//Convert to game world waypoints
xPercentage = (touchX/gameRenderer.screenWidth);
yPercentage = ((touchY/gameRenderer.screenHeight));
xWaypoint = (gameRenderer.drawLeft - (xPercentage * (gameRenderer.drawLeft - gameRenderer.drawRight)));
yWaypoint = (gameRenderer.drawTop - (yPercentage * (gameRenderer.drawTop - gameRenderer.drawBottom)));
//Notify bots that require it
for(int i=0;i<notifyOnTouchList.size();i++)
{
notifyOnTouchList.get(i).onTouchEvent(xWaypoint, yWaypoint);
}
}
previousTouchX = touchX;
previousTouchY = touchY;
// Flag that we handled this touch event.
glSurfaceView.touchNeedsToBeHandled = false;
}
}
public GameTypes getGameType(){
return this.gameType;
}
@Override
protected void onResume()
{
super.onResume();
glSurfaceView.onResume();
preloadTextures(); //Reload textures on resume to prevent missing texture / white square problem.
}
@Override
protected void onPause()
{
super.onPause();
glSurfaceView.onPause();
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (mp != null)
mp.release();
gameLoop = false;
if (t != null)
t.cancel();
if (ilvm != null)
ilvm.stop();
finish();
}
}
| false | true | public void startGameLoop()
{
Runnable gR = new Runnable()
{
//Proof of concept variables
int shotCount = 0;
boolean thisFrameDrawn = false;
//Testing FPS Only
long startTime = 0;
long endTime = 0;
long timeCount = 0;
int frameCount = 0;
//Game Loop
public void run()
{
while(gameLoop)
{
startTime = System.currentTimeMillis();
//IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION
thisFrameDrawn = false;
//Handle touch events
HandleTouchEvents();
//check victory conditions
gameType.Update();
//gameType.getBot().getDrawableBot().moveByTouch(0.1f);
gameType.getBot().getDrawableBot().move();
//gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90);
// Run Interpreter
// ilvm.resume(30);
ilvm.resume(4);
//update players bot's gun
if(gameType.getBot().getDrawableBot().isAlive)
{
gameType.getBot().getDrawableGun().update();
}
//update all other bot's gun's
for(int i = 0; i < gameType.getBots().length; i++)
{
if(gameType.getBots()[i].getDrawableBot().isAlive)
{
gameType.getBots()[i].getDrawableGun().update();
}
}
// //no?
// if(shotCount >= 10)
// {
// if(gameType.getBot().getDrawableBot().isAlive)
// {
// gameType.getBot().getDrawableGun().fire();
// }
// for(int i = 0; i < gameType.getBots().length; i++)
// {
// if(gameType.getBots()[i].getDrawableBot().isAlive)
// {
// gameType.getBots()[i].getDrawableGun().fire();
// }
// }
// numShotsFired++;
// shotCount = 0;
// }
// shotCount++;
//Collision Detection Updater
collisionManager.update();
//Particle Emitter Updater
particleEmitter.update();
//Camera Stuff
gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0];
gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1];
// Add bots to the drawlist if they are alive
for (int i = 0; i < gameType.getBots().length; i++)
if(gameType.getBots()[i].getDrawableBot().isAlive)
addToDrawList(gameType.getBots()[i]);
// Add the player to the drawlist if he is alive.
if (gameType.getBot().getDrawableBot().isAlive)
addToDrawList(gameType.getBot());
//Renderer Synchronization / Draw Frame Request
while (!thisFrameDrawn && gameLoop)
{
if(gameRenderer.getFrameDrawn())
{
gameRenderer.drawListSize = drawListPointer;
for(int i=0;i<2;i++)
for(int j=0;j<drawListPointer;j++)
gameRenderer.drawList[i][j] = drawList[i][j];
//gameRenderer.setFrameDrawn(false);
gameRenderer.frameDrawn = false;
glSurfaceView.requestRender();
thisFrameDrawn = true;
drawListPointer = 0;
}
// If we're waiting on the gameRenderer, should the thread pause
// to let other stuff happen?
// try {Thread.sleep(1);}
// catch (InterruptedException e) {}
}
// Count up the number of frames and every second print that number
// out and reset the count.
endTime = System.currentTimeMillis();
timeCount += (endTime-startTime);
frameCount++;
if(timeCount >= 1000.0)
{
Log.v("bitbot", "FPS: " + frameCount);
frameCount = 0;
timeCount = 0;
}
}
}
};
Thread gT = new Thread(gR);
gT.setName("Game Thread: " + gT.getName());
gT.start();
}
| public void startGameLoop()
{
Runnable gR = new Runnable()
{
//Proof of concept variables
int shotCount = 0;
boolean thisFrameDrawn = false;
//Testing FPS Only
long startTime = 0;
long endTime = 0;
long timeCount = 0;
int frameCount = 0;
//Game Loop
public void run()
{
while(gameLoop)
{
startTime = System.currentTimeMillis();
//IMPORTANT VARIABLE FOR RENDERER SYNCHRONIZATION
thisFrameDrawn = false;
//Handle touch events
HandleTouchEvents();
//check victory conditions
gameType.Update();
//gameType.getBot().getDrawableBot().moveByTouch(0.1f);
gameType.getBot().getDrawableBot().move();
//gameType.getBot().getBotLayer().setRotationAngle(gameType.getBot().getDrawableBot().moveAngle-90);
// Run Interpreter
// ilvm.resume(30);
//update players bot's gun
if(gameType.getBot().getDrawableBot().isAlive)
{
gameType.getBot().getDrawableGun().update();
}
//update all other bot's gun's
for(int i = 0; i < gameType.getBots().length; i++)
{
if(gameType.getBots()[i].getDrawableBot().isAlive)
{
gameType.getBots()[i].getDrawableGun().update();
}
}
ilvm.resume(4);
// //no?
// if(shotCount >= 10)
// {
// if(gameType.getBot().getDrawableBot().isAlive)
// {
// gameType.getBot().getDrawableGun().fire();
// }
// for(int i = 0; i < gameType.getBots().length; i++)
// {
// if(gameType.getBots()[i].getDrawableBot().isAlive)
// {
// gameType.getBots()[i].getDrawableGun().fire();
// }
// }
// numShotsFired++;
// shotCount = 0;
// }
// shotCount++;
//Collision Detection Updater
collisionManager.update();
//Particle Emitter Updater
particleEmitter.update();
//Camera Stuff
gameRenderer.cameraX = gameType.getBot().getDrawableBot().parameters[0];
gameRenderer.cameraY = gameType.getBot().getDrawableBot().parameters[1];
// Add bots to the drawlist if they are alive
for (int i = 0; i < gameType.getBots().length; i++)
if(gameType.getBots()[i].getDrawableBot().isAlive)
addToDrawList(gameType.getBots()[i]);
// Add the player to the drawlist if he is alive.
if (gameType.getBot().getDrawableBot().isAlive)
addToDrawList(gameType.getBot());
//Renderer Synchronization / Draw Frame Request
while (!thisFrameDrawn && gameLoop)
{
if(gameRenderer.getFrameDrawn())
{
gameRenderer.drawListSize = drawListPointer;
for(int i=0;i<2;i++)
for(int j=0;j<drawListPointer;j++)
gameRenderer.drawList[i][j] = drawList[i][j];
//gameRenderer.setFrameDrawn(false);
gameRenderer.frameDrawn = false;
glSurfaceView.requestRender();
thisFrameDrawn = true;
drawListPointer = 0;
}
// If we're waiting on the gameRenderer, should the thread pause
// to let other stuff happen?
// try {Thread.sleep(1);}
// catch (InterruptedException e) {}
}
// Count up the number of frames and every second print that number
// out and reset the count.
endTime = System.currentTimeMillis();
timeCount += (endTime-startTime);
frameCount++;
if(timeCount >= 1000.0)
{
Log.v("bitbot", "FPS: " + frameCount);
frameCount = 0;
timeCount = 0;
}
}
}
};
Thread gT = new Thread(gR);
gT.setName("Game Thread: " + gT.getName());
gT.start();
}
|
diff --git a/src/com/android/music/MediaPlaybackActivityStarter.java b/src/com/android/music/MediaPlaybackActivityStarter.java
index 373c61c..248a5f1 100644
--- a/src/com/android/music/MediaPlaybackActivityStarter.java
+++ b/src/com/android/music/MediaPlaybackActivityStarter.java
@@ -1,40 +1,41 @@
/*
* Copyright (C) 2007 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.music;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MediaPlaybackActivityStarter extends Activity
{
public MediaPlaybackActivityStarter()
{
}
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
- Intent i = new Intent(this, MediaPlaybackActivity.class);
+ Intent i = new Intent(getIntent());
+ i.setClass(this, MediaPlaybackActivity.class);
startActivity(i);
finish();
}
}
| true | true | public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
Intent i = new Intent(this, MediaPlaybackActivity.class);
startActivity(i);
finish();
}
| public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
Intent i = new Intent(getIntent());
i.setClass(this, MediaPlaybackActivity.class);
startActivity(i);
finish();
}
|
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/AuthInterceptor.java b/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/AuthInterceptor.java
index b19962593..83d22ed12 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/AuthInterceptor.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/resteasy/interceptor/AuthInterceptor.java
@@ -1,176 +1,176 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.resteasy.interceptor;
import java.util.ArrayList;
import java.util.Date;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import org.apache.log4j.Logger;
import org.fedoraproject.candlepin.auth.ConsumerPrincipal;
import org.fedoraproject.candlepin.auth.NoAuthPrincipal;
import org.fedoraproject.candlepin.auth.Principal;
import org.fedoraproject.candlepin.auth.Role;
import org.fedoraproject.candlepin.auth.interceptor.AllowRoles;
import org.fedoraproject.candlepin.config.Config;
import org.fedoraproject.candlepin.exceptions.UnauthorizedException;
import org.fedoraproject.candlepin.model.Consumer;
import org.fedoraproject.candlepin.model.ConsumerCurator;
import org.fedoraproject.candlepin.model.OwnerCurator;
import org.fedoraproject.candlepin.service.UserServiceAdapter;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethod;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
import org.xnap.commons.i18n.I18n;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
* NoAuthInterceptor
*/
@Provider
@ServerInterceptor
public class AuthInterceptor implements PreProcessInterceptor {
private static Logger log = Logger.getLogger(AuthInterceptor.class);
private Injector injector;
private ConsumerCurator consumerCurator;
private OwnerCurator ownerCurator;
private Config config;
private UserServiceAdapter userService;
private AuthProvider[] providers = new AuthProvider[0];
private int providerCount = 0;
@Inject
public AuthInterceptor(Config config, UserServiceAdapter userService,
OwnerCurator ownerCurator, ConsumerCurator consumerCurator,
Injector injector) {
super();
this.consumerCurator = consumerCurator;
this.injector = injector;
this.config = config;
this.userService = userService;
this.ownerCurator = ownerCurator;
this.setupAuthStrategies();
}
/**
* Set up the various providers which can be used to authenticate the user
*/
public void setupAuthStrategies() {
ArrayList<AuthProvider> providers = new ArrayList<AuthProvider>();
// use oauth
if (config.oAuthEnabled()) {
providerCount++;
log.debug("OAuth Authentication is enabled.");
providers
.add(new OAuth(userService, ownerCurator, injector, config));
}
// basic http access
if (config.basicAuthEnabled()) {
providerCount++;
log.debug("Basic Authentication is enabled.");
providers.add(new BasicAuth(userService, ownerCurator, injector));
}
// consumer certificates
if (config.sslAuthEnabled()) {
providerCount++;
log.debug("Certificate Based Authentication is enabled.");
providers.add(new SSLAuth(consumerCurator));
}
// trusted headers
if (config.trustedAuthEnabled()) {
providerCount++;
log.debug("Trusted Authentication is enabled.");
providers.add(new TrustedConsumerAuth(consumerCurator));
}
this.providers = providers.toArray(this.providers);
}
/**
* Interrogates the request and sets the principal for the request.
*
* @throws WebApplicationException when no auths result in a valid principal
* @throws Failure when there is an unkown failure in the code
* @return the Server Response
*/
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
I18n i18n = injector.getInstance(I18n.class);
Principal principal = null;
boolean noAuthAllowed = false;
if (log.isDebugEnabled()) {
log.debug("Authentication check for " + request.getUri().getPath());
}
// Check to see if authentication is required.
AllowRoles roles = method.getMethod().getAnnotation(AllowRoles.class);
if (roles != null) {
for (Role role : roles.roles()) {
if (role == Role.NO_AUTH) {
noAuthAllowed = true;
}
}
}
// No authentication is required, give a no auth principal
if (noAuthAllowed) {
log.debug("No auth allowed for resource; setting NoAuth principal");
principal = new NoAuthPrincipal();
}
// Check all the configured providers
for (int x = 0; (x < providerCount) && (principal == null); x++) {
principal = providers[x].getPrincipal(request);
if (principal != null) {
break;
}
}
if (principal != null) {
// Expose the principal for Resteasy to inject via @Context
ResteasyProviderFactory.pushContext(Principal.class, principal);
if (principal.isConsumer()) {
// HACK: We need to do this after the principal has been pushed,
// lest our security settings start getting upset when we try to
// update a consumer without any roles:
ConsumerPrincipal p = (ConsumerPrincipal) principal;
Consumer c = p.consumer();
updateLastCheckin(c);
}
return null;
}
- throw new UnauthorizedException(i18n.tr("Invalid username or password"));
+ throw new UnauthorizedException(i18n.tr("Invalid Credentials"));
}
private void updateLastCheckin(Consumer consumer) {
consumer.setLastCheckin(new Date());
consumerCurator.update(consumer);
}
}
| true | true | public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
I18n i18n = injector.getInstance(I18n.class);
Principal principal = null;
boolean noAuthAllowed = false;
if (log.isDebugEnabled()) {
log.debug("Authentication check for " + request.getUri().getPath());
}
// Check to see if authentication is required.
AllowRoles roles = method.getMethod().getAnnotation(AllowRoles.class);
if (roles != null) {
for (Role role : roles.roles()) {
if (role == Role.NO_AUTH) {
noAuthAllowed = true;
}
}
}
// No authentication is required, give a no auth principal
if (noAuthAllowed) {
log.debug("No auth allowed for resource; setting NoAuth principal");
principal = new NoAuthPrincipal();
}
// Check all the configured providers
for (int x = 0; (x < providerCount) && (principal == null); x++) {
principal = providers[x].getPrincipal(request);
if (principal != null) {
break;
}
}
if (principal != null) {
// Expose the principal for Resteasy to inject via @Context
ResteasyProviderFactory.pushContext(Principal.class, principal);
if (principal.isConsumer()) {
// HACK: We need to do this after the principal has been pushed,
// lest our security settings start getting upset when we try to
// update a consumer without any roles:
ConsumerPrincipal p = (ConsumerPrincipal) principal;
Consumer c = p.consumer();
updateLastCheckin(c);
}
return null;
}
throw new UnauthorizedException(i18n.tr("Invalid username or password"));
}
| public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
I18n i18n = injector.getInstance(I18n.class);
Principal principal = null;
boolean noAuthAllowed = false;
if (log.isDebugEnabled()) {
log.debug("Authentication check for " + request.getUri().getPath());
}
// Check to see if authentication is required.
AllowRoles roles = method.getMethod().getAnnotation(AllowRoles.class);
if (roles != null) {
for (Role role : roles.roles()) {
if (role == Role.NO_AUTH) {
noAuthAllowed = true;
}
}
}
// No authentication is required, give a no auth principal
if (noAuthAllowed) {
log.debug("No auth allowed for resource; setting NoAuth principal");
principal = new NoAuthPrincipal();
}
// Check all the configured providers
for (int x = 0; (x < providerCount) && (principal == null); x++) {
principal = providers[x].getPrincipal(request);
if (principal != null) {
break;
}
}
if (principal != null) {
// Expose the principal for Resteasy to inject via @Context
ResteasyProviderFactory.pushContext(Principal.class, principal);
if (principal.isConsumer()) {
// HACK: We need to do this after the principal has been pushed,
// lest our security settings start getting upset when we try to
// update a consumer without any roles:
ConsumerPrincipal p = (ConsumerPrincipal) principal;
Consumer c = p.consumer();
updateLastCheckin(c);
}
return null;
}
throw new UnauthorizedException(i18n.tr("Invalid Credentials"));
}
|
diff --git a/LaneDemo.java b/LaneDemo.java
index a56e922..99d9d0f 100644
--- a/LaneDemo.java
+++ b/LaneDemo.java
@@ -1,207 +1,207 @@
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import javax.swing.JPanel;
//TODO: fix diverter arm being blocked by diverter platform
@SuppressWarnings("serial")
public class LaneDemo extends JPanel
{
WholeLane lane1;
Part p1;
Part p2;
GUILane gl;
GUIPart gp1;
GUIPart gp2;
GUIFeeder gf;
GUIDiverter gd;
GUIDiverterArm gda;
GUIBin gpb;
GUIPart gp3;
GUIPart gp4;
GUIPart lastPart;
int paintCount = 0;
public LaneDemo()
{
//panel size
this.setPreferredSize(new Dimension(800,400));
//load images
Painter.loadImages();
//initialize
lane1 = new WholeLane();
gl = new GUILane( lane1.getLane(), true, 5, 90, 110 );
gl.turnOn(System.currentTimeMillis());
gf = new GUIFeeder( lane1.getFeeder(), 470, 110 );
gd = new GUIDiverter( 390, 112 );
gda = new GUIDiverterArm( 390, 155 );
gda.movement = new Movement(new Point2D.Double(390,155), 0, System.currentTimeMillis(), new Point2D.Double(390,155), 0.7, System.currentTimeMillis()+1);
gpb = null;
p1 = new Part("p1", "a random part", 5, Painter.ImageEnum.CORNFLAKE);
p2 = new Part("p2", "another random part", 6, Painter.ImageEnum.NUT);
//parts that are not shown
gp3 = new GUIPart(p1, 460, 150);
gp4 = new GUIPart(p2, 460, 150);
lastPart = null;
}
public void paint(Graphics gfx)
{
Graphics2D g = (Graphics2D)gfx;
if (gl.shouldReset(System.currentTimeMillis())) gl.reset(System.currentTimeMillis());
if( lane1.getActiveLane() == 1 ){ //if top lane
//top lane moving parts
if( lastPart != null && lastPart == gp3 ){ //box had cornflakes
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p1, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p1, 390, 120);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p1, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p1, 390, 120);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
} else if (lastPart != null && lastPart == gp4) { //box had nuts
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p2, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p2, 390, 120);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p2, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p2, 390, 120);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
} else { //no parts yet
gp1 = null;
gp2 = null;
}
} else { //bottom lane
//bot lane moving parts
if( lastPart != null && lastPart == gp3 ){ //box had cornflakes
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p1, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p1, 390, 180);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p1, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p1, 390, 180);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
} else if( lastPart != null && lastPart == gp4 ){ //box had nuts
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p2, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p2, 390, 180);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p2, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p2, 390, 180);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
} else { //no parts yet
gp1 = null;
gp2 = null;
}
}
//change lane every 5, 105
if( paintCount % 200 == 5 || paintCount % 200 == 105){
lane1.divert();
if(lane1.getActiveLane() == 1) { //arm rotates from top to bot
gda.movement = new Movement(new Point2D.Double(390,155), -0.7, System.currentTimeMillis(), new Point2D.Double(390,155), 0.7, System.currentTimeMillis()+500);
} else { //arm rotates from bot to top
gda.movement = new Movement(new Point2D.Double(390,155), 0.7, System.currentTimeMillis(), new Point2D.Double(390,155), -0.7, System.currentTimeMillis()+500);
}
}
gl.draw(g, System.currentTimeMillis());
gf.draw(g, System.currentTimeMillis());
gd.draw(g, System.currentTimeMillis());
gda.draw(g, System.currentTimeMillis());
//make box appear
if( paintCount % 200 == 0 ) { //cornflakes
- gpb = new GUIBin( /*gp3,*/ new Bin(gp3, 10), 512, 110 );
+ gpb = new GUIBin( /*gp3,*/ new Bin(gp3.part, 10), 512, 110 );
lastPart = gp3;
}
if( paintCount % 200 == 100 ) { //nuts
- gpb = new GUIBin( /*gp4,*/ new Bin(gp3, 10), 512, 110 );
+ gpb = new GUIBin( /*gp4,*/ new Bin(gp3.part, 10), 512, 110 );
lastPart = gp4;
}
//make box disappear
if( paintCount % 200 == 20 || paintCount % 200 == 120)
gpb = null;
if( gpb != null )
gpb.draw(g, System.currentTimeMillis(), false);
if( gp1 != null )
gp1.draw(g, System.currentTimeMillis());
if( gp2 != null )
gp2.draw(g, System.currentTimeMillis());
// if (paintCount % 100 == 75)
// if ( lane1.areLanesOn() )
// lane1.turnOffLane();
// else
// lane1.turnOnLane();
paintCount++;
}
}
| false | true | public void paint(Graphics gfx)
{
Graphics2D g = (Graphics2D)gfx;
if (gl.shouldReset(System.currentTimeMillis())) gl.reset(System.currentTimeMillis());
if( lane1.getActiveLane() == 1 ){ //if top lane
//top lane moving parts
if( lastPart != null && lastPart == gp3 ){ //box had cornflakes
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p1, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p1, 390, 120);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p1, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p1, 390, 120);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
} else if (lastPart != null && lastPart == gp4) { //box had nuts
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p2, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p2, 390, 120);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p2, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p2, 390, 120);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
} else { //no parts yet
gp1 = null;
gp2 = null;
}
} else { //bottom lane
//bot lane moving parts
if( lastPart != null && lastPart == gp3 ){ //box had cornflakes
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p1, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p1, 390, 180);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p1, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p1, 390, 180);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
} else if( lastPart != null && lastPart == gp4 ){ //box had nuts
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p2, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p2, 390, 180);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p2, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p2, 390, 180);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
} else { //no parts yet
gp1 = null;
gp2 = null;
}
}
//change lane every 5, 105
if( paintCount % 200 == 5 || paintCount % 200 == 105){
lane1.divert();
if(lane1.getActiveLane() == 1) { //arm rotates from top to bot
gda.movement = new Movement(new Point2D.Double(390,155), -0.7, System.currentTimeMillis(), new Point2D.Double(390,155), 0.7, System.currentTimeMillis()+500);
} else { //arm rotates from bot to top
gda.movement = new Movement(new Point2D.Double(390,155), 0.7, System.currentTimeMillis(), new Point2D.Double(390,155), -0.7, System.currentTimeMillis()+500);
}
}
gl.draw(g, System.currentTimeMillis());
gf.draw(g, System.currentTimeMillis());
gd.draw(g, System.currentTimeMillis());
gda.draw(g, System.currentTimeMillis());
//make box appear
if( paintCount % 200 == 0 ) { //cornflakes
gpb = new GUIBin( /*gp3,*/ new Bin(gp3, 10), 512, 110 );
lastPart = gp3;
}
if( paintCount % 200 == 100 ) { //nuts
gpb = new GUIBin( /*gp4,*/ new Bin(gp3, 10), 512, 110 );
lastPart = gp4;
}
//make box disappear
if( paintCount % 200 == 20 || paintCount % 200 == 120)
gpb = null;
if( gpb != null )
gpb.draw(g, System.currentTimeMillis(), false);
if( gp1 != null )
gp1.draw(g, System.currentTimeMillis());
if( gp2 != null )
gp2.draw(g, System.currentTimeMillis());
// if (paintCount % 100 == 75)
// if ( lane1.areLanesOn() )
// lane1.turnOffLane();
// else
// lane1.turnOnLane();
paintCount++;
}
| public void paint(Graphics gfx)
{
Graphics2D g = (Graphics2D)gfx;
if (gl.shouldReset(System.currentTimeMillis())) gl.reset(System.currentTimeMillis());
if( lane1.getActiveLane() == 1 ){ //if top lane
//top lane moving parts
if( lastPart != null && lastPart == gp3 ){ //box had cornflakes
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p1, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p1, 390, 120);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p1, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p1, 390, 120);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
} else if (lastPart != null && lastPart == gp4) { //box had nuts
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p2, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p2, 390, 120);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p2, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,120), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p2, 390, 120);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,120), 0, lane1.getSpeed());
}
} else { //no parts yet
gp1 = null;
gp2 = null;
}
} else { //bottom lane
//bot lane moving parts
if( lastPart != null && lastPart == gp3 ){ //box had cornflakes
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p1, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p1, 390, 180);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p1, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p1, 390, 180);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
} else if( lastPart != null && lastPart == gp4 ){ //box had nuts
if (paintCount % 200 == 20 || paintCount % 200 == 120 ) { //from diverter moving to lane
gp1 = new GUIPart(p2, 460, 150);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 40 || paintCount % 200 == 140 ) { //moving on lane
gp1 = new GUIPart(p2, 390, 180);
gp1.movement = Movement.fromSpeed(gp1.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 70 || paintCount % 200 == 170 ) { //from diverter moving to lane
gp2 = new GUIPart(p2, 460, 150);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(390,180), 0, lane1.getSpeed());
}
if (paintCount % 200 == 90 || paintCount % 200 == 190 ) { //moving on lane
gp2 = new GUIPart(p2, 390, 180);
gp2.movement = Movement.fromSpeed(gp2.movement.calcPos(System.currentTimeMillis()), 0, System.currentTimeMillis(), new Point2D.Double(70,180), 0, lane1.getSpeed());
}
} else { //no parts yet
gp1 = null;
gp2 = null;
}
}
//change lane every 5, 105
if( paintCount % 200 == 5 || paintCount % 200 == 105){
lane1.divert();
if(lane1.getActiveLane() == 1) { //arm rotates from top to bot
gda.movement = new Movement(new Point2D.Double(390,155), -0.7, System.currentTimeMillis(), new Point2D.Double(390,155), 0.7, System.currentTimeMillis()+500);
} else { //arm rotates from bot to top
gda.movement = new Movement(new Point2D.Double(390,155), 0.7, System.currentTimeMillis(), new Point2D.Double(390,155), -0.7, System.currentTimeMillis()+500);
}
}
gl.draw(g, System.currentTimeMillis());
gf.draw(g, System.currentTimeMillis());
gd.draw(g, System.currentTimeMillis());
gda.draw(g, System.currentTimeMillis());
//make box appear
if( paintCount % 200 == 0 ) { //cornflakes
gpb = new GUIBin( /*gp3,*/ new Bin(gp3.part, 10), 512, 110 );
lastPart = gp3;
}
if( paintCount % 200 == 100 ) { //nuts
gpb = new GUIBin( /*gp4,*/ new Bin(gp3.part, 10), 512, 110 );
lastPart = gp4;
}
//make box disappear
if( paintCount % 200 == 20 || paintCount % 200 == 120)
gpb = null;
if( gpb != null )
gpb.draw(g, System.currentTimeMillis(), false);
if( gp1 != null )
gp1.draw(g, System.currentTimeMillis());
if( gp2 != null )
gp2.draw(g, System.currentTimeMillis());
// if (paintCount % 100 == 75)
// if ( lane1.areLanesOn() )
// lane1.turnOffLane();
// else
// lane1.turnOnLane();
paintCount++;
}
|
diff --git a/software/camod/src/gov/nih/nci/camod/webapp/action/ViewTOCSearchResultsAction.java b/software/camod/src/gov/nih/nci/camod/webapp/action/ViewTOCSearchResultsAction.java
index 620ef852..353c76c4 100755
--- a/software/camod/src/gov/nih/nci/camod/webapp/action/ViewTOCSearchResultsAction.java
+++ b/software/camod/src/gov/nih/nci/camod/webapp/action/ViewTOCSearchResultsAction.java
@@ -1,163 +1,162 @@
/**
*
* $Id: ViewTOCSearchResultsAction.java,v 1.12 2009-06-11 17:42:53 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.11 2009/06/01 17:02:53 pandyas
* getting ready for QA build
*
* Revision 1.10 2008/10/22 18:19:07 schroedn
* Removed the criteria table data from the search results for TOC
*
* Revision 1.9 2008/07/28 17:20:47 pandyas
* Modifed to prevent SQL inject - added HTTP Header
* App scan performed on July 24, 2008
*
* Revision 1.8 2008/07/15 15:18:48 pandyas
* minor change
*
* Revision 1.7 2008/07/15 15:18:26 pandyas
* Modified to prevent SQL injection
* Scan conducted on July 14 2008
*
* Revision 1.6 2008/05/27 14:58:04 pandyas
* Removed debug statements
*
* Revision 1.5 2008/05/27 14:52:52 pandyas
* Modified to prevent SQL injection
* Cleaned parameter name before proceeding
* Re: Apps Scan run 05/23/2008
*
* Revision 1.4 2008/05/21 19:06:53 pandyas
* Modified TOC action to prevent SQL injection
* Re: Apps Scan run 05/15/2008
*
* Revision 1.3 2006/04/17 19:09:40 pandyas
* caMod 2.1 OM changes
*
*
*/
package gov.nih.nci.camod.webapp.action;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.service.impl.*;
import gov.nih.nci.camod.util.NameValueList;
import gov.nih.nci.camod.util.SafeHTMLUtil;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
public class ViewTOCSearchResultsAction extends BaseAction {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
log.info("In ViewTOCSearchResultsAction.execute");
// get and clean header to prevent SQL injection
String sID = null;
if (request.getHeader("X-Forwarded-For") != null){
sID = request.getHeader("X-Forwarded-For");
log.info("cleaned X-Forwarded-For: " + sID);
sID = SafeHTMLUtil.clean(sID);
}
sID = request.getHeader("Referer");
// prevents Referer Header injection
- if ( sID != null && sID != "" && sID.contains("camod")) {}
- if ( sID != null && sID != "" && sID.contains("emice")) {}
+ if ( sID != null && sID != "" && ( sID.contains("camod") || sID.contains("emice"))) {}
else {
return (mapping.findForward("failure"));
}
// Clean all headers for security scan (careful about what chars you allow)
String headername = "";
for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();){
headername = (String)e.nextElement();
log.info("ViewTOCSearchResultsAction headername: " + headername);
String cleanHeaders = SafeHTMLUtil.clean(headername);
log.debug("ViewTOCSearchResultsAction cleaned headername: " + headername);
}
String theForward = "next";
try {
// clean TOCQUERYKEY ahead of try loop - then loop checks if it is a valid choice - security scan code
String theKey = (String) request.getParameter(Constants.Parameters.TOCQUERYKEY);
if (theKey != null && theKey.length() > 0) {
theKey = SafeHTMLUtil.clean(theKey);
log.info("ViewTOCSearchResultsAction cleaned theKey: " + theKey);
}
//Remove any retained criteriatable values
request.getSession().setAttribute(Constants.CRITERIATABLE, "" );
request.getSession().setAttribute(Constants.NOSAVEOPTION, "false");
// This is meant to prevent SQL injection into the key value of the TOC queries
// Security scan failed so this is checked first and the query will not run unless clean
if (theKey != null && theKey.length() > 0)
{
NameValueList.generateTableOfContentsList();
request.getSession().setAttribute(Constants.Dropdowns.SEARCHTOCDROP, NameValueList.getTableOfContentsList());
if (!SafeHTMLUtil.isValidValue(theKey,Constants.Dropdowns.SEARCHTOCDROP,request))
{
// set theForward to failure - fail gracefully but do not let query continue
System.out.println("TOC: The key is not an accepted value - end query " + theKey);
theForward = "failure";
} else {
log.debug("theKey is a valid value - continue with querry: " + theKey);
// Handle external linkage
if (request.getSession().getAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS) == null) {
// Get the TOC manager workflow
TOCManager theTOCManager = new TOCManager(getServlet().getServletContext().getRealPath("/")
+ Constants.TOCSearch.TOC_QUERY_FILE);
List theResults = theTOCManager.process();
log.debug("TOC: " + theResults);
request.getSession().setAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS, theResults);
}
List theGroupList = (List) request.getSession().getAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS);
log.debug("theGroupList: " + theGroupList);
for (int i = 0; i < theGroupList.size(); i++) {
TOCQueryGroup theQueryGroup = (TOCQueryGroup) theGroupList.get(i);
List theQueryList = theQueryGroup.getQueries();
for (int j = 0; j < theQueryList.size(); j++) {
TOCQuery theQuery = (TOCQuery) theQueryList.get(j);
if (theQuery.getKey().equals(theKey)) {
request.getSession().setAttribute(Constants.SEARCH_RESULTS, theQuery.getResults());
log.info("TOC theQuery.getResults(): " + theQuery.getResults());
break;
}
}
}
} // end of SafeHTMLUtil.isValidValue
} // end of theKey != null
} catch (Exception e) {
theForward = "failure";
log.debug("Caught an error running the canned query: ", e);
// Encountered an error saving the model.
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
log.info("Exiting ViewTOCSearchResultsAction theForward: "+ theForward);
return mapping.findForward(theForward);
}
}
| true | true | public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
log.info("In ViewTOCSearchResultsAction.execute");
// get and clean header to prevent SQL injection
String sID = null;
if (request.getHeader("X-Forwarded-For") != null){
sID = request.getHeader("X-Forwarded-For");
log.info("cleaned X-Forwarded-For: " + sID);
sID = SafeHTMLUtil.clean(sID);
}
sID = request.getHeader("Referer");
// prevents Referer Header injection
if ( sID != null && sID != "" && sID.contains("camod")) {}
if ( sID != null && sID != "" && sID.contains("emice")) {}
else {
return (mapping.findForward("failure"));
}
// Clean all headers for security scan (careful about what chars you allow)
String headername = "";
for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();){
headername = (String)e.nextElement();
log.info("ViewTOCSearchResultsAction headername: " + headername);
String cleanHeaders = SafeHTMLUtil.clean(headername);
log.debug("ViewTOCSearchResultsAction cleaned headername: " + headername);
}
String theForward = "next";
try {
// clean TOCQUERYKEY ahead of try loop - then loop checks if it is a valid choice - security scan code
String theKey = (String) request.getParameter(Constants.Parameters.TOCQUERYKEY);
if (theKey != null && theKey.length() > 0) {
theKey = SafeHTMLUtil.clean(theKey);
log.info("ViewTOCSearchResultsAction cleaned theKey: " + theKey);
}
//Remove any retained criteriatable values
request.getSession().setAttribute(Constants.CRITERIATABLE, "" );
request.getSession().setAttribute(Constants.NOSAVEOPTION, "false");
// This is meant to prevent SQL injection into the key value of the TOC queries
// Security scan failed so this is checked first and the query will not run unless clean
if (theKey != null && theKey.length() > 0)
{
NameValueList.generateTableOfContentsList();
request.getSession().setAttribute(Constants.Dropdowns.SEARCHTOCDROP, NameValueList.getTableOfContentsList());
if (!SafeHTMLUtil.isValidValue(theKey,Constants.Dropdowns.SEARCHTOCDROP,request))
{
// set theForward to failure - fail gracefully but do not let query continue
System.out.println("TOC: The key is not an accepted value - end query " + theKey);
theForward = "failure";
} else {
log.debug("theKey is a valid value - continue with querry: " + theKey);
// Handle external linkage
if (request.getSession().getAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS) == null) {
// Get the TOC manager workflow
TOCManager theTOCManager = new TOCManager(getServlet().getServletContext().getRealPath("/")
+ Constants.TOCSearch.TOC_QUERY_FILE);
List theResults = theTOCManager.process();
log.debug("TOC: " + theResults);
request.getSession().setAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS, theResults);
}
List theGroupList = (List) request.getSession().getAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS);
log.debug("theGroupList: " + theGroupList);
for (int i = 0; i < theGroupList.size(); i++) {
TOCQueryGroup theQueryGroup = (TOCQueryGroup) theGroupList.get(i);
List theQueryList = theQueryGroup.getQueries();
for (int j = 0; j < theQueryList.size(); j++) {
TOCQuery theQuery = (TOCQuery) theQueryList.get(j);
if (theQuery.getKey().equals(theKey)) {
request.getSession().setAttribute(Constants.SEARCH_RESULTS, theQuery.getResults());
log.info("TOC theQuery.getResults(): " + theQuery.getResults());
break;
}
}
}
} // end of SafeHTMLUtil.isValidValue
} // end of theKey != null
} catch (Exception e) {
theForward = "failure";
log.debug("Caught an error running the canned query: ", e);
// Encountered an error saving the model.
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
log.info("Exiting ViewTOCSearchResultsAction theForward: "+ theForward);
return mapping.findForward(theForward);
}
| public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
log.info("In ViewTOCSearchResultsAction.execute");
// get and clean header to prevent SQL injection
String sID = null;
if (request.getHeader("X-Forwarded-For") != null){
sID = request.getHeader("X-Forwarded-For");
log.info("cleaned X-Forwarded-For: " + sID);
sID = SafeHTMLUtil.clean(sID);
}
sID = request.getHeader("Referer");
// prevents Referer Header injection
if ( sID != null && sID != "" && ( sID.contains("camod") || sID.contains("emice"))) {}
else {
return (mapping.findForward("failure"));
}
// Clean all headers for security scan (careful about what chars you allow)
String headername = "";
for(Enumeration e = request.getHeaderNames(); e.hasMoreElements();){
headername = (String)e.nextElement();
log.info("ViewTOCSearchResultsAction headername: " + headername);
String cleanHeaders = SafeHTMLUtil.clean(headername);
log.debug("ViewTOCSearchResultsAction cleaned headername: " + headername);
}
String theForward = "next";
try {
// clean TOCQUERYKEY ahead of try loop - then loop checks if it is a valid choice - security scan code
String theKey = (String) request.getParameter(Constants.Parameters.TOCQUERYKEY);
if (theKey != null && theKey.length() > 0) {
theKey = SafeHTMLUtil.clean(theKey);
log.info("ViewTOCSearchResultsAction cleaned theKey: " + theKey);
}
//Remove any retained criteriatable values
request.getSession().setAttribute(Constants.CRITERIATABLE, "" );
request.getSession().setAttribute(Constants.NOSAVEOPTION, "false");
// This is meant to prevent SQL injection into the key value of the TOC queries
// Security scan failed so this is checked first and the query will not run unless clean
if (theKey != null && theKey.length() > 0)
{
NameValueList.generateTableOfContentsList();
request.getSession().setAttribute(Constants.Dropdowns.SEARCHTOCDROP, NameValueList.getTableOfContentsList());
if (!SafeHTMLUtil.isValidValue(theKey,Constants.Dropdowns.SEARCHTOCDROP,request))
{
// set theForward to failure - fail gracefully but do not let query continue
System.out.println("TOC: The key is not an accepted value - end query " + theKey);
theForward = "failure";
} else {
log.debug("theKey is a valid value - continue with querry: " + theKey);
// Handle external linkage
if (request.getSession().getAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS) == null) {
// Get the TOC manager workflow
TOCManager theTOCManager = new TOCManager(getServlet().getServletContext().getRealPath("/")
+ Constants.TOCSearch.TOC_QUERY_FILE);
List theResults = theTOCManager.process();
log.debug("TOC: " + theResults);
request.getSession().setAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS, theResults);
}
List theGroupList = (List) request.getSession().getAttribute(Constants.TOCSearch.TOC_QUERY_RESULTS);
log.debug("theGroupList: " + theGroupList);
for (int i = 0; i < theGroupList.size(); i++) {
TOCQueryGroup theQueryGroup = (TOCQueryGroup) theGroupList.get(i);
List theQueryList = theQueryGroup.getQueries();
for (int j = 0; j < theQueryList.size(); j++) {
TOCQuery theQuery = (TOCQuery) theQueryList.get(j);
if (theQuery.getKey().equals(theKey)) {
request.getSession().setAttribute(Constants.SEARCH_RESULTS, theQuery.getResults());
log.info("TOC theQuery.getResults(): " + theQuery.getResults());
break;
}
}
}
} // end of SafeHTMLUtil.isValidValue
} // end of theKey != null
} catch (Exception e) {
theForward = "failure";
log.debug("Caught an error running the canned query: ", e);
// Encountered an error saving the model.
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
}
log.info("Exiting ViewTOCSearchResultsAction theForward: "+ theForward);
return mapping.findForward(theForward);
}
|
diff --git a/src/java/cz/cuni/mff/d3s/spl/core/impl/formula/LogicOr.java b/src/java/cz/cuni/mff/d3s/spl/core/impl/formula/LogicOr.java
index 6d70824..cbabfab 100644
--- a/src/java/cz/cuni/mff/d3s/spl/core/impl/formula/LogicOr.java
+++ b/src/java/cz/cuni/mff/d3s/spl/core/impl/formula/LogicOr.java
@@ -1,47 +1,47 @@
package cz.cuni.mff.d3s.spl.core.impl.formula;
import cz.cuni.mff.d3s.spl.core.Formula;
import cz.cuni.mff.d3s.spl.core.Result;
public class LogicOr extends LogicOp {
public LogicOr(Formula left, Formula right) {
super(left, right);
}
/*
* We are using Kleene three-value logic.
*/
@Override
public Result evaluate() {
Result leftResult = left.evaluate();
/*
* If the left one is TRUE, we do not need
* to evaluate the right one.
*/
if (leftResult == Result.TRUE) {
return Result.TRUE;
}
Result rightResult = right.evaluate();
/*
* The same works other way round.
*/
if (rightResult == Result.TRUE) {
return Result.TRUE;
}
/*
* FALSE is returned only if both are false, otherwise
* we return CANNOT_COMPUTE.
*/
- if ((rightResult == Result.FALSE) || (leftResult == Result.FALSE)) {
+ if ((rightResult == Result.FALSE) && (leftResult == Result.FALSE)) {
return Result.FALSE;
} else {
return Result.CANNOT_COMPUTE;
}
}
}
| true | true | public Result evaluate() {
Result leftResult = left.evaluate();
/*
* If the left one is TRUE, we do not need
* to evaluate the right one.
*/
if (leftResult == Result.TRUE) {
return Result.TRUE;
}
Result rightResult = right.evaluate();
/*
* The same works other way round.
*/
if (rightResult == Result.TRUE) {
return Result.TRUE;
}
/*
* FALSE is returned only if both are false, otherwise
* we return CANNOT_COMPUTE.
*/
if ((rightResult == Result.FALSE) || (leftResult == Result.FALSE)) {
return Result.FALSE;
} else {
return Result.CANNOT_COMPUTE;
}
}
| public Result evaluate() {
Result leftResult = left.evaluate();
/*
* If the left one is TRUE, we do not need
* to evaluate the right one.
*/
if (leftResult == Result.TRUE) {
return Result.TRUE;
}
Result rightResult = right.evaluate();
/*
* The same works other way round.
*/
if (rightResult == Result.TRUE) {
return Result.TRUE;
}
/*
* FALSE is returned only if both are false, otherwise
* we return CANNOT_COMPUTE.
*/
if ((rightResult == Result.FALSE) && (leftResult == Result.FALSE)) {
return Result.FALSE;
} else {
return Result.CANNOT_COMPUTE;
}
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java b/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java
index 4813dbcd2..e0a74735b 100644
--- a/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java
+++ b/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java
@@ -1,318 +1,323 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.DomEvent.Type;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.StyleConstants;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VCaption;
import com.vaadin.terminal.gwt.client.VConsole;
import com.vaadin.terminal.gwt.client.ValueMap;
public class VCssLayout extends SimplePanel implements Paintable, Container {
public static final String TAGNAME = "csslayout";
public static final String CLASSNAME = "v-" + TAGNAME;
public static final String CLICK_EVENT_IDENTIFIER = "click";
private FlowPane panel = new FlowPane();
private Element margin = DOM.createDiv();
private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler(
this, CLICK_EVENT_IDENTIFIER) {
@Override
protected Paintable getChildComponent(Element element) {
return panel.getComponent(element);
}
@Override
protected <H extends EventHandler> HandlerRegistration registerHandler(
H handler, Type<H> type) {
return addDomHandler(handler, type);
}
};
private boolean hasHeight;
private boolean hasWidth;
private boolean rendering;
public VCssLayout() {
super();
getElement().appendChild(margin);
setStyleName(CLASSNAME);
margin.setClassName(CLASSNAME + "-margin");
setWidget(panel);
}
@Override
protected Element getContainerElement() {
return margin;
}
@Override
public void setWidth(String width) {
super.setWidth(width);
// panel.setWidth(width);
hasWidth = width != null && !width.equals("");
if (!rendering) {
panel.updateRelativeSizes();
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
// panel.setHeight(height);
hasHeight = height != null && !height.equals("");
if (!rendering) {
panel.updateRelativeSizes();
}
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
clickEventHandler.handleEventHandlerRegistration(client);
final VMarginInfo margins = new VMarginInfo(
uidl.getIntAttribute("margins"));
setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_TOP,
margins.hasTop());
setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_RIGHT,
margins.hasRight());
setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_BOTTOM,
margins.hasBottom());
setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_LEFT,
margins.hasLeft());
setStyleName(margin, CLASSNAME + "-" + "spacing",
uidl.hasAttribute("spacing"));
panel.updateFromUIDL(uidl, client);
rendering = false;
}
public boolean hasChildComponent(Widget component) {
return panel.hasChildComponent(component);
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
panel.replaceChildComponent(oldComponent, newComponent);
}
public void updateCaption(Paintable component, UIDL uidl) {
panel.updateCaption(component, uidl);
}
public class FlowPane extends FlowPanel {
private final HashMap<Widget, VCaption> widgetToCaption = new HashMap<Widget, VCaption>();
private ApplicationConnection client;
public FlowPane() {
super();
setStyleName(CLASSNAME + "-container");
}
public void updateRelativeSizes() {
for (Widget w : getChildren()) {
if (w instanceof Paintable) {
client.handleComponentRelativeSize(w);
}
}
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// for later requests
this.client = client;
final ArrayList<Widget> oldWidgets = new ArrayList<Widget>();
for (final Iterator<Widget> iterator = iterator(); iterator
.hasNext();) {
oldWidgets.add(iterator.next());
}
clear();
ValueMap mapAttribute = null;
if (uidl.hasAttribute("css")) {
mapAttribute = uidl.getMapAttribute("css");
}
for (final Iterator<Object> i = uidl.getChildIterator(); i
.hasNext();) {
final UIDL r = (UIDL) i.next();
final Paintable child = client.getPaintable(r);
if (oldWidgets.contains(child)) {
oldWidgets.remove(child);
+ VCaption vCaption = widgetToCaption.get(child);
+ if (vCaption != null) {
+ add(vCaption);
+ oldWidgets.remove(vCaption);
+ }
}
add((Widget) child);
if (mapAttribute != null && mapAttribute.containsKey(r.getId())) {
String css = null;
try {
Style style = ((Widget) child).getElement().getStyle();
css = mapAttribute.getString(r.getId());
String[] cssRules = css.split(";");
for (int j = 0; j < cssRules.length; j++) {
String[] rule = cssRules[j].split(":");
if (rule.length == 0) {
continue;
} else {
style.setProperty(
makeCamelCase(rule[0].trim()),
rule[1].trim());
}
}
} catch (Exception e) {
VConsole.log("CssLayout encounterd invalid css string: "
+ css);
}
}
if (!r.getBooleanAttribute("cached")) {
child.updateFromUIDL(r, client);
}
}
// loop oldWidgetWrappers that where not re-attached and unregister
// them
for (Widget w : oldWidgets) {
if (w instanceof Paintable) {
final Paintable p = (Paintable) w;
client.unregisterPaintable(p);
}
widgetToCaption.remove(w);
}
}
public boolean hasChildComponent(Widget component) {
return component.getParent() == this;
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
VCaption caption = widgetToCaption.get(oldComponent);
if (caption != null) {
remove(caption);
widgetToCaption.remove(oldComponent);
}
int index = getWidgetIndex(oldComponent);
if (index >= 0) {
remove(oldComponent);
insert(newComponent, index);
}
}
public void updateCaption(Paintable component, UIDL uidl) {
VCaption caption = widgetToCaption.get(component);
if (VCaption.isNeeded(uidl)) {
Widget widget = (Widget) component;
if (caption == null) {
caption = new VCaption(component, client);
widgetToCaption.put(widget, caption);
insert(caption, getWidgetIndex(widget));
} else if (!caption.isAttached()) {
insert(caption, getWidgetIndex(widget));
}
caption.updateCaption(uidl);
} else if (caption != null) {
remove(caption);
widgetToCaption.remove(component);
}
}
private Paintable getComponent(Element element) {
return Util.getChildPaintableForElement(client, VCssLayout.this,
element);
}
}
private RenderSpace space;
public RenderSpace getAllocatedSpace(Widget child) {
if (space == null) {
space = new RenderSpace(-1, -1) {
@Override
public int getWidth() {
if (BrowserInfo.get().isIE()) {
int width = getOffsetWidth();
int margins = margin.getOffsetWidth()
- panel.getOffsetWidth();
return width - margins;
} else {
return panel.getOffsetWidth();
}
}
@Override
public int getHeight() {
int height = getOffsetHeight();
int margins = margin.getOffsetHeight()
- panel.getOffsetHeight();
return height - margins;
}
};
}
return space;
}
public boolean requestLayout(Set<Paintable> children) {
if (hasSize()) {
return true;
} else {
// Size may have changed
// TODO optimize this: cache size if not fixed, handle both width
// and height separately
return false;
}
}
private boolean hasSize() {
return hasWidth && hasHeight;
}
private static final String makeCamelCase(String cssProperty) {
// TODO this might be cleaner to implement with regexp
while (cssProperty.contains("-")) {
int indexOf = cssProperty.indexOf("-");
cssProperty = cssProperty.substring(0, indexOf)
+ String.valueOf(cssProperty.charAt(indexOf + 1))
.toUpperCase() + cssProperty.substring(indexOf + 2);
}
if ("float".equals(cssProperty)) {
if (BrowserInfo.get().isIE()) {
return "styleFloat";
} else {
return "cssFloat";
}
}
return cssProperty;
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// for later requests
this.client = client;
final ArrayList<Widget> oldWidgets = new ArrayList<Widget>();
for (final Iterator<Widget> iterator = iterator(); iterator
.hasNext();) {
oldWidgets.add(iterator.next());
}
clear();
ValueMap mapAttribute = null;
if (uidl.hasAttribute("css")) {
mapAttribute = uidl.getMapAttribute("css");
}
for (final Iterator<Object> i = uidl.getChildIterator(); i
.hasNext();) {
final UIDL r = (UIDL) i.next();
final Paintable child = client.getPaintable(r);
if (oldWidgets.contains(child)) {
oldWidgets.remove(child);
}
add((Widget) child);
if (mapAttribute != null && mapAttribute.containsKey(r.getId())) {
String css = null;
try {
Style style = ((Widget) child).getElement().getStyle();
css = mapAttribute.getString(r.getId());
String[] cssRules = css.split(";");
for (int j = 0; j < cssRules.length; j++) {
String[] rule = cssRules[j].split(":");
if (rule.length == 0) {
continue;
} else {
style.setProperty(
makeCamelCase(rule[0].trim()),
rule[1].trim());
}
}
} catch (Exception e) {
VConsole.log("CssLayout encounterd invalid css string: "
+ css);
}
}
if (!r.getBooleanAttribute("cached")) {
child.updateFromUIDL(r, client);
}
}
// loop oldWidgetWrappers that where not re-attached and unregister
// them
for (Widget w : oldWidgets) {
if (w instanceof Paintable) {
final Paintable p = (Paintable) w;
client.unregisterPaintable(p);
}
widgetToCaption.remove(w);
}
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// for later requests
this.client = client;
final ArrayList<Widget> oldWidgets = new ArrayList<Widget>();
for (final Iterator<Widget> iterator = iterator(); iterator
.hasNext();) {
oldWidgets.add(iterator.next());
}
clear();
ValueMap mapAttribute = null;
if (uidl.hasAttribute("css")) {
mapAttribute = uidl.getMapAttribute("css");
}
for (final Iterator<Object> i = uidl.getChildIterator(); i
.hasNext();) {
final UIDL r = (UIDL) i.next();
final Paintable child = client.getPaintable(r);
if (oldWidgets.contains(child)) {
oldWidgets.remove(child);
VCaption vCaption = widgetToCaption.get(child);
if (vCaption != null) {
add(vCaption);
oldWidgets.remove(vCaption);
}
}
add((Widget) child);
if (mapAttribute != null && mapAttribute.containsKey(r.getId())) {
String css = null;
try {
Style style = ((Widget) child).getElement().getStyle();
css = mapAttribute.getString(r.getId());
String[] cssRules = css.split(";");
for (int j = 0; j < cssRules.length; j++) {
String[] rule = cssRules[j].split(":");
if (rule.length == 0) {
continue;
} else {
style.setProperty(
makeCamelCase(rule[0].trim()),
rule[1].trim());
}
}
} catch (Exception e) {
VConsole.log("CssLayout encounterd invalid css string: "
+ css);
}
}
if (!r.getBooleanAttribute("cached")) {
child.updateFromUIDL(r, client);
}
}
// loop oldWidgetWrappers that where not re-attached and unregister
// them
for (Widget w : oldWidgets) {
if (w instanceof Paintable) {
final Paintable p = (Paintable) w;
client.unregisterPaintable(p);
}
widgetToCaption.remove(w);
}
}
|
diff --git a/src/main/java/org/thymeleaf/context/AbstractProcessingContext.java b/src/main/java/org/thymeleaf/context/AbstractProcessingContext.java
index ec856244..2703c7b6 100644
--- a/src/main/java/org/thymeleaf/context/AbstractProcessingContext.java
+++ b/src/main/java/org/thymeleaf/context/AbstractProcessingContext.java
@@ -1,238 +1,238 @@
/*
* =============================================================================
*
* Copyright (c) 2011-2012, The THYMELEAF team (http://www.thymeleaf.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.
*
* =============================================================================
*/
package org.thymeleaf.context;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.thymeleaf.expression.ExpressionEvaluatorObjects;
import org.thymeleaf.util.Validate;
/**
*
* @author Daniel Fernández
*
* @since 2.0.9
*
*/
public abstract class AbstractProcessingContext implements IProcessingContext {
protected static final String EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME = "%%{SELECTION_TARGET}%%";
private IContext context;
private Object evaluationRoot;
private Object selectionEvaluationRoot;
private final HashMap<String,Object> localVariables;
private boolean computedBaseContextVariables = false;
private Map<String, Object> expressionObjects = null;
protected AbstractProcessingContext(final IContext context) {
this(context, null, null, false);
}
protected AbstractProcessingContext(
final IContext context, final Map<String,Object> localVariables) {
this(context, localVariables, null, false);
}
protected AbstractProcessingContext(
final IContext context, final Map<String,Object> localVariables,
final Object selectionTarget, final boolean selectionTargetSet) {
super();
Validate.notNull(context, "Context cannot be null");
this.context = context;
this.localVariables =
(localVariables != null?
new HashMap<String,Object>(localVariables) :
- (selectionTarget != null?
+ (selectionTargetSet?
new HashMap<String, Object>() :
null));
if (selectionTargetSet) {
this.localVariables.put(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME, selectionTarget);
}
this.evaluationRoot = createEvaluationRoot();
this.selectionEvaluationRoot = createSelectedEvaluationRoot();
}
private Object createEvaluationRoot() {
final Map<String,Object> newEvaluationRoot = new VariablesMap<String,Object>();
newEvaluationRoot.putAll(this.context.getVariables());
if (hasLocalVariables()) {
newEvaluationRoot.putAll(this.localVariables);
}
return newEvaluationRoot;
}
private Object createSelectedEvaluationRoot() {
if (hasSelectionTarget()) {
return getSelectionTarget();
}
return this.evaluationRoot;
}
protected Map<String,Object> computeExpressionObjects() {
return ExpressionEvaluatorObjects.computeEvaluationObjects(this);
}
/**
* @deprecated Use {@link #getExpressionObjects()} instead. Will be removed in 2.1.x
*/
@Deprecated
public Map<String,Object> getBaseContextVariables() {
return getExpressionObjects();
}
public Map<String,Object> getExpressionObjects() {
if (!this.computedBaseContextVariables) {
// Base context variables are computed lazily so that subclasses have
// the chance to override the basic computing behaviour.
// The boolean flag is modified first so that if this method is called by
// error during the implementation of "computeExpressionObjects()" it does
// not result in an infinite loop.
this.computedBaseContextVariables = true;
this.expressionObjects = computeExpressionObjects();
}
return this.expressionObjects;
}
public IContext getContext() {
return this.context;
}
public Object getExpressionEvaluationRoot() {
return this.evaluationRoot;
}
public Object getExpressionSelectionEvaluationRoot() {
return this.selectionEvaluationRoot;
}
public boolean hasSelectionTarget() {
return hasLocalVariable(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME) ||
getContext().getVariables().containsKey(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME);
}
public Object getSelectionTarget() {
if (hasLocalVariable(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME)) {
return getLocalVariable(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME);
}
if (getContext().getVariables().containsKey(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME)) {
return getContext().getVariables().get(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME);
}
return null;
}
public boolean hasLocalVariables() {
return this.localVariables != null && this.localVariables.size() > 0;
}
public boolean hasLocalVariable(final String variableName) {
if (this.localVariables == null) {
return false;
}
return this.localVariables.containsKey(variableName);
}
public Object getLocalVariable(final String variableName) {
if (this.localVariables == null) {
return null;
}
return this.localVariables.get(variableName);
}
public Map<String,Object> getLocalVariables() {
if (this.localVariables != null) {
return Collections.unmodifiableMap(this.localVariables);
}
return null;
}
/**
* <p>
* Returns the real inner map of local variables. This
* method should not be called directly.
* </p>
*
* @return the local variables map, which could be null if no variables are defined
* @deprecated Use {@link #getLocalVariables()} instead. Will be removed in 2.1.x.
*/
@Deprecated
public HashMap<String,Object> unsafeGetLocalVariables() {
return this.localVariables;
}
protected Map<String,Object> mergeNewLocalVariables(final Map<String,Object> newVariables) {
if (newVariables == null || newVariables.isEmpty()) {
return this.localVariables;
}
final int localVariablesSize = (this.localVariables != null? this.localVariables.size() : 0);
final HashMap<String,Object> cloneLocalVariables =
new HashMap<String, Object>(localVariablesSize + newVariables.size() + 1, 1.0f);
if (this.localVariables != null) {
cloneLocalVariables.putAll(this.localVariables);
}
cloneLocalVariables.putAll(newVariables);
return cloneLocalVariables;
}
}
| true | true | protected AbstractProcessingContext(
final IContext context, final Map<String,Object> localVariables,
final Object selectionTarget, final boolean selectionTargetSet) {
super();
Validate.notNull(context, "Context cannot be null");
this.context = context;
this.localVariables =
(localVariables != null?
new HashMap<String,Object>(localVariables) :
(selectionTarget != null?
new HashMap<String, Object>() :
null));
if (selectionTargetSet) {
this.localVariables.put(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME, selectionTarget);
}
this.evaluationRoot = createEvaluationRoot();
this.selectionEvaluationRoot = createSelectedEvaluationRoot();
}
| protected AbstractProcessingContext(
final IContext context, final Map<String,Object> localVariables,
final Object selectionTarget, final boolean selectionTargetSet) {
super();
Validate.notNull(context, "Context cannot be null");
this.context = context;
this.localVariables =
(localVariables != null?
new HashMap<String,Object>(localVariables) :
(selectionTargetSet?
new HashMap<String, Object>() :
null));
if (selectionTargetSet) {
this.localVariables.put(EVAL_SELECTION_TARGET_LOCAL_VARIABLE_NAME, selectionTarget);
}
this.evaluationRoot = createEvaluationRoot();
this.selectionEvaluationRoot = createSelectedEvaluationRoot();
}
|
diff --git a/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/gmf/tools/tree/EmptyOperationViewFilter.java b/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/gmf/tools/tree/EmptyOperationViewFilter.java
index c6c50f3c14..5fc706cd9d 100644
--- a/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/gmf/tools/tree/EmptyOperationViewFilter.java
+++ b/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/gmf/tools/tree/EmptyOperationViewFilter.java
@@ -1,44 +1,44 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* 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.0 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.bonitasoft.studio.common.gmf.tools.tree;
import org.bonitasoft.studio.model.expression.Operation;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
/**
* @author Aurelie Zara
*
*/
public class EmptyOperationViewFilter extends ViewerFilter {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof Operation){
Operation op = (Operation)element;
- if ((op.getLeftOperand().getContent()==null || op.getLeftOperand().getContent().isEmpty()) && (op.getRightOperand().getContent()==null || op.getRightOperand().getContent().isEmpty())){
+ if (( op.getLeftOperand()==null || op.getLeftOperand().getContent()==null || op.getLeftOperand().getContent().isEmpty()) && ( op.getRightOperand()==null || op.getRightOperand().getContent()==null || op.getRightOperand().getContent().isEmpty())){
return false;
}
}
return true;
}
}
| true | true | public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof Operation){
Operation op = (Operation)element;
if ((op.getLeftOperand().getContent()==null || op.getLeftOperand().getContent().isEmpty()) && (op.getRightOperand().getContent()==null || op.getRightOperand().getContent().isEmpty())){
return false;
}
}
return true;
}
| public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof Operation){
Operation op = (Operation)element;
if (( op.getLeftOperand()==null || op.getLeftOperand().getContent()==null || op.getLeftOperand().getContent().isEmpty()) && ( op.getRightOperand()==null || op.getRightOperand().getContent()==null || op.getRightOperand().getContent().isEmpty())){
return false;
}
}
return true;
}
|
diff --git a/src/minecraft/andrew/powersuits/modules/LeafBlowerModule.java b/src/minecraft/andrew/powersuits/modules/LeafBlowerModule.java
index 9e2b334..a439257 100644
--- a/src/minecraft/andrew/powersuits/modules/LeafBlowerModule.java
+++ b/src/minecraft/andrew/powersuits/modules/LeafBlowerModule.java
@@ -1,129 +1,129 @@
package andrew.powersuits.modules;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFlower;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.List;
/**
* Created by User: Andrew2448
* 7:13 PM 4/21/13
*/
public class LeafBlowerModule extends PowerModuleBase implements IRightClickModule {
private static final String MODULE_LEAF_BLOWER = "Leaf Blower";
private static final String LEAF_BLOWER_ENERGY_CONSUMPTION = "Energy Consumption";
private static final String PLANT_RADIUS = "Plant Radius";
private static final String LEAF_RADIUS = "Leaf Radius";
public LeafBlowerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(new ItemStack(Item.ingotIron, 3));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.solenoid, 1));
addBaseProperty(LEAF_BLOWER_ENERGY_CONSUMPTION, 100, "J");
addBaseProperty(PLANT_RADIUS, 1, "m");
addBaseProperty(LEAF_RADIUS, 1, "m");
addIntTradeoffProperty(PLANT_RADIUS, PLANT_RADIUS, 2, "m", 1, 0);
addIntTradeoffProperty(LEAF_RADIUS, LEAF_RADIUS, 2, "m", 1, 0);
}
public PowerModuleBase addIntTradeoffProperty(String tradeoffName, String propertyName, double multiplier, String unit, int roundTo, int offset) {
units.put(propertyName, unit);
return addPropertyModifier(propertyName, new PropertyModifierIntLinearAdditive(tradeoffName, multiplier, roundTo, offset));
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_TOOL;
}
@Override
public String getName() {
return MODULE_LEAF_BLOWER;
}
@Override
public String getDescription() {
return "Create a torrent of air to knock plants out of the ground and leaves off of trees.";
}
@Override
public String getTextureFile() {
return "leafblower";
}
@Override
public void onRightClick(EntityPlayer player, World world, ItemStack item) {}
@Override
public void onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
int blockID = world.getBlockId(x, y, z);
Block block = Block.blocksList[blockID];
int plant = (int) ModuleManager.computeModularProperty(itemStack, PLANT_RADIUS);
int leaf = (int) ModuleManager.computeModularProperty(itemStack, LEAF_RADIUS);
int totalEnergyDrain = 0;
// Leaves
if (block != null && block.isLeaves(world, x, y, z)) {
for (int i = -leaf; i < leaf; i++) {
for (int j = -leaf; j < leaf; j++) {
for (int k = -leaf; k < leaf; k++) {
int id = world.getBlockId(x + i, y + j, z + k);
int meta = world.getBlockMetadata(x + i, y + j, z + k);
Block tempBlock = Block.blocksList[id];
if (tempBlock != null && tempBlock.isLeaves(world, x + i, y + j, z + k)) {
- if (block.canHarvestBlock(player, meta)) {
- block.harvestBlock(world, player, x + i, y + j, z + k, meta);
+ if (tempBlock.canHarvestBlock(player, meta)) {
+ tempBlock.harvestBlock(world, player, x + i, y + j, z + k, meta);
totalEnergyDrain += ModuleManager.computeModularProperty(itemStack, LEAF_BLOWER_ENERGY_CONSUMPTION);
}
world.setBlockToAir(x + i, y + j, z + k);
}
}
}
}
}
// Plants
for (int i = -plant; i < plant; i++) {
for (int j = -plant; j < plant; j++) {
for (int k = -plant; k < plant; k++) {
int id = world.getBlockId(x + i, y + j, z + k);
int meta = world.getBlockMetadata(x + i, y + j, z + k);
Block tempBlock = Block.blocksList[id];
if (tempBlock != null && tempBlock instanceof BlockFlower) {
- if (block.canHarvestBlock(player, meta)) {
+ if (tempBlock.canHarvestBlock(player, meta)) {
//AddonLogger.logDebug("X: "+Math.abs(x+i)+" Y: "+Math.abs(y+j)+" Z: "+Math.abs(z+k));
//AddonLogger.logDebug("Block ID: "+id);
//AddonLogger.logDebug("Block Meta: "+meta);
- block.harvestBlock(world, player, x + i, y + j, z + k, meta);
+ tempBlock.harvestBlock(world, player, x + i, y + j, z + k, meta);
totalEnergyDrain += ModuleManager.computeModularProperty(itemStack, LEAF_BLOWER_ENERGY_CONSUMPTION);
world.setBlockToAir(x + i, y + j, z + k);
}
}
}
}
}
ElectricItemUtils.drainPlayerEnergy(player, totalEnergyDrain);
}
@Override
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
return false;
}
@Override
public void onPlayerStoppedUsing(ItemStack itemStack, World world, EntityPlayer player, int par4) {
}
}
| false | true | public void onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
int blockID = world.getBlockId(x, y, z);
Block block = Block.blocksList[blockID];
int plant = (int) ModuleManager.computeModularProperty(itemStack, PLANT_RADIUS);
int leaf = (int) ModuleManager.computeModularProperty(itemStack, LEAF_RADIUS);
int totalEnergyDrain = 0;
// Leaves
if (block != null && block.isLeaves(world, x, y, z)) {
for (int i = -leaf; i < leaf; i++) {
for (int j = -leaf; j < leaf; j++) {
for (int k = -leaf; k < leaf; k++) {
int id = world.getBlockId(x + i, y + j, z + k);
int meta = world.getBlockMetadata(x + i, y + j, z + k);
Block tempBlock = Block.blocksList[id];
if (tempBlock != null && tempBlock.isLeaves(world, x + i, y + j, z + k)) {
if (block.canHarvestBlock(player, meta)) {
block.harvestBlock(world, player, x + i, y + j, z + k, meta);
totalEnergyDrain += ModuleManager.computeModularProperty(itemStack, LEAF_BLOWER_ENERGY_CONSUMPTION);
}
world.setBlockToAir(x + i, y + j, z + k);
}
}
}
}
}
// Plants
for (int i = -plant; i < plant; i++) {
for (int j = -plant; j < plant; j++) {
for (int k = -plant; k < plant; k++) {
int id = world.getBlockId(x + i, y + j, z + k);
int meta = world.getBlockMetadata(x + i, y + j, z + k);
Block tempBlock = Block.blocksList[id];
if (tempBlock != null && tempBlock instanceof BlockFlower) {
if (block.canHarvestBlock(player, meta)) {
//AddonLogger.logDebug("X: "+Math.abs(x+i)+" Y: "+Math.abs(y+j)+" Z: "+Math.abs(z+k));
//AddonLogger.logDebug("Block ID: "+id);
//AddonLogger.logDebug("Block Meta: "+meta);
block.harvestBlock(world, player, x + i, y + j, z + k, meta);
totalEnergyDrain += ModuleManager.computeModularProperty(itemStack, LEAF_BLOWER_ENERGY_CONSUMPTION);
world.setBlockToAir(x + i, y + j, z + k);
}
}
}
}
}
ElectricItemUtils.drainPlayerEnergy(player, totalEnergyDrain);
}
| public void onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
int blockID = world.getBlockId(x, y, z);
Block block = Block.blocksList[blockID];
int plant = (int) ModuleManager.computeModularProperty(itemStack, PLANT_RADIUS);
int leaf = (int) ModuleManager.computeModularProperty(itemStack, LEAF_RADIUS);
int totalEnergyDrain = 0;
// Leaves
if (block != null && block.isLeaves(world, x, y, z)) {
for (int i = -leaf; i < leaf; i++) {
for (int j = -leaf; j < leaf; j++) {
for (int k = -leaf; k < leaf; k++) {
int id = world.getBlockId(x + i, y + j, z + k);
int meta = world.getBlockMetadata(x + i, y + j, z + k);
Block tempBlock = Block.blocksList[id];
if (tempBlock != null && tempBlock.isLeaves(world, x + i, y + j, z + k)) {
if (tempBlock.canHarvestBlock(player, meta)) {
tempBlock.harvestBlock(world, player, x + i, y + j, z + k, meta);
totalEnergyDrain += ModuleManager.computeModularProperty(itemStack, LEAF_BLOWER_ENERGY_CONSUMPTION);
}
world.setBlockToAir(x + i, y + j, z + k);
}
}
}
}
}
// Plants
for (int i = -plant; i < plant; i++) {
for (int j = -plant; j < plant; j++) {
for (int k = -plant; k < plant; k++) {
int id = world.getBlockId(x + i, y + j, z + k);
int meta = world.getBlockMetadata(x + i, y + j, z + k);
Block tempBlock = Block.blocksList[id];
if (tempBlock != null && tempBlock instanceof BlockFlower) {
if (tempBlock.canHarvestBlock(player, meta)) {
//AddonLogger.logDebug("X: "+Math.abs(x+i)+" Y: "+Math.abs(y+j)+" Z: "+Math.abs(z+k));
//AddonLogger.logDebug("Block ID: "+id);
//AddonLogger.logDebug("Block Meta: "+meta);
tempBlock.harvestBlock(world, player, x + i, y + j, z + k, meta);
totalEnergyDrain += ModuleManager.computeModularProperty(itemStack, LEAF_BLOWER_ENERGY_CONSUMPTION);
world.setBlockToAir(x + i, y + j, z + k);
}
}
}
}
}
ElectricItemUtils.drainPlayerEnergy(player, totalEnergyDrain);
}
|
diff --git a/lib/java/src/protocol/TProtocolUtil.java b/lib/java/src/protocol/TProtocolUtil.java
index 935163c..ad333bc 100644
--- a/lib/java/src/protocol/TProtocolUtil.java
+++ b/lib/java/src/protocol/TProtocolUtil.java
@@ -1,93 +1,104 @@
// Copyright (c) 2006- Facebook
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
package com.facebook.thrift.protocol;
import com.facebook.thrift.TException;
import com.facebook.thrift.transport.TTransport;
/**
* Utility class with static methods for interacting with protocol data
* streams.
*
* @author Mark Slee <[email protected]>
*/
public class TProtocolUtil {
public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
+ break;
}
case TType.BYTE:
{
prot.readByte();
+ break;
}
case TType.I16:
{
prot.readI16();
+ break;
}
case TType.I32:
{
prot.readI32();
+ break;
}
case TType.I64:
{
prot.readI64();
+ break;
}
case TType.DOUBLE:
{
prot.readDouble();
+ break;
}
case TType.STRING:
{
prot.readString();
+ break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
+ break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
+ break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
+ break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
+ break;
}
default:
- return;
+ break;
}
}
}
| false | true | public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
}
case TType.BYTE:
{
prot.readByte();
}
case TType.I16:
{
prot.readI16();
}
case TType.I32:
{
prot.readI32();
}
case TType.I64:
{
prot.readI64();
}
case TType.DOUBLE:
{
prot.readDouble();
}
case TType.STRING:
{
prot.readString();
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
}
default:
return;
}
}
| public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
prot.readString();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
|
diff --git a/src/com/dmdirc/config/ConfigSource.java b/src/com/dmdirc/config/ConfigSource.java
index f0e8ec34d..76ebc7a6f 100644
--- a/src/com/dmdirc/config/ConfigSource.java
+++ b/src/com/dmdirc/config/ConfigSource.java
@@ -1,252 +1,252 @@
/*
* 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.config;
import com.dmdirc.ui.messages.ColourManager;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Defines methods to get options from a config source in various forms.
*
* @author chris
*/
public abstract class ConfigSource {
/**
* Retrieves the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @return The value of the option
*/
public abstract String getOption(final String domain, final String option);
/**
* Determines if this manager has the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @return True iff the option exists, false otherwise.
*/
protected abstract boolean hasOption(final String domain, final String option);
/**
* Determines if this manager has the specified String option.
*
* @param domain The domain of the option
* @param option The name of the option
* @since 0.6.3m1
* @return True iff the option exists and is not empty, false otherwise
*/
public boolean hasOptionString(final String domain, final String option) {
return hasOption(domain, option) && !getOption(domain, option).isEmpty();
}
/**
* Determines if this manager has the specified integer option.
*
* @param domain The domain of the option
* @param option The name of the option
* @since 0.6.3m1
* @return True iff the option exists and is parsable as an integer,
* false otherwise.
*/
public boolean hasOptionInt(final String domain, final String option) {
if (hasOption(domain, option)) {
try {
getOptionInt(domain, option);
return true;
} catch (NumberFormatException ex) {
// Do nothing
}
}
return false;
}
/**
* Determines if this manager has the specified character option.
*
* @param domain The domain of the option
* @param option The name of the option
* @since 0.6.3m1
* @return True iff the option exists and is parsable as a char,
* false otherwise.
*/
public boolean hasOptionChar(final String domain, final String option) {
return hasOption(domain, option) && !getOption(domain, option).isEmpty();
}
/**
* Determines if this manager has the specified colour option.
*
* @param domain The domain of the option
* @param option The name of the option
* @since 0.6.3m1
* @return True iff the option exists and is parsable as a colour,
* false otherwise.
*/
public boolean hasOptionColour(final String domain, final String option) {
if (hasOption(domain, option)) {
String value = getOption(domain, option);
String colour;
if (value.startsWith("false:")) {
return false;
} else if (value.startsWith("true:")) {
colour = value.substring(5);
} else {
colour = value;
}
- return ColourManager.parseColour(value, null) != null;
+ return ColourManager.parseColour(colour, null) != null;
} else {
return false;
}
}
/**
* Retrieves a boolean representation of the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @return The boolean representation of the option
*/
public boolean hasOptionBool(final String domain, final String option) {
return hasOption(domain, option);
}
/**
* Retrieves the specified option as a character.
*
* @param domain The domain of the option
* @param option The name of the option
* @return The value of the option
*/
public char getOptionChar(final String domain, final String option) {
return getOption(domain, option).charAt(0);
}
/**
* Retrieves a colour representation of the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @param fallbacks An ordered array of further domains and options
* (in pairs) to try if the specified domain/option isn't found
* @return The colour representation of the option
* @since 0.6.3m1
*/
public Color getOptionColour(final String domain, final String option,
final String ... fallbacks) {
if (hasOptionColour(domain, option)) {
final String value = getOption(domain, option);
return ColourManager.parseColour(value.startsWith("true:")
? value.substring(5) : value, null);
} else {
return fallbacks.length >= 2 ? getOptionColour(fallbacks[0], fallbacks[1],
Arrays.copyOfRange(fallbacks, 2, fallbacks.length)) : null;
}
}
/**
* Retrieves a boolean representation of the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @return The boolean representation of the option
*/
public boolean getOptionBool(final String domain, final String option) {
return Boolean.parseBoolean(getOption(domain, option));
}
/**
* Retrieves a list representation of the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @param trimEmpty Whether or not to trim empty lines
* @return The list representation of the option
*/
public List<String> getOptionList(final String domain, final String option,
final boolean trimEmpty) {
final List<String> res = new ArrayList<String>();
if (hasOption(domain, option)) {
for (String line : getOption(domain, option).split("\n")) {
if (!line.isEmpty() || !trimEmpty) {
res.add(line);
}
}
}
return res;
}
/**
* Retrieves a list representation of the specified option, trimming empty
* lines by default.
*
* @param domain The domain of the option
* @param option The name of the option
* @return The list representation of the option
*/
public List<String> getOptionList(final String domain, final String option) {
return getOptionList(domain, option, true);
}
/**
* Retrieves an integral representation of the specified option.
*
* @param domain The domain of the option
* @param option The name of the option
* @param fallbacks An ordered array of further domains and options
* (in pairs) to try if the specified domain/option isn't found
* @throws NumberFormatException If the setting can't be parsed
* @return The integer representation of the option or null if optional
* setting is false
*/
public Integer getOptionInt(final String domain, final String option,
final String ... fallbacks) {
String value;
if (!hasOption(domain, option) || (value = getOption(domain, option))
.startsWith("false:")) {
return fallbacks.length >= 2 ? getOptionInt(fallbacks[0], fallbacks[1],
Arrays.copyOfRange(fallbacks, 2, fallbacks.length)) : null;
}
if (value.startsWith("true:")) {
return Integer.parseInt(getOption(domain, option).trim().substring(
5));
} else if (value.startsWith("false:")) {
return null;
} else {
return Integer.parseInt(getOption(domain, option).trim());
}
}
}
| true | true | public boolean hasOptionColour(final String domain, final String option) {
if (hasOption(domain, option)) {
String value = getOption(domain, option);
String colour;
if (value.startsWith("false:")) {
return false;
} else if (value.startsWith("true:")) {
colour = value.substring(5);
} else {
colour = value;
}
return ColourManager.parseColour(value, null) != null;
} else {
return false;
}
}
| public boolean hasOptionColour(final String domain, final String option) {
if (hasOption(domain, option)) {
String value = getOption(domain, option);
String colour;
if (value.startsWith("false:")) {
return false;
} else if (value.startsWith("true:")) {
colour = value.substring(5);
} else {
colour = value;
}
return ColourManager.parseColour(colour, null) != null;
} else {
return false;
}
}
|
diff --git a/src/game/GameplayState.java b/src/game/GameplayState.java
index 1b80898..929b483 100644
--- a/src/game/GameplayState.java
+++ b/src/game/GameplayState.java
@@ -1,112 +1,112 @@
package game;
import lights.PointLight;
import map.Cell;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.Music;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import sounds.Sounds;
import utils.MapLoader;
import utils.npeloader.EnemyLoader;
import GUI.GUI;
import entities.players.Player;
public class GameplayState extends MouseCapture {
private final int stateID;
private Cell currentCell;
private Player player;
private Music music;
private static World world = new World(new Vec2(0, 9.8f), false);
private GUI gui = new GUI();
GameplayState(int stateID) {
this.stateID = stateID;
}
@Override
public int getID() {
return stateID;
}
@Override
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
//load enemy data
new EnemyLoader().load("data/enemydata.xml");
//map loading goes here. Needs a better home
//method needed to load all maps into their correct index in the array
MapLoader.setDimensions(3,2);
MapLoader.loadMap("data/JezMap01.tmx", 0, 0);
MapLoader.loadMap("data/JezMap02.tmx", 1, 0);
MapLoader.loadMap("data/JezMap03.tmx", 2, 0);
MapLoader.loadMap("data/JezMap13.tmx", 2, 1);
//set initial map
player = new Player(2,2);
currentCell = MapLoader.setCurrentCell(player,0,0);
//create player
currentCell.addEntity(player);
//audio
music = new Music("data/sounds/theme.ogg", true);
music.play(1.0f, 0.15f);
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException {
currentCell.render(gc, sbg, g);
renderLighting(gc,g);
gui.render(g);
}
private void renderLighting(GameContainer gc, Graphics g){
//clear alpha map in preparation
g.clearAlphaMap();
//render each light
new PointLight(0, 0, 12).render(gc,g);
new PointLight(gc.getWidth(), 0, 12).render(gc,g);
//fill remaining area with darkness... i think... :/
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_DST_ALPHA);
g.fillRect(0, 0, gc.getWidth(), gc.getHeight());
g.setDrawMode(Graphics.MODE_NORMAL);
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
//update map
currentCell = MapLoader.getCurrentCell();
//check input
Input input = gc.getInput();
if (input.isKeyPressed(Input.KEY_ESCAPE)){
if(gui.anyWindowOpen()){
gui.closeWindow();
}else{
gc.sleep(300);
music.release();
Sounds.releaseSounds();
gc.exit();
}
}
if(!gui.anyWindowOpen()){
currentCell.updateEntities(gc, sbg, delta);
world.step(delta/1000f, 8, 3);
- gui.update(gc, sbg, delta);
}
+ gui.update(gc, sbg, delta);
}
public static World getWorld() {
return world;
}
}
| false | true | public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
//update map
currentCell = MapLoader.getCurrentCell();
//check input
Input input = gc.getInput();
if (input.isKeyPressed(Input.KEY_ESCAPE)){
if(gui.anyWindowOpen()){
gui.closeWindow();
}else{
gc.sleep(300);
music.release();
Sounds.releaseSounds();
gc.exit();
}
}
if(!gui.anyWindowOpen()){
currentCell.updateEntities(gc, sbg, delta);
world.step(delta/1000f, 8, 3);
gui.update(gc, sbg, delta);
}
}
| public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
//update map
currentCell = MapLoader.getCurrentCell();
//check input
Input input = gc.getInput();
if (input.isKeyPressed(Input.KEY_ESCAPE)){
if(gui.anyWindowOpen()){
gui.closeWindow();
}else{
gc.sleep(300);
music.release();
Sounds.releaseSounds();
gc.exit();
}
}
if(!gui.anyWindowOpen()){
currentCell.updateEntities(gc, sbg, delta);
world.step(delta/1000f, 8, 3);
}
gui.update(gc, sbg, delta);
}
|
diff --git a/portal/src/hot/org/vamdc/portal/session/queryLog/ResponseFacade.java b/portal/src/hot/org/vamdc/portal/session/queryLog/ResponseFacade.java
index 60681a9..a29eba6 100644
--- a/portal/src/hot/org/vamdc/portal/session/queryLog/ResponseFacade.java
+++ b/portal/src/hot/org/vamdc/portal/session/queryLog/ResponseFacade.java
@@ -1,41 +1,41 @@
package org.vamdc.portal.session.queryLog;
import java.util.UUID;
import org.vamdc.portal.entity.query.HttpHeadResponse;
public class ResponseFacade implements ResponseInterface {
private HttpHeadResponse response;
public ResponseFacade (HttpHeadResponse node){
this.response=node;
if (response==null)
throw new IllegalArgumentException("Response is null!");
}
public String getNodeIVOAId(){
return response.getIvoaID();
}
public String getStatsString(){
if (response!=null)
return "Sp: "+response.getSpecies()+" -st:"+response.getStates()+" - Pr:"+response.getProcesses();
return "?";
}
public String getFullQueryURL(){
return response.getFullQueryURL();
}
public String getId(){
String result=null;
- if (response!=null){
+ if (response!=null && response.getRecordID()!=null){
result = response.getRecordID().toString();
}
if (result==null || result.length()==0)
result = UUID.randomUUID().toString();
return result;
}
}
| true | true | public String getId(){
String result=null;
if (response!=null){
result = response.getRecordID().toString();
}
if (result==null || result.length()==0)
result = UUID.randomUUID().toString();
return result;
}
| public String getId(){
String result=null;
if (response!=null && response.getRecordID()!=null){
result = response.getRecordID().toString();
}
if (result==null || result.length()==0)
result = UUID.randomUUID().toString();
return result;
}
|
diff --git a/src/main/java/com/netflix/postreview/p4/P4Runner.java b/src/main/java/com/netflix/postreview/p4/P4Runner.java
index 6784e32..a655610 100644
--- a/src/main/java/com/netflix/postreview/p4/P4Runner.java
+++ b/src/main/java/com/netflix/postreview/p4/P4Runner.java
@@ -1,25 +1,25 @@
package com.netflix.postreview.p4;
import com.netflix.postreview.Runner;
import java.io.IOException;
/**
* Variant of Runner tailored for invoking p4
*/
public class P4Runner extends Runner {
/**
* Requires environment variables (P4USER, P4CLIENT, P4PORT, P4PASSWD)
*/
- public P4Runner(String port, String client, String user, String passwd) throws IOException {
+ public P4Runner(String port, String client, String user, String passwd) throws IOException {
if (port != null) environment.put("P4PORT", port);
if (client != null) environment.put("P4CLIENT", client);
if (user != null) environment.put("P4USER", user);
if (passwd != null) environment.put("P4PASSWD", passwd);
// Retrieve the basic info on the client to make sure that all params are OK.
Client c = Client.invokeWith(this, client);
if (c == null) throw new IOException("Client not found: " + client);
}
}
| true | true | public P4Runner(String port, String client, String user, String passwd) throws IOException {
if (port != null) environment.put("P4PORT", port);
if (client != null) environment.put("P4CLIENT", client);
if (user != null) environment.put("P4USER", user);
if (passwd != null) environment.put("P4PASSWD", passwd);
// Retrieve the basic info on the client to make sure that all params are OK.
Client c = Client.invokeWith(this, client);
if (c == null) throw new IOException("Client not found: " + client);
}
| public P4Runner(String port, String client, String user, String passwd) throws IOException {
if (port != null) environment.put("P4PORT", port);
if (client != null) environment.put("P4CLIENT", client);
if (user != null) environment.put("P4USER", user);
if (passwd != null) environment.put("P4PASSWD", passwd);
// Retrieve the basic info on the client to make sure that all params are OK.
Client c = Client.invokeWith(this, client);
if (c == null) throw new IOException("Client not found: " + client);
}
|
diff --git a/src/ussr/remote/facade/SimulationTabControl.java b/src/ussr/remote/facade/SimulationTabControl.java
index 00a11739..ed141e5e 100644
--- a/src/ussr/remote/facade/SimulationTabControl.java
+++ b/src/ussr/remote/facade/SimulationTabControl.java
@@ -1,88 +1,88 @@
package ussr.remote.facade;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import ussr.builder.helpers.BuilderHelper;
import ussr.description.geometry.VectorDescription;
import ussr.model.Module;
import ussr.physics.PhysicsSimulation;
import ussr.physics.jme.JMESimulation;
public class SimulationTabControl extends UnicastRemoteObject implements SimulationTabControlInter{
/**
* JME level simulation.
*/
private JMESimulation jmeSimulation;
public SimulationTabControl(JMESimulation jmeSimulation) throws RemoteException {
this.jmeSimulation = jmeSimulation;
}
public void setModulePosition(int moduleID,VectorDescription newModulePosition)throws RemoteException{
int amountModules = jmeSimulation.getModules().size();
for (int index=0; index<amountModules; index++){
if (jmeSimulation.getModules().get(index).getID()==moduleID){
jmeSimulation.getModules().get(index).setPosition(newModulePosition);
}
}
}
public VectorDescription getModulePosition(int moduleID)throws RemoteException{
int amountModules = jmeSimulation.getModules().size();
for (int index=0; index<amountModules; index++){
if (jmeSimulation.getModules().get(index).getID()==moduleID){
return jmeSimulation.getModules().get(index).getPhysics().get(0).getPosition();
}
}
return null;
}
private int amountModules =0;
public void deleteModules(List<Integer> ids)throws RemoteException{
//jmeSimulation.getModules().clear();
for(int moduleID=0;moduleID<ids.size();moduleID++){
amountModules = jmeSimulation.getModules().size();
System.out.println("Size List:"+ jmeSimulation.getModules().size());
for (int index=0; index<amountModules; index++){
System.out.println("ID:"+ ids.get(moduleID));
int currentModuleID = jmeSimulation.getModules().get(index).getID();
Module currentModule =jmeSimulation.getModules().get(index);
int moduleToDeleteID = ids.get(moduleID);
if (currentModuleID==moduleToDeleteID ){
- BuilderHelper.deleteModule(currentModule,false);
+ BuilderHelper.deleteModule(currentModule,true);
PhysicsSimulation simulation= currentModule.getSimulation();
List<Module> modules = simulation.getModules();
modules.remove(currentModule);
JMESimulation jmeSimulation =(JMESimulation)simulation;
jmeSimulation.setModules(modules);
//PhysicsSimulation physicsSimulation = currentModule.getSimulation();
//physicsSimulation.getModules().remove(currentModule);
//amountModules = jmeSimulation.getModules().size();
break;
}
}
}
}
}
| true | true | public void deleteModules(List<Integer> ids)throws RemoteException{
//jmeSimulation.getModules().clear();
for(int moduleID=0;moduleID<ids.size();moduleID++){
amountModules = jmeSimulation.getModules().size();
System.out.println("Size List:"+ jmeSimulation.getModules().size());
for (int index=0; index<amountModules; index++){
System.out.println("ID:"+ ids.get(moduleID));
int currentModuleID = jmeSimulation.getModules().get(index).getID();
Module currentModule =jmeSimulation.getModules().get(index);
int moduleToDeleteID = ids.get(moduleID);
if (currentModuleID==moduleToDeleteID ){
BuilderHelper.deleteModule(currentModule,false);
PhysicsSimulation simulation= currentModule.getSimulation();
List<Module> modules = simulation.getModules();
modules.remove(currentModule);
JMESimulation jmeSimulation =(JMESimulation)simulation;
jmeSimulation.setModules(modules);
//PhysicsSimulation physicsSimulation = currentModule.getSimulation();
//physicsSimulation.getModules().remove(currentModule);
//amountModules = jmeSimulation.getModules().size();
break;
}
}
}
}
| public void deleteModules(List<Integer> ids)throws RemoteException{
//jmeSimulation.getModules().clear();
for(int moduleID=0;moduleID<ids.size();moduleID++){
amountModules = jmeSimulation.getModules().size();
System.out.println("Size List:"+ jmeSimulation.getModules().size());
for (int index=0; index<amountModules; index++){
System.out.println("ID:"+ ids.get(moduleID));
int currentModuleID = jmeSimulation.getModules().get(index).getID();
Module currentModule =jmeSimulation.getModules().get(index);
int moduleToDeleteID = ids.get(moduleID);
if (currentModuleID==moduleToDeleteID ){
BuilderHelper.deleteModule(currentModule,true);
PhysicsSimulation simulation= currentModule.getSimulation();
List<Module> modules = simulation.getModules();
modules.remove(currentModule);
JMESimulation jmeSimulation =(JMESimulation)simulation;
jmeSimulation.setModules(modules);
//PhysicsSimulation physicsSimulation = currentModule.getSimulation();
//physicsSimulation.getModules().remove(currentModule);
//amountModules = jmeSimulation.getModules().size();
break;
}
}
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.ui/src/org/eclipse/tcf/te/tcf/processes/ui/internal/preferences/PreferencesInitializer.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.ui/src/org/eclipse/tcf/te/tcf/processes/ui/internal/preferences/PreferencesInitializer.java
index bd00b4aec..490d4b946 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.ui/src/org/eclipse/tcf/te/tcf/processes/ui/internal/preferences/PreferencesInitializer.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.ui/src/org/eclipse/tcf/te/tcf/processes/ui/internal/preferences/PreferencesInitializer.java
@@ -1,81 +1,82 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.processes.ui.internal.preferences;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.tcf.te.tcf.processes.ui.activator.UIPlugin;
/**
* The bundle's preference initializer implementation.
*/
public class PreferencesInitializer extends AbstractPreferenceInitializer implements IPreferenceConsts {
/**
* Constructor.
*/
public PreferencesInitializer() {
super();
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
IPreferenceStore preferenceStore = UIPlugin.getDefault().getPreferenceStore();
preferenceStore.setDefault(PREF_INTERVAL_GRADES, DEFAULT_INTERVAL_GRADES);
preferenceStore.setDefault(PREF_INTERVAL_MRU_COUNT, DEFAULT_INTERVAL_MRU_COUNT);
}
/**
* Update the most recently used interval adding
* a new interval.
*
* @param interval The new interval.
*/
public static void addMRUInterval(int interval){
+ if (interval <= 0 || DEFAULT_INTERVAL_GRADES.contains(":" + interval)) return; //$NON-NLS-1$
IPreferenceStore prefStore = UIPlugin.getDefault().getPreferenceStore();
String mruList = prefStore.getString(PREF_INTERVAL_MRU_LIST);
if (mruList == null || mruList.trim().length() == 0) {
mruList = "" + interval; //$NON-NLS-1$
}else{
StringTokenizer st = new StringTokenizer(mruList, ":"); //$NON-NLS-1$
int maxCount = prefStore.getInt(PREF_INTERVAL_MRU_COUNT);
boolean found = false;
while (st.hasMoreTokens()) {
String token = st.nextToken();
try {
int s = Integer.parseInt(token);
if(s == interval ) {
found = true;
break;
}
}
catch (NumberFormatException nfe) {
}
}
if(!found) {
mruList = mruList + ":" + interval; //$NON-NLS-1$
st = new StringTokenizer(mruList, ":"); //$NON-NLS-1$
if(st.countTokens() > maxCount) {
int comma = mruList.indexOf(":"); //$NON-NLS-1$
if(comma != -1) {
mruList = mruList.substring(comma+1);
}
}
}
}
prefStore.setValue(PREF_INTERVAL_MRU_LIST, mruList);
}
}
| true | true | public static void addMRUInterval(int interval){
IPreferenceStore prefStore = UIPlugin.getDefault().getPreferenceStore();
String mruList = prefStore.getString(PREF_INTERVAL_MRU_LIST);
if (mruList == null || mruList.trim().length() == 0) {
mruList = "" + interval; //$NON-NLS-1$
}else{
StringTokenizer st = new StringTokenizer(mruList, ":"); //$NON-NLS-1$
int maxCount = prefStore.getInt(PREF_INTERVAL_MRU_COUNT);
boolean found = false;
while (st.hasMoreTokens()) {
String token = st.nextToken();
try {
int s = Integer.parseInt(token);
if(s == interval ) {
found = true;
break;
}
}
catch (NumberFormatException nfe) {
}
}
if(!found) {
mruList = mruList + ":" + interval; //$NON-NLS-1$
st = new StringTokenizer(mruList, ":"); //$NON-NLS-1$
if(st.countTokens() > maxCount) {
int comma = mruList.indexOf(":"); //$NON-NLS-1$
if(comma != -1) {
mruList = mruList.substring(comma+1);
}
}
}
}
prefStore.setValue(PREF_INTERVAL_MRU_LIST, mruList);
}
| public static void addMRUInterval(int interval){
if (interval <= 0 || DEFAULT_INTERVAL_GRADES.contains(":" + interval)) return; //$NON-NLS-1$
IPreferenceStore prefStore = UIPlugin.getDefault().getPreferenceStore();
String mruList = prefStore.getString(PREF_INTERVAL_MRU_LIST);
if (mruList == null || mruList.trim().length() == 0) {
mruList = "" + interval; //$NON-NLS-1$
}else{
StringTokenizer st = new StringTokenizer(mruList, ":"); //$NON-NLS-1$
int maxCount = prefStore.getInt(PREF_INTERVAL_MRU_COUNT);
boolean found = false;
while (st.hasMoreTokens()) {
String token = st.nextToken();
try {
int s = Integer.parseInt(token);
if(s == interval ) {
found = true;
break;
}
}
catch (NumberFormatException nfe) {
}
}
if(!found) {
mruList = mruList + ":" + interval; //$NON-NLS-1$
st = new StringTokenizer(mruList, ":"); //$NON-NLS-1$
if(st.countTokens() > maxCount) {
int comma = mruList.indexOf(":"); //$NON-NLS-1$
if(comma != -1) {
mruList = mruList.substring(comma+1);
}
}
}
}
prefStore.setValue(PREF_INTERVAL_MRU_LIST, mruList);
}
|
diff --git a/servers/jain-slee/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java b/servers/jain-slee/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java
index 19df8324f..c0046c86f 100644
--- a/servers/jain-slee/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java
+++ b/servers/jain-slee/core/jar/src/main/java/org/mobicents/slee/container/management/SbbManagement.java
@@ -1,520 +1,526 @@
package org.mobicents.slee.container.management;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingException;
import javax.slee.facilities.AlarmFacility;
import javax.slee.facilities.Level;
import javax.slee.management.DeploymentException;
import javax.transaction.SystemException;
import org.jboss.logging.Logger;
import org.jboss.naming.NonSerializableFactory;
import org.mobicents.slee.container.SleeContainer;
import org.mobicents.slee.container.component.ComponentRepositoryImpl;
import org.mobicents.slee.container.component.ResourceAdaptorTypeComponent;
import org.mobicents.slee.container.component.SbbComponent;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.MEnvEntry;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.common.references.MEjbRef;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MResourceAdaptorEntityBinding;
import org.mobicents.slee.container.component.deployment.jaxb.descriptors.sbb.MResourceAdaptorTypeBinding;
import org.mobicents.slee.container.deployment.SbbClassCodeGenerator;
import org.mobicents.slee.container.service.ServiceActivityContextInterfaceFactoryImpl;
import org.mobicents.slee.container.service.ServiceActivityFactoryImpl;
import org.mobicents.slee.resource.ResourceAdaptorEntity;
import org.mobicents.slee.runtime.facilities.SbbAlarmFacilityImpl;
import org.mobicents.slee.runtime.facilities.TimerFacilityImpl;
import org.mobicents.slee.runtime.transaction.SleeTransactionManager;
/**
* Manages sbbs in container
*
* @author martins
*
*/
public class SbbManagement {
private static final Logger logger = Logger.getLogger(SbbManagement.class);
private final SleeContainer sleeContainer;
public SbbManagement(SleeContainer sleeContainer) {
this.sleeContainer = sleeContainer;
}
/**
* Deploys an SBB. This generates the code to convert abstract to concrete
* class and registers the component in the component table and creates an
* object pool for the sbb id.
*
* @param mobicentsSbbDescriptor
* the descriptor of the sbb to install
* @throws Exception
*/
public void installSbb(SbbComponent sbbComponent)
throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Installing " + sbbComponent);
}
final SleeTransactionManager sleeTransactionManager = sleeContainer
.getTransactionManager();
sleeTransactionManager.mandateTransaction();
// change classloader
ClassLoader oldClassLoader = Thread.currentThread()
.getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(
sbbComponent.getClassLoader());
// Set up the comp/env naming context for the Sbb.
setupSbbEnvironment(sbbComponent);
// generate class code for the sbb
new SbbClassCodeGenerator().process(sbbComponent);
//FIXME: this will erase stack trace.
//} catch (Exception ex) {
// throw ex;
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
// Set 1.0 Trace to off
sleeContainer.getTraceFacility().setTraceLevelOnTransaction(
sbbComponent.getSbbID(), Level.OFF);
sleeContainer.getAlarmFacility().registerComponent(
sbbComponent.getSbbID());
}
private void setupSbbEnvironment(SbbComponent sbbComponent) throws Exception {
Context ctx = (Context) new InitialContext().lookup("java:comp");
if (logger.isDebugEnabled()) {
logger.debug("Setting up SBB env. Initial context is " + ctx);
}
Context envCtx = null;
try {
envCtx = ctx.createSubcontext("env");
} catch (NameAlreadyBoundException ex) {
envCtx = (Context) ctx.lookup("env");
}
Context sleeCtx = null;
try {
sleeCtx = envCtx.createSubcontext("slee");
} catch (NameAlreadyBoundException ex) {
sleeCtx = (Context) envCtx.lookup("slee");
}
// Do all the context binding stuff just once during init and
// just do the linking here.
Context newCtx;
String containerName = "java:slee/container/Container";
try {
newCtx = sleeCtx.createSubcontext("container");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("container");
}
try {
newCtx.bind("Container", new LinkRef(containerName));
} catch (NameAlreadyBoundException ex) {
}
String nullAciFactory = "java:slee/nullactivity/nullactivitycontextinterfacefactory";
String nullActivityFactory = "java:slee/nullactivity/nullactivityfactory";
try {
newCtx = sleeCtx.createSubcontext("nullactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("nullactivity");
}
try {
newCtx.bind("activitycontextinterfacefactory", new LinkRef(
nullAciFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("factory", new LinkRef(nullActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String serviceActivityContextInterfaceFactory = "java:slee/serviceactivity/"
+ ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME;
String serviceActivityFactory = "java:slee/serviceactivity/"
+ ServiceActivityFactoryImpl.JNDI_NAME;
try {
newCtx = sleeCtx.createSubcontext("serviceactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("serviceactivity");
}
try {
newCtx.bind(ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME,
new LinkRef(serviceActivityContextInterfaceFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind(ServiceActivityFactoryImpl.JNDI_NAME, new LinkRef(
serviceActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String timer = "java:slee/facilities/" + TimerFacilityImpl.JNDI_NAME;
String aciNaming = "java:slee/facilities/activitycontextnaming";
try {
newCtx = sleeCtx.createSubcontext("facilities");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("facilities");
}
try {
newCtx.bind("timer", new LinkRef(timer));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("activitycontextnaming", new LinkRef(aciNaming));
} catch (NameAlreadyBoundException ex) {
}
String trace = "java:slee/facilities/trace";
try {
newCtx.bind("trace", new LinkRef(trace));
} catch (NameAlreadyBoundException ex) {
}
String alarm = "java:slee/facilities/alarm";
try {
//This has to be checked, to be sure sbb have it under correct jndi binding
AlarmFacility sbbAlarmFacility = new SbbAlarmFacilityImpl(sbbComponent.getSbbID(),sleeContainer.getAlarmFacility());
newCtx.bind("alarm", sbbAlarmFacility);
} catch (NameAlreadyBoundException ex) {
}
String profile = "java:slee/facilities/profile";
try {
newCtx.bind("profile", new LinkRef(profile));
} catch (NameAlreadyBoundException ex) {
}
String profilteTableAciFactory = "java:slee/facilities/profiletableactivitycontextinterfacefactory";
try {
newCtx.bind("profiletableactivitycontextinterfacefactory",
new LinkRef(profilteTableAciFactory));
} catch (NameAlreadyBoundException ex) {
}
// For each resource that the Sbb references, bind the implementing
// object name to its comp/env
if (logger.isDebugEnabled()) {
logger.debug("Number of Resource Bindings:"
+ sbbComponent.getDescriptor().getResourceAdaptorTypeBindings());
}
ComponentRepositoryImpl componentRepository = sleeContainer.getComponentRepositoryImpl();
for (MResourceAdaptorTypeBinding raTypeBinding : sbbComponent.getDescriptor().getResourceAdaptorTypeBindings()) {
ResourceAdaptorTypeComponent raTypeComponent = componentRepository.getComponentByID(raTypeBinding.getResourceAdaptorTypeRef());
for (MResourceAdaptorEntityBinding raEntityBinding : raTypeBinding.getResourceAdaptorEntityBinding()) {
String raObjectName = raEntityBinding.getResourceAdaptorObjectName();
String linkName = raEntityBinding.getResourceAdaptorEntityLink();
/*
* The Deployment descriptor specifies Zero or more
* resource-adaptor-entity-binding elements. Each
* resource-adaptor-entity-binding element binds an object that
* implements the resource adaptor interface of the resource
* adaptor type into the JNDI comp onent environment of the SBB
* (see Section 6.13.3). Each resource- adaptorentity- binding
* element contains the following sub-elements: A description
* element. This is an optional informational element. A
* resource-adaptor-object?name element. This element specifies
* the location within the JNDI component environment to which
* the object that implements the resource adaptor interface
* will be bound. A resource-adaptor-entity-link element. This
* is an optional element. It identifies the resource adaptor
* entity that provides the object that should be bound into the
* JNDI component environment of the SBB. The identified
* resource adaptor entity must be an instance of a resource
* adaptor whose resource adaptor type is specified by the
* resourceadaptor- type-ref sub-element of the enclosing
* resource-adaptortype- binding element.
*/
ResourceManagement resourceManagement = sleeContainer.getResourceManagement();
ResourceAdaptorEntity raEntity = resourceManagement
.getResourceAdaptorEntity(resourceManagement
.getResourceAdaptorEntityName(linkName));
if (raEntity == null)
throw new Exception(
"Could not find Resource adaptor Entity for Link Name: ["
+ linkName + "] of RA Type ["
+ raTypeComponent + "]");
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(raObjectName);
int tokenCount = local.size();
Context subContext = envCtx;
for (int i = 0; i < tokenCount - 1; i++) {
String nextTok = local.get(i);
try {
subContext.lookup(nextTok);
} catch (NameNotFoundException nfe) {
subContext.createSubcontext(nextTok);
} finally {
subContext = (Context) subContext.lookup(nextTok);
}
}
String lastTok = local.get(tokenCount - 1);
// Bind the resource adaptor instance to where the Sbb expects
// to find it.
if (logger.isDebugEnabled()) {
logger
.debug("setupSbbEnvironment: Binding a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
try {
- NonSerializableFactory.rebind(subContext, lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
- //subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
+ Object raSbbInterface = raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef());
+ if (raSbbInterface != null) {
+ NonSerializableFactory.rebind(subContext, lastTok,raSbbInterface);
+ //subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
+ }
+ else {
+ throw new DeploymentException("Unable to retrieve the RA interface for RA entity "+raEntity.getName()+" and RAType " +raTypeBinding.getResourceAdaptorTypeRef());
+ }
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
String localFactoryName = raTypeBinding.getActivityContextInterfaceFactoryName();
if (localFactoryName != null) {
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(localFactoryName);
int nameSize = local.size();
Context tempCtx = envCtx;
for (int a = 0; a < nameSize - 1; a++) {
String temp = local.get(a);
try {
tempCtx.lookup(temp);
} catch (NameNotFoundException ne) {
tempCtx.createSubcontext(temp);
} finally {
tempCtx = (Context) tempCtx.lookup(temp);
}
}
if (logger.isDebugEnabled()) {
logger
.debug(
"setupSbbEnvironment: Binding a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
String factoryRefName = local.get(nameSize - 1);
try {
tempCtx
.bind(factoryRefName,raTypeComponent.getActivityContextInterfaceFactory());
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
}
/*
* Bind the ejb-refs
*/
try {
envCtx.createSubcontext("ejb");
} catch (NameAlreadyBoundException ex) {
envCtx.lookup("ejb");
}
if (logger.isDebugEnabled()) {
logger.debug("Created ejb local context");
}
for (MEjbRef ejbRef : sbbComponent.getDescriptor().getEjbRefs()) {
String jndiName = ejbRef.getEjbRefName();
if (logger.isDebugEnabled()) {
logger.debug("Binding ejb: " + ejbRef.getEjbRefName()
+ " with link to " + jndiName);
}
try {
envCtx.bind(ejbRef.getEjbRefName(), new LinkRef(jndiName));
} catch (NameAlreadyBoundException ex) {
}
/*
* Validate the ejb reference has the correct type and classes as
* specified in deployment descriptor
*/
/*
* TODO I think I know the problem here. It seems the ejb is loaded
* AFTER the sbb is loaded, hence the validation fails here since it
* cannot locate the ejb. We need to force the ejb to be loaded
* before the sbb
*/
/*
* Commented out for now
*
*
* Object obj = new InitialContext().lookup("java:comp/env/" +
* ejbRef.getEjbRefName());
*
* Object homeObject = null; try { Class homeClass =
* Thread.currentThread().getContextClassLoader().loadClass(home);
*
* homeObject = PortableRemoteObject.narrow(obj, homeClass);
*
* if (!homeClass.isInstance(homeObject)) { throw new
* DeploymentException("Looked up ejb home is not an instanceof " +
* home); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + home); } catch
* (ClassCastException e) { throw new DeploymentException("Failed to
* lookup ejb reference using jndi name " + jndiName); }
*
* Object ejb = null; try { Method m =
* homeObject.getClass().getMethod("create", null); Object ejbObject =
* m.invoke(home, null);
*
* Class ejbClass =
* Thread.currentThread().getContextClassLoader().loadClass(remote);
* if (!ejbClass.isInstance(ejbObject)) { throw new
* DeploymentException("Looked up ejb object is not an instanceof " +
* remote); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + remote); }
*
*/
/*
* A note on the <ejb-link> link. The semantics of ejb-link when
* used to reference a remote ejb are not defined in the SLEE spec.
* In J2EE it is defined to mean a reference to an ejb deployed in
* the same J2EE application whose <ejb-name> is the same as the
* link (optionally the ejb-jar) file is also specifed. In SLEE
* there is no J2EE application and ejbs cannot be deployed in the
* SLEE container, therefore we do nothing with <ejb-link> since I
* am not sure what should be done with it anyway! - Tim
*/
}
/* Set the environment entries */
for (MEnvEntry mEnvEntry : sbbComponent.getDescriptor().getEnvEntries()) {
Class type = null;
if (logger.isDebugEnabled()) {
logger.debug("Got an environment entry:" + mEnvEntry);
}
try {
type = Thread.currentThread().getContextClassLoader()
.loadClass(mEnvEntry.getEnvEntryType());
} catch (Exception e) {
throw new DeploymentException(mEnvEntry.getEnvEntryType()
+ " is not a valid type for an environment entry");
}
Object entry = null;
String s = mEnvEntry.getEnvEntryValue();
try {
if (type == String.class) {
entry = new String(s);
} else if (type == Character.class) {
if (s.length() != 1) {
throw new DeploymentException(
s
+ " is not a valid value for an environment entry of type Character");
}
entry = new Character(s.charAt(0));
} else if (type == Integer.class) {
entry = new Integer(s);
} else if (type == Boolean.class) {
entry = new Boolean(s);
} else if (type == Double.class) {
entry = new Double(s);
} else if (type == Byte.class) {
entry = new Byte(s);
} else if (type == Short.class) {
entry = new Short(s);
} else if (type == Long.class) {
entry = new Long(s);
} else if (type == Float.class) {
entry = new Float(s);
}
} catch (NumberFormatException e) {
throw new DeploymentException("Environment entry value " + s
+ " is not a valid value for type " + type);
}
if (logger.isDebugEnabled()) {
logger.debug("Binding environment entry with name:"
+ mEnvEntry.getEnvEntryName() + " type " + entry.getClass()
+ " with value:" + entry + ". Current classloader = "
+ Thread.currentThread().getContextClassLoader());
}
try {
envCtx.bind(mEnvEntry.getEnvEntryName(), entry);
} catch (NameAlreadyBoundException ex) {
logger.error("Name already bound ! ", ex);
}
}
}
public void uninstallSbb(SbbComponent sbbComponent)
throws SystemException, Exception, NamingException {
final SleeTransactionManager sleeTransactionManager = sleeContainer
.getTransactionManager();
sleeTransactionManager.mandateTransaction();
if (logger.isDebugEnabled())
logger.debug("Uninstalling "+sbbComponent);
// remove sbb from trace and alarm facilities
sleeContainer.getTraceFacility().unSetTraceLevel(
sbbComponent.getSbbID());
sleeContainer.getAlarmFacility().unRegisterComponent(
sbbComponent.getSbbID());
if (logger.isDebugEnabled()) {
logger.debug("Removed SBB " + sbbComponent.getSbbID()
+ " from trace and alarm facilities");
}
}
}
| true | true | private void setupSbbEnvironment(SbbComponent sbbComponent) throws Exception {
Context ctx = (Context) new InitialContext().lookup("java:comp");
if (logger.isDebugEnabled()) {
logger.debug("Setting up SBB env. Initial context is " + ctx);
}
Context envCtx = null;
try {
envCtx = ctx.createSubcontext("env");
} catch (NameAlreadyBoundException ex) {
envCtx = (Context) ctx.lookup("env");
}
Context sleeCtx = null;
try {
sleeCtx = envCtx.createSubcontext("slee");
} catch (NameAlreadyBoundException ex) {
sleeCtx = (Context) envCtx.lookup("slee");
}
// Do all the context binding stuff just once during init and
// just do the linking here.
Context newCtx;
String containerName = "java:slee/container/Container";
try {
newCtx = sleeCtx.createSubcontext("container");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("container");
}
try {
newCtx.bind("Container", new LinkRef(containerName));
} catch (NameAlreadyBoundException ex) {
}
String nullAciFactory = "java:slee/nullactivity/nullactivitycontextinterfacefactory";
String nullActivityFactory = "java:slee/nullactivity/nullactivityfactory";
try {
newCtx = sleeCtx.createSubcontext("nullactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("nullactivity");
}
try {
newCtx.bind("activitycontextinterfacefactory", new LinkRef(
nullAciFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("factory", new LinkRef(nullActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String serviceActivityContextInterfaceFactory = "java:slee/serviceactivity/"
+ ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME;
String serviceActivityFactory = "java:slee/serviceactivity/"
+ ServiceActivityFactoryImpl.JNDI_NAME;
try {
newCtx = sleeCtx.createSubcontext("serviceactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("serviceactivity");
}
try {
newCtx.bind(ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME,
new LinkRef(serviceActivityContextInterfaceFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind(ServiceActivityFactoryImpl.JNDI_NAME, new LinkRef(
serviceActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String timer = "java:slee/facilities/" + TimerFacilityImpl.JNDI_NAME;
String aciNaming = "java:slee/facilities/activitycontextnaming";
try {
newCtx = sleeCtx.createSubcontext("facilities");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("facilities");
}
try {
newCtx.bind("timer", new LinkRef(timer));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("activitycontextnaming", new LinkRef(aciNaming));
} catch (NameAlreadyBoundException ex) {
}
String trace = "java:slee/facilities/trace";
try {
newCtx.bind("trace", new LinkRef(trace));
} catch (NameAlreadyBoundException ex) {
}
String alarm = "java:slee/facilities/alarm";
try {
//This has to be checked, to be sure sbb have it under correct jndi binding
AlarmFacility sbbAlarmFacility = new SbbAlarmFacilityImpl(sbbComponent.getSbbID(),sleeContainer.getAlarmFacility());
newCtx.bind("alarm", sbbAlarmFacility);
} catch (NameAlreadyBoundException ex) {
}
String profile = "java:slee/facilities/profile";
try {
newCtx.bind("profile", new LinkRef(profile));
} catch (NameAlreadyBoundException ex) {
}
String profilteTableAciFactory = "java:slee/facilities/profiletableactivitycontextinterfacefactory";
try {
newCtx.bind("profiletableactivitycontextinterfacefactory",
new LinkRef(profilteTableAciFactory));
} catch (NameAlreadyBoundException ex) {
}
// For each resource that the Sbb references, bind the implementing
// object name to its comp/env
if (logger.isDebugEnabled()) {
logger.debug("Number of Resource Bindings:"
+ sbbComponent.getDescriptor().getResourceAdaptorTypeBindings());
}
ComponentRepositoryImpl componentRepository = sleeContainer.getComponentRepositoryImpl();
for (MResourceAdaptorTypeBinding raTypeBinding : sbbComponent.getDescriptor().getResourceAdaptorTypeBindings()) {
ResourceAdaptorTypeComponent raTypeComponent = componentRepository.getComponentByID(raTypeBinding.getResourceAdaptorTypeRef());
for (MResourceAdaptorEntityBinding raEntityBinding : raTypeBinding.getResourceAdaptorEntityBinding()) {
String raObjectName = raEntityBinding.getResourceAdaptorObjectName();
String linkName = raEntityBinding.getResourceAdaptorEntityLink();
/*
* The Deployment descriptor specifies Zero or more
* resource-adaptor-entity-binding elements. Each
* resource-adaptor-entity-binding element binds an object that
* implements the resource adaptor interface of the resource
* adaptor type into the JNDI comp onent environment of the SBB
* (see Section 6.13.3). Each resource- adaptorentity- binding
* element contains the following sub-elements: A description
* element. This is an optional informational element. A
* resource-adaptor-object?name element. This element specifies
* the location within the JNDI component environment to which
* the object that implements the resource adaptor interface
* will be bound. A resource-adaptor-entity-link element. This
* is an optional element. It identifies the resource adaptor
* entity that provides the object that should be bound into the
* JNDI component environment of the SBB. The identified
* resource adaptor entity must be an instance of a resource
* adaptor whose resource adaptor type is specified by the
* resourceadaptor- type-ref sub-element of the enclosing
* resource-adaptortype- binding element.
*/
ResourceManagement resourceManagement = sleeContainer.getResourceManagement();
ResourceAdaptorEntity raEntity = resourceManagement
.getResourceAdaptorEntity(resourceManagement
.getResourceAdaptorEntityName(linkName));
if (raEntity == null)
throw new Exception(
"Could not find Resource adaptor Entity for Link Name: ["
+ linkName + "] of RA Type ["
+ raTypeComponent + "]");
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(raObjectName);
int tokenCount = local.size();
Context subContext = envCtx;
for (int i = 0; i < tokenCount - 1; i++) {
String nextTok = local.get(i);
try {
subContext.lookup(nextTok);
} catch (NameNotFoundException nfe) {
subContext.createSubcontext(nextTok);
} finally {
subContext = (Context) subContext.lookup(nextTok);
}
}
String lastTok = local.get(tokenCount - 1);
// Bind the resource adaptor instance to where the Sbb expects
// to find it.
if (logger.isDebugEnabled()) {
logger
.debug("setupSbbEnvironment: Binding a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
try {
NonSerializableFactory.rebind(subContext, lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
//subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
String localFactoryName = raTypeBinding.getActivityContextInterfaceFactoryName();
if (localFactoryName != null) {
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(localFactoryName);
int nameSize = local.size();
Context tempCtx = envCtx;
for (int a = 0; a < nameSize - 1; a++) {
String temp = local.get(a);
try {
tempCtx.lookup(temp);
} catch (NameNotFoundException ne) {
tempCtx.createSubcontext(temp);
} finally {
tempCtx = (Context) tempCtx.lookup(temp);
}
}
if (logger.isDebugEnabled()) {
logger
.debug(
"setupSbbEnvironment: Binding a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
String factoryRefName = local.get(nameSize - 1);
try {
tempCtx
.bind(factoryRefName,raTypeComponent.getActivityContextInterfaceFactory());
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
}
/*
* Bind the ejb-refs
*/
try {
envCtx.createSubcontext("ejb");
} catch (NameAlreadyBoundException ex) {
envCtx.lookup("ejb");
}
if (logger.isDebugEnabled()) {
logger.debug("Created ejb local context");
}
for (MEjbRef ejbRef : sbbComponent.getDescriptor().getEjbRefs()) {
String jndiName = ejbRef.getEjbRefName();
if (logger.isDebugEnabled()) {
logger.debug("Binding ejb: " + ejbRef.getEjbRefName()
+ " with link to " + jndiName);
}
try {
envCtx.bind(ejbRef.getEjbRefName(), new LinkRef(jndiName));
} catch (NameAlreadyBoundException ex) {
}
/*
* Validate the ejb reference has the correct type and classes as
* specified in deployment descriptor
*/
/*
* TODO I think I know the problem here. It seems the ejb is loaded
* AFTER the sbb is loaded, hence the validation fails here since it
* cannot locate the ejb. We need to force the ejb to be loaded
* before the sbb
*/
/*
* Commented out for now
*
*
* Object obj = new InitialContext().lookup("java:comp/env/" +
* ejbRef.getEjbRefName());
*
* Object homeObject = null; try { Class homeClass =
* Thread.currentThread().getContextClassLoader().loadClass(home);
*
* homeObject = PortableRemoteObject.narrow(obj, homeClass);
*
* if (!homeClass.isInstance(homeObject)) { throw new
* DeploymentException("Looked up ejb home is not an instanceof " +
* home); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + home); } catch
* (ClassCastException e) { throw new DeploymentException("Failed to
* lookup ejb reference using jndi name " + jndiName); }
*
* Object ejb = null; try { Method m =
* homeObject.getClass().getMethod("create", null); Object ejbObject =
* m.invoke(home, null);
*
* Class ejbClass =
* Thread.currentThread().getContextClassLoader().loadClass(remote);
* if (!ejbClass.isInstance(ejbObject)) { throw new
* DeploymentException("Looked up ejb object is not an instanceof " +
* remote); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + remote); }
*
*/
/*
* A note on the <ejb-link> link. The semantics of ejb-link when
* used to reference a remote ejb are not defined in the SLEE spec.
* In J2EE it is defined to mean a reference to an ejb deployed in
* the same J2EE application whose <ejb-name> is the same as the
* link (optionally the ejb-jar) file is also specifed. In SLEE
* there is no J2EE application and ejbs cannot be deployed in the
* SLEE container, therefore we do nothing with <ejb-link> since I
* am not sure what should be done with it anyway! - Tim
*/
}
/* Set the environment entries */
for (MEnvEntry mEnvEntry : sbbComponent.getDescriptor().getEnvEntries()) {
Class type = null;
if (logger.isDebugEnabled()) {
logger.debug("Got an environment entry:" + mEnvEntry);
}
try {
type = Thread.currentThread().getContextClassLoader()
.loadClass(mEnvEntry.getEnvEntryType());
} catch (Exception e) {
throw new DeploymentException(mEnvEntry.getEnvEntryType()
+ " is not a valid type for an environment entry");
}
Object entry = null;
String s = mEnvEntry.getEnvEntryValue();
try {
if (type == String.class) {
entry = new String(s);
} else if (type == Character.class) {
if (s.length() != 1) {
throw new DeploymentException(
s
+ " is not a valid value for an environment entry of type Character");
}
entry = new Character(s.charAt(0));
} else if (type == Integer.class) {
entry = new Integer(s);
} else if (type == Boolean.class) {
entry = new Boolean(s);
} else if (type == Double.class) {
entry = new Double(s);
} else if (type == Byte.class) {
entry = new Byte(s);
} else if (type == Short.class) {
entry = new Short(s);
} else if (type == Long.class) {
entry = new Long(s);
} else if (type == Float.class) {
entry = new Float(s);
}
} catch (NumberFormatException e) {
throw new DeploymentException("Environment entry value " + s
+ " is not a valid value for type " + type);
}
if (logger.isDebugEnabled()) {
logger.debug("Binding environment entry with name:"
+ mEnvEntry.getEnvEntryName() + " type " + entry.getClass()
+ " with value:" + entry + ". Current classloader = "
+ Thread.currentThread().getContextClassLoader());
}
try {
envCtx.bind(mEnvEntry.getEnvEntryName(), entry);
} catch (NameAlreadyBoundException ex) {
logger.error("Name already bound ! ", ex);
}
}
}
| private void setupSbbEnvironment(SbbComponent sbbComponent) throws Exception {
Context ctx = (Context) new InitialContext().lookup("java:comp");
if (logger.isDebugEnabled()) {
logger.debug("Setting up SBB env. Initial context is " + ctx);
}
Context envCtx = null;
try {
envCtx = ctx.createSubcontext("env");
} catch (NameAlreadyBoundException ex) {
envCtx = (Context) ctx.lookup("env");
}
Context sleeCtx = null;
try {
sleeCtx = envCtx.createSubcontext("slee");
} catch (NameAlreadyBoundException ex) {
sleeCtx = (Context) envCtx.lookup("slee");
}
// Do all the context binding stuff just once during init and
// just do the linking here.
Context newCtx;
String containerName = "java:slee/container/Container";
try {
newCtx = sleeCtx.createSubcontext("container");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("container");
}
try {
newCtx.bind("Container", new LinkRef(containerName));
} catch (NameAlreadyBoundException ex) {
}
String nullAciFactory = "java:slee/nullactivity/nullactivitycontextinterfacefactory";
String nullActivityFactory = "java:slee/nullactivity/nullactivityfactory";
try {
newCtx = sleeCtx.createSubcontext("nullactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("nullactivity");
}
try {
newCtx.bind("activitycontextinterfacefactory", new LinkRef(
nullAciFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("factory", new LinkRef(nullActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String serviceActivityContextInterfaceFactory = "java:slee/serviceactivity/"
+ ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME;
String serviceActivityFactory = "java:slee/serviceactivity/"
+ ServiceActivityFactoryImpl.JNDI_NAME;
try {
newCtx = sleeCtx.createSubcontext("serviceactivity");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("serviceactivity");
}
try {
newCtx.bind(ServiceActivityContextInterfaceFactoryImpl.JNDI_NAME,
new LinkRef(serviceActivityContextInterfaceFactory));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind(ServiceActivityFactoryImpl.JNDI_NAME, new LinkRef(
serviceActivityFactory));
} catch (NameAlreadyBoundException ex) {
}
String timer = "java:slee/facilities/" + TimerFacilityImpl.JNDI_NAME;
String aciNaming = "java:slee/facilities/activitycontextnaming";
try {
newCtx = sleeCtx.createSubcontext("facilities");
} catch (NameAlreadyBoundException ex) {
} finally {
newCtx = (Context) sleeCtx.lookup("facilities");
}
try {
newCtx.bind("timer", new LinkRef(timer));
} catch (NameAlreadyBoundException ex) {
}
try {
newCtx.bind("activitycontextnaming", new LinkRef(aciNaming));
} catch (NameAlreadyBoundException ex) {
}
String trace = "java:slee/facilities/trace";
try {
newCtx.bind("trace", new LinkRef(trace));
} catch (NameAlreadyBoundException ex) {
}
String alarm = "java:slee/facilities/alarm";
try {
//This has to be checked, to be sure sbb have it under correct jndi binding
AlarmFacility sbbAlarmFacility = new SbbAlarmFacilityImpl(sbbComponent.getSbbID(),sleeContainer.getAlarmFacility());
newCtx.bind("alarm", sbbAlarmFacility);
} catch (NameAlreadyBoundException ex) {
}
String profile = "java:slee/facilities/profile";
try {
newCtx.bind("profile", new LinkRef(profile));
} catch (NameAlreadyBoundException ex) {
}
String profilteTableAciFactory = "java:slee/facilities/profiletableactivitycontextinterfacefactory";
try {
newCtx.bind("profiletableactivitycontextinterfacefactory",
new LinkRef(profilteTableAciFactory));
} catch (NameAlreadyBoundException ex) {
}
// For each resource that the Sbb references, bind the implementing
// object name to its comp/env
if (logger.isDebugEnabled()) {
logger.debug("Number of Resource Bindings:"
+ sbbComponent.getDescriptor().getResourceAdaptorTypeBindings());
}
ComponentRepositoryImpl componentRepository = sleeContainer.getComponentRepositoryImpl();
for (MResourceAdaptorTypeBinding raTypeBinding : sbbComponent.getDescriptor().getResourceAdaptorTypeBindings()) {
ResourceAdaptorTypeComponent raTypeComponent = componentRepository.getComponentByID(raTypeBinding.getResourceAdaptorTypeRef());
for (MResourceAdaptorEntityBinding raEntityBinding : raTypeBinding.getResourceAdaptorEntityBinding()) {
String raObjectName = raEntityBinding.getResourceAdaptorObjectName();
String linkName = raEntityBinding.getResourceAdaptorEntityLink();
/*
* The Deployment descriptor specifies Zero or more
* resource-adaptor-entity-binding elements. Each
* resource-adaptor-entity-binding element binds an object that
* implements the resource adaptor interface of the resource
* adaptor type into the JNDI comp onent environment of the SBB
* (see Section 6.13.3). Each resource- adaptorentity- binding
* element contains the following sub-elements: A description
* element. This is an optional informational element. A
* resource-adaptor-object?name element. This element specifies
* the location within the JNDI component environment to which
* the object that implements the resource adaptor interface
* will be bound. A resource-adaptor-entity-link element. This
* is an optional element. It identifies the resource adaptor
* entity that provides the object that should be bound into the
* JNDI component environment of the SBB. The identified
* resource adaptor entity must be an instance of a resource
* adaptor whose resource adaptor type is specified by the
* resourceadaptor- type-ref sub-element of the enclosing
* resource-adaptortype- binding element.
*/
ResourceManagement resourceManagement = sleeContainer.getResourceManagement();
ResourceAdaptorEntity raEntity = resourceManagement
.getResourceAdaptorEntity(resourceManagement
.getResourceAdaptorEntityName(linkName));
if (raEntity == null)
throw new Exception(
"Could not find Resource adaptor Entity for Link Name: ["
+ linkName + "] of RA Type ["
+ raTypeComponent + "]");
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(raObjectName);
int tokenCount = local.size();
Context subContext = envCtx;
for (int i = 0; i < tokenCount - 1; i++) {
String nextTok = local.get(i);
try {
subContext.lookup(nextTok);
} catch (NameNotFoundException nfe) {
subContext.createSubcontext(nextTok);
} finally {
subContext = (Context) subContext.lookup(nextTok);
}
}
String lastTok = local.get(tokenCount - 1);
// Bind the resource adaptor instance to where the Sbb expects
// to find it.
if (logger.isDebugEnabled()) {
logger
.debug("setupSbbEnvironment: Binding a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
try {
Object raSbbInterface = raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef());
if (raSbbInterface != null) {
NonSerializableFactory.rebind(subContext, lastTok,raSbbInterface);
//subContext.bind(lastTok, raEntity.getResourceAdaptorInterface(raTypeBinding.getResourceAdaptorTypeRef()));
}
else {
throw new DeploymentException("Unable to retrieve the RA interface for RA entity "+raEntity.getName()+" and RAType " +raTypeBinding.getResourceAdaptorTypeRef());
}
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to sbb interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
String localFactoryName = raTypeBinding.getActivityContextInterfaceFactoryName();
if (localFactoryName != null) {
NameParser parser = ctx.getNameParser("");
Name local = parser.parse(localFactoryName);
int nameSize = local.size();
Context tempCtx = envCtx;
for (int a = 0; a < nameSize - 1; a++) {
String temp = local.get(a);
try {
tempCtx.lookup(temp);
} catch (NameNotFoundException ne) {
tempCtx.createSubcontext(temp);
} finally {
tempCtx = (Context) tempCtx.lookup(temp);
}
}
if (logger.isDebugEnabled()) {
logger
.debug(
"setupSbbEnvironment: Binding a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef());
}
String factoryRefName = local.get(nameSize - 1);
try {
tempCtx
.bind(factoryRefName,raTypeComponent.getActivityContextInterfaceFactory());
} catch (NameAlreadyBoundException e) {
logger.warn(
"setupSbbEnvironment: Unable to bind a JNDI reference to aci factory interface of "+raTypeBinding.getResourceAdaptorTypeRef(), e);
}
}
}
/*
* Bind the ejb-refs
*/
try {
envCtx.createSubcontext("ejb");
} catch (NameAlreadyBoundException ex) {
envCtx.lookup("ejb");
}
if (logger.isDebugEnabled()) {
logger.debug("Created ejb local context");
}
for (MEjbRef ejbRef : sbbComponent.getDescriptor().getEjbRefs()) {
String jndiName = ejbRef.getEjbRefName();
if (logger.isDebugEnabled()) {
logger.debug("Binding ejb: " + ejbRef.getEjbRefName()
+ " with link to " + jndiName);
}
try {
envCtx.bind(ejbRef.getEjbRefName(), new LinkRef(jndiName));
} catch (NameAlreadyBoundException ex) {
}
/*
* Validate the ejb reference has the correct type and classes as
* specified in deployment descriptor
*/
/*
* TODO I think I know the problem here. It seems the ejb is loaded
* AFTER the sbb is loaded, hence the validation fails here since it
* cannot locate the ejb. We need to force the ejb to be loaded
* before the sbb
*/
/*
* Commented out for now
*
*
* Object obj = new InitialContext().lookup("java:comp/env/" +
* ejbRef.getEjbRefName());
*
* Object homeObject = null; try { Class homeClass =
* Thread.currentThread().getContextClassLoader().loadClass(home);
*
* homeObject = PortableRemoteObject.narrow(obj, homeClass);
*
* if (!homeClass.isInstance(homeObject)) { throw new
* DeploymentException("Looked up ejb home is not an instanceof " +
* home); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + home); } catch
* (ClassCastException e) { throw new DeploymentException("Failed to
* lookup ejb reference using jndi name " + jndiName); }
*
* Object ejb = null; try { Method m =
* homeObject.getClass().getMethod("create", null); Object ejbObject =
* m.invoke(home, null);
*
* Class ejbClass =
* Thread.currentThread().getContextClassLoader().loadClass(remote);
* if (!ejbClass.isInstance(ejbObject)) { throw new
* DeploymentException("Looked up ejb object is not an instanceof " +
* remote); } } catch (ClassNotFoundException e) { throw new
* DeploymentException("Failed to load class " + remote); }
*
*/
/*
* A note on the <ejb-link> link. The semantics of ejb-link when
* used to reference a remote ejb are not defined in the SLEE spec.
* In J2EE it is defined to mean a reference to an ejb deployed in
* the same J2EE application whose <ejb-name> is the same as the
* link (optionally the ejb-jar) file is also specifed. In SLEE
* there is no J2EE application and ejbs cannot be deployed in the
* SLEE container, therefore we do nothing with <ejb-link> since I
* am not sure what should be done with it anyway! - Tim
*/
}
/* Set the environment entries */
for (MEnvEntry mEnvEntry : sbbComponent.getDescriptor().getEnvEntries()) {
Class type = null;
if (logger.isDebugEnabled()) {
logger.debug("Got an environment entry:" + mEnvEntry);
}
try {
type = Thread.currentThread().getContextClassLoader()
.loadClass(mEnvEntry.getEnvEntryType());
} catch (Exception e) {
throw new DeploymentException(mEnvEntry.getEnvEntryType()
+ " is not a valid type for an environment entry");
}
Object entry = null;
String s = mEnvEntry.getEnvEntryValue();
try {
if (type == String.class) {
entry = new String(s);
} else if (type == Character.class) {
if (s.length() != 1) {
throw new DeploymentException(
s
+ " is not a valid value for an environment entry of type Character");
}
entry = new Character(s.charAt(0));
} else if (type == Integer.class) {
entry = new Integer(s);
} else if (type == Boolean.class) {
entry = new Boolean(s);
} else if (type == Double.class) {
entry = new Double(s);
} else if (type == Byte.class) {
entry = new Byte(s);
} else if (type == Short.class) {
entry = new Short(s);
} else if (type == Long.class) {
entry = new Long(s);
} else if (type == Float.class) {
entry = new Float(s);
}
} catch (NumberFormatException e) {
throw new DeploymentException("Environment entry value " + s
+ " is not a valid value for type " + type);
}
if (logger.isDebugEnabled()) {
logger.debug("Binding environment entry with name:"
+ mEnvEntry.getEnvEntryName() + " type " + entry.getClass()
+ " with value:" + entry + ". Current classloader = "
+ Thread.currentThread().getContextClassLoader());
}
try {
envCtx.bind(mEnvEntry.getEnvEntryName(), entry);
} catch (NameAlreadyBoundException ex) {
logger.error("Name already bound ! ", ex);
}
}
}
|
diff --git a/WEB-INF/src/edu/wustl/common/beans/NameValueBean.java b/WEB-INF/src/edu/wustl/common/beans/NameValueBean.java
index 4514c08a3..e700725d6 100644
--- a/WEB-INF/src/edu/wustl/common/beans/NameValueBean.java
+++ b/WEB-INF/src/edu/wustl/common/beans/NameValueBean.java
@@ -1,88 +1,88 @@
/**
*<p>Title: </p>
*<p>Description: </p>
*<p>Copyright: (c) Washington University, School of Medicine 2004</p>
*<p>Company: Washington University, School of Medicine, St. Louis.</p>
*@author Aarti Sharma
*@version 1.0
*/
package edu.wustl.common.beans;
/**
*<p>Title: </p>
*<p>Description: </p>
*<p>Copyright: (c) Washington University, School of Medicine 2005</p>
*<p>Company: Washington University, School of Medicine, St. Louis.</p>
*@author Aarti Sharma
*@version 1.0
*/
public class NameValueBean implements Comparable
{
private String name=new String();
private String value=new String();
public NameValueBean()
{
}
public NameValueBean(String name, String value)
{
this.name = name;
this.value = value;
}
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return Returns the value.
*/
public String getValue()
{
return value;
}
/**
* @param value The value to set.
*/
public void setValue(String value)
{
this.value = value;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return new String("name:"+ name +" value:"+value);
}
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compareTo(Object obj)
{
if(obj instanceof NameValueBean)
{
NameValueBean nameValueBean = (NameValueBean)obj;
- return name.compareTo(nameValueBean.getName());
+ return name.toLowerCase().compareTo(nameValueBean.getName().toLowerCase());
}
return 0;
}
}
| true | true | public int compareTo(Object obj)
{
if(obj instanceof NameValueBean)
{
NameValueBean nameValueBean = (NameValueBean)obj;
return name.compareTo(nameValueBean.getName());
}
return 0;
}
| public int compareTo(Object obj)
{
if(obj instanceof NameValueBean)
{
NameValueBean nameValueBean = (NameValueBean)obj;
return name.toLowerCase().compareTo(nameValueBean.getName().toLowerCase());
}
return 0;
}
|
diff --git a/src/PongBall.java b/src/PongBall.java
index 417d0f4..a355a49 100644
--- a/src/PongBall.java
+++ b/src/PongBall.java
@@ -1,54 +1,54 @@
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class PongBall extends MoveableObject {
private double speedX = 1f;
private double speedY = 1f;
// Uses pythagoras to decide overall speed of the ball.
private double speedXY = Math.sqrt(speedX*speedX + speedY*speedY);
public PongBall() throws SlickException{
super();
object = new Image("data/ball.png");
sx = object.getWidth();
sy = object.getHeight();
}
/**
* Moves the pong ball. Makes it bounce on walls and players.
*/
@Override
public void move(String direction) {
px += speedX;
py += speedY;
}
public void wallBounce(){
speedY = -speedY;
}
public void playerBounce(MoveableObject player){
double ballLength = this.object.getHeight();
double ballCenterY = this.py + ballLength/2;
- double paddleLength = player.object.getWidth();
+ double paddleLength = player.object.getHeight();
double paddleCenterY = player.getPositionY() + paddleLength/2;
// This number decides the influence that the length between the
// ball and the player has on the bounce of the ball in Y speed.
// Number must be between 0 and 1.
final double influenceY = 0.75;
// Calculate the position of the ball relative to the center of
// the paddle, and express this as a number between -1 and 1
double posY = (ballCenterY - paddleCenterY) / (paddleLength/2);
speedY = speedXY * posY * influenceY;
// The new Y speed will always be nonzero as long as the X speed
// is less than the original overall speed.
speedX = Math.sqrt(speedXY*speedXY - speedY*speedY) *
(speedX > 0? -1 : 1);
}
}
| true | true | public void playerBounce(MoveableObject player){
double ballLength = this.object.getHeight();
double ballCenterY = this.py + ballLength/2;
double paddleLength = player.object.getWidth();
double paddleCenterY = player.getPositionY() + paddleLength/2;
// This number decides the influence that the length between the
// ball and the player has on the bounce of the ball in Y speed.
// Number must be between 0 and 1.
final double influenceY = 0.75;
// Calculate the position of the ball relative to the center of
// the paddle, and express this as a number between -1 and 1
double posY = (ballCenterY - paddleCenterY) / (paddleLength/2);
speedY = speedXY * posY * influenceY;
// The new Y speed will always be nonzero as long as the X speed
// is less than the original overall speed.
speedX = Math.sqrt(speedXY*speedXY - speedY*speedY) *
(speedX > 0? -1 : 1);
}
| public void playerBounce(MoveableObject player){
double ballLength = this.object.getHeight();
double ballCenterY = this.py + ballLength/2;
double paddleLength = player.object.getHeight();
double paddleCenterY = player.getPositionY() + paddleLength/2;
// This number decides the influence that the length between the
// ball and the player has on the bounce of the ball in Y speed.
// Number must be between 0 and 1.
final double influenceY = 0.75;
// Calculate the position of the ball relative to the center of
// the paddle, and express this as a number between -1 and 1
double posY = (ballCenterY - paddleCenterY) / (paddleLength/2);
speedY = speedXY * posY * influenceY;
// The new Y speed will always be nonzero as long as the X speed
// is less than the original overall speed.
speedX = Math.sqrt(speedXY*speedXY - speedY*speedY) *
(speedX > 0? -1 : 1);
}
|
diff --git a/src/com/android/gallery3d/app/CropImage.java b/src/com/android/gallery3d/app/CropImage.java
index 03cd48f..14d8be0 100644
--- a/src/com/android/gallery3d/app/CropImage.java
+++ b/src/com/android/gallery3d/app/CropImage.java
@@ -1,955 +1,955 @@
/*
* 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.gallery3d.app;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;
import com.android.gallery3d.R;
import com.android.gallery3d.common.BitmapUtils;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.data.DataManager;
import com.android.gallery3d.data.LocalImage;
import com.android.gallery3d.data.MediaItem;
import com.android.gallery3d.data.MediaObject;
import com.android.gallery3d.data.Path;
import com.android.gallery3d.picasasource.PicasaSource;
import com.android.gallery3d.ui.BitmapTileProvider;
import com.android.gallery3d.ui.CropView;
import com.android.gallery3d.ui.GLRoot;
import com.android.gallery3d.ui.SynchronizedHandler;
import com.android.gallery3d.ui.TileImageViewAdapter;
import com.android.gallery3d.util.Future;
import com.android.gallery3d.util.FutureListener;
import com.android.gallery3d.util.GalleryUtils;
import com.android.gallery3d.util.InterruptableOutputStream;
import com.android.gallery3d.util.ThreadPool.CancelListener;
import com.android.gallery3d.util.ThreadPool.Job;
import com.android.gallery3d.util.ThreadPool.JobContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* The activity can crop specific region of interest from an image.
*/
public class CropImage extends AbstractGalleryActivity {
private static final String TAG = "CropImage";
public static final String ACTION_CROP = "com.android.camera.action.CROP";
private static final int MAX_PIXEL_COUNT = 5 * 1000000; // 5M pixels
private static final int MAX_FILE_INDEX = 1000;
private static final int TILE_SIZE = 512;
private static final int BACKUP_PIXEL_COUNT = 480000; // around 800x600
private static final int MSG_LARGE_BITMAP = 1;
private static final int MSG_BITMAP = 2;
private static final int MSG_SAVE_COMPLETE = 3;
private static final int MSG_SHOW_SAVE_ERROR = 4;
private static final int MAX_BACKUP_IMAGE_SIZE = 320;
private static final int DEFAULT_COMPRESS_QUALITY = 90;
public static final String KEY_RETURN_DATA = "return-data";
public static final String KEY_CROPPED_RECT = "cropped-rect";
public static final String KEY_ASPECT_X = "aspectX";
public static final String KEY_ASPECT_Y = "aspectY";
public static final String KEY_SPOTLIGHT_X = "spotlightX";
public static final String KEY_SPOTLIGHT_Y = "spotlightY";
public static final String KEY_OUTPUT_X = "outputX";
public static final String KEY_OUTPUT_Y = "outputY";
public static final String KEY_SCALE = "scale";
public static final String KEY_DATA = "data";
public static final String KEY_SCALE_UP_IF_NEEDED = "scaleUpIfNeeded";
public static final String KEY_OUTPUT_FORMAT = "outputFormat";
public static final String KEY_SET_AS_WALLPAPER = "set-as-wallpaper";
public static final String KEY_NO_FACE_DETECTION = "noFaceDetection";
private static final String KEY_STATE = "state";
private static final int STATE_INIT = 0;
private static final int STATE_LOADED = 1;
private static final int STATE_SAVING = 2;
public static final String DOWNLOAD_STRING = "download";
public static final File DOWNLOAD_BUCKET = new File(
Environment.getExternalStorageDirectory(), DOWNLOAD_STRING);
public static final String CROP_ACTION = "com.android.camera.action.CROP";
private int mState = STATE_INIT;
private CropView mCropView;
private boolean mDoFaceDetection = true;
private Handler mMainHandler;
// We keep the following members so that we can free them
// mBitmap is the unrotated bitmap we pass in to mCropView for detect faces.
// mCropView is responsible for rotating it to the way that it is viewed by users.
private Bitmap mBitmap;
private BitmapTileProvider mBitmapTileProvider;
private BitmapRegionDecoder mRegionDecoder;
private Bitmap mBitmapInIntent;
private boolean mUseRegionDecoder = false;
private ProgressDialog mProgressDialog;
private Future<BitmapRegionDecoder> mLoadTask;
private Future<Bitmap> mLoadBitmapTask;
private Future<Intent> mSaveTask;
private MediaItem mMediaItem;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
// Initialize UI
setContentView(R.layout.cropimage);
mCropView = new CropView(this);
getGLRoot().setContentPane(mCropView);
mMainHandler = new SynchronizedHandler(getGLRoot()) {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_LARGE_BITMAP: {
mProgressDialog.dismiss();
onBitmapRegionDecoderAvailable((BitmapRegionDecoder) message.obj);
break;
}
case MSG_BITMAP: {
mProgressDialog.dismiss();
onBitmapAvailable((Bitmap) message.obj);
break;
}
case MSG_SHOW_SAVE_ERROR: {
mProgressDialog.dismiss();
setResult(RESULT_CANCELED);
Toast.makeText(CropImage.this,
CropImage.this.getString(R.string.save_error),
Toast.LENGTH_LONG).show();
finish();
}
case MSG_SAVE_COMPLETE: {
mProgressDialog.dismiss();
setResult(RESULT_OK, (Intent) message.obj);
finish();
break;
}
}
}
};
setCropParameters();
}
@Override
protected void onSaveInstanceState(Bundle saveState) {
saveState.putInt(KEY_STATE, mState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.crop, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cancel: {
setResult(RESULT_CANCELED);
finish();
break;
}
case R.id.save: {
onSaveClicked();
break;
}
}
return true;
}
private class SaveOutput implements Job<Intent> {
private RectF mCropRect;
public SaveOutput(RectF cropRect) {
mCropRect = cropRect;
}
public Intent run(JobContext jc) {
RectF cropRect = mCropRect;
Bundle extra = getIntent().getExtras();
Rect rect = new Rect(
Math.round(cropRect.left), Math.round(cropRect.top),
Math.round(cropRect.right), Math.round(cropRect.bottom));
Intent result = new Intent();
result.putExtra(KEY_CROPPED_RECT, rect);
Bitmap cropped = null;
boolean outputted = false;
if (extra != null) {
Uri uri = (Uri) extra.getParcelable(MediaStore.EXTRA_OUTPUT);
if (uri != null) {
if (jc.isCancelled()) return null;
outputted = true;
cropped = getCroppedImage(rect);
if (!saveBitmapToUri(jc, cropped, uri)) return null;
}
if (extra.getBoolean(KEY_RETURN_DATA, false)) {
if (jc.isCancelled()) return null;
outputted = true;
if (cropped == null) cropped = getCroppedImage(rect);
result.putExtra(KEY_DATA, cropped);
}
if (extra.getBoolean(KEY_SET_AS_WALLPAPER, false)) {
if (jc.isCancelled()) return null;
outputted = true;
if (cropped == null) cropped = getCroppedImage(rect);
if (!setAsWallpaper(jc, cropped)) return null;
}
}
if (!outputted) {
if (jc.isCancelled()) return null;
if (cropped == null) cropped = getCroppedImage(rect);
Uri data = saveToMediaProvider(jc, cropped);
if (data != null) result.setData(data);
}
return result;
}
}
public static String determineCompressFormat(MediaObject obj) {
String compressFormat = "JPEG";
if (obj instanceof MediaItem) {
String mime = ((MediaItem) obj).getMimeType();
if (mime.contains("png") || mime.contains("gif")) {
// Set the compress format to PNG for png and gif images
// because they may contain alpha values.
compressFormat = "PNG";
}
}
return compressFormat;
}
private boolean setAsWallpaper(JobContext jc, Bitmap wallpaper) {
try {
WallpaperManager.getInstance(this).setBitmap(wallpaper);
} catch (IOException e) {
Log.w(TAG, "fail to set wall paper", e);
}
return true;
}
private File saveMedia(
JobContext jc, Bitmap cropped, File directory, String filename) {
// Try file-1.jpg, file-2.jpg, ... until we find a filename
// which does not exist yet.
File candidate = null;
String fileExtension = getFileExtension();
for (int i = 1; i < MAX_FILE_INDEX; ++i) {
candidate = new File(directory, filename + "-" + i + "."
+ fileExtension);
try {
if (candidate.createNewFile()) break;
} catch (IOException e) {
Log.e(TAG, "fail to create new file: "
+ candidate.getAbsolutePath(), e);
return null;
}
}
if (!candidate.exists() || !candidate.isFile()) {
throw new RuntimeException("cannot create file: " + filename);
}
candidate.setReadable(true, false);
candidate.setWritable(true, false);
try {
FileOutputStream fos = new FileOutputStream(candidate);
try {
saveBitmapToOutputStream(jc, cropped,
convertExtensionToCompressFormat(fileExtension), fos);
} finally {
fos.close();
}
} catch (IOException e) {
Log.e(TAG, "fail to save image: "
+ candidate.getAbsolutePath(), e);
candidate.delete();
return null;
}
if (jc.isCancelled()) {
candidate.delete();
return null;
}
return candidate;
}
private Uri saveToMediaProvider(JobContext jc, Bitmap cropped) {
if (PicasaSource.isPicasaImage(mMediaItem)) {
return savePicasaImage(jc, cropped);
} else if (mMediaItem instanceof LocalImage) {
return saveLocalImage(jc, cropped);
} else {
Log.w(TAG, "no output for crop image " + mMediaItem);
return null;
}
}
private Uri savePicasaImage(JobContext jc, Bitmap cropped) {
if (!DOWNLOAD_BUCKET.isDirectory() && !DOWNLOAD_BUCKET.mkdirs()) {
throw new RuntimeException("cannot create download folder");
}
String filename = PicasaSource.getImageTitle(mMediaItem);
int pos = filename.lastIndexOf('.');
if (pos >= 0) filename = filename.substring(0, pos);
File output = saveMedia(jc, cropped, DOWNLOAD_BUCKET, filename);
if (output == null) return null;
copyExif(mMediaItem, output.getAbsolutePath(), cropped.getWidth(), cropped.getHeight());
long now = System.currentTimeMillis() / 1000;
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, PicasaSource.getImageTitle(mMediaItem));
values.put(Images.Media.DISPLAY_NAME, output.getName());
values.put(Images.Media.DATE_TAKEN, PicasaSource.getDateTaken(mMediaItem));
values.put(Images.Media.DATE_MODIFIED, now);
values.put(Images.Media.DATE_ADDED, now);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.ORIENTATION, 0);
values.put(Images.Media.DATA, output.getAbsolutePath());
values.put(Images.Media.SIZE, output.length());
double latitude = PicasaSource.getLatitude(mMediaItem);
double longitude = PicasaSource.getLongitude(mMediaItem);
if (GalleryUtils.isValidLocation(latitude, longitude)) {
values.put(Images.Media.LATITUDE, latitude);
values.put(Images.Media.LONGITUDE, longitude);
}
return getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
}
private Uri saveLocalImage(JobContext jc, Bitmap cropped) {
LocalImage localImage = (LocalImage) mMediaItem;
File oldPath = new File(localImage.filePath);
File directory = new File(oldPath.getParent());
String filename = oldPath.getName();
int pos = filename.lastIndexOf('.');
if (pos >= 0) filename = filename.substring(0, pos);
File output = saveMedia(jc, cropped, directory, filename);
if (output == null) return null;
copyExif(oldPath.getAbsolutePath(), output.getAbsolutePath(),
cropped.getWidth(), cropped.getHeight());
long now = System.currentTimeMillis() / 1000;
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, localImage.caption);
values.put(Images.Media.DISPLAY_NAME, output.getName());
values.put(Images.Media.DATE_TAKEN, localImage.dateTakenInMs);
values.put(Images.Media.DATE_MODIFIED, now);
values.put(Images.Media.DATE_ADDED, now);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.ORIENTATION, 0);
values.put(Images.Media.DATA, output.getAbsolutePath());
values.put(Images.Media.SIZE, output.length());
if (GalleryUtils.isValidLocation(localImage.latitude, localImage.longitude)) {
values.put(Images.Media.LATITUDE, localImage.latitude);
values.put(Images.Media.LONGITUDE, localImage.longitude);
}
return getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
}
private boolean saveBitmapToOutputStream(
JobContext jc, Bitmap bitmap, CompressFormat format, OutputStream os) {
// We wrap the OutputStream so that it can be interrupted.
final InterruptableOutputStream ios = new InterruptableOutputStream(os);
jc.setCancelListener(new CancelListener() {
public void onCancel() {
ios.interrupt();
}
});
try {
bitmap.compress(format, DEFAULT_COMPRESS_QUALITY, os);
return !jc.isCancelled();
} finally {
jc.setCancelListener(null);
Utils.closeSilently(os);
}
}
private boolean saveBitmapToUri(JobContext jc, Bitmap bitmap, Uri uri) {
try {
return saveBitmapToOutputStream(jc, bitmap,
convertExtensionToCompressFormat(getFileExtension()),
getContentResolver().openOutputStream(uri));
} catch (FileNotFoundException e) {
Log.w(TAG, "cannot write output", e);
}
return true;
}
private CompressFormat convertExtensionToCompressFormat(String extension) {
return extension.equals("png")
? CompressFormat.PNG
: CompressFormat.JPEG;
}
private String getFileExtension() {
String requestFormat = getIntent().getStringExtra(KEY_OUTPUT_FORMAT);
String outputFormat = (requestFormat == null)
? determineCompressFormat(mMediaItem)
: requestFormat;
outputFormat = outputFormat.toLowerCase();
return (outputFormat.equals("png") || outputFormat.equals("gif"))
? "png" // We don't support gif compression.
: "jpg";
}
private void onSaveClicked() {
Bundle extra = getIntent().getExtras();
RectF cropRect = mCropView.getCropRectangle();
if (cropRect == null) return;
mState = STATE_SAVING;
int messageId = extra != null && extra.getBoolean(KEY_SET_AS_WALLPAPER)
? R.string.wallpaper
: R.string.saving_image;
mProgressDialog = ProgressDialog.show(
this, null, getString(messageId), true, false);
mSaveTask = getThreadPool().submit(new SaveOutput(cropRect),
new FutureListener<Intent>() {
public void onFutureDone(Future<Intent> future) {
mSaveTask = null;
if (future.isCancelled()) return;
Intent intent = future.get();
if (intent != null) {
mMainHandler.sendMessage(mMainHandler.obtainMessage(
MSG_SAVE_COMPLETE, intent));
} else {
mMainHandler.sendEmptyMessage(MSG_SHOW_SAVE_ERROR);
}
}
});
}
private Bitmap getCroppedImage(Rect rect) {
Utils.assertTrue(rect.width() > 0 && rect.height() > 0);
Bundle extras = getIntent().getExtras();
// (outputX, outputY) = the width and height of the returning bitmap.
int outputX = rect.width();
int outputY = rect.height();
if (extras != null) {
outputX = extras.getInt(KEY_OUTPUT_X, outputX);
outputY = extras.getInt(KEY_OUTPUT_Y, outputY);
}
if (outputX * outputY > MAX_PIXEL_COUNT) {
float scale = (float) Math.sqrt(
(double) MAX_PIXEL_COUNT / outputX / outputY);
Log.w(TAG, "scale down the cropped image: " + scale);
outputX = Math.round(scale * outputX);
outputY = Math.round(scale * outputY);
}
// (rect.width() * scaleX, rect.height() * scaleY) =
// the size of drawing area in output bitmap
float scaleX = 1;
float scaleY = 1;
Rect dest = new Rect(0, 0, outputX, outputY);
if (extras == null || extras.getBoolean(KEY_SCALE, true)) {
scaleX = (float) outputX / rect.width();
scaleY = (float) outputY / rect.height();
if (extras == null || !extras.getBoolean(
KEY_SCALE_UP_IF_NEEDED, false)) {
if (scaleX > 1f) scaleX = 1;
if (scaleY > 1f) scaleY = 1;
}
}
// Keep the content in the center (or crop the content)
int rectWidth = Math.round(rect.width() * scaleX);
int rectHeight = Math.round(rect.height() * scaleY);
dest.set(Math.round((outputX - rectWidth) / 2f),
Math.round((outputY - rectHeight) / 2f),
Math.round((outputX + rectWidth) / 2f),
Math.round((outputY + rectHeight) / 2f));
if (mBitmapInIntent != null) {
Bitmap source = mBitmapInIntent;
Bitmap result = Bitmap.createBitmap(
outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(source, rect, dest, null);
return result;
}
- int rotation = mMediaItem.getRotation();
+ int rotation = mMediaItem.getFullImageRotation();
rotateRectangle(rect, mCropView.getImageWidth(),
mCropView.getImageHeight(), 360 - rotation);
rotateRectangle(dest, outputX, outputY, 360 - rotation);
if (mUseRegionDecoder) {
BitmapFactory.Options options = new BitmapFactory.Options();
int sample = BitmapUtils.computeSampleSizeLarger(
Math.max(scaleX, scaleY));
options.inSampleSize = sample;
if ((rect.width() / sample) == dest.width()
&& (rect.height() / sample) == dest.height()
&& rotation == 0) {
// To prevent concurrent access in GLThread
synchronized (mRegionDecoder) {
return mRegionDecoder.decodeRegion(rect, options);
}
}
Bitmap result = Bitmap.createBitmap(
outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rotateCanvas(canvas, outputX, outputY, rotation);
drawInTiles(canvas, mRegionDecoder, rect, dest, sample);
return result;
} else {
Bitmap result = Bitmap.createBitmap(outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rotateCanvas(canvas, outputX, outputY, rotation);
canvas.drawBitmap(mBitmap,
rect, dest, new Paint(Paint.FILTER_BITMAP_FLAG));
return result;
}
}
private static void rotateCanvas(
Canvas canvas, int width, int height, int rotation) {
canvas.translate(width / 2, height / 2);
canvas.rotate(rotation);
if (((rotation / 90) & 0x01) == 0) {
canvas.translate(-width / 2, -height / 2);
} else {
canvas.translate(-height / 2, -width / 2);
}
}
private static void rotateRectangle(
Rect rect, int width, int height, int rotation) {
if (rotation == 0 || rotation == 360) return;
int w = rect.width();
int h = rect.height();
switch (rotation) {
case 90: {
rect.top = rect.left;
rect.left = height - rect.bottom;
rect.right = rect.left + h;
rect.bottom = rect.top + w;
return;
}
case 180: {
rect.left = width - rect.right;
rect.top = height - rect.bottom;
rect.right = rect.left + w;
rect.bottom = rect.top + h;
return;
}
case 270: {
rect.left = rect.top;
rect.top = width - rect.right;
rect.right = rect.left + h;
rect.bottom = rect.top + w;
return;
}
default: throw new AssertionError();
}
}
private void drawInTiles(Canvas canvas,
BitmapRegionDecoder decoder, Rect rect, Rect dest, int sample) {
int tileSize = TILE_SIZE * sample;
Rect tileRect = new Rect();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888;
options.inSampleSize = sample;
canvas.translate(dest.left, dest.top);
canvas.scale((float) sample * dest.width() / rect.width(),
(float) sample * dest.height() / rect.height());
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
for (int tx = rect.left, x = 0;
tx < rect.right; tx += tileSize, x += TILE_SIZE) {
for (int ty = rect.top, y = 0;
ty < rect.bottom; ty += tileSize, y += TILE_SIZE) {
tileRect.set(tx, ty, tx + tileSize, ty + tileSize);
if (tileRect.intersect(rect)) {
Bitmap bitmap;
// To prevent concurrent access in GLThread
synchronized (decoder) {
bitmap = decoder.decodeRegion(tileRect, options);
}
canvas.drawBitmap(bitmap, x, y, paint);
bitmap.recycle();
}
}
}
}
private void onBitmapRegionDecoderAvailable(
BitmapRegionDecoder regionDecoder) {
if (regionDecoder == null) {
Toast.makeText(this, "fail to load image", Toast.LENGTH_SHORT).show();
finish();
return;
}
mRegionDecoder = regionDecoder;
mUseRegionDecoder = true;
mState = STATE_LOADED;
BitmapFactory.Options options = new BitmapFactory.Options();
int width = regionDecoder.getWidth();
int height = regionDecoder.getHeight();
options.inSampleSize = BitmapUtils.computeSampleSize(width, height,
BitmapUtils.UNCONSTRAINED, BACKUP_PIXEL_COUNT);
mBitmap = regionDecoder.decodeRegion(
new Rect(0, 0, width, height), options);
mCropView.setDataModel(new TileImageViewAdapter(
mBitmap, regionDecoder), mMediaItem.getRotation());
if (mDoFaceDetection) {
mCropView.detectFaces(mBitmap);
} else {
mCropView.initializeHighlightRectangle();
}
}
private void onBitmapAvailable(Bitmap bitmap) {
if (bitmap == null) {
Toast.makeText(this, "fail to load image", Toast.LENGTH_SHORT).show();
finish();
return;
}
mUseRegionDecoder = false;
mState = STATE_LOADED;
mBitmap = bitmap;
BitmapFactory.Options options = new BitmapFactory.Options();
mCropView.setDataModel(new BitmapTileProvider(bitmap, 512),
mMediaItem.getRotation());
if (mDoFaceDetection) {
mCropView.detectFaces(bitmap);
} else {
mCropView.initializeHighlightRectangle();
}
}
private void setCropParameters() {
Bundle extras = getIntent().getExtras();
if (extras == null)
return;
int aspectX = extras.getInt(KEY_ASPECT_X, 0);
int aspectY = extras.getInt(KEY_ASPECT_Y, 0);
if (aspectX != 0 && aspectY != 0) {
mCropView.setAspectRatio((float) aspectX / aspectY);
}
float spotlightX = extras.getFloat(KEY_SPOTLIGHT_X, 0);
float spotlightY = extras.getFloat(KEY_SPOTLIGHT_Y, 0);
if (spotlightX != 0 && spotlightY != 0) {
mCropView.setSpotlightRatio(spotlightX, spotlightY);
}
}
private void initializeData() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey(KEY_NO_FACE_DETECTION)) {
mDoFaceDetection = !extras.getBoolean(KEY_NO_FACE_DETECTION);
}
mBitmapInIntent = extras.getParcelable(KEY_DATA);
if (mBitmapInIntent != null) {
mBitmapTileProvider =
new BitmapTileProvider(mBitmapInIntent, MAX_BACKUP_IMAGE_SIZE);
mCropView.setDataModel(mBitmapTileProvider, 0);
if (mDoFaceDetection) {
mCropView.detectFaces(mBitmapInIntent);
} else {
mCropView.initializeHighlightRectangle();
}
mState = STATE_LOADED;
return;
}
}
mProgressDialog = ProgressDialog.show(
this, null, getString(R.string.loading_image), true, false);
mMediaItem = getMediaItemFromIntentData();
if (mMediaItem == null) return;
boolean supportedByBitmapRegionDecoder =
(mMediaItem.getSupportedOperations() & MediaItem.SUPPORT_FULL_IMAGE) != 0;
if (supportedByBitmapRegionDecoder) {
mLoadTask = getThreadPool().submit(new LoadDataTask(mMediaItem),
new FutureListener<BitmapRegionDecoder>() {
public void onFutureDone(Future<BitmapRegionDecoder> future) {
mLoadTask = null;
BitmapRegionDecoder decoder = future.get();
if (future.isCancelled()) {
if (decoder != null) decoder.recycle();
return;
}
mMainHandler.sendMessage(mMainHandler.obtainMessage(
MSG_LARGE_BITMAP, decoder));
}
});
} else {
mLoadBitmapTask = getThreadPool().submit(new LoadBitmapDataTask(mMediaItem),
new FutureListener<Bitmap>() {
public void onFutureDone(Future<Bitmap> future) {
mLoadBitmapTask = null;
Bitmap bitmap = future.get();
if (future.isCancelled()) {
if (bitmap != null) bitmap.recycle();
return;
}
mMainHandler.sendMessage(mMainHandler.obtainMessage(
MSG_BITMAP, bitmap));
}
});
}
}
@Override
protected void onResume() {
super.onResume();
if (mState == STATE_INIT) initializeData();
if (mState == STATE_SAVING) onSaveClicked();
// TODO: consider to do it in GLView system
GLRoot root = getGLRoot();
root.lockRenderThread();
try {
mCropView.resume();
} finally {
root.unlockRenderThread();
}
}
@Override
protected void onPause() {
super.onPause();
Future<BitmapRegionDecoder> loadTask = mLoadTask;
if (loadTask != null && !loadTask.isDone()) {
// load in progress, try to cancel it
loadTask.cancel();
loadTask.waitDone();
mProgressDialog.dismiss();
}
Future<Bitmap> loadBitmapTask = mLoadBitmapTask;
if (loadBitmapTask != null && !loadBitmapTask.isDone()) {
// load in progress, try to cancel it
loadBitmapTask.cancel();
loadBitmapTask.waitDone();
mProgressDialog.dismiss();
}
Future<Intent> saveTask = mSaveTask;
if (saveTask != null && !saveTask.isDone()) {
// save in progress, try to cancel it
saveTask.cancel();
saveTask.waitDone();
mProgressDialog.dismiss();
}
GLRoot root = getGLRoot();
root.lockRenderThread();
try {
mCropView.pause();
} finally {
root.unlockRenderThread();
}
}
private MediaItem getMediaItemFromIntentData() {
Uri uri = getIntent().getData();
DataManager manager = getDataManager();
if (uri == null) {
Log.w(TAG, "no data given");
return null;
}
Path path = manager.findPathByUri(uri);
if (path == null) {
Log.w(TAG, "cannot get path for: " + uri);
return null;
}
return (MediaItem) manager.getMediaObject(path);
}
private class LoadDataTask implements Job<BitmapRegionDecoder> {
MediaItem mItem;
public LoadDataTask(MediaItem item) {
mItem = item;
}
public BitmapRegionDecoder run(JobContext jc) {
return mItem == null ? null : mItem.requestLargeImage().run(jc);
}
}
private class LoadBitmapDataTask implements Job<Bitmap> {
MediaItem mItem;
public LoadBitmapDataTask(MediaItem item) {
mItem = item;
}
public Bitmap run(JobContext jc) {
return mItem == null
? null
: mItem.requestImage(MediaItem.TYPE_THUMBNAIL).run(jc);
}
}
private static final String[] EXIF_TAGS = {
ExifInterface.TAG_DATETIME,
ExifInterface.TAG_MAKE,
ExifInterface.TAG_MODEL,
ExifInterface.TAG_FLASH,
ExifInterface.TAG_GPS_LATITUDE,
ExifInterface.TAG_GPS_LONGITUDE,
ExifInterface.TAG_GPS_LATITUDE_REF,
ExifInterface.TAG_GPS_LONGITUDE_REF,
ExifInterface.TAG_GPS_ALTITUDE,
ExifInterface.TAG_GPS_ALTITUDE_REF,
ExifInterface.TAG_GPS_TIMESTAMP,
ExifInterface.TAG_GPS_DATESTAMP,
ExifInterface.TAG_WHITE_BALANCE,
ExifInterface.TAG_FOCAL_LENGTH,
ExifInterface.TAG_GPS_PROCESSING_METHOD};
private static void copyExif(MediaItem item, String destination, int newWidth, int newHeight) {
try {
ExifInterface newExif = new ExifInterface(destination);
PicasaSource.extractExifValues(item, newExif);
newExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, String.valueOf(newWidth));
newExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, String.valueOf(newHeight));
newExif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(0));
newExif.saveAttributes();
} catch (Throwable t) {
Log.w(TAG, "cannot copy exif: " + item, t);
}
}
private static void copyExif(String source, String destination, int newWidth, int newHeight) {
try {
ExifInterface oldExif = new ExifInterface(source);
ExifInterface newExif = new ExifInterface(destination);
newExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, String.valueOf(newWidth));
newExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, String.valueOf(newHeight));
newExif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(0));
for (String tag : EXIF_TAGS) {
String value = oldExif.getAttribute(tag);
if (value != null) {
newExif.setAttribute(tag, value);
}
}
// Handle some special values here
String value = oldExif.getAttribute(ExifInterface.TAG_APERTURE);
if (value != null) {
try {
float aperture = Float.parseFloat(value);
newExif.setAttribute(ExifInterface.TAG_APERTURE,
String.valueOf((int) (aperture * 10 + 0.5f)) + "/10");
} catch (NumberFormatException e) {
Log.w(TAG, "cannot parse aperture: " + value);
}
}
// TODO: The code is broken, need to fix the JHEAD lib
/*
value = oldExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME);
if (value != null) {
try {
double exposure = Double.parseDouble(value);
testToRational("test exposure", exposure);
newExif.setAttribute(ExifInterface.TAG_EXPOSURE_TIME, value);
} catch (NumberFormatException e) {
Log.w(TAG, "cannot parse exposure time: " + value);
}
}
value = oldExif.getAttribute(ExifInterface.TAG_ISO);
if (value != null) {
try {
int iso = Integer.parseInt(value);
newExif.setAttribute(ExifInterface.TAG_ISO, String.valueOf(iso) + "/1");
} catch (NumberFormatException e) {
Log.w(TAG, "cannot parse exposure time: " + value);
}
}*/
newExif.saveAttributes();
} catch (Throwable t) {
Log.w(TAG, "cannot copy exif: " + source, t);
}
}
}
| true | true | private Bitmap getCroppedImage(Rect rect) {
Utils.assertTrue(rect.width() > 0 && rect.height() > 0);
Bundle extras = getIntent().getExtras();
// (outputX, outputY) = the width and height of the returning bitmap.
int outputX = rect.width();
int outputY = rect.height();
if (extras != null) {
outputX = extras.getInt(KEY_OUTPUT_X, outputX);
outputY = extras.getInt(KEY_OUTPUT_Y, outputY);
}
if (outputX * outputY > MAX_PIXEL_COUNT) {
float scale = (float) Math.sqrt(
(double) MAX_PIXEL_COUNT / outputX / outputY);
Log.w(TAG, "scale down the cropped image: " + scale);
outputX = Math.round(scale * outputX);
outputY = Math.round(scale * outputY);
}
// (rect.width() * scaleX, rect.height() * scaleY) =
// the size of drawing area in output bitmap
float scaleX = 1;
float scaleY = 1;
Rect dest = new Rect(0, 0, outputX, outputY);
if (extras == null || extras.getBoolean(KEY_SCALE, true)) {
scaleX = (float) outputX / rect.width();
scaleY = (float) outputY / rect.height();
if (extras == null || !extras.getBoolean(
KEY_SCALE_UP_IF_NEEDED, false)) {
if (scaleX > 1f) scaleX = 1;
if (scaleY > 1f) scaleY = 1;
}
}
// Keep the content in the center (or crop the content)
int rectWidth = Math.round(rect.width() * scaleX);
int rectHeight = Math.round(rect.height() * scaleY);
dest.set(Math.round((outputX - rectWidth) / 2f),
Math.round((outputY - rectHeight) / 2f),
Math.round((outputX + rectWidth) / 2f),
Math.round((outputY + rectHeight) / 2f));
if (mBitmapInIntent != null) {
Bitmap source = mBitmapInIntent;
Bitmap result = Bitmap.createBitmap(
outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(source, rect, dest, null);
return result;
}
int rotation = mMediaItem.getRotation();
rotateRectangle(rect, mCropView.getImageWidth(),
mCropView.getImageHeight(), 360 - rotation);
rotateRectangle(dest, outputX, outputY, 360 - rotation);
if (mUseRegionDecoder) {
BitmapFactory.Options options = new BitmapFactory.Options();
int sample = BitmapUtils.computeSampleSizeLarger(
Math.max(scaleX, scaleY));
options.inSampleSize = sample;
if ((rect.width() / sample) == dest.width()
&& (rect.height() / sample) == dest.height()
&& rotation == 0) {
// To prevent concurrent access in GLThread
synchronized (mRegionDecoder) {
return mRegionDecoder.decodeRegion(rect, options);
}
}
Bitmap result = Bitmap.createBitmap(
outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rotateCanvas(canvas, outputX, outputY, rotation);
drawInTiles(canvas, mRegionDecoder, rect, dest, sample);
return result;
} else {
Bitmap result = Bitmap.createBitmap(outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rotateCanvas(canvas, outputX, outputY, rotation);
canvas.drawBitmap(mBitmap,
rect, dest, new Paint(Paint.FILTER_BITMAP_FLAG));
return result;
}
}
| private Bitmap getCroppedImage(Rect rect) {
Utils.assertTrue(rect.width() > 0 && rect.height() > 0);
Bundle extras = getIntent().getExtras();
// (outputX, outputY) = the width and height of the returning bitmap.
int outputX = rect.width();
int outputY = rect.height();
if (extras != null) {
outputX = extras.getInt(KEY_OUTPUT_X, outputX);
outputY = extras.getInt(KEY_OUTPUT_Y, outputY);
}
if (outputX * outputY > MAX_PIXEL_COUNT) {
float scale = (float) Math.sqrt(
(double) MAX_PIXEL_COUNT / outputX / outputY);
Log.w(TAG, "scale down the cropped image: " + scale);
outputX = Math.round(scale * outputX);
outputY = Math.round(scale * outputY);
}
// (rect.width() * scaleX, rect.height() * scaleY) =
// the size of drawing area in output bitmap
float scaleX = 1;
float scaleY = 1;
Rect dest = new Rect(0, 0, outputX, outputY);
if (extras == null || extras.getBoolean(KEY_SCALE, true)) {
scaleX = (float) outputX / rect.width();
scaleY = (float) outputY / rect.height();
if (extras == null || !extras.getBoolean(
KEY_SCALE_UP_IF_NEEDED, false)) {
if (scaleX > 1f) scaleX = 1;
if (scaleY > 1f) scaleY = 1;
}
}
// Keep the content in the center (or crop the content)
int rectWidth = Math.round(rect.width() * scaleX);
int rectHeight = Math.round(rect.height() * scaleY);
dest.set(Math.round((outputX - rectWidth) / 2f),
Math.round((outputY - rectHeight) / 2f),
Math.round((outputX + rectWidth) / 2f),
Math.round((outputY + rectHeight) / 2f));
if (mBitmapInIntent != null) {
Bitmap source = mBitmapInIntent;
Bitmap result = Bitmap.createBitmap(
outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(source, rect, dest, null);
return result;
}
int rotation = mMediaItem.getFullImageRotation();
rotateRectangle(rect, mCropView.getImageWidth(),
mCropView.getImageHeight(), 360 - rotation);
rotateRectangle(dest, outputX, outputY, 360 - rotation);
if (mUseRegionDecoder) {
BitmapFactory.Options options = new BitmapFactory.Options();
int sample = BitmapUtils.computeSampleSizeLarger(
Math.max(scaleX, scaleY));
options.inSampleSize = sample;
if ((rect.width() / sample) == dest.width()
&& (rect.height() / sample) == dest.height()
&& rotation == 0) {
// To prevent concurrent access in GLThread
synchronized (mRegionDecoder) {
return mRegionDecoder.decodeRegion(rect, options);
}
}
Bitmap result = Bitmap.createBitmap(
outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rotateCanvas(canvas, outputX, outputY, rotation);
drawInTiles(canvas, mRegionDecoder, rect, dest, sample);
return result;
} else {
Bitmap result = Bitmap.createBitmap(outputX, outputY, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
rotateCanvas(canvas, outputX, outputY, rotation);
canvas.drawBitmap(mBitmap,
rect, dest, new Paint(Paint.FILTER_BITMAP_FLAG));
return result;
}
}
|
diff --git a/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java b/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java
index 173d435847..8d55e8df43 100644
--- a/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java
+++ b/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java
@@ -1,855 +1,858 @@
package org.drools.common;
/*
* Copyright 2005 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.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantLock;
import org.drools.PackageIntegrationException;
import org.drools.RuleBase;
import org.drools.RuleBaseConfiguration;
import org.drools.StatefulSession;
import org.drools.concurrent.CommandExecutor;
import org.drools.concurrent.ExecutorService;
import org.drools.event.RuleBaseEventListener;
import org.drools.event.RuleBaseEventSupport;
import org.drools.objenesis.Objenesis;
import org.drools.objenesis.ObjenesisStd;
import org.drools.process.core.Process;
import org.drools.rule.CompositePackageClassLoader;
import org.drools.rule.DialectDatas;
import org.drools.rule.EntryPoint;
import org.drools.rule.ImportDeclaration;
import org.drools.rule.InvalidPatternException;
import org.drools.rule.MapBackedClassLoader;
import org.drools.rule.Package;
import org.drools.rule.Rule;
import org.drools.rule.TypeDeclaration;
import org.drools.spi.ExecutorServiceFactory;
import org.drools.spi.FactHandleFactory;
import org.drools.util.ObjectHashSet;
/**
* Implementation of <code>RuleBase</code>.
*
* @author <a href="mailto:[email protected]">bob mcwhirter</a>
* @author <a href="mailto:[email protected]">Mark Proctor</a>
*
* @version $Id: RuleBaseImpl.java,v 1.5 2005/08/14 22:44:12 mproctor Exp $
*/
abstract public class AbstractRuleBase
implements
InternalRuleBase,
Externalizable {
// ------------------------------------------------------------
// Instance members
// ------------------------------------------------------------
protected String id;
protected int workingMemoryCounter;
protected RuleBaseConfiguration config;
protected Map<String, Package> pkgs;
protected Map processes;
protected Map agendaGroupRuleTotals;
protected transient CompositePackageClassLoader packageClassLoader;
protected transient MapBackedClassLoader classLoader;
private transient Objenesis objenesis;
/** The fact handle factory. */
protected FactHandleFactory factHandleFactory;
protected Map globals;
private ReloadPackageCompilationData reloadPackageCompilationData = null;
private RuleBaseEventSupport eventSupport = new RuleBaseEventSupport( this );
/**
* WeakHashMap to keep references of WorkingMemories but allow them to be
* garbage collected
*/
protected transient ObjectHashSet statefulSessions;
// wms used for lock list during dynamic updates
InternalWorkingMemory[] wms;
// indexed used to track invariant lock
int lastAquiredLock;
// lock for entire rulebase, used for dynamic updates
protected final ReentrantLock lock = new ReentrantLock();
private int additionsSinceLock;
private int removalsSinceLock;
private transient Map<Class< ? >, TypeDeclaration> classTypeDeclaration;
/**
* Default constructor - for Externalizable. This should never be used by a user, as it
* will result in an invalid state for the instance.
*/
public AbstractRuleBase() {
}
public synchronized int nextWorkingMemoryCounter() {
return this.workingMemoryCounter++;
}
/**
* Construct.
*
* @param rete
* The rete network.
*/
public AbstractRuleBase(final String id,
final RuleBaseConfiguration config,
final FactHandleFactory factHandleFactory) {
if ( id != null ) {
this.id = id;
} else {
this.id = "default";
}
this.config = (config != null) ? config : new RuleBaseConfiguration();
this.config.makeImmutable();
this.factHandleFactory = factHandleFactory;
if ( this.config.isSequential() ) {
this.agendaGroupRuleTotals = new HashMap();
}
this.packageClassLoader = new CompositePackageClassLoader( this.config.getClassLoader() );
this.classLoader = new MapBackedClassLoader( this.config.getClassLoader() );
this.packageClassLoader.addClassLoader( this.classLoader );
this.pkgs = new HashMap<String, Package>();
this.processes = new HashMap();
this.globals = new HashMap();
this.statefulSessions = new ObjectHashSet();
this.objenesis = createObjenesis();
this.classTypeDeclaration = new HashMap<Class< ? >, TypeDeclaration>();
}
// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
/**
* Handles the write serialization of the Package. Patterns in Rules may reference generated data which cannot be serialized by default methods.
* The Package uses PackageCompilationData to hold a reference to the generated bytecode. The generated bytecode must be restored before any Rules.
*
*/
public void doWriteExternal(final ObjectOutput stream,
final Object[] objects) throws IOException {
stream.writeObject( this.pkgs );
stream.writeObject( this.classLoader.getStore() );
// Rules must be restored by an ObjectInputStream that can resolve using a given ClassLoader to handle seaprately by storing as
// a byte[]
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ObjectOutput out = new ObjectOutputStream( bos );
out.writeObject( this.id );
out.writeObject( this.processes );
out.writeObject( this.agendaGroupRuleTotals );
out.writeObject( this.factHandleFactory );
out.writeObject( this.globals );
out.writeObject( this.config );
this.eventSupport.removeEventListener( RuleBaseEventListener.class );
out.writeObject( this.eventSupport );
for ( int i = 0, length = objects.length; i < length; i++ ) {
out.writeObject( objects[i] );
}
out.close();
stream.writeObject( bos.toByteArray() );
}
/**
* Handles the read serialization of the Package. Patterns in Rules may reference generated data which cannot be serialized by default methods.
* The Package uses PackageCompilationData to hold a reference to the generated bytecode; which must be restored before any Rules.
* A custom ObjectInputStream, able to resolve classes against the bytecode in the PackageCompilationData, is used to restore the Rules.
*
*/
public void doReadExternal(final ObjectInput stream,
final Object[] objects) throws IOException,
ClassNotFoundException {
// PackageCompilationData must be restored before Rules as it has the ClassLoader needed to resolve the generated code references in Rules
this.pkgs = (Map) stream.readObject();
Map store = (Map) stream.readObject();
if ( stream instanceof DroolsObjectInputStream ) {
final DroolsObjectInputStream parentStream = (DroolsObjectInputStream) stream;
parentStream.setRuleBase( this );
this.packageClassLoader = new CompositePackageClassLoader( parentStream.getClassLoader() );
this.classLoader = new MapBackedClassLoader( parentStream.getClassLoader(), store );
} else {
this.packageClassLoader = new CompositePackageClassLoader( Thread.currentThread().getContextClassLoader() );
this.classLoader = new MapBackedClassLoader( Thread.currentThread().getContextClassLoader(), store );
}
this.packageClassLoader.addClassLoader( this.classLoader );
this.objenesis = createObjenesis();
for ( final Iterator it = this.pkgs.values().iterator(); it.hasNext(); ) {
this.packageClassLoader.addClassLoader( ((Package) it.next()).getDialectDatas().getClassLoader() );
}
// Return the rules stored as a byte[]
final byte[] bytes = (byte[]) stream.readObject();
// Use a custom ObjectInputStream that can resolve against a given classLoader
final DroolsObjectInputStream childStream = new DroolsObjectInputStream( new ByteArrayInputStream( bytes ),
this.packageClassLoader );
childStream.setRuleBase( this );
this.id = (String) childStream.readObject();
this.processes = (Map) childStream.readObject();
this.agendaGroupRuleTotals = (Map) childStream.readObject();
this.factHandleFactory = (FactHandleFactory) childStream.readObject();
this.globals = (Map) childStream.readObject();
this.config = (RuleBaseConfiguration) childStream.readObject();
this.config.setClassLoader( childStream.getClassLoader() );
this.eventSupport = (RuleBaseEventSupport) childStream.readObject();
this.eventSupport.setRuleBase( this );
this.statefulSessions = new ObjectHashSet();
for ( int i = 0, length = objects.length; i < length; i++ ) {
objects[i] = childStream.readObject();
}
childStream.close();
this.populateTypeDeclarationMaps();
}
/**
* Creates Objenesis instance for the RuleBase.
* @return a standart Objenesis instanse with caching turned on.
*/
protected Objenesis createObjenesis() {
return new ObjenesisStd( true );
}
private void populateTypeDeclarationMaps() {
this.classTypeDeclaration = new HashMap<Class<?>, TypeDeclaration>();
for( Package pkg : this.pkgs.values() ) {
for( TypeDeclaration type : pkg.getTypeDeclarations().values() ) {
this.classTypeDeclaration.put( type.getTypeClass(), type );
}
}
}
/**
* @return the id
*/
public String getId() {
return this.id;
}
/**
* @see RuleBase
*/
public StatefulSession newStatefulSession() {
return newStatefulSession( true );
}
/**
* @see RuleBase
*/
abstract public StatefulSession newStatefulSession(boolean keepReference);
public synchronized void disposeStatefulSession(final StatefulSession statefulSession) {
this.statefulSessions.remove( statefulSession );
for ( Iterator it = statefulSession.getRuleBaseUpdateListeners().iterator(); it.hasNext(); ) {
this.removeEventListener( (RuleBaseEventListener) it.next() );
}
}
/**
* @see RuleBase
*/
public FactHandleFactory getFactHandleFactory() {
return this.factHandleFactory;
}
public FactHandleFactory newFactHandleFactory() {
return this.factHandleFactory.newInstance();
}
public Process[] getProcesses() {
return (Process[]) this.processes.values().toArray( new Process[this.processes.size()] );
}
public Package[] getPackages() {
return (Package[]) this.pkgs.values().toArray( new Package[this.pkgs.size()] );
}
public Map getPackagesMap() {
return this.pkgs;
}
public Map getGlobals() {
return this.globals;
}
public Map getAgendaGroupRuleTotals() {
return this.agendaGroupRuleTotals;
}
public int getAdditionsSinceLock() {
return additionsSinceLock;
}
public int getRemovalsSinceLock() {
return removalsSinceLock;
}
public void lock() {
this.additionsSinceLock = 0;
this.removalsSinceLock = 0;
this.eventSupport.fireBeforeRuleBaseLocked();
this.lock.lock();
// INVARIANT: lastAquiredLock always contains the index of the last aquired lock +1
// in the working memory array
this.lastAquiredLock = 0;
this.wms = getWorkingMemories();
// Iterate each workingMemory and lock it
// This is so we don't update the Rete network during propagation
for ( this.lastAquiredLock = 0; this.lastAquiredLock < this.wms.length; this.lastAquiredLock++ ) {
this.wms[this.lastAquiredLock].getLock().lock();
}
this.eventSupport.fireAfterRuleBaseLocked();
}
public void unlock() {
this.eventSupport.fireBeforeRuleBaseUnlocked();
// Iterate each workingMemory and attempt to fire any rules, that were activated as a result
// as per the INVARIANT defined above, we need to iterate from lastAquiredLock-1 to 0.
for ( this.lastAquiredLock--; this.lastAquiredLock > -1; this.lastAquiredLock-- ) {
this.wms[this.lastAquiredLock].getLock().unlock();
}
this.lock.unlock();
this.eventSupport.fireAfterRuleBaseUnlocked();
this.wms = null;
}
/**
* Add a <code>Package</code> to the network. Iterates through the
* <code>Package</code> adding Each individual <code>Rule</code> to the
* network. Before update network each referenced <code>WorkingMemory</code>
* is locked.
*
* @param pkg
* The package to add.
*/
public synchronized void addPackage(final Package newPkg) {
newPkg.checkValidity();
synchronized ( this.pkgs ) {
final Package pkg = (Package) this.pkgs.get( newPkg.getName() );
// only acquire the lock if it hasn't been done explicitely
boolean doUnlock = false;
if ( !this.lock.isHeldByCurrentThread() && (this.wms == null || this.wms.length == 0) ) {
lock();
doUnlock = true;
}
this.additionsSinceLock++;
this.eventSupport.fireBeforePackageAdded( newPkg );
if ( pkg != null ) {
mergePackage( pkg,
newPkg );
} else {
this.pkgs.put( newPkg.getName(),
newPkg );
}
final Map newGlobals = newPkg.getGlobals();
// Check that the global data is valid, we cannot change the type
// of an already declared global variable
for ( final Iterator it = newGlobals.keySet().iterator(); it.hasNext(); ) {
final String identifier = (String) it.next();
final Class type = (Class) newGlobals.get( identifier );
final boolean f = this.globals.containsKey( identifier );
if ( f ) {
final boolean y = !this.globals.get( identifier ).equals( type );
if ( f && y ) {
throw new PackageIntegrationException( pkg );
}
}
}
this.globals.putAll( newGlobals );
// Add type declarations
for ( TypeDeclaration type : newPkg.getTypeDeclarations().values() ) {
// should we allow overrides?
if ( !this.classTypeDeclaration.containsKey( type.getTypeClass() ) ) {
this.classTypeDeclaration.put( type.getTypeClass(),
type );
}
}
final Rule[] rules = newPkg.getRules();
for ( int i = 0; i < rules.length; ++i ) {
+ if ( pkg != null && pkg.getRule( rules[i].getName() ) != null ) {
+ removeRule( pkg, pkg.getRule( rules[i].getName() ) );
+ }
addRule( newPkg,
rules[i] );
}
//and now the rule flows
if ( newPkg.getRuleFlows() != Collections.EMPTY_MAP ) {
final Map flows = newPkg.getRuleFlows();
for ( final Iterator iter = flows.entrySet().iterator(); iter.hasNext(); ) {
final Entry flow = (Entry) iter.next();
this.processes.put( flow.getKey(),
flow.getValue() );
}
}
this.packageClassLoader.addClassLoader( newPkg.getDialectDatas().getClassLoader() );
this.eventSupport.fireAfterPackageAdded( newPkg );
// only unlock if it had been acquired implicitely
if ( doUnlock ) {
unlock();
}
}
}
/**
* Merge a new package with an existing package.
* Most of the work is done by the concrete implementations,
* but this class does some work (including combining imports, compilation data, globals,
* and the actual Rule objects into the package).
*/
private void mergePackage(final Package pkg,
final Package newPkg) {
final Map globals = pkg.getGlobals();
final Map<String, ImportDeclaration> imports = pkg.getImports();
// Merge imports
imports.putAll( newPkg.getImports() );
// Add globals
for ( final Iterator it = newPkg.getGlobals().keySet().iterator(); it.hasNext(); ) {
final String identifier = (String) it.next();
final Class type = (Class) globals.get( identifier );
if ( globals.containsKey( identifier ) && !globals.get( identifier ).equals( type ) ) {
throw new PackageIntegrationException( "Unable to merge new Package",
newPkg );
}
}
globals.putAll( newPkg.getGlobals() );
// add type declarations
for ( TypeDeclaration type : newPkg.getTypeDeclarations().values() ) {
// should we allow overrides?
if ( !this.classTypeDeclaration.containsKey( type.getTypeClass() ) ) {
this.classTypeDeclaration.put( type.getTypeClass(),
type );
}
if ( !pkg.getTypeDeclarations().containsKey( type.getTypeName() ) ) {
pkg.addTypeDeclaration( type );
}
}
//Add rules into the RuleBase package
//as this is needed for individual rule removal later on
final Rule[] newRules = newPkg.getRules();
for ( int i = 0; i < newRules.length; i++ ) {
final Rule newRule = newRules[i];
if ( pkg.getRule( newRule.getName() ) == null ) {
pkg.addRule( newRule );
}
}
//and now the rule flows
if ( newPkg.getRuleFlows() != Collections.EMPTY_MAP ) {
final Map flows = newPkg.getRuleFlows();
for ( final Iterator iter = flows.values().iterator(); iter.hasNext(); ) {
final Process flow = (Process) iter.next();
pkg.addRuleFlow( flow );
}
}
pkg.getDialectDatas().merge( newPkg.getDialectDatas() );
if ( this.reloadPackageCompilationData == null ) {
this.reloadPackageCompilationData = new ReloadPackageCompilationData();
}
this.reloadPackageCompilationData.addDialectDatas( pkg.getDialectDatas() );
}
public TypeDeclaration getTypeDeclaration(Class< ? > clazz) {
return this.classTypeDeclaration.get( clazz );
}
private synchronized void addRule(final Package pkg,
final Rule rule) throws InvalidPatternException {
this.eventSupport.fireBeforeRuleAdded( pkg,
rule );
if ( !rule.isValid() ) {
throw new IllegalArgumentException( "The rule called " + rule.getName() + " is not valid. Check for compile errors reported." );
}
addRule( rule );
this.eventSupport.fireAfterRuleAdded( pkg,
rule );
}
protected abstract void addRule(final Rule rule) throws InvalidPatternException;
public void removePackage(final String packageName) {
synchronized ( this.pkgs ) {
final Package pkg = (Package) this.pkgs.get( packageName );
if ( pkg == null ) {
throw new IllegalArgumentException( "Package name '" + packageName + "' does not exist for this Rule Base." );
}
// only acquire the lock if it hasn't been done explicitely
boolean doUnlock = false;
if ( !this.lock.isHeldByCurrentThread() && (this.wms == null || this.wms.length == 0) ) {
lock();
doUnlock = true;
}
try {
this.removalsSinceLock++;
this.eventSupport.fireBeforePackageRemoved( pkg );
final Rule[] rules = pkg.getRules();
for ( int i = 0; i < rules.length; ++i ) {
removeRule( pkg,
rules[i] );
}
this.packageClassLoader.removeClassLoader( pkg.getDialectDatas().getClassLoader() );
// getting the list of referenced globals
final Set referencedGlobals = new HashSet();
for ( final Iterator it = this.pkgs.values().iterator(); it.hasNext(); ) {
final org.drools.rule.Package pkgref = (org.drools.rule.Package) it.next();
if ( pkgref != pkg ) {
referencedGlobals.addAll( pkgref.getGlobals().keySet() );
}
}
// removing globals declared inside the package that are not shared
for ( final Iterator it = pkg.getGlobals().keySet().iterator(); it.hasNext(); ) {
final String globalName = (String) it.next();
if ( !referencedGlobals.contains( globalName ) ) {
this.globals.remove( globalName );
}
}
//and now the rule flows
final Map flows = pkg.getRuleFlows();
for ( final Iterator iter = flows.keySet().iterator(); iter.hasNext(); ) {
removeProcess( (String) iter.next() );
}
// removing the package itself from the list
this.pkgs.remove( pkg.getName() );
//clear all members of the pkg
pkg.clear();
this.eventSupport.fireAfterPackageRemoved( pkg );
// only unlock if it had been acquired implicitely
} finally {
if ( doUnlock ) {
unlock();
}
}
}
}
public void removeRule(final String packageName,
final String ruleName) {
synchronized ( this.pkgs ) {
final Package pkg = (Package) this.pkgs.get( packageName );
if ( pkg == null ) {
throw new IllegalArgumentException( "Package name '" + packageName + "' does not exist for this Rule Base." );
}
final Rule rule = pkg.getRule( ruleName );
if ( rule == null ) {
throw new IllegalArgumentException( "Rule name '" + ruleName + "' does not exist in the Package '" + packageName + "'." );
}
// only acquire the lock if it hasn't been done explicitely
boolean doUnlock = false;
if ( !this.lock.isHeldByCurrentThread() && (this.wms == null || this.wms.length == 0) ) {
lock();
doUnlock = true;
}
this.removalsSinceLock++;
removeRule( pkg,
rule );
pkg.removeRule( rule );
if ( this.reloadPackageCompilationData == null ) {
this.reloadPackageCompilationData = new ReloadPackageCompilationData();
}
this.reloadPackageCompilationData.addDialectDatas( pkg.getDialectDatas() );
// only unlock if it had been acquired implicitely
if ( doUnlock ) {
unlock();
}
}
}
private void removeRule(final Package pkg,
final Rule rule) {
this.eventSupport.fireBeforeRuleRemoved( pkg,
rule );
removeRule( rule );
this.eventSupport.fireAfterRuleRemoved( pkg,
rule );
}
protected abstract void removeRule(Rule rule);
public void removeFunction(final String packageName,
final String functionName) {
synchronized ( this.pkgs ) {
final Package pkg = (Package) this.pkgs.get( packageName );
if ( pkg == null ) {
throw new IllegalArgumentException( "Package name '" + packageName + "' does not exist for this Rule Base." );
}
this.eventSupport.fireBeforeFunctionRemoved( pkg,
functionName );
if ( !pkg.getFunctions().containsKey( functionName ) ) {
throw new IllegalArgumentException( "function name '" + packageName + "' does not exist in the Package '" + packageName + "'." );
}
pkg.removeFunction( functionName );
if ( this.reloadPackageCompilationData == null ) {
this.reloadPackageCompilationData = new ReloadPackageCompilationData();
}
this.reloadPackageCompilationData.addDialectDatas( pkg.getDialectDatas() );
this.eventSupport.fireAfterFunctionRemoved( pkg,
functionName );
}
}
public synchronized void addProcess(final Process process) {
synchronized ( this.pkgs ) {
this.processes.put( process.getId(),
process );
}
}
public synchronized void removeProcess(final String id) {
synchronized ( this.pkgs ) {
this.processes.remove( id );
}
}
public Process getProcess(final String id) {
Process process = null;
synchronized ( this.pkgs ) {
process = (Process) this.processes.get( id );
}
return process;
}
public Objenesis getObjenesis() {
return objenesis;
}
protected synchronized void addStatefulSession(final StatefulSession statefulSession) {
this.statefulSessions.add( statefulSession );
}
public Package getPackage(final String name) {
return (Package) this.pkgs.get( name );
}
public StatefulSession[] getStatefulSessions() {
return (StatefulSession[]) this.statefulSessions.toArray( new StatefulSession[this.statefulSessions.size()] );
}
public InternalWorkingMemory[] getWorkingMemories() {
return (InternalWorkingMemory[]) this.statefulSessions.toArray( new InternalWorkingMemory[this.statefulSessions.size()] );
}
public RuleBaseConfiguration getConfiguration() {
return this.config;
}
public StatefulSession newStatefulSession(final InputStream stream) throws IOException,
ClassNotFoundException {
return newStatefulSession( stream,
true );
}
public StatefulSession newStatefulSession(final InputStream stream,
final boolean keepReference) throws IOException,
ClassNotFoundException {
if ( this.config.isSequential() ) {
throw new RuntimeException( "Cannot have a stateful rule session, with sequential configuration set to true" );
}
final DroolsObjectInputStream streamWithLoader = new DroolsObjectInputStream( stream,
this.packageClassLoader );
streamWithLoader.setRuleBase( this );
final StatefulSession session = (StatefulSession) streamWithLoader.readObject();
synchronized ( this.pkgs ) {
((InternalWorkingMemory) session).setRuleBase( this );
((InternalWorkingMemory) session).setId( (nextWorkingMemoryCounter()) );
ExecutorService executor = ExecutorServiceFactory.createExecutorService( this.config.getExecutorService() );
executor.setCommandExecutor( new CommandExecutor( session ) );
((InternalWorkingMemory) session).setExecutorService( executor );
if ( keepReference ) {
addStatefulSession( session );
for ( Iterator it = session.getRuleBaseUpdateListeners().iterator(); it.hasNext(); ) {
addEventListener( (RuleBaseEventListener) it.next() );
}
}
return (StatefulSession) session;
}
}
public void addClass(final String className,
final byte[] bytes) {
this.classLoader.addClass( className,
bytes );
}
public CompositePackageClassLoader getCompositePackageClassLoader() {
return this.packageClassLoader;
}
public MapBackedClassLoader getMapBackedClassLoader() {
return this.classLoader;
}
public void executeQueuedActions() {
synchronized ( this.pkgs ) {
if ( this.reloadPackageCompilationData != null ) {
this.reloadPackageCompilationData.execute( this );
this.reloadPackageCompilationData = null;
}
}
}
public void addEventListener(final RuleBaseEventListener listener) {
// since the event support is thread-safe, no need for locks... right?
this.eventSupport.addEventListener( listener );
}
public void removeEventListener(final RuleBaseEventListener listener) {
// since the event support is thread-safe, no need for locks... right?
this.eventSupport.removeEventListener( listener );
}
public List<RuleBaseEventListener> getRuleBaseEventListeners() {
// since the event support is thread-safe, no need for locks... right?
return this.eventSupport.getEventListeners();
}
public boolean isEvent(Class clazz) {
for ( Package pkg : this.pkgs.values() ) {
if ( pkg.isEvent( clazz ) ) {
return true;
}
}
return false;
}
public static class ReloadPackageCompilationData
implements
RuleBaseAction {
private static final long serialVersionUID = 1L;
private Set set;
public void addDialectDatas(final DialectDatas dialectDatas) {
if ( this.set == null ) {
this.set = new HashSet();
}
this.set.add( dialectDatas );
}
public void execute(final InternalRuleBase ruleBase) {
for ( final Iterator it = this.set.iterator(); it.hasNext(); ) {
final DialectDatas dialectDatas = (DialectDatas) it.next();
dialectDatas.reloadDirty();
}
}
}
public static interface RuleBaseAction
extends
Serializable {
public void execute(InternalRuleBase ruleBase);
}
}
| true | true | public synchronized void addPackage(final Package newPkg) {
newPkg.checkValidity();
synchronized ( this.pkgs ) {
final Package pkg = (Package) this.pkgs.get( newPkg.getName() );
// only acquire the lock if it hasn't been done explicitely
boolean doUnlock = false;
if ( !this.lock.isHeldByCurrentThread() && (this.wms == null || this.wms.length == 0) ) {
lock();
doUnlock = true;
}
this.additionsSinceLock++;
this.eventSupport.fireBeforePackageAdded( newPkg );
if ( pkg != null ) {
mergePackage( pkg,
newPkg );
} else {
this.pkgs.put( newPkg.getName(),
newPkg );
}
final Map newGlobals = newPkg.getGlobals();
// Check that the global data is valid, we cannot change the type
// of an already declared global variable
for ( final Iterator it = newGlobals.keySet().iterator(); it.hasNext(); ) {
final String identifier = (String) it.next();
final Class type = (Class) newGlobals.get( identifier );
final boolean f = this.globals.containsKey( identifier );
if ( f ) {
final boolean y = !this.globals.get( identifier ).equals( type );
if ( f && y ) {
throw new PackageIntegrationException( pkg );
}
}
}
this.globals.putAll( newGlobals );
// Add type declarations
for ( TypeDeclaration type : newPkg.getTypeDeclarations().values() ) {
// should we allow overrides?
if ( !this.classTypeDeclaration.containsKey( type.getTypeClass() ) ) {
this.classTypeDeclaration.put( type.getTypeClass(),
type );
}
}
final Rule[] rules = newPkg.getRules();
for ( int i = 0; i < rules.length; ++i ) {
addRule( newPkg,
rules[i] );
}
//and now the rule flows
if ( newPkg.getRuleFlows() != Collections.EMPTY_MAP ) {
final Map flows = newPkg.getRuleFlows();
for ( final Iterator iter = flows.entrySet().iterator(); iter.hasNext(); ) {
final Entry flow = (Entry) iter.next();
this.processes.put( flow.getKey(),
flow.getValue() );
}
}
this.packageClassLoader.addClassLoader( newPkg.getDialectDatas().getClassLoader() );
this.eventSupport.fireAfterPackageAdded( newPkg );
// only unlock if it had been acquired implicitely
if ( doUnlock ) {
unlock();
}
}
}
| public synchronized void addPackage(final Package newPkg) {
newPkg.checkValidity();
synchronized ( this.pkgs ) {
final Package pkg = (Package) this.pkgs.get( newPkg.getName() );
// only acquire the lock if it hasn't been done explicitely
boolean doUnlock = false;
if ( !this.lock.isHeldByCurrentThread() && (this.wms == null || this.wms.length == 0) ) {
lock();
doUnlock = true;
}
this.additionsSinceLock++;
this.eventSupport.fireBeforePackageAdded( newPkg );
if ( pkg != null ) {
mergePackage( pkg,
newPkg );
} else {
this.pkgs.put( newPkg.getName(),
newPkg );
}
final Map newGlobals = newPkg.getGlobals();
// Check that the global data is valid, we cannot change the type
// of an already declared global variable
for ( final Iterator it = newGlobals.keySet().iterator(); it.hasNext(); ) {
final String identifier = (String) it.next();
final Class type = (Class) newGlobals.get( identifier );
final boolean f = this.globals.containsKey( identifier );
if ( f ) {
final boolean y = !this.globals.get( identifier ).equals( type );
if ( f && y ) {
throw new PackageIntegrationException( pkg );
}
}
}
this.globals.putAll( newGlobals );
// Add type declarations
for ( TypeDeclaration type : newPkg.getTypeDeclarations().values() ) {
// should we allow overrides?
if ( !this.classTypeDeclaration.containsKey( type.getTypeClass() ) ) {
this.classTypeDeclaration.put( type.getTypeClass(),
type );
}
}
final Rule[] rules = newPkg.getRules();
for ( int i = 0; i < rules.length; ++i ) {
if ( pkg != null && pkg.getRule( rules[i].getName() ) != null ) {
removeRule( pkg, pkg.getRule( rules[i].getName() ) );
}
addRule( newPkg,
rules[i] );
}
//and now the rule flows
if ( newPkg.getRuleFlows() != Collections.EMPTY_MAP ) {
final Map flows = newPkg.getRuleFlows();
for ( final Iterator iter = flows.entrySet().iterator(); iter.hasNext(); ) {
final Entry flow = (Entry) iter.next();
this.processes.put( flow.getKey(),
flow.getValue() );
}
}
this.packageClassLoader.addClassLoader( newPkg.getDialectDatas().getClassLoader() );
this.eventSupport.fireAfterPackageAdded( newPkg );
// only unlock if it had been acquired implicitely
if ( doUnlock ) {
unlock();
}
}
}
|
diff --git a/MercredyMurderParty/src/fr/mercredymurderparty/ihm/composants/ComposantGestionIndices.java b/MercredyMurderParty/src/fr/mercredymurderparty/ihm/composants/ComposantGestionIndices.java
index 406aa4c..c5d6d11 100644
--- a/MercredyMurderParty/src/fr/mercredymurderparty/ihm/composants/ComposantGestionIndices.java
+++ b/MercredyMurderParty/src/fr/mercredymurderparty/ihm/composants/ComposantGestionIndices.java
@@ -1,1482 +1,1482 @@
package fr.mercredymurderparty.ihm.composants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import fr.mercredymurderparty.ihm.fenetres.FenetreAdmin;
import fr.mercredymurderparty.outil.BaseDeDonnees;
import fr.mercredymurderparty.outil.Message;
import fr.mercredymurderparty.serveur.CoeurServeur;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import net.miginfocom.swing.MigLayout;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.DefaultComboBoxModel;
import java.awt.Font;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.FlowLayout;
@SuppressWarnings("serial")
public class ComposantGestionIndices extends JPanel
{
// ----- ATTRIBUTS ----- //
// ----- INTERFACE GRAPHIQUE ----- //
private JPanel panelGestionIndices;
private File image;
private JTextField champTitre;
private JTextField champNomPerso;
private JTextField champImageLien;
private JTextArea zoneContenu;
private JComboBox choixImportance;
private JCheckBox checkIndicePenalite;
private JComboBox choixPersonnage;
private JComboBox choixPersonnage2;
private JCheckBox checkTousLesJoueurs;
private DefaultTableModel modeleTableIndice;
private JTable tableIndices;
private JPanel pnlFormulaire;
private JButton btnAjouter;
private JButton btnModifier;
private JButton btnAjouterToJoueur;
private JCheckBox checkMemo;
// ----- MODELES & CLASSES ----- //
private BaseDeDonnees bdd;
private CoeurServeur coeurServeur;
// ----- VARIABLES ----- //
private boolean tempsPenalite = false;
private boolean tempsTousJoueurs = false;
private boolean verrouillerComposant = false;
private int idIndice = -1;
private String loginJoueur = null;
private JPanel panel;
private JTextField champHeure;
private JLabel lblNewLabel;
private JTextField champMin;
private JLabel lblM;
private JTextField champSec;
private JLabel lblNewLabel_1;
// ----- CONSTRUCTEUR ----- //
/**
* FIXME
* @param _fenetre
* @param _springLayout
* @param _coeurServeur
*/
public ComposantGestionIndices(FenetreAdmin _fenetre, final SpringLayout _springLayout, CoeurServeur _coeurServeur)
{
coeurServeur = _coeurServeur;
panelGestionIndices = new JPanel();
panelGestionIndices.setOpaque(false);
_springLayout.putConstraint(SpringLayout.NORTH, panelGestionIndices, -200, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
- _springLayout.putConstraint(SpringLayout.SOUTH, panelGestionIndices, 300, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
+ _springLayout.putConstraint(SpringLayout.SOUTH, panelGestionIndices, 350, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.WEST, panelGestionIndices, -350, SpringLayout.HORIZONTAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.EAST, panelGestionIndices, 400, SpringLayout.HORIZONTAL_CENTER, _fenetre.getContentPane());
_fenetre.getContentPane().add(panelGestionIndices);
panelGestionIndices.setLayout(new MigLayout("", "[][10.00][grow]", "[335.00,top]"));
this.setLayout(_springLayout);
SpringLayout springLayout = new SpringLayout();
setLayout(springLayout);
pnlFormulaire = new JPanel();
pnlFormulaire.setOpaque(false);
springLayout.putConstraint(SpringLayout.NORTH, pnlFormulaire, 10, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.WEST, pnlFormulaire, 10, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, pnlFormulaire, 394, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, pnlFormulaire, 315, SpringLayout.WEST, this);
panelGestionIndices.add(pnlFormulaire, "cell 0 0");
pnlFormulaire.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(48dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(50dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(50dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("max(45dlu;min)"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("default:grow"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JButton btnNouveauIndice = new JButton("Nouveau indice");
btnNouveauIndice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
effacerFormulaire();
}
});
pnlFormulaire.add(btnNouveauIndice, "4, 2, 3, 1");
JLabel lblTitre = new JLabel("Titre :");
pnlFormulaire.add(lblTitre, "2, 4");
champTitre = new JTextField();
pnlFormulaire.add(champTitre, "4, 4, 3, 1, fill, default");
champTitre.setColumns(10);
JLabel lblContenu = new JLabel("Contenu :");
pnlFormulaire.add(lblContenu, "2, 6");
JScrollPane scrollPaneArea = new JScrollPane();
pnlFormulaire.add(scrollPaneArea, "4, 6, 3, 1, fill, fill");
zoneContenu = new JTextArea();
zoneContenu.setLineWrap(true);
scrollPaneArea.setViewportView(zoneContenu);
JLabel lblPersonnage = new JLabel("Personnage :");
pnlFormulaire.add(lblPersonnage, "2, 8");
choixPersonnage = new JComboBox();
choixPersonnage.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _e)
{
if (verrouillerComposant == false)
{
String[] identiteJoueur = new String[2];
identiteJoueur = identiteJoueur((String) choixPersonnage.getSelectedItem());
if (identiteJoueur[0] != null)
{
champNomPerso.setText(identiteJoueur[0] + " " + identiteJoueur[1]);
}
else
{
rafraichirListeIndices();
}
}
if (getIdIndice() == -1)
{
btnAjouter.setText("Ajouter");
}
}
});
pnlFormulaire.add(choixPersonnage, "4, 8, 3, 1, fill, default");
champNomPerso = new JTextField();
champNomPerso.setFont(new Font("Tahoma", Font.PLAIN, 10));
champNomPerso.setEditable(false);
pnlFormulaire.add(champNomPerso, "4, 10, 3, 1, fill, default");
champNomPerso.setColumns(10);
JLabel lblImage = new JLabel("Image :");
pnlFormulaire.add(lblImage, "2, 12");
champImageLien = new JTextField();
pnlFormulaire.add(champImageLien, "4, 12, fill, default");
champImageLien.setColumns(10);
JButton btnChoisirImage = new JButton("Choisir");
btnChoisirImage.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _e)
{
choisirImage();
}
});
pnlFormulaire.add(btnChoisirImage, "6, 12");
JLabel lblPriorite = new JLabel("Importance :");
pnlFormulaire.add(lblPriorite, "2, 14");
choixImportance = new JComboBox();
choixImportance.setModel((ComboBoxModel) new DefaultComboBoxModel(new String[] {"Peu important", "Important", "Tr\u00E8s important"}));
pnlFormulaire.add(choixImportance, "4, 14, 3, 1, fill, default");
JLabel lblTemps = new JLabel("P\u00E9nalit\u00E9 :");
pnlFormulaire.add(lblTemps, "2, 16");
panel = new JPanel();
pnlFormulaire.add(panel, "4, 16, 4, 1, left, fill");
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
champHeure = new JTextField();
panel.add(champHeure);
champHeure.setColumns(3);
lblNewLabel = new JLabel("h");
panel.add(lblNewLabel);
champMin = new JTextField();
panel.add(champMin);
champMin.setColumns(3);
lblM = new JLabel("m");
panel.add(lblM);
champSec = new JTextField();
panel.add(champSec);
champSec.setColumns(3);
lblNewLabel_1 = new JLabel("s");
panel.add(lblNewLabel_1);
JLabel lblOptions = new JLabel("Options:");
pnlFormulaire.add(lblOptions, "2, 18");
checkIndicePenalite = new JCheckBox("Indice contre du temps");
checkIndicePenalite.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (checkIndicePenalite.isSelected())
{
champHeure.setText("00");
champMin.setText("00");
champSec.setText("00");
tempsPenalite = true;
}
else
{
champHeure.setText(null);
champMin.setText(null);
champSec.setText(null);
tempsPenalite = false;
}
}
});
pnlFormulaire.add(checkIndicePenalite, "4, 18, 4, 1");
checkTousLesJoueurs = new JCheckBox("Indice pour tous les joueurs");
checkTousLesJoueurs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (checkTousLesJoueurs.isSelected())
{
tempsTousJoueurs = true;
champHeure.setEditable(false);
champMin.setEditable(false);
champSec.setEditable(false);
choixPersonnage.setSelectedIndex(0);
choixPersonnage.setEnabled(false);
champNomPerso.setText("Tous les joueurs !");
}
else
{
tempsTousJoueurs = false;
champHeure.setEditable(true);
champMin.setEditable(true);
champSec.setEditable(true);
choixPersonnage.setEnabled(true);
champNomPerso.setText(null);
}
}
});
pnlFormulaire.add(checkTousLesJoueurs, "4, 20, 4, 1");
btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// V�rifier si les champs sont biens remplis
if (champTitre.getText() != null && zoneContenu.getText() != null)
{
if (ajouterIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� ajout� avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che d'ajouter l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un ou plusieurs champs n'ont pas �t�s remplis ou ne correspondent pas aux crit�res requis.\nChamps obligatoires: titre, contenu.", "Formulaire non valide", JOptionPane.ERROR_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
btnAjouterToJoueur = new JButton("Ajouter � un joueur");
btnAjouterToJoueur.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// V�rifier si les champs sont biens remplis
if (champTitre.getText() != null && zoneContenu.getText() != null)
{
if (ajouterRelationJoueurIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� ajout� avec succ�s au joueur !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che d'ajouter l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un ou plusieurs champs n'ont pas �t�s remplis ou ne correspondent pas aux crit�res requis.\nChamps obligatoires: titre, contenu.", "Formulaire non valide", JOptionPane.ERROR_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
btnModifier = new JButton("Modifier");
btnModifier.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
if (getIdIndice() != -1)
{
if (tempsTousJoueurs == false)
{
if (modifierIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� modif� avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che de modifier l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
indiceTousLesJoueurs();
}
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
checkMemo = new JCheckBox("Se souvenir des donn\u00E9es");
checkMemo.setToolTipText("Cochez cette case pour garder les donn\u00E9es du dernier\r\nindice afin de les r\u00E9utiliser sur un autre\r\npersonnage, de fa\u00E7on diff\u00E9rente...");
pnlFormulaire.add(checkMemo, "4, 22, 4, 1");
pnlFormulaire.add(btnModifier, "4, 24");
pnlFormulaire.add(btnAjouter, "6, 24");
pnlFormulaire.add(btnAjouterToJoueur, "4, 26");
JPanel pnlIndices = new JPanel();
pnlIndices.setOpaque(false);
panelGestionIndices.add(pnlIndices, "cell 2 0,grow");
pnlIndices.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(64dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
RowSpec.decode("max(15dlu;default)"),
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("max(160dlu;min)"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblHistoriqueDesIndices = new JLabel("Historique des indices :");
lblHistoriqueDesIndices.setFont(new Font("Tahoma", Font.BOLD, 11));
pnlIndices.add(lblHistoriqueDesIndices, "2, 1, 3, 1");
JLabel lblIndicesDuJoueur = new JLabel("Indices du Joueur:");
pnlIndices.add(lblIndicesDuJoueur, "2, 2, right, default");
choixPersonnage2 = new JComboBox();
choixPersonnage2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
if ((String) choixPersonnage2.getSelectedItem() != null)
{
int nombreLignes = tableIndices.getRowCount();
for(int i = nombreLignes - 1; i >= 0; i--)
{
modeleTableIndice.removeRow(i);
}
historique(tableIndices, (String) choixPersonnage2.getSelectedItem());
}
else
{
rafraichirListeIndices();
}
}
});
pnlIndices.add(choixPersonnage2, "4, 2, fill, default");
JScrollPane spIndices = new JScrollPane();
pnlIndices.add(spIndices, "2, 4, 3, 5, fill, fill");
// Charger les personnages
modeleTableIndice = new DefaultTableModel();
tableIndices = new JTable(modeleTableIndice);
tableIndices.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
setIdIndice((Integer) contenuPremiereCelluleTableau(tableIndices, 0));
setLoginJoueur((String) contenuPremiereCelluleTableau(tableIndices, 1));
recupererContenuIndice(getIdIndice(), getLoginJoueur());
}
});
spIndices.setViewportView(tableIndices);
JLabel lblChoisirUnIndice = new JLabel("Choisir un indice dans l'historique pour l'\u00E9diter ou supprimer");
lblChoisirUnIndice.setFont(new Font("Tahoma", Font.ITALIC, 11));
pnlIndices.add(lblChoisirUnIndice, "2, 10, 3, 1");
JButton btnSupprimerIndice = new JButton("Supprimer l'indice");
btnSupprimerIndice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// Si on a s�lectionner un indice, on le supprime
if (getIdIndice() != -1)
{
if (supprimerIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� supprimer avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che la suppression de l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Vous n'avez pas s�lectionner l'indice � supprimer !", "Attention", JOptionPane.WARNING_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
pnlIndices.add(btnSupprimerIndice, "2, 14, 3, 1");
}
// ----- METHODES ----- //
/**
* La m�thode estVisible permet d'afficher ou non le conteneur de gestion indices
* @param _visible : "boolean" affiche ou masque ce conteneur
*/
final public void estVisible(boolean _visible)
{
if (_visible)
this.setEnabled(true);
else
this.setEnabled(false);
panelGestionIndices.setVisible(_visible);
}
/**
* Proc�dure qui r�cup�re dans la bdd l'identit� du joueur
* @param _login Login du joueur
* @return Tableau avec nom et prenom
*/
private String[] identiteJoueur(String _login)
{
String login = _login;
String[] identite = new String[2];
bdd = new BaseDeDonnees(coeurServeur);
try
{
ResultSet rs = bdd.executerRequete("SELECT nom, prenom FROM personnage WHERE login = '" + login + "'");
while (rs.next())
{
identite[0] = rs.getString("nom");
identite[1] = rs.getString("prenom");
}
rs.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
bdd.fermerConnexion();
return identite;
}
/**
* Proc�dure qui charger les personnages de la partie en cours dans le combobox
*/
public void chargerPersonnages()
{
choixPersonnage.removeAllItems();
choixPersonnage2.removeAllItems();
choixPersonnage.addItem(null);
choixPersonnage2.addItem(null);
// Ouvrire une nouvelle connexion a la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
ResultSet rs = bdd.executerRequete("SELECT login FROM personnage");
while (rs.next())
{
choixPersonnage.addItem(rs.getString("login"));
choixPersonnage2.addItem(rs.getString("login"));
}
rs.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
// Fermer la connexion a la bdd
bdd.fermerConnexion();
}
/**
* Choisir une image sur le disque dur afin de d�finir l'indice visuel
*/
private void choisirImage()
{
JFileChooser dialogue = new JFileChooser(new File("."));
PrintWriter sortie;
File fichier;
if (dialogue.showOpenDialog(null)== JFileChooser.APPROVE_OPTION)
{
fichier = dialogue.getSelectedFile();
try
{
sortie = new PrintWriter(new FileWriter(fichier.getPath(), true));
sortie.println();
sortie.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
champImageLien.setText(fichier.getName());
image = fichier;
}
}
}
/**
* Proc�dure qui recupere le contenu d'un indice afin de l'�diter ou le supprimer
* @param _idIndice Num�ro d'identifiant de l'indice (pris depuis un jTable par exemple)
*/
public void recupererContenuIndice(int _idIndice, String _loginJoueur)
{
// Variables locale
String loginJoueur = _loginJoueur;
int idIndice = _idIndice;
String loginTemp = null;
// Verrouille certains composants qui risquent de rentrer en conflits
verrouillerComposant = true;
if (idIndice != -1)
{
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// recuperer l'id du joueur
int idJoueur = -1;
if (loginJoueur != null)
{
ResultSet rs = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + _loginJoueur + "'");
rs.next();
idJoueur = rs.getInt("id"); if (rs.wasNull()) idJoueur = -1;
rs.close();
}
ResultSet rs2;
if (loginJoueur != null)
{
rs2 = bdd.executerRequete("" +
" SELECT ind.titre, ind.contenu, ind.importance, perso.login " +
" FROM indice ind, indice_relation indr " +
" LEFT JOIN personnage perso ON indr.ref_perso = perso.id " +
" WHERE ind.id = " + idIndice + " " +
" AND ind.id = indr.ref_indice" +
" AND indr.ref_perso = " + idJoueur + " "
);
}
else
{
rs2 = bdd.executerRequete("" +
" SELECT ind.titre, ind.contenu, ind.importance, perso.login " +
" FROM indice ind, indice_relation indr " +
" LEFT JOIN personnage perso ON indr.ref_perso = perso.id " +
" WHERE ind.id = " + idIndice + " " +
" AND ind.id = indr.ref_indice"
);
}
// Afficher les donn�es du ResultSet
while (rs2.next())
{
// On temporise le login pour l'utiliser plus bas en dehors du ResultSet
loginTemp = rs2.getString("login");
champTitre.setText(rs2.getString("titre"));
zoneContenu.setText(rs2.getString("contenu"));
choixPersonnage.setSelectedItem(loginTemp);
choixImportance.setSelectedIndex(Integer.parseInt(rs2.getString("importance")));
}
// Fermer le ResultSet
rs2.close();
// On d�finit le nom et prenom dans le champ appropri� pour savoir a qui appartient le login
String[] identiteJoueur = new String[2];
identiteJoueur = identiteJoueur(loginTemp);
if (identiteJoueur[0] != null)
{
champNomPerso.setText(identiteJoueur[0] + " " + identiteJoueur[1]);
}
else
{
champNomPerso.setText(null);
}
}
catch (SQLException sqe)
{
System.out.println("Erreur base de donn�es: " + sqe.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
// On rentre en mode �dition
btnModifier.setEnabled(true);
}
// Fermer la connexion � la bdd
bdd.fermerConnexion();
}
// D�-Verrouille certains composants qui risquent de rentrer en conflits
verrouillerComposant = false;
}
/**
* Proc�dure qui enregistre un nouvelle indice dans la bdd
*/
public boolean ajouterIndice()
{
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// Ajouter un nouvel indice dans la base de donn�es
String sqlNouveauIndice = "INSERT INTO indice (titre, contenu, importance) VALUES (" +
"\"" + champTitre.getText() + "\", " +
"\"" + zoneContenu.getText() + "\", " +
"" + choixImportance.getSelectedIndex() +
" ) ";
// Si le MJ veux ajouter un indice a 1 ou tous les personnages...
if (tempsTousJoueurs == false)
{
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction(sqlNouveauIndice);
// On recup�re le dernier id de l'indice dans la bdd
int idIndice = -1;
idIndice = bdd.executerRequete("SELECT last_insert_rowid()").getInt("last_insert_rowid()");
// si on a d�finit une image, on l'ins�re
if (champImageLien.getText().length() > 0)
{
bdd.enregistrerImage(image.getAbsolutePath(), idIndice);
}
// On recup�re l'id du joueur
int idJoueur = -1;
if (choixPersonnage.getSelectedItem() != null)
idJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + (String) choixPersonnage.getSelectedItem() + "'").getInt("id");
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction("INSERT INTO indice_relation (ref_perso, ref_indice) VALUES (" +
" " + idJoueur + ", " +
" " + idIndice + " )" +
"");
}
else
{
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction(sqlNouveauIndice);
// On recup�re le dernier id de l'indice dans la bdd
int idIndice = -1;
idIndice = bdd.executerRequete("SELECT last_insert_rowid()").getInt("last_insert_rowid()");
// si on a d�finit une image, on l'ins�re
if (champImageLien.getText().length() > 0)
{
bdd.enregistrerImage(image.getAbsolutePath(), idIndice);
}
for (int i=0; i<choixPersonnage.getItemCount(); i++)
{
if (choixPersonnage.getItemAt(i) != null)
{
// On recup�re l'id du joueur
int idJoueur = -1;
idJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + choixPersonnage.getItemAt(i) + "'").getInt("id");
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction("INSERT INTO indice_relation (ref_perso, ref_indice) VALUES (" +
" " + idJoueur + ", " +
" " + idIndice + " )" +
"");
}
}
}
// Penalit� du temps joueur
if (tempsPenalite && choixPersonnage.getSelectedItem() != null)
{
tempsContreIndice((String) choixPersonnage.getSelectedItem());
}
}
catch (SQLException sqe)
{
System.out.println("Erreur base de donn�es: " + sqe.getMessage());
return false;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return false;
}
// Fermer la connexion � la base de donn�es
bdd.fermerConnexion();
// Actualiser la liste des indices
rafraichirListeIndices();
// R.A.Z des composants du formulaire
effacerFormulaire();
// Si on arrive ici, c'est qu'on a pas eu de probl�mes
return true;
}
/**
* Proc�dure qui enregistre un nouvelle indice dans la bdd
*/
public boolean ajouterRelationJoueurIndice()
{
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// Si le MJ veux ajouter un indice a 1 ou tous les personnages...
if (tempsTousJoueurs == false)
{
int idInd = getIdIndice();
System.out.println(idInd);
// si on a d�finit une image, on l'ins�re
if (champImageLien.getText().length() > 0)
{
bdd.enregistrerImage(image.getAbsolutePath(), idIndice);
}
// On recup�re l'id du joueur
int idJoueur = -1;
if (choixPersonnage.getSelectedItem() != null)
idJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + (String) choixPersonnage.getSelectedItem() + "'").getInt("id");
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction("INSERT INTO indice_relation (ref_perso, ref_indice) VALUES (" +
" " + idJoueur + ", " +
" " + idIndice + " )" +
"");
}
else
{
// On recup�re le dernier id de l'indice dans la bdd
int idIndice = -1;
idIndice = bdd.executerRequete("SELECT last_insert_rowid()").getInt("last_insert_rowid()");
// si on a d�finit une image, on l'ins�re
if (champImageLien.getText().length() > 0)
{
bdd.enregistrerImage(image.getAbsolutePath(), idIndice);
}
for (int i=0; i<choixPersonnage.getItemCount(); i++)
{
if (choixPersonnage.getItemAt(i) != null)
{
// On recup�re l'id du joueur
int idJoueur = -1;
idJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + choixPersonnage.getItemAt(i) + "'").getInt("id");
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction("INSERT INTO indice_relation (ref_perso, ref_indice) VALUES (" +
" " + idJoueur + ", " +
" " + idIndice + " )" +
"");
}
}
}
// Penalit� du temps joueur
if (tempsPenalite && choixPersonnage.getSelectedItem() != null)
{
tempsContreIndice((String) choixPersonnage.getSelectedItem());
}
}
catch (SQLException sqe)
{
System.out.println("Erreur base de donn�es: " + sqe.getMessage());
return false;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return false;
}
// Fermer la connexion � la base de donn�es
bdd.fermerConnexion();
// Actualiser la liste des indices
rafraichirListeIndices();
// R.A.Z des composants du formulaire
effacerFormulaire();
// Si on arrive ici, c'est qu'on a pas eu de probl�mes
return true;
}
/**
* Proc�dure qui modifie un indice existant dans la bdd
*/
public boolean modifierIndice()
{
// Variables locale
int idIndice = getIdIndice();
String loginJoueur = getLoginJoueur();
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction("UPDATE indice SET " +
" titre = \"" + champTitre.getText() + "\", " +
" contenu = \"" + zoneContenu.getText() + "\", " +
" importance = " + choixImportance.getSelectedIndex() +
" WHERE id = " + idIndice
);
// si on a d�finit une image, on l'ins�re
if (champImageLien.getText().length() > 0)
{
bdd.enregistrerImage(image.getAbsolutePath(), idIndice);
}
// recuperer l'id du joueur
int idNouveauJoueur = -1;
if ((loginJoueur != null && (String) choixPersonnage.getSelectedItem() != null) || (String) choixPersonnage.getSelectedItem() != null)
{
idNouveauJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + (String) choixPersonnage.getSelectedItem() + "'").getInt("id");
}
// Si on modifie selon le login d'un joueur
// recuperer l'id du joueur
int idAncienJoueur = -1;
if (loginJoueur != null)
{
idAncienJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + getLoginJoueur() + "'").getInt("id");
}
if (loginJoueur != null)
{
// Mettre a jours les relations indices <> personnages
bdd.executerInstruction("UPDATE indice_relation SET " +
" ref_perso = " + idNouveauJoueur +
" WHERE ref_indice = " + idIndice +
" AND ref_perso = " + idAncienJoueur
);
}
else
{
if (idNouveauJoueur == -1)
{
// Mettre a jours les relations indices <> personnages
bdd.executerInstruction("UPDATE indice_relation SET " +
" ref_perso = -1 " +
" WHERE ref_indice = " + idIndice +
" AND ref_perso = " + idAncienJoueur
);
}
else
{
// Mettre a jours les relations indices <> personnages
bdd.executerInstruction("UPDATE indice_relation SET " +
" ref_perso = " + idNouveauJoueur +
" WHERE ref_indice = " + idIndice +
" AND ref_perso = " + idAncienJoueur
);
}
}
// Penalit� du temps joueur
if (tempsPenalite && choixPersonnage.getSelectedItem() != null)
{
tempsContreIndice((String) choixPersonnage.getSelectedItem());
}
}
catch (SQLException sqe)
{
System.out.println("Erreur base de donn�es: " + sqe.getMessage());
return false;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return false;
}
// Fermer la connexion � la base de donn�es
bdd.fermerConnexion();
// Actualiser la liste des indices
rafraichirListeIndices();
// R.A.Z des composants du formulaire
effacerFormulaire();
// Si on arrive ici, c'est qu'on a pas eu de probl�mes
return true;
}
/**
* On traite comme cas � part quand on souhaite ajouter / modifier indice(s) pour tous les joueurs
*/
public boolean indiceTousLesJoueurs()
{
int idIndiceLocal = getIdIndice();
String sqlNouveauIndice = null;
boolean etat = true;
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// Ajouter un nouvel indice dans la base de donn�es
sqlNouveauIndice = "INSERT INTO indice (titre, contenu, importance) VALUES (" +
"\"" + champTitre.getText() + "\", " +
"\"" + zoneContenu.getText() + "\", " +
"" + choixImportance.getSelectedIndex() +
" ) ";
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction(sqlNouveauIndice);
// On recup�re le dernier id de l'indice dans la bdd
int idIndice = -1;
idIndice = bdd.executerRequete("SELECT last_insert_rowid()").getInt("last_insert_rowid()");
// si on a d�finit une image, on met a jours le champs en question
if (champImageLien.getText().length() > 0)
{
bdd.enregistrerImage(image.getAbsolutePath(), idIndice);
}
for (int i=0; i<choixPersonnage.getItemCount(); i++)
{
if (choixPersonnage.getItemAt(i) != null)
{
// On recup�re l'id du joueur
int idJoueur = -1;
idJoueur = bdd.executerRequete("SELECT id FROM personnage WHERE login = '" + choixPersonnage.getItemAt(i) + "'").getInt("id");
// Ajouter un nouvel indice dans la base de donn�es
bdd.executerInstruction("INSERT INTO indice_relation (ref_perso, ref_indice) VALUES (" +
" " + idJoueur + ", " +
" " + idIndice + " )" +
"");
}
}
// Supprimer l'indice vide & sa relation
bdd.executerInstruction("DELETE FROM indice " + " WHERE id = " + idIndiceLocal);
bdd.executerInstruction("DELETE FROM indice_relation " + " WHERE ref_indice = " + idIndiceLocal);
// Message de confirmation
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� distribu� a tous les joueurs avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception e)
{
// Trace debug
System.out.println("Erreur lors du traitement pour les indices vers tous les joueurs: \n" + e.getStackTrace());
// Message d'erreur
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che de distribuer l'indice � tous les joueurs :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
// Changer l'etat de fin de fonction
etat = false;
}
// Fermer la connexion � la bdd
bdd.fermerConnexion();
// Actualiser la liste des indices
rafraichirListeIndices();
// R.A.Z des composants du formulaire
effacerFormulaire();
// Retourner l'etat de la fonction
return etat;
}
/**
* Proc�dure qui rafraichit les indices dans le tableau
* A utiliser par exemple si vous avez ajouter un nouvelle indice � la bdd
*/
public void rafraichirListeIndices()
{
int nombreLignes = tableIndices.getRowCount();
for(int i = nombreLignes - 1; i >= 0; i--)
{
modeleTableIndice.removeRow(i);
}
tableIndices = historique(tableIndices, null);
}
/**
* Petite fonction qui retourne les donn�es de la ligne du tableau point� par la sourie
* @param _table Fournir un tableau de type JTable
* @param _indexLigne Indexe de la ligne
* @param _indexColonne Index de la colonne
* @return Le contenu � la ligne et colonne specifi� en param�tre
*/
public Object obtenirDonneesLigneTableau(JTable _table, int _indexLigne, int _indexColonne)
{
return _table.getModel().getValueAt(_indexLigne, _indexColonne);
}
/**
* Fonction qui prend le contenu de la ligne et colonne point� par la sourie
* @param _table Fourir le tableau de type JTable
* @return Un objet generique � caster comme vous voulez (string, int, ...)
*/
public Object contenuCelluleTableau(JTable _table)
{
// Variables locale
Object cellule = null;
int ligne = _table.getSelectedRow();
int colonne = _table.getSelectedColumn();
// V�rifier si on a une ligne et une colonne point�
if (ligne != -1 & colonne != -1)
{
cellule = _table.getValueAt(ligne,colonne);
}
// Retourner le contenu de la cellule
return cellule;
}
/**
* Fonction qui prend le contenu de la 1�re colonne � la 1�re ligne du tableau
* @param _table Fourir le tableau de type JTable
* @param _indexColonne A quelle colonne le contenu doit etre piocher (par d�faut mettre 0 !!!)
* @return Un objet generique � caster comme vous voulez (string, int, ...)
*/
public Object contenuPremiereCelluleTableau(JTable _table, int _indexColonne)
{
// Variables locale
Object cellule = null;
int ligne = _table.getSelectedRow();
int colonne = _indexColonne;
// V�rifier si on a une ligne point�
if (ligne != -1)
{
cellule = _table.getValueAt(ligne, colonne);
}
return cellule;
}
/**
* Afficher l'histoirique des indices
* Si login non null, on affiche les indices du joeur en question
* @param _table Composant JTable ou seront affich�s les indices
* @param _login Identifiant du joueur
* @return Un Jtable remplis de donn�es
*/
public final JTable historique(JTable _table, String _login)
{
// Variables locales
ResultSet rs;
JTable tableLocal = _table;
String login = _login;
String sqlJoint = " ";
if (login != null)
{
sqlJoint = " AND perso.login = '" + login + "' ";
}
bdd = new BaseDeDonnees(coeurServeur);
try
{
// D�finition des colonnes de la table
String[] tableColumnsName = { "N�", "Joueur", "Titre" };
DefaultTableModel tableModele = (DefaultTableModel) tableLocal.getModel();
tableModele.setColumnIdentifiers(tableColumnsName);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModele);
tableLocal.setRowSorter(sorter);
// Parser les donn�es de la requ�te dans un ResultSet
rs = bdd.executerRequete("" +
" SELECT ind.id, perso.login, ind.titre " +
" FROM indice ind, indice_relation indr " +
" LEFT JOIN personnage perso ON indr.ref_perso = perso.id " +
" WHERE ind.id = indr.ref_indice " +
sqlJoint +
" ORDER BY ind.importance DESC "
);
ResultSetMetaData rsMetaData = rs.getMetaData();
// R�cuperer le nombre de colonnes
int numeroColonne = rsMetaData.getColumnCount();
// Boucle � travers le ResultSet et le transfert dans le mod�le
while (rs.next())
{
Object[] objet = new Object[numeroColonne];
for (int i = 0; i < numeroColonne; i++)
{
objet[i] = rs.getObject(i + 1);
}
// Ajouter une ligne dans le JTable avec les donn�es du l'array objet
tableModele.addRow(objet);
}
tableLocal.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// D�finir le mod�le du tableau
tableLocal.setModel(tableModele);
// D�finir la taille des colonnes
TableColumn tableColonne = tableIndices.getColumnModel().getColumn(0);
tableColonne.setPreferredWidth(50);
TableColumn tableColonne2 = tableIndices.getColumnModel().getColumn(2);
tableColonne2.setPreferredWidth(250);
return tableLocal;
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
/**
* Proc�dure qui supprimer un indice selectionner dans le tableau
*/
private boolean supprimerIndice()
{
// Variables locale
int idIndice = getIdIndice();
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// Supprimer l'indice de la bdd
bdd.executerInstruction("DELETE FROM indice " +
" WHERE id = " + idIndice
);
// Supprimer les relations personnage li� a l'indice
bdd.executerInstruction("DELETE FROM indice_relation " +
" WHERE ref_indice = " + idIndice
);
}
catch (SQLException sqe)
{
System.out.println("Erreur base de donn�es: " + sqe.getMessage());
return false;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return false;
}
// Fermer la connexion � la base de donn�es
bdd.fermerConnexion();
// Actualiser la liste des indices
rafraichirListeIndices();
// R.A.Z des composants du formulaire
effacerFormulaire();
// Si on arrive ici, cela signifie qu'on a pas eut de problemes
return true;
}
/**
* Supprimer tous les indices du joueur
* @param _idJoueur Identifiant du joueur
* @return Confirmation que tout est ok
*/
public boolean supprimerIndicesJoueur(int _idJoueur)
{
int refIndiceTemp = -1;
int cptIndices = 0;
try
{
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
while (refIndiceTemp != 0)
{
// On recup�re l'id de l'indice dans la relation selon le personnage
refIndiceTemp = bdd.executerRequete("SELECT ref_indice FROM indice_relation WHERE ref_perso = " + _idJoueur).getInt("ref_indice");
// Supprimer les relations personnage li� a l'indice
bdd.executerInstruction("DELETE FROM indice_relation " +
" WHERE ref_indice = " + refIndiceTemp +
" AND ref_perso = " + _idJoueur
);
// Voir si l'indice est encore utilis� par quelqu'un
cptIndices = bdd.executerRequete("SELECT count(id) cpt FROM indice_relation WHERE ref_indice = " + refIndiceTemp).getInt("cpt");
if (cptIndices == 0)
{
// Supprimer l'indice
bdd.executerInstruction("DELETE FROM indice " +
" WHERE id = " + refIndiceTemp
);
}
}
// Fermer la connexion � la base de donn�es
bdd.fermerConnexion();
}
catch (Exception e)
{
e.getMessage();
return false;
}
return true;
}
private void tempsContreIndice(String _personnage)
{
// Ouvrir une nouvelle connexion � la bdd
bdd = new BaseDeDonnees(coeurServeur);
try
{
// recuperation du JTextField
int champChronoInt = Integer.decode(champHeure.getText())*3600 + Integer.decode(champMin.getText())*60 + Integer.decode(champSec.getText());
// Recuperation du temps actuel du joueur
int ancienTempsChrono = bdd.executerRequete("SELECT temps FROM personnage WHERE login = \"" + _personnage + "\" ").getInt("temps");
// D�finir le nouveau temps
int nouveauTempsChrono = ancienTempsChrono - champChronoInt;
// Mettre a jours la base de donn�es
bdd.executerInstruction("UPDATE personnage SET " +
" temps = " + nouveauTempsChrono + " " +
" WHERE login = \"" + _personnage + "\" "
);
}
catch (Exception e)
{
e.getStackTrace();
}
// Fermer la connexion � la base de donn�es
bdd.fermerConnexion();
}
/**
* Proc�dure qui efface les donn�es saisies dans le formulaires
*/
public void effacerFormulaire()
{
// Si cette case est choch�, cela signifie que le client veux se souvenir
// du contenu de l'indice car, il veux l'atribuer a quelqu'un d'autre
if(!checkMemo.isSelected())
{
champTitre.setText(null);
zoneContenu.setText(null);
choixPersonnage.setSelectedIndex(0);
champNomPerso.setText(null);
champImageLien.setText(null);
choixImportance.setSelectedIndex(0);
champHeure.setText(null);
champMin.setText(null);
champSec.setText(null);
tableIndices.getSelectionModel().clearSelection();
setLoginJoueur(null);
champTitre.requestFocusInWindow();
}
tableIndices.getSelectionModel().clearSelection();
setIdIndice(-1);
btnModifier.setEnabled(false);
}
// ----- Getters & Setters ----- //
/**
* Getter du panel gestion des indices
* @return Un composant JPanel
*/
public JPanel getPanelGestionIndices()
{
return panelGestionIndices;
}
/**
* Setter du panel gestion des indices
* @param panelGestionIndices Un composant JPanel
*/
public void setPanelGestionIndices(JPanel _panelGestionIndices)
{
this.panelGestionIndices = _panelGestionIndices;
}
/**
* Getter de l'id de l'indice en m�moire
* @return Le num�ro d'indice
*/
public int getIdIndice()
{
return idIndice;
}
/**
* Setter pour d�finir un id d'indice en m�moire
* @param _idIndice Le num�ro d'indice
*/
public void setIdIndice(int _idIndice)
{
this.idIndice = _idIndice;
}
/**
* Getter du login du joueur
* @return Un login du joueur
*/
public String getLoginJoueur()
{
return loginJoueur;
}
/**
* Setter pour d�finir le login du joueur
* @param _loginJoueur Un login du joueur
*/
public void setLoginJoueur(String _loginJoueur)
{
this.loginJoueur = _loginJoueur;
}
}
| true | true | public ComposantGestionIndices(FenetreAdmin _fenetre, final SpringLayout _springLayout, CoeurServeur _coeurServeur)
{
coeurServeur = _coeurServeur;
panelGestionIndices = new JPanel();
panelGestionIndices.setOpaque(false);
_springLayout.putConstraint(SpringLayout.NORTH, panelGestionIndices, -200, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.SOUTH, panelGestionIndices, 300, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.WEST, panelGestionIndices, -350, SpringLayout.HORIZONTAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.EAST, panelGestionIndices, 400, SpringLayout.HORIZONTAL_CENTER, _fenetre.getContentPane());
_fenetre.getContentPane().add(panelGestionIndices);
panelGestionIndices.setLayout(new MigLayout("", "[][10.00][grow]", "[335.00,top]"));
this.setLayout(_springLayout);
SpringLayout springLayout = new SpringLayout();
setLayout(springLayout);
pnlFormulaire = new JPanel();
pnlFormulaire.setOpaque(false);
springLayout.putConstraint(SpringLayout.NORTH, pnlFormulaire, 10, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.WEST, pnlFormulaire, 10, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, pnlFormulaire, 394, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, pnlFormulaire, 315, SpringLayout.WEST, this);
panelGestionIndices.add(pnlFormulaire, "cell 0 0");
pnlFormulaire.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(48dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(50dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(50dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("max(45dlu;min)"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("default:grow"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JButton btnNouveauIndice = new JButton("Nouveau indice");
btnNouveauIndice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
effacerFormulaire();
}
});
pnlFormulaire.add(btnNouveauIndice, "4, 2, 3, 1");
JLabel lblTitre = new JLabel("Titre :");
pnlFormulaire.add(lblTitre, "2, 4");
champTitre = new JTextField();
pnlFormulaire.add(champTitre, "4, 4, 3, 1, fill, default");
champTitre.setColumns(10);
JLabel lblContenu = new JLabel("Contenu :");
pnlFormulaire.add(lblContenu, "2, 6");
JScrollPane scrollPaneArea = new JScrollPane();
pnlFormulaire.add(scrollPaneArea, "4, 6, 3, 1, fill, fill");
zoneContenu = new JTextArea();
zoneContenu.setLineWrap(true);
scrollPaneArea.setViewportView(zoneContenu);
JLabel lblPersonnage = new JLabel("Personnage :");
pnlFormulaire.add(lblPersonnage, "2, 8");
choixPersonnage = new JComboBox();
choixPersonnage.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _e)
{
if (verrouillerComposant == false)
{
String[] identiteJoueur = new String[2];
identiteJoueur = identiteJoueur((String) choixPersonnage.getSelectedItem());
if (identiteJoueur[0] != null)
{
champNomPerso.setText(identiteJoueur[0] + " " + identiteJoueur[1]);
}
else
{
rafraichirListeIndices();
}
}
if (getIdIndice() == -1)
{
btnAjouter.setText("Ajouter");
}
}
});
pnlFormulaire.add(choixPersonnage, "4, 8, 3, 1, fill, default");
champNomPerso = new JTextField();
champNomPerso.setFont(new Font("Tahoma", Font.PLAIN, 10));
champNomPerso.setEditable(false);
pnlFormulaire.add(champNomPerso, "4, 10, 3, 1, fill, default");
champNomPerso.setColumns(10);
JLabel lblImage = new JLabel("Image :");
pnlFormulaire.add(lblImage, "2, 12");
champImageLien = new JTextField();
pnlFormulaire.add(champImageLien, "4, 12, fill, default");
champImageLien.setColumns(10);
JButton btnChoisirImage = new JButton("Choisir");
btnChoisirImage.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _e)
{
choisirImage();
}
});
pnlFormulaire.add(btnChoisirImage, "6, 12");
JLabel lblPriorite = new JLabel("Importance :");
pnlFormulaire.add(lblPriorite, "2, 14");
choixImportance = new JComboBox();
choixImportance.setModel((ComboBoxModel) new DefaultComboBoxModel(new String[] {"Peu important", "Important", "Tr\u00E8s important"}));
pnlFormulaire.add(choixImportance, "4, 14, 3, 1, fill, default");
JLabel lblTemps = new JLabel("P\u00E9nalit\u00E9 :");
pnlFormulaire.add(lblTemps, "2, 16");
panel = new JPanel();
pnlFormulaire.add(panel, "4, 16, 4, 1, left, fill");
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
champHeure = new JTextField();
panel.add(champHeure);
champHeure.setColumns(3);
lblNewLabel = new JLabel("h");
panel.add(lblNewLabel);
champMin = new JTextField();
panel.add(champMin);
champMin.setColumns(3);
lblM = new JLabel("m");
panel.add(lblM);
champSec = new JTextField();
panel.add(champSec);
champSec.setColumns(3);
lblNewLabel_1 = new JLabel("s");
panel.add(lblNewLabel_1);
JLabel lblOptions = new JLabel("Options:");
pnlFormulaire.add(lblOptions, "2, 18");
checkIndicePenalite = new JCheckBox("Indice contre du temps");
checkIndicePenalite.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (checkIndicePenalite.isSelected())
{
champHeure.setText("00");
champMin.setText("00");
champSec.setText("00");
tempsPenalite = true;
}
else
{
champHeure.setText(null);
champMin.setText(null);
champSec.setText(null);
tempsPenalite = false;
}
}
});
pnlFormulaire.add(checkIndicePenalite, "4, 18, 4, 1");
checkTousLesJoueurs = new JCheckBox("Indice pour tous les joueurs");
checkTousLesJoueurs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (checkTousLesJoueurs.isSelected())
{
tempsTousJoueurs = true;
champHeure.setEditable(false);
champMin.setEditable(false);
champSec.setEditable(false);
choixPersonnage.setSelectedIndex(0);
choixPersonnage.setEnabled(false);
champNomPerso.setText("Tous les joueurs !");
}
else
{
tempsTousJoueurs = false;
champHeure.setEditable(true);
champMin.setEditable(true);
champSec.setEditable(true);
choixPersonnage.setEnabled(true);
champNomPerso.setText(null);
}
}
});
pnlFormulaire.add(checkTousLesJoueurs, "4, 20, 4, 1");
btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// V�rifier si les champs sont biens remplis
if (champTitre.getText() != null && zoneContenu.getText() != null)
{
if (ajouterIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� ajout� avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che d'ajouter l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un ou plusieurs champs n'ont pas �t�s remplis ou ne correspondent pas aux crit�res requis.\nChamps obligatoires: titre, contenu.", "Formulaire non valide", JOptionPane.ERROR_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
btnAjouterToJoueur = new JButton("Ajouter � un joueur");
btnAjouterToJoueur.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// V�rifier si les champs sont biens remplis
if (champTitre.getText() != null && zoneContenu.getText() != null)
{
if (ajouterRelationJoueurIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� ajout� avec succ�s au joueur !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che d'ajouter l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un ou plusieurs champs n'ont pas �t�s remplis ou ne correspondent pas aux crit�res requis.\nChamps obligatoires: titre, contenu.", "Formulaire non valide", JOptionPane.ERROR_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
btnModifier = new JButton("Modifier");
btnModifier.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
if (getIdIndice() != -1)
{
if (tempsTousJoueurs == false)
{
if (modifierIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� modif� avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che de modifier l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
indiceTousLesJoueurs();
}
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
checkMemo = new JCheckBox("Se souvenir des donn\u00E9es");
checkMemo.setToolTipText("Cochez cette case pour garder les donn\u00E9es du dernier\r\nindice afin de les r\u00E9utiliser sur un autre\r\npersonnage, de fa\u00E7on diff\u00E9rente...");
pnlFormulaire.add(checkMemo, "4, 22, 4, 1");
pnlFormulaire.add(btnModifier, "4, 24");
pnlFormulaire.add(btnAjouter, "6, 24");
pnlFormulaire.add(btnAjouterToJoueur, "4, 26");
JPanel pnlIndices = new JPanel();
pnlIndices.setOpaque(false);
panelGestionIndices.add(pnlIndices, "cell 2 0,grow");
pnlIndices.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(64dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
RowSpec.decode("max(15dlu;default)"),
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("max(160dlu;min)"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblHistoriqueDesIndices = new JLabel("Historique des indices :");
lblHistoriqueDesIndices.setFont(new Font("Tahoma", Font.BOLD, 11));
pnlIndices.add(lblHistoriqueDesIndices, "2, 1, 3, 1");
JLabel lblIndicesDuJoueur = new JLabel("Indices du Joueur:");
pnlIndices.add(lblIndicesDuJoueur, "2, 2, right, default");
choixPersonnage2 = new JComboBox();
choixPersonnage2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
if ((String) choixPersonnage2.getSelectedItem() != null)
{
int nombreLignes = tableIndices.getRowCount();
for(int i = nombreLignes - 1; i >= 0; i--)
{
modeleTableIndice.removeRow(i);
}
historique(tableIndices, (String) choixPersonnage2.getSelectedItem());
}
else
{
rafraichirListeIndices();
}
}
});
pnlIndices.add(choixPersonnage2, "4, 2, fill, default");
JScrollPane spIndices = new JScrollPane();
pnlIndices.add(spIndices, "2, 4, 3, 5, fill, fill");
// Charger les personnages
modeleTableIndice = new DefaultTableModel();
tableIndices = new JTable(modeleTableIndice);
tableIndices.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
setIdIndice((Integer) contenuPremiereCelluleTableau(tableIndices, 0));
setLoginJoueur((String) contenuPremiereCelluleTableau(tableIndices, 1));
recupererContenuIndice(getIdIndice(), getLoginJoueur());
}
});
spIndices.setViewportView(tableIndices);
JLabel lblChoisirUnIndice = new JLabel("Choisir un indice dans l'historique pour l'\u00E9diter ou supprimer");
lblChoisirUnIndice.setFont(new Font("Tahoma", Font.ITALIC, 11));
pnlIndices.add(lblChoisirUnIndice, "2, 10, 3, 1");
JButton btnSupprimerIndice = new JButton("Supprimer l'indice");
btnSupprimerIndice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// Si on a s�lectionner un indice, on le supprime
if (getIdIndice() != -1)
{
if (supprimerIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� supprimer avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che la suppression de l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Vous n'avez pas s�lectionner l'indice � supprimer !", "Attention", JOptionPane.WARNING_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
pnlIndices.add(btnSupprimerIndice, "2, 14, 3, 1");
}
| public ComposantGestionIndices(FenetreAdmin _fenetre, final SpringLayout _springLayout, CoeurServeur _coeurServeur)
{
coeurServeur = _coeurServeur;
panelGestionIndices = new JPanel();
panelGestionIndices.setOpaque(false);
_springLayout.putConstraint(SpringLayout.NORTH, panelGestionIndices, -200, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.SOUTH, panelGestionIndices, 350, SpringLayout.VERTICAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.WEST, panelGestionIndices, -350, SpringLayout.HORIZONTAL_CENTER, _fenetre.getContentPane());
_springLayout.putConstraint(SpringLayout.EAST, panelGestionIndices, 400, SpringLayout.HORIZONTAL_CENTER, _fenetre.getContentPane());
_fenetre.getContentPane().add(panelGestionIndices);
panelGestionIndices.setLayout(new MigLayout("", "[][10.00][grow]", "[335.00,top]"));
this.setLayout(_springLayout);
SpringLayout springLayout = new SpringLayout();
setLayout(springLayout);
pnlFormulaire = new JPanel();
pnlFormulaire.setOpaque(false);
springLayout.putConstraint(SpringLayout.NORTH, pnlFormulaire, 10, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.WEST, pnlFormulaire, 10, SpringLayout.WEST, this);
springLayout.putConstraint(SpringLayout.SOUTH, pnlFormulaire, 394, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.EAST, pnlFormulaire, 315, SpringLayout.WEST, this);
panelGestionIndices.add(pnlFormulaire, "cell 0 0");
pnlFormulaire.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(48dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(50dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(50dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("max(45dlu;min)"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("default:grow"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JButton btnNouveauIndice = new JButton("Nouveau indice");
btnNouveauIndice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
effacerFormulaire();
}
});
pnlFormulaire.add(btnNouveauIndice, "4, 2, 3, 1");
JLabel lblTitre = new JLabel("Titre :");
pnlFormulaire.add(lblTitre, "2, 4");
champTitre = new JTextField();
pnlFormulaire.add(champTitre, "4, 4, 3, 1, fill, default");
champTitre.setColumns(10);
JLabel lblContenu = new JLabel("Contenu :");
pnlFormulaire.add(lblContenu, "2, 6");
JScrollPane scrollPaneArea = new JScrollPane();
pnlFormulaire.add(scrollPaneArea, "4, 6, 3, 1, fill, fill");
zoneContenu = new JTextArea();
zoneContenu.setLineWrap(true);
scrollPaneArea.setViewportView(zoneContenu);
JLabel lblPersonnage = new JLabel("Personnage :");
pnlFormulaire.add(lblPersonnage, "2, 8");
choixPersonnage = new JComboBox();
choixPersonnage.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _e)
{
if (verrouillerComposant == false)
{
String[] identiteJoueur = new String[2];
identiteJoueur = identiteJoueur((String) choixPersonnage.getSelectedItem());
if (identiteJoueur[0] != null)
{
champNomPerso.setText(identiteJoueur[0] + " " + identiteJoueur[1]);
}
else
{
rafraichirListeIndices();
}
}
if (getIdIndice() == -1)
{
btnAjouter.setText("Ajouter");
}
}
});
pnlFormulaire.add(choixPersonnage, "4, 8, 3, 1, fill, default");
champNomPerso = new JTextField();
champNomPerso.setFont(new Font("Tahoma", Font.PLAIN, 10));
champNomPerso.setEditable(false);
pnlFormulaire.add(champNomPerso, "4, 10, 3, 1, fill, default");
champNomPerso.setColumns(10);
JLabel lblImage = new JLabel("Image :");
pnlFormulaire.add(lblImage, "2, 12");
champImageLien = new JTextField();
pnlFormulaire.add(champImageLien, "4, 12, fill, default");
champImageLien.setColumns(10);
JButton btnChoisirImage = new JButton("Choisir");
btnChoisirImage.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _e)
{
choisirImage();
}
});
pnlFormulaire.add(btnChoisirImage, "6, 12");
JLabel lblPriorite = new JLabel("Importance :");
pnlFormulaire.add(lblPriorite, "2, 14");
choixImportance = new JComboBox();
choixImportance.setModel((ComboBoxModel) new DefaultComboBoxModel(new String[] {"Peu important", "Important", "Tr\u00E8s important"}));
pnlFormulaire.add(choixImportance, "4, 14, 3, 1, fill, default");
JLabel lblTemps = new JLabel("P\u00E9nalit\u00E9 :");
pnlFormulaire.add(lblTemps, "2, 16");
panel = new JPanel();
pnlFormulaire.add(panel, "4, 16, 4, 1, left, fill");
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
champHeure = new JTextField();
panel.add(champHeure);
champHeure.setColumns(3);
lblNewLabel = new JLabel("h");
panel.add(lblNewLabel);
champMin = new JTextField();
panel.add(champMin);
champMin.setColumns(3);
lblM = new JLabel("m");
panel.add(lblM);
champSec = new JTextField();
panel.add(champSec);
champSec.setColumns(3);
lblNewLabel_1 = new JLabel("s");
panel.add(lblNewLabel_1);
JLabel lblOptions = new JLabel("Options:");
pnlFormulaire.add(lblOptions, "2, 18");
checkIndicePenalite = new JCheckBox("Indice contre du temps");
checkIndicePenalite.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (checkIndicePenalite.isSelected())
{
champHeure.setText("00");
champMin.setText("00");
champSec.setText("00");
tempsPenalite = true;
}
else
{
champHeure.setText(null);
champMin.setText(null);
champSec.setText(null);
tempsPenalite = false;
}
}
});
pnlFormulaire.add(checkIndicePenalite, "4, 18, 4, 1");
checkTousLesJoueurs = new JCheckBox("Indice pour tous les joueurs");
checkTousLesJoueurs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (checkTousLesJoueurs.isSelected())
{
tempsTousJoueurs = true;
champHeure.setEditable(false);
champMin.setEditable(false);
champSec.setEditable(false);
choixPersonnage.setSelectedIndex(0);
choixPersonnage.setEnabled(false);
champNomPerso.setText("Tous les joueurs !");
}
else
{
tempsTousJoueurs = false;
champHeure.setEditable(true);
champMin.setEditable(true);
champSec.setEditable(true);
choixPersonnage.setEnabled(true);
champNomPerso.setText(null);
}
}
});
pnlFormulaire.add(checkTousLesJoueurs, "4, 20, 4, 1");
btnAjouter = new JButton("Ajouter");
btnAjouter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// V�rifier si les champs sont biens remplis
if (champTitre.getText() != null && zoneContenu.getText() != null)
{
if (ajouterIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� ajout� avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che d'ajouter l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un ou plusieurs champs n'ont pas �t�s remplis ou ne correspondent pas aux crit�res requis.\nChamps obligatoires: titre, contenu.", "Formulaire non valide", JOptionPane.ERROR_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
btnAjouterToJoueur = new JButton("Ajouter � un joueur");
btnAjouterToJoueur.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// V�rifier si les champs sont biens remplis
if (champTitre.getText() != null && zoneContenu.getText() != null)
{
if (ajouterRelationJoueurIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� ajout� avec succ�s au joueur !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che d'ajouter l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un ou plusieurs champs n'ont pas �t�s remplis ou ne correspondent pas aux crit�res requis.\nChamps obligatoires: titre, contenu.", "Formulaire non valide", JOptionPane.ERROR_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
btnModifier = new JButton("Modifier");
btnModifier.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
if (getIdIndice() != -1)
{
if (tempsTousJoueurs == false)
{
if (modifierIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� modif� avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che de modifier l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
indiceTousLesJoueurs();
}
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
checkMemo = new JCheckBox("Se souvenir des donn\u00E9es");
checkMemo.setToolTipText("Cochez cette case pour garder les donn\u00E9es du dernier\r\nindice afin de les r\u00E9utiliser sur un autre\r\npersonnage, de fa\u00E7on diff\u00E9rente...");
pnlFormulaire.add(checkMemo, "4, 22, 4, 1");
pnlFormulaire.add(btnModifier, "4, 24");
pnlFormulaire.add(btnAjouter, "6, 24");
pnlFormulaire.add(btnAjouterToJoueur, "4, 26");
JPanel pnlIndices = new JPanel();
pnlIndices.setOpaque(false);
panelGestionIndices.add(pnlIndices, "cell 2 0,grow");
pnlIndices.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(64dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
RowSpec.decode("max(15dlu;default)"),
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
RowSpec.decode("max(160dlu;min)"),
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
JLabel lblHistoriqueDesIndices = new JLabel("Historique des indices :");
lblHistoriqueDesIndices.setFont(new Font("Tahoma", Font.BOLD, 11));
pnlIndices.add(lblHistoriqueDesIndices, "2, 1, 3, 1");
JLabel lblIndicesDuJoueur = new JLabel("Indices du Joueur:");
pnlIndices.add(lblIndicesDuJoueur, "2, 2, right, default");
choixPersonnage2 = new JComboBox();
choixPersonnage2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
if ((String) choixPersonnage2.getSelectedItem() != null)
{
int nombreLignes = tableIndices.getRowCount();
for(int i = nombreLignes - 1; i >= 0; i--)
{
modeleTableIndice.removeRow(i);
}
historique(tableIndices, (String) choixPersonnage2.getSelectedItem());
}
else
{
rafraichirListeIndices();
}
}
});
pnlIndices.add(choixPersonnage2, "4, 2, fill, default");
JScrollPane spIndices = new JScrollPane();
pnlIndices.add(spIndices, "2, 4, 3, 5, fill, fill");
// Charger les personnages
modeleTableIndice = new DefaultTableModel();
tableIndices = new JTable(modeleTableIndice);
tableIndices.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
setIdIndice((Integer) contenuPremiereCelluleTableau(tableIndices, 0));
setLoginJoueur((String) contenuPremiereCelluleTableau(tableIndices, 1));
recupererContenuIndice(getIdIndice(), getLoginJoueur());
}
});
spIndices.setViewportView(tableIndices);
JLabel lblChoisirUnIndice = new JLabel("Choisir un indice dans l'historique pour l'\u00E9diter ou supprimer");
lblChoisirUnIndice.setFont(new Font("Tahoma", Font.ITALIC, 11));
pnlIndices.add(lblChoisirUnIndice, "2, 10, 3, 1");
JButton btnSupprimerIndice = new JButton("Supprimer l'indice");
btnSupprimerIndice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent _arg0)
{
// Si on a s�lectionner un indice, on le supprime
if (getIdIndice() != -1)
{
if (supprimerIndice())
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "L'indice a �t� supprimer avec succ�s !", "Message de confirmation", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Un probl�me emp�che la suppression de l'indice :(", "Message d'erreur", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(ComposantGestionIndices.this, "Vous n'avez pas s�lectionner l'indice � supprimer !", "Attention", JOptionPane.WARNING_MESSAGE);
}
coeurServeur.traiterMessage(1, new Message(1, Message.MAJ_LISTE_INDICES, (String) choixPersonnage.getSelectedItem()));
}
});
pnlIndices.add(btnSupprimerIndice, "2, 14, 3, 1");
}
|
diff --git a/src/net/wehi/socrates/AnnotatePairedClusters.java b/src/net/wehi/socrates/AnnotatePairedClusters.java
index 52f26ef..b4681ce 100644
--- a/src/net/wehi/socrates/AnnotatePairedClusters.java
+++ b/src/net/wehi/socrates/AnnotatePairedClusters.java
@@ -1,451 +1,450 @@
package net.wehi.socrates;
/**
*
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.FileOutputStream;
//import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.HashSet;
import net.wehi.socrates.util.SAMFileInfo;
//import net.wehi.socrates.util.SAMRecordSummary;
import net.wehi.socrates.util.TabixReader;
import net.wehi.socrates.util.Utilities;
import net.wehi.socrates.util.MemoryMappedFile;
import net.wehi.socrates.util.SeekableMemoryStream;
//import net.sf.samtools.SAMFileReader;
//import net.sf.samtools.SAMRecord;
//import net.sf.samtools.SAMRecordIterator;
import java.io.File;
import java.util.concurrent.*;
//import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* @author hsu
*
* Created on Mar 14, 2013
*/
@SuppressWarnings("static-access")
public class AnnotatePairedClusters implements Callable<Integer> {
private static final Options options = new Options();
static {
Option help = new Option( "h", "help", false, "print this message" );
Option verbose = new Option( "v", "verbose", false, "be verbose of progress" );
/* Option threads = OptionBuilder.withArgName( "threads" )
.hasArg()
.withDescription("Number of threads to use [default: 3]")
.withType( Number.class )
.withLongOpt( "threads" )
.create( 't' );*/
Option normal = OptionBuilder.withArgName("normal")
.hasArg()
.withDescription("Socrates paired breakpoint calls for normal sample")
.withType( String.class )
.withLongOpt("normal")
.create('n');
Option flank = OptionBuilder.withArgName("flank")
.hasArg()
.withDescription("Normal breakpoint within FLANK nt of tumour breakpoint is considered as the same [default=10(nt)]")
.withType( Integer.class )
.withLongOpt( "flank" )
.create( 'f' );
Option rmsk = OptionBuilder.withArgName("repeatmask")
.hasArg()
.withDescription("UCSC repeat masker track file")
.withType( String.class )
.withLongOpt( "repeatmask" )
.create( 'r' );
//options.addOption( threads );
options.addOption(normal);
options.addOption(rmsk);
options.addOption(flank);
options.addOption(verbose);
options.addOption(help);
}
public static void printHelp() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "AnnotatePairedClusters [options] socrates_paired_cluster_output", options );
}
private static File tabixFile = null;
private static MemoryMappedFile tabixMemory = null;
private static TabixReader annotations = null;
public static final HashSet<String> SINE_LINE_LTR = new HashSet<String>();
public static final HashSet<String> SATELLITE = new HashSet<String>();
public static final HashSet<String> SIMPLE_RPT = new HashSet<String>();
static {
SINE_LINE_LTR.add("SINE"); SINE_LINE_LTR.add("LINE"); SINE_LINE_LTR.add("LTR"); SINE_LINE_LTR.add("SINE?"); SINE_LINE_LTR.add("LINE?"); SINE_LINE_LTR.add("LTR?");
SATELLITE.add("Satellite");
SIMPLE_RPT.add("Low_complexity"); SIMPLE_RPT.add("Simple_repeat");
}
public AnnotatePairedClusters() {
}
public Integer call() {
return new Integer(0);
}
public static ArrayList<PairedCluster> loadBreakpoints(String filename) {
ArrayList<PairedCluster> pb = new ArrayList<PairedCluster>();
int discarded_chrom = 0;
try {
BufferedReader breader = new BufferedReader(new FileReader(filename));
String line = null; //breader.readLine(); // skip header line
while ((line=breader.readLine())!=null) {
if (line.charAt(0)=='#') continue;
String[] tokens = line.split("\t");
// check chrom
if (tokens[0].indexOf('_')!=-1 || tokens[3].indexOf('_')!=-1 || tokens[12].indexOf('_')!=-1 || tokens[15].indexOf('_')!=-1) {
discarded_chrom++;
continue;
}
PairedCluster p = new PairedCluster(tokens);
p.text = line;
pb.add( p );
}
breader.close();
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("Discarded cluster pairs - non-ordinal chromosomes: " + discarded_chrom);
System.err.println("Loaded cluster pairs: " + pb.size());
return pb;
}
private static String extractColumnNames(String filename){
try {
BufferedReader breader = new BufferedReader(new FileReader(filename));
String line = breader.readLine();
if (line.charAt(0)=='#')
return line;
return null;
} catch (Exception e) { e.printStackTrace(); }
return null;
}
private static String extendColumnNames(String names, String newItem) {
if (names==null) return null;
return names + "\t" + newItem;
}
/**
* @param args
*/
public static void main(String[] args) {
CommandLineParser parser = new GnuParser();
try {
/*
* Parsing options from command line
*/
CommandLine cmd = parser.parse( options, args );
String norm = ((String)cmd.getParsedOptionValue("normal"));
int flank = cmd.hasOption("flank") ? ((Integer)cmd.getParsedOptionValue("flank")) : 10;
String rpt = cmd.hasOption("repeatmask") ? ((String)cmd.getParsedOptionValue("repeatmask")) : null;
- System.out.println(norm+"\t"+rpt);
if (norm==null && rpt==null) {
System.err.println("No annotation specified.");
System.err.println("Use --normal and/or --repeatmask options to annotate results.");
printHelp();
System.exit(1);
}
String[] rargs = cmd.getArgs();
if (rargs.length!=1) {
printHelp();
System.exit(1);
}
ArrayList<PairedCluster> clusterPairs = loadBreakpoints( rargs[0] );
String colNames = extractColumnNames(rargs[0]);
if (norm != null) {
annotateNormal( norm, clusterPairs, flank );
colNames = extendColumnNames(colNames, "normal");
}
if (rpt != null) {
annotateRepeat( rpt, clusterPairs );
colNames = extendColumnNames(colNames, "repeat");
}
String out = rargs[0]+".annotated";
outputAnnotation( out, colNames, clusterPairs );
} catch( ParseException exp ) {
System.err.println( exp.getMessage() );
printHelp();
System.exit(1);
}
//ArrayList<PairedCluster> clusterPairs = loadBreakpoints( clustersPairFile );
}
public static void annotateNormal(String normalResult, ArrayList<PairedCluster> tumourClusterPairs, int tolerance) {
TreeSet<PairedCluster> clustersTumour = new TreeSet<PairedCluster>( tumourClusterPairs );
TreeSet<PairedCluster> clustersNormal = new TreeSet<PairedCluster>( loadBreakpoints( normalResult ) );
for (PairedCluster tumourCluster : clustersTumour) {
PairedCluster lower = new PairedCluster(tumourCluster, -2*tolerance);
PairedCluster upper = new PairedCluster(tumourCluster, 2*tolerance);
PairedCluster matched = null;
for (PairedCluster normalCluster : clustersNormal.subSet(lower, true, upper, true)) {
if (tumourCluster.match(normalCluster, tolerance)) {
matched = normalCluster;
break;
}
}
if (matched != null) {
tumourCluster.text += "\tnormal";
} else {
tumourCluster.text += "\t";
}
}
}
public static void annotateRepeat(String rmskFile, ArrayList<PairedCluster> clusterPairs) {
boolean isBed = rmskFile.indexOf(".bed") != -1;
tabixFile = new File(rmskFile);
tabixMemory = new MemoryMappedFile(tabixFile, true);
annotations = new TabixReader(rmskFile, new SeekableMemoryStream(tabixMemory));
// int x=0;
for (PairedCluster pc : clusterPairs) {
// x++;
String ann1 = annotateCluster(pc.cluster1, isBed);
String ann2 = annotateCluster(pc.cluster2, isBed);
pc.text += "\t" + ann1 + "\t" + ann2;
}
}
public static void outputAnnotation(String outputFilename, String colNames, ArrayList<PairedCluster> clusterPairs) {
try {
PrintWriter out = new PrintWriter(new FileOutputStream(new File( outputFilename ) ) );
if (colNames != null)
out.println(colNames);
for (PairedCluster pc : clusterPairs) {
out.println( pc.text );
}
out.close();
} catch (Exception e) {e.printStackTrace();}
}
public static String annotateCluster(Cluster cluster, boolean isBed) {
String ann1 = "";
try {
int s = (cluster.realignPos-10) <= 0 ? 1 : (cluster.realignPos-10);
String reg = cluster.realignChr+":"+s+"-"+(cluster.realignPos+10);
TabixReader.Iterator annIter = annotations.query( reg );
while (annIter!=null && (ann1=annIter.next())!=null) {
String[] tokens = ann1.split("\t");
if (!isBed) {
String rpt = tokens[11];
if (SINE_LINE_LTR.contains(rpt) || SATELLITE.contains(rpt) || SIMPLE_RPT.contains(rpt)) return rpt;
} else return tokens[3];
}} catch (Exception e) { e.printStackTrace(); }
return "";
}
public static String[] toArray(ArrayList<String> list) {
String[] s = new String[list.size()];
for (int i=0;i<list.size();i++) { s[i] = list.get(i); }
return s;
}
}
class Cluster implements Comparable<Cluster> {
private String smallChr="", largeChr="";
private int smallPos=-1, largePos=-1, smallDir=-1, largeDir=-1;
public String realignChr="", anchorChr="";
public int realignPos=-1, anchorPos=-1;
public int supportLong=0, supportLongBases, supportShort=0, supportShortBases, supportShortMaxLen;
public float avg_mapq = 0f;
public boolean realignFwd=false, anchorFwd=false, isShortCluster=false;
public byte[] realignSeq=null, anchorSeq=null;
public Cluster() {}
public Cluster(String[] fields) {
String[] realignCoords = fields[0].split(":");
realignFwd = fields[1].equals("+");
realignChr = realignCoords[0];
realignPos = Integer.parseInt(realignCoords[1]);
String f1 = fields[2].replaceAll("\\*", "");
realignSeq = Utilities.stringToByte(f1);
String[] anchorCoords = fields[3].split(":");
anchorFwd = fields[4].equals("+");
anchorChr = anchorCoords[0];
anchorPos = Integer.parseInt(anchorCoords[1]);
String f2 = fields[5].replaceAll("\\*", "");
anchorSeq = Utilities.stringToByte(f2);
if (realignSeq.length==0) isShortCluster=true;
this.supportLong = Integer.parseInt(fields[6]);
this.supportLongBases = Integer.parseInt(fields[7]);
this.supportShort = Integer.parseInt(fields[8]);
this.supportShortBases = Integer.parseInt(fields[9]);
this.supportShortMaxLen = Integer.parseInt(fields[10]);
this.avg_mapq = Float.parseFloat(fields[11]);
setSmallLarge();
}
public void setRealignCoord(String chrom, int pos, boolean fwd) {
realignChr = chrom; realignPos = pos; realignFwd = fwd; setSmallLarge();
}
public void setAnchorCoord(String chrom, int pos, boolean fwd) {
anchorChr = chrom; anchorPos = pos; anchorFwd = fwd; setSmallLarge();
}
private void setSmallLarge() {
if (realignChr.compareTo(anchorChr)<0) {
smallChr = realignChr; smallPos = realignPos; smallDir = realignFwd ? -1 : 1;
largeChr = anchorChr; largePos = anchorPos; largeDir = anchorFwd ? -1 : 1;
} else if (realignChr.compareTo(anchorChr) > 0){
largeChr = realignChr; largePos = realignPos; largeDir = realignFwd ? -1 : 1;
smallChr = anchorChr; smallPos = anchorPos; smallDir = anchorFwd ? -1 : 1;
} else {
if (realignPos < anchorPos) {
smallChr = realignChr; smallPos = realignPos; smallDir = realignFwd ? -1 : 1;
largeChr = anchorChr; largePos = anchorPos; largeDir = anchorFwd ? -1 : 1;
} else if (realignPos > anchorPos) {
largeChr = realignChr; largePos = realignPos; largeDir = realignFwd ? -1 : 1;
smallChr = anchorChr; smallPos = anchorPos; smallDir = anchorFwd ? -1 : 1;
} else {
if (realignFwd && !anchorFwd) {
smallChr = realignChr; smallPos = realignPos; smallDir = realignFwd ? -1 : 1;
largeChr = anchorChr; largePos = anchorPos; largeDir = anchorFwd ? -1 : 1;
} else {
largeChr = realignChr; largePos = realignPos; largeDir = realignFwd ? -1 : 1;
smallChr = anchorChr; smallPos = anchorPos; smallDir = anchorFwd ? -1 : 1;
}
}
}
}
public String toString(SAMFileInfo info) {
String c1 = realignChr+":"+realignPos+"\t"+(realignFwd?'+':'-');
String c2 = anchorChr+":"+anchorPos+"\t"+(anchorFwd?'+':'-');
return c1 + "\t" + c2 + "\t" + supportLong + "\t" + supportShort;
}
public int compareTo(Cluster other) {
if (!smallChr.equals(other.smallChr)) return smallChr.compareTo(other.smallChr);
if (smallPos != other.smallPos) return smallPos - other.smallPos;
if (smallDir != other.smallDir) return smallDir - other.smallDir;
if (!largeChr.equals(other.largeChr)) return largeChr.compareTo(other.largeChr);
if (largePos != other.largePos) return largePos - other.largePos;
if (largeDir != other.largeDir) return largeDir - other.largeDir;
return 0;
}
public boolean match(Cluster other, int tolerance) {
if (!smallChr.equals(other.smallChr) || !largeChr.equals(other.largeChr)) return false;
if (smallDir != other.smallDir || largeDir != other.largeDir) return false;
return (Math.abs(smallPos - other.smallPos) <= tolerance && Math.abs(largePos - other.largePos) <= tolerance);
}
}
class PairedCluster implements Comparable<PairedCluster> {
String text;
Cluster cluster1, cluster2;
private Cluster small, large;
public PairedCluster(String[] tokens) {
String[] c1 = Arrays.copyOfRange(tokens, 0, 12);
String[] c2 = Arrays.copyOfRange(tokens, 12, 24);
cluster1 = new Cluster(c1);
cluster2 = new Cluster(c2);
//StringBuilder b = new StringBuilder();
//for (int i=0; i< tokens.length; i++) {
// b.append(tokens[i]);
// if (i!=tokens.length-1) b.append("\t");
//}
//text = b.toString();
if (cluster1.compareTo(cluster2)<0) {
small = cluster1; large = cluster2;
} else {
small = cluster2; large = cluster1;
}
}
public PairedCluster(PairedCluster template, int offset) {
cluster1 = new Cluster();
cluster1.setRealignCoord(template.cluster1.realignChr, template.cluster1.realignPos+offset, template.cluster1.realignFwd);
cluster1.setAnchorCoord(template.cluster1.anchorChr, template.cluster1.anchorPos+offset, template.cluster1.anchorFwd);
cluster1.realignSeq = template.cluster1.realignSeq;
cluster1.anchorSeq = template.cluster1.anchorSeq;
cluster2 = new Cluster();
cluster2.setRealignCoord(template.cluster2.realignChr, template.cluster2.realignPos+offset, template.cluster2.realignFwd);
cluster2.setAnchorCoord(template.cluster2.anchorChr, template.cluster2.anchorPos+offset, template.cluster2.anchorFwd);
cluster2.realignSeq = template.cluster2.realignSeq;
cluster2.anchorSeq = template.cluster2.anchorSeq;
if (cluster2.realignSeq.length==0) cluster2.isShortCluster=true;
if (cluster1.compareTo(cluster2)<0) {
small = cluster1; large = cluster2;
} else {
small = cluster2; large = cluster1;
}
}
public boolean match(PairedCluster other, int tolerance) {
return (small.match(other.small, tolerance) && large.match(other.large, tolerance));
}
public int compareTo(PairedCluster other) {
int smallVsSmall = this.small.compareTo(other.small);
if (smallVsSmall != 0) return smallVsSmall;
else return this.large.compareTo(other.large);
}
@Override
public boolean equals(Object o) {
PairedCluster other = (PairedCluster)o;
return this.compareTo(other)==0;
}
public String toString(SAMFileInfo info) {
return cluster1.toString(info) + "\t" + cluster2.toString(info);
}
}
| true | true | public static void main(String[] args) {
CommandLineParser parser = new GnuParser();
try {
/*
* Parsing options from command line
*/
CommandLine cmd = parser.parse( options, args );
String norm = ((String)cmd.getParsedOptionValue("normal"));
int flank = cmd.hasOption("flank") ? ((Integer)cmd.getParsedOptionValue("flank")) : 10;
String rpt = cmd.hasOption("repeatmask") ? ((String)cmd.getParsedOptionValue("repeatmask")) : null;
System.out.println(norm+"\t"+rpt);
if (norm==null && rpt==null) {
System.err.println("No annotation specified.");
System.err.println("Use --normal and/or --repeatmask options to annotate results.");
printHelp();
System.exit(1);
}
String[] rargs = cmd.getArgs();
if (rargs.length!=1) {
printHelp();
System.exit(1);
}
ArrayList<PairedCluster> clusterPairs = loadBreakpoints( rargs[0] );
String colNames = extractColumnNames(rargs[0]);
if (norm != null) {
annotateNormal( norm, clusterPairs, flank );
colNames = extendColumnNames(colNames, "normal");
}
if (rpt != null) {
annotateRepeat( rpt, clusterPairs );
colNames = extendColumnNames(colNames, "repeat");
}
String out = rargs[0]+".annotated";
outputAnnotation( out, colNames, clusterPairs );
} catch( ParseException exp ) {
System.err.println( exp.getMessage() );
printHelp();
System.exit(1);
}
//ArrayList<PairedCluster> clusterPairs = loadBreakpoints( clustersPairFile );
}
| public static void main(String[] args) {
CommandLineParser parser = new GnuParser();
try {
/*
* Parsing options from command line
*/
CommandLine cmd = parser.parse( options, args );
String norm = ((String)cmd.getParsedOptionValue("normal"));
int flank = cmd.hasOption("flank") ? ((Integer)cmd.getParsedOptionValue("flank")) : 10;
String rpt = cmd.hasOption("repeatmask") ? ((String)cmd.getParsedOptionValue("repeatmask")) : null;
if (norm==null && rpt==null) {
System.err.println("No annotation specified.");
System.err.println("Use --normal and/or --repeatmask options to annotate results.");
printHelp();
System.exit(1);
}
String[] rargs = cmd.getArgs();
if (rargs.length!=1) {
printHelp();
System.exit(1);
}
ArrayList<PairedCluster> clusterPairs = loadBreakpoints( rargs[0] );
String colNames = extractColumnNames(rargs[0]);
if (norm != null) {
annotateNormal( norm, clusterPairs, flank );
colNames = extendColumnNames(colNames, "normal");
}
if (rpt != null) {
annotateRepeat( rpt, clusterPairs );
colNames = extendColumnNames(colNames, "repeat");
}
String out = rargs[0]+".annotated";
outputAnnotation( out, colNames, clusterPairs );
} catch( ParseException exp ) {
System.err.println( exp.getMessage() );
printHelp();
System.exit(1);
}
//ArrayList<PairedCluster> clusterPairs = loadBreakpoints( clustersPairFile );
}
|
diff --git a/src/java/com/idega/block/news/data/News.java b/src/java/com/idega/block/news/data/News.java
index 6ab5501..4c23cc0 100755
--- a/src/java/com/idega/block/news/data/News.java
+++ b/src/java/com/idega/block/news/data/News.java
@@ -1,130 +1,130 @@
//idega 2000 - �gir og eiki
package com.idega.block.news.data;
//import java.util.*;
import java.sql.*;
//import com.idega.data.*;
import com.idega.data.*;
public class News extends GenericEntity{
public News(){
super();
}
public News(int id)throws SQLException{
super(id);
}
public void initializeAttributes(){
addAttribute(getIDColumnName());
- addAttribute(getNewsCategoryIdColumnName(), "Category", true, true, "java.lang.Integer", "many-to-one","com.idega.jmodule.news.data.NewsCategory");
- addAttribute(getHeadLineColumnName(), "Headline", true, true, "java.lang.String");
- addAttribute(getNewsTextColumnName(), "Text", true, true, "java.lang.String",4000);
- addAttribute(getIncludeImageColumnName(), "Photo Included", true, true, "java.lang.String");
- addAttribute(getImageIdColumnName(), "Photo", true, true, "java.lang.Integer");
- addAttribute(getNewsDateColumnName(), "Date", true, true, "java.sql.Timestamp");
- addAttribute(getAuthorColumnName(), "Author", true, true, "java.lang.String");
- addAttribute(getSourceColumnName(), "Source", true, true, "java.lang.String");
- addAttribute(getDaysShownColumnName(), "Days shown", true, true, "java.lang.Integer");
+ addAttribute(getNewsCategoryIdColumnName(), "Category", true, true, Integer.class, "many-to-one",NewsCategory.class);
+ addAttribute(getHeadLineColumnName(), "Headline", true, true, String.class);
+ addAttribute(getNewsTextColumnName(), "Text", true, true, String.class,4000);
+ addAttribute(getIncludeImageColumnName(), "Photo Included", true, true, String.class);
+ addAttribute(getImageIdColumnName(), "Photo", true, true, Integer.class);
+ addAttribute(getNewsDateColumnName(), "Date", true, true, java.sql.Timestamp.class);
+ addAttribute(getAuthorColumnName(), "Author", true, true, String.class);
+ addAttribute(getSourceColumnName(), "Source", true, true, String.class);
+ addAttribute(getDaysShownColumnName(), "Days shown", true, true, String.class);
}
public String getEntityName(){
return getNewsTableName();
}
public static String getNewsTableName(){return "NW_NEWS";}
public static String getNewsCategoryIdColumnName(){return "NW_NEWS_CAT_ID";}
public static String getHeadLineColumnName(){return "HEADLINE";}
public static String getNewsTextColumnName(){return "NEWSTEXT";}
public static String getIncludeImageColumnName(){return "INCLUDE_IMAGE";}
public static String getNewsDateColumnName(){return "NEWS_DATE";}
public static String getAuthorColumnName(){return "AUTHOR";}
public static String getSourceColumnName(){return "SOURCE";}
public static String getDaysShownColumnName(){return "DAYS_SHOWN";}
public static String getImageIdColumnName(){return"IC_IMAGE_ID";}
public String getName(){
return getHeadline();
}
public void setDefaultValues() {
this.setNewsCategoryId(1);
this.setHeadline("");
this.setIncludeImage("N");
this.setText("");
this.setImageId(-1);
this.setDaysShown(-1);
this.setSource("");
this.setAuthor("");
this.setDate(new com.idega.util.idegaTimestamp().getTimestampRightNow());
}
public int getNewsCategoryId(){
return getIntColumnValue(getNewsCategoryIdColumnName());
}
public void setNewsCategoryId(Integer news_category_id){
setColumn(getNewsCategoryIdColumnName(), news_category_id);
}
public void setNewsCategoryId(int news_category_id){
setColumn(getNewsCategoryIdColumnName(), new Integer(news_category_id));
}
public String getHeadline(){
return getStringColumnValue(getHeadLineColumnName());
}
public void setHeadline(String headline){
setColumn(getHeadLineColumnName(), headline);
}
public String getText(){
return getStringColumnValue(getNewsTextColumnName());
}
public void setText(String newstext){
setColumn(getNewsTextColumnName(), newstext);
}
public String getIncludeImage(){
return getStringColumnValue(getIncludeImageColumnName());
}
public void setIncludeImage(String include_image){
setColumn(getIncludeImageColumnName(), include_image);
}
public int getImageId(){
return getIntColumnValue(getImageIdColumnName());
}
public void setImageId(Integer image_id){
setColumn(getImageIdColumnName(), image_id);
}
public void setImageId(int image_id){
setColumn(getImageIdColumnName(),new Integer(image_id));
}
public java.sql.Timestamp getDate(){
return (java.sql.Timestamp) getColumnValue(getNewsDateColumnName());
}
public java.sql.Timestamp getNewsDate(){
return getDate();
}
public void setDate(java.sql.Timestamp news_date){
setColumn(getNewsDateColumnName(), news_date);
}
public void setNewsDate(java.sql.Timestamp news_date){
setDate(news_date);
}
public String getAuthor(){
return getStringColumnValue(getAuthorColumnName());
}
public void setAuthor(String author){
setColumn(getAuthorColumnName(), author);
}
public String getSource(){
return getStringColumnValue(getSourceColumnName());
}
public void setSource(String source){
setColumn(getSourceColumnName(), source);
}
public int getDaysShown(){
return getIntColumnValue(getDaysShownColumnName());
}
public void setDaysShown(Integer days_shown){
setColumn(getDaysShownColumnName(), days_shown);
}
public void setDaysShown(int days_shown){
setColumn(getDaysShownColumnName(), new Integer(days_shown));
}
}
| true | true | public void initializeAttributes(){
addAttribute(getIDColumnName());
addAttribute(getNewsCategoryIdColumnName(), "Category", true, true, "java.lang.Integer", "many-to-one","com.idega.jmodule.news.data.NewsCategory");
addAttribute(getHeadLineColumnName(), "Headline", true, true, "java.lang.String");
addAttribute(getNewsTextColumnName(), "Text", true, true, "java.lang.String",4000);
addAttribute(getIncludeImageColumnName(), "Photo Included", true, true, "java.lang.String");
addAttribute(getImageIdColumnName(), "Photo", true, true, "java.lang.Integer");
addAttribute(getNewsDateColumnName(), "Date", true, true, "java.sql.Timestamp");
addAttribute(getAuthorColumnName(), "Author", true, true, "java.lang.String");
addAttribute(getSourceColumnName(), "Source", true, true, "java.lang.String");
addAttribute(getDaysShownColumnName(), "Days shown", true, true, "java.lang.Integer");
}
| public void initializeAttributes(){
addAttribute(getIDColumnName());
addAttribute(getNewsCategoryIdColumnName(), "Category", true, true, Integer.class, "many-to-one",NewsCategory.class);
addAttribute(getHeadLineColumnName(), "Headline", true, true, String.class);
addAttribute(getNewsTextColumnName(), "Text", true, true, String.class,4000);
addAttribute(getIncludeImageColumnName(), "Photo Included", true, true, String.class);
addAttribute(getImageIdColumnName(), "Photo", true, true, Integer.class);
addAttribute(getNewsDateColumnName(), "Date", true, true, java.sql.Timestamp.class);
addAttribute(getAuthorColumnName(), "Author", true, true, String.class);
addAttribute(getSourceColumnName(), "Source", true, true, String.class);
addAttribute(getDaysShownColumnName(), "Days shown", true, true, String.class);
}
|
diff --git a/src/main/java/hex/gbm/GBM.java b/src/main/java/hex/gbm/GBM.java
index d7bd66553..7aa5bc0f6 100644
--- a/src/main/java/hex/gbm/GBM.java
+++ b/src/main/java/hex/gbm/GBM.java
@@ -1,468 +1,468 @@
package hex.gbm;
import static water.util.Utils.div;
import hex.gbm.DTree.DecidedNode;
import hex.gbm.DTree.LeafNode;
import hex.gbm.DTree.TreeModel.TreeStats;
import hex.gbm.DTree.UndecidedNode;
import water.*;
import water.api.DocGen;
import water.api.GBMProgressPage;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.util.*;
import water.util.Log.Tag.Sys;
// Gradient Boosted Trees
//
// Based on "Elements of Statistical Learning, Second Edition, page 387"
public class GBM extends SharedTreeModelBuilder<GBM.GBMModel> {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help = "Learning rate, from 0. to 1.0", filter = Default.class, dmin=0, dmax=1)
public double learn_rate = 0.1;
@API(help = "Grid search parallelism", filter = Default.class, lmax = 4, gridable=false)
public int grid_parallelism = 1;
public static class GBMModel extends DTree.TreeModel {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help = "Learning rate, from 0. to 1.0") final double learn_rate;
public GBMModel(Key key, Key dataKey, Key testKey, String names[], String domains[][], int ntrees, int max_depth, int min_rows, int nbins, double learn_rate) {
super(key,dataKey,testKey,names,domains,ntrees,max_depth,min_rows,nbins);
this.learn_rate = learn_rate;
}
public GBMModel(DTree.TreeModel prior, DTree[] trees, double err, long [][] cm, TreeStats tstats) {
super(prior, trees, err, cm, tstats);
this.learn_rate = ((GBMModel)prior).learn_rate;
}
@Override protected float[] score0(double[] data, float[] preds) {
float sum = 0;
float[] p = super.score0(data, preds);
if (nclasses()>1) { // classification
// Because we call Math.exp, we have to be numerically stable or else
// we get Infinities, and then shortly NaN's. Rescale the data so the
// largest value is +/-1 and the other values are smaller.
float rescale=0;
for(int k=0; k<p.length;k++) rescale = Math.max(rescale,Math.abs(p[k]));
if( rescale < 1.0f ) rescale=1.0f;
float dsum=0;
for(int k=0; k<p.length;k++)
dsum+=(p[k]=(float)Math.exp(p[k]/rescale));
div(p,dsum);
} else { // regression
// do nothing for regression
}
return p;
}
@Override protected void generateModelDescription(StringBuilder sb) {
DocGen.HTML.paragraph(sb,"Learn rate: "+learn_rate);
}
@Override protected void toJavaUnifyPreds(SB bodyCtxSB) {
if (isClassifier()) {
bodyCtxSB.i().p("// Compute Probabilities").nl();
bodyCtxSB.i().p("float sum = 0;").nl();
bodyCtxSB.i().p("for(int i=1;i<preds.length; i++) sum += (preds[i]=(float) Math.exp(preds[i]));").nl();
bodyCtxSB.i().p("for(int i=1; i<preds.length; i++) preds[i] = (float) preds[i] / sum;").nl();
}
}
}
public Frame score( Frame fr ) { return ((GBMModel)UKV.get(dest())).score(fr); }
@Override protected Log.Tag.Sys logTag() { return Sys.GBM__; }
@Override protected GBMModel makeModel( GBMModel model, DTree ktrees[], double err, long cm[][], TreeStats tstats) {
return new GBMModel(model, ktrees, err, cm, tstats);
}
public GBM() { description = "Distributed GBM"; }
/** Return the query link to this page */
public static String link(Key k, String content) {
RString rs = new RString("<a href='GBM.query?source=%$key'>%content</a>");
rs.replace("key", k.toString());
rs.replace("content", content);
return rs.toString();
}
@Override protected void logStart() {
Log.info("Starting GBM model build...");
super.logStart();
Log.info(" learn_rate: " + learn_rate);
}
@Override protected Status exec() {
logStart();
buildModel();
return Status.Done;
}
@Override public int gridParallelism() {
return grid_parallelism;
}
@Override protected Response redirect() {
return GBMProgressPage.redirect(this, self(), dest());
}
// ==========================================================================
// Compute a GBM tree.
// Start by splitting all the data according to some criteria (minimize
// variance at the leaves). Record on each row which split it goes to, and
// assign a split number to it (for next pass). On *this* pass, use the
// split-number to build a per-split histogram, with a per-histogram-bucket
// variance.
@Override protected void buildModel( final Frame fr, String names[], String domains[][], final Key outputKey, final Key dataKey, final Key testKey, Timer t_build ) {
GBMModel model = new GBMModel(outputKey, dataKey, testKey, names, domains, ntrees, max_depth, min_rows, nbins, learn_rate);
DKV.put(outputKey, model);
// Tag out rows missing the response column
new ExcludeNAResponse().doAll(fr);
// Build trees until we hit the limit
int tid;
DTree[] ktrees = null; // Trees
TreeStats tstats = new TreeStats(); // Tree stats
for( tid=0; tid<ntrees; tid++) {
// ESL2, page 387
// Step 2a: Compute prediction (prob distribution) from prior tree results:
// Work <== f(Tree)
new ComputeProb().doAll(fr);
// ESL2, page 387
// Step 2b i: Compute residuals from the prediction (probability distribution)
// Work <== f(Work)
new ComputeRes().doAll(fr);
// ESL2, page 387, Step 2b ii, iii, iv
ktrees = buildNextKTrees(fr);
if( cancelled() ) break; // If canceled during building, do not bulkscore
// Check latest predictions
tstats.updateBy(ktrees);
model = doScoring(model, outputKey, fr, ktrees, tid, tstats, false, false, false);
}
// Final scoring
model = doScoring(model, outputKey, fr, ktrees, tid, tstats, true, false, false);
cleanUp(fr,t_build); // Shared cleanup
}
// --------------------------------------------------------------------------
// Tag out rows missing the response column
class ExcludeNAResponse extends MRTask2<ExcludeNAResponse> {
@Override public void map( Chunk chks[] ) {
Chunk ys = chk_resp(chks);
for( int row=0; row<ys._len; row++ )
if( ys.isNA0(row) )
for( int t=0; t<_nclass; t++ )
chk_nids(chks,t).set0(row,-1);
}
}
// --------------------------------------------------------------------------
// Compute Prediction from prior tree results.
// Classification: Probability Distribution of loglikelyhoods
// Prob_k = exp(Work_k)/sum_all_K exp(Work_k)
// Regression: Just prior tree results
// Work <== f(Tree)
class ComputeProb extends MRTask2<ComputeProb> {
@Override public void map( Chunk chks[] ) {
Chunk ys = chk_resp(chks);
if( _nclass > 1 ) { // Classification
double ds[] = new double[_nclass];
for( int row=0; row<ys._len; row++ ) {
double sum = score0(chks,ds,row);
if( Double.isInfinite(sum) ) // Overflow (happens for constant responses)
for( int k=0; k<_nclass; k++ )
chk_work(chks,k).set0(row,Double.isInfinite(ds[k])?1.0f:0.0f);
else
for( int k=0; k<_nclass; k++ ) // Save as a probability distribution
chk_work(chks,k).set0(row,(float)(ds[k]/sum));
}
} else { // Regression
Chunk tr = chk_tree(chks,0); // Prior tree sums
Chunk wk = chk_work(chks,0); // Predictions
for( int row=0; row<ys._len; row++ )
wk.set0(row,(float)tr.at0(row));
}
}
}
// Read the 'tree' columns, do model-specific math and put the results in the
// ds[] array, and return the sum. Dividing any ds[] element by the sum
// turns the results into a probability distribution.
@Override protected double score0( Chunk chks[], double ds[/*nclass*/], int row ) {
if( _nclass == 1 ) // Classification?
return chk_tree(chks,0).at0(row);
if( _nclass == 2 ) { // The Boolean Optimization
// This optimization assumes the 2nd tree of a 2-class system is the
// inverse of the first. Fill in the missing tree
ds[0] = Math.exp(chk_tree(chks,0).at0(row));
ds[1] = 1.0/ds[0]; // exp(-d) === 1/d
return ds[0]+ds[1];
}
double sum=0;
for( int k=0; k<_nclass; k++ ) // Sum across of likelyhoods
sum+=(ds[k]=Math.exp(chk_tree(chks,k).at0(row)));
return sum;
}
// --------------------------------------------------------------------------
// Compute Residuals from Actuals
// Work <== f(Work)
class ComputeRes extends MRTask2<ComputeRes> {
@Override public void map( Chunk chks[] ) {
Chunk ys = chk_resp(chks);
if( _nclass > 1 ) { // Classification
for( int row=0; row<ys._len; row++ ) {
if( ys.isNA0(row) ) continue;
int y = (int)ys.at80(row); // zero-based response variable
// Actual is '1' for class 'y' and '0' for all other classes
for( int k=0; k<_nclass; k++ ) {
if( _distribution[k] != 0 ) {
Chunk wk = chk_work(chks,k);
wk.set0(row, (y==k?1f:0f)-(float)wk.at0(row) );
}
}
}
} else { // Regression
Chunk wk = chk_work(chks,0); // Prediction==>Residuals
for( int row=0; row<ys._len; row++ )
wk.set0(row, (float)(ys.at0(row)-wk.at0(row)) );
}
}
}
// --------------------------------------------------------------------------
// Build the next k-trees, which is trying to correct the residual error from
// the prior trees. From LSE2, page 387. Step 2b ii, iii.
private DTree[] buildNextKTrees(Frame fr) {
// We're going to build K (nclass) trees - each focused on correcting
// errors for a single class.
final DTree[] ktrees = new DTree[_nclass];
// Initial set of histograms. All trees; one leaf per tree (the root
// leaf); all columns
DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols];
for( int k=0; k<_nclass; k++ ) {
// Initially setup as-if an empty-split had just happened
if( _distribution == null || _distribution[k] != 0 ) {
// The Boolean Optimization
// This optimization assumes the 2nd tree of a 2-class system is the
// inverse of the first. This is false for DRF (and true for GBM) -
// DRF picks a random different set of columns for the 2nd tree.
if( k==1 && _nclass==2 ) continue;
ktrees[k] = new DTree(fr._names,_ncols,(char)nbins,(char)_nclass,min_rows);
new GBMUndecidedNode(ktrees[k],-1,DHistogram.initialHist(fr,_ncols,nbins,hcs[k][0],false) ); // The "root" node
}
}
int[] leafs = new int[_nclass]; // Define a "working set" of leaf splits, from here to tree._len
// ----
// ESL2, page 387. Step 2b ii.
// One Big Loop till the ktrees are of proper depth.
// Adds a layer to the trees each pass.
int depth=0;
for( ; depth<max_depth; depth++ ) {
if( cancelled() ) return null;
hcs = buildLayer(fr, ktrees, leafs, hcs, false, false);
// If we did not make any new splits, then the tree is split-to-death
if( hcs == null ) break;
}
// Each tree bottomed-out in a DecidedNode; go 1 more level and insert
// LeafNodes to hold predictions.
for( int k=0; k<_nclass; k++ ) {
DTree tree = ktrees[k];
if( tree == null ) continue;
int leaf = leafs[k] = tree.len();
for( int nid=0; nid<leaf; nid++ ) {
if( tree.node(nid) instanceof DecidedNode ) {
DecidedNode dn = tree.decided(nid);
for( int i=0; i<dn._nids.length; i++ ) {
int cnid = dn._nids[i];
if( cnid == -1 || // Bottomed out (predictors or responses known constant)
tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth
(tree.node(cnid) instanceof DecidedNode && // Or not possible to split
((DecidedNode)tree.node(cnid))._split.col()==-1) )
dn._nids[i] = new GBMLeafNode(tree,nid).nid(); // Mark a leaf here
}
// Handle the trivial non-splitting tree
if( nid==0 && dn._split.col() == -1 )
new GBMLeafNode(tree,-1,0);
}
}
} // -- k-trees are done
// ----
// ESL2, page 387. Step 2b iii. Compute the gammas, and store them back
// into the tree leaves. Includes learn_rate.
// gamma_i_k = (nclass-1)/nclass * (sum res_i / sum (|res_i|*(1-|res_i|)))
// For regression:
// gamma_i_k = sum res_i / count(res_i)
GammaPass gp = new GammaPass(ktrees,leafs).doAll(fr);
double m1class = _nclass > 1 ? (double)(_nclass-1)/_nclass : 1.0; // K-1/K
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
for( int i=0; i<tree._len-leafs[k]; i++ ) {
double g = gp._gss[k][i] == 0 // Constant response?
- ? 1000 // Cap (exponential) learn, instead of dealing with Inf
+ ? (gp._rss[k][i]==0?0:1000) // Cap (exponential) learn, instead of dealing with Inf
: learn_rate*m1class*gp._rss[k][i]/gp._gss[k][i];
assert !Double.isNaN(g);
((LeafNode)tree.node(leafs[k]+i))._pred = g;
}
}
// ----
// ESL2, page 387. Step 2b iv. Cache the sum of all the trees, plus the
// new tree, in the 'tree' columns. Also, zap the NIDs for next pass.
// Tree <== f(Tree)
// Nids <== 0
new MRTask2() {
@Override public void map( Chunk chks[] ) {
// For all tree/klasses
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
final Chunk nids = chk_nids(chks,k);
final Chunk ct = chk_tree(chks,k);
for( int row=0; row<nids._len; row++ ) {
int nid = (int)nids.at80(row);
if( nid < 0 ) continue;
ct.set0(row, (float)(ct.at0(row) + ((LeafNode)tree.node(nid))._pred));
nids.set0(row,0);
}
}
}
}.doAll(fr);
// Collect leaves stats
for (int i=0; i<ktrees.length; i++)
if( ktrees[i] != null )
ktrees[i].leaves = ktrees[i].len() - leafs[i];
// DEBUG: Print the generated K trees
// printGenerateTrees(ktrees);
return ktrees;
}
// ---
// ESL2, page 387. Step 2b iii.
// Nids <== f(Nids)
private class GammaPass extends MRTask2<GammaPass> {
final DTree _trees[]; // Read-only, shared (except at the histograms in the Nodes)
final int _leafs[]; // Number of active leaves (per tree)
// Per leaf: sum(res);
double _rss[/*tree/klass*/][/*tree-relative node-id*/];
// Per leaf: sum(|res|*1-|res|)
double _gss[/*tree/klass*/][/*tree-relative node-id*/];
GammaPass(DTree trees[], int leafs[]) { _leafs=leafs; _trees=trees; }
@Override public void map( Chunk[] chks ) {
_gss = new double[_nclass][];
_rss = new double[_nclass][];
// For all tree/klasses
for( int k=0; k<_nclass; k++ ) {
final DTree tree = _trees[k];
final int leaf = _leafs[k];
if( tree == null ) continue; // Empty class is ignored
// A leaf-biased array of all active Tree leaves.
final double gs[] = _gss[k] = new double[tree._len-leaf];
final double rs[] = _rss[k] = new double[tree._len-leaf];
final Chunk nids = chk_nids(chks,k); // Node-ids for this tree/class
final Chunk ress = chk_work(chks,k); // Residuals for this tree/class
// If we have all constant responses, then we do not split even the
// root and the residuals should be zero.
if( tree.root() instanceof LeafNode ) continue;
for( int row=0; row<nids._len; row++ ) { // For all rows
int nid = (int)nids.at80(row); // Get Node to decide from
if( nid < 0 ) continue; // Missing response
if( tree.node(nid) instanceof UndecidedNode ) // If we bottomed out the tree
nid = tree.node(nid)._pid; // Then take parent's decision
DecidedNode dn = tree.decided(nid); // Must have a decision point
if( dn._split._col == -1 ) // Unable to decide?
dn = tree.decided(nid = dn._pid); // Then take parent's decision
int leafnid = dn.ns(chks,row); // Decide down to a leafnode
assert leaf <= leafnid && leafnid < tree._len;
assert tree.node(leafnid) instanceof LeafNode;
// Note: I can which leaf/region I end up in, but I do not care for
// the prediction presented by the tree. For GBM, we compute the
// sum-of-residuals (and sum/abs/mult residuals) for all rows in the
// leaf, and get our prediction from that.
nids.set0(row,leafnid);
assert !ress.isNA0(row);
double res = ress.at0(row);
double ares = Math.abs(res);
gs[leafnid-leaf] += _nclass > 1 ? ares*(1-ares) : 1;
rs[leafnid-leaf] += res;
}
}
}
@Override public void reduce( GammaPass gp ) {
Utils.add(_gss,gp._gss);
Utils.add(_rss,gp._rss);
}
}
@Override protected DecidedNode makeDecided( UndecidedNode udn, DHistogram hs[] ) {
return new GBMDecidedNode(udn,hs);
}
// ---
// GBM DTree decision node: same as the normal DecidedNode, but
// specifies a decision algorithm given complete histograms on all
// columns. GBM algo: find the lowest error amongst *all* columns.
static class GBMDecidedNode extends DecidedNode {
GBMDecidedNode( UndecidedNode n, DHistogram[] hs ) { super(n,hs); }
@Override public UndecidedNode makeUndecidedNode(DHistogram[] hs ) {
return new GBMUndecidedNode(_tree,_nid,hs);
}
// Find the column with the best split (lowest score). Unlike RF, GBM
// scores on all columns and selects splits on all columns.
@Override public DTree.Split bestCol( UndecidedNode u, DHistogram[] hs ) {
DTree.Split best = new DTree.Split(-1,-1,false,Double.MAX_VALUE,Double.MAX_VALUE,0L,0L,0,0);
if( hs == null ) return best;
for( int i=0; i<hs.length; i++ ) {
if( hs[i]==null || hs[i].nbins() <= 1 ) continue;
DTree.Split s = hs[i].scoreMSE(i);
if( s == null ) continue;
if( best == null || s.se() < best.se() ) best = s;
if( s.se() <= 0 ) break; // No point in looking further!
}
return best;
}
}
// ---
// GBM DTree undecided node: same as the normal UndecidedNode, but specifies
// a list of columns to score on now, and then decide over later.
// GBM algo: use all columns
static class GBMUndecidedNode extends UndecidedNode {
GBMUndecidedNode( DTree tree, int pid, DHistogram hs[] ) { super(tree,pid,hs); }
// Randomly select mtry columns to 'score' in following pass over the data.
// In GBM, we use all columns (as opposed to RF, which uses a random subset).
@Override public int[] scoreCols( DHistogram[] hs ) { return null; }
}
// ---
static class GBMLeafNode extends LeafNode {
GBMLeafNode( DTree tree, int pid ) { super(tree,pid); }
GBMLeafNode( DTree tree, int pid, int nid ) { super(tree,pid,nid); }
// Insert just the predictions: a single byte/short if we are predicting a
// single class, or else the full distribution.
@Override protected AutoBuffer compress(AutoBuffer ab) { assert !Double.isNaN(_pred); return ab.put4f((float)_pred); }
@Override protected int size() { return 4; }
}
}
| true | true | private DTree[] buildNextKTrees(Frame fr) {
// We're going to build K (nclass) trees - each focused on correcting
// errors for a single class.
final DTree[] ktrees = new DTree[_nclass];
// Initial set of histograms. All trees; one leaf per tree (the root
// leaf); all columns
DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols];
for( int k=0; k<_nclass; k++ ) {
// Initially setup as-if an empty-split had just happened
if( _distribution == null || _distribution[k] != 0 ) {
// The Boolean Optimization
// This optimization assumes the 2nd tree of a 2-class system is the
// inverse of the first. This is false for DRF (and true for GBM) -
// DRF picks a random different set of columns for the 2nd tree.
if( k==1 && _nclass==2 ) continue;
ktrees[k] = new DTree(fr._names,_ncols,(char)nbins,(char)_nclass,min_rows);
new GBMUndecidedNode(ktrees[k],-1,DHistogram.initialHist(fr,_ncols,nbins,hcs[k][0],false) ); // The "root" node
}
}
int[] leafs = new int[_nclass]; // Define a "working set" of leaf splits, from here to tree._len
// ----
// ESL2, page 387. Step 2b ii.
// One Big Loop till the ktrees are of proper depth.
// Adds a layer to the trees each pass.
int depth=0;
for( ; depth<max_depth; depth++ ) {
if( cancelled() ) return null;
hcs = buildLayer(fr, ktrees, leafs, hcs, false, false);
// If we did not make any new splits, then the tree is split-to-death
if( hcs == null ) break;
}
// Each tree bottomed-out in a DecidedNode; go 1 more level and insert
// LeafNodes to hold predictions.
for( int k=0; k<_nclass; k++ ) {
DTree tree = ktrees[k];
if( tree == null ) continue;
int leaf = leafs[k] = tree.len();
for( int nid=0; nid<leaf; nid++ ) {
if( tree.node(nid) instanceof DecidedNode ) {
DecidedNode dn = tree.decided(nid);
for( int i=0; i<dn._nids.length; i++ ) {
int cnid = dn._nids[i];
if( cnid == -1 || // Bottomed out (predictors or responses known constant)
tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth
(tree.node(cnid) instanceof DecidedNode && // Or not possible to split
((DecidedNode)tree.node(cnid))._split.col()==-1) )
dn._nids[i] = new GBMLeafNode(tree,nid).nid(); // Mark a leaf here
}
// Handle the trivial non-splitting tree
if( nid==0 && dn._split.col() == -1 )
new GBMLeafNode(tree,-1,0);
}
}
} // -- k-trees are done
// ----
// ESL2, page 387. Step 2b iii. Compute the gammas, and store them back
// into the tree leaves. Includes learn_rate.
// gamma_i_k = (nclass-1)/nclass * (sum res_i / sum (|res_i|*(1-|res_i|)))
// For regression:
// gamma_i_k = sum res_i / count(res_i)
GammaPass gp = new GammaPass(ktrees,leafs).doAll(fr);
double m1class = _nclass > 1 ? (double)(_nclass-1)/_nclass : 1.0; // K-1/K
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
for( int i=0; i<tree._len-leafs[k]; i++ ) {
double g = gp._gss[k][i] == 0 // Constant response?
? 1000 // Cap (exponential) learn, instead of dealing with Inf
: learn_rate*m1class*gp._rss[k][i]/gp._gss[k][i];
assert !Double.isNaN(g);
((LeafNode)tree.node(leafs[k]+i))._pred = g;
}
}
// ----
// ESL2, page 387. Step 2b iv. Cache the sum of all the trees, plus the
// new tree, in the 'tree' columns. Also, zap the NIDs for next pass.
// Tree <== f(Tree)
// Nids <== 0
new MRTask2() {
@Override public void map( Chunk chks[] ) {
// For all tree/klasses
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
final Chunk nids = chk_nids(chks,k);
final Chunk ct = chk_tree(chks,k);
for( int row=0; row<nids._len; row++ ) {
int nid = (int)nids.at80(row);
if( nid < 0 ) continue;
ct.set0(row, (float)(ct.at0(row) + ((LeafNode)tree.node(nid))._pred));
nids.set0(row,0);
}
}
}
}.doAll(fr);
// Collect leaves stats
for (int i=0; i<ktrees.length; i++)
if( ktrees[i] != null )
ktrees[i].leaves = ktrees[i].len() - leafs[i];
// DEBUG: Print the generated K trees
// printGenerateTrees(ktrees);
return ktrees;
}
| private DTree[] buildNextKTrees(Frame fr) {
// We're going to build K (nclass) trees - each focused on correcting
// errors for a single class.
final DTree[] ktrees = new DTree[_nclass];
// Initial set of histograms. All trees; one leaf per tree (the root
// leaf); all columns
DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols];
for( int k=0; k<_nclass; k++ ) {
// Initially setup as-if an empty-split had just happened
if( _distribution == null || _distribution[k] != 0 ) {
// The Boolean Optimization
// This optimization assumes the 2nd tree of a 2-class system is the
// inverse of the first. This is false for DRF (and true for GBM) -
// DRF picks a random different set of columns for the 2nd tree.
if( k==1 && _nclass==2 ) continue;
ktrees[k] = new DTree(fr._names,_ncols,(char)nbins,(char)_nclass,min_rows);
new GBMUndecidedNode(ktrees[k],-1,DHistogram.initialHist(fr,_ncols,nbins,hcs[k][0],false) ); // The "root" node
}
}
int[] leafs = new int[_nclass]; // Define a "working set" of leaf splits, from here to tree._len
// ----
// ESL2, page 387. Step 2b ii.
// One Big Loop till the ktrees are of proper depth.
// Adds a layer to the trees each pass.
int depth=0;
for( ; depth<max_depth; depth++ ) {
if( cancelled() ) return null;
hcs = buildLayer(fr, ktrees, leafs, hcs, false, false);
// If we did not make any new splits, then the tree is split-to-death
if( hcs == null ) break;
}
// Each tree bottomed-out in a DecidedNode; go 1 more level and insert
// LeafNodes to hold predictions.
for( int k=0; k<_nclass; k++ ) {
DTree tree = ktrees[k];
if( tree == null ) continue;
int leaf = leafs[k] = tree.len();
for( int nid=0; nid<leaf; nid++ ) {
if( tree.node(nid) instanceof DecidedNode ) {
DecidedNode dn = tree.decided(nid);
for( int i=0; i<dn._nids.length; i++ ) {
int cnid = dn._nids[i];
if( cnid == -1 || // Bottomed out (predictors or responses known constant)
tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth
(tree.node(cnid) instanceof DecidedNode && // Or not possible to split
((DecidedNode)tree.node(cnid))._split.col()==-1) )
dn._nids[i] = new GBMLeafNode(tree,nid).nid(); // Mark a leaf here
}
// Handle the trivial non-splitting tree
if( nid==0 && dn._split.col() == -1 )
new GBMLeafNode(tree,-1,0);
}
}
} // -- k-trees are done
// ----
// ESL2, page 387. Step 2b iii. Compute the gammas, and store them back
// into the tree leaves. Includes learn_rate.
// gamma_i_k = (nclass-1)/nclass * (sum res_i / sum (|res_i|*(1-|res_i|)))
// For regression:
// gamma_i_k = sum res_i / count(res_i)
GammaPass gp = new GammaPass(ktrees,leafs).doAll(fr);
double m1class = _nclass > 1 ? (double)(_nclass-1)/_nclass : 1.0; // K-1/K
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
for( int i=0; i<tree._len-leafs[k]; i++ ) {
double g = gp._gss[k][i] == 0 // Constant response?
? (gp._rss[k][i]==0?0:1000) // Cap (exponential) learn, instead of dealing with Inf
: learn_rate*m1class*gp._rss[k][i]/gp._gss[k][i];
assert !Double.isNaN(g);
((LeafNode)tree.node(leafs[k]+i))._pred = g;
}
}
// ----
// ESL2, page 387. Step 2b iv. Cache the sum of all the trees, plus the
// new tree, in the 'tree' columns. Also, zap the NIDs for next pass.
// Tree <== f(Tree)
// Nids <== 0
new MRTask2() {
@Override public void map( Chunk chks[] ) {
// For all tree/klasses
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
final Chunk nids = chk_nids(chks,k);
final Chunk ct = chk_tree(chks,k);
for( int row=0; row<nids._len; row++ ) {
int nid = (int)nids.at80(row);
if( nid < 0 ) continue;
ct.set0(row, (float)(ct.at0(row) + ((LeafNode)tree.node(nid))._pred));
nids.set0(row,0);
}
}
}
}.doAll(fr);
// Collect leaves stats
for (int i=0; i<ktrees.length; i++)
if( ktrees[i] != null )
ktrees[i].leaves = ktrees[i].len() - leafs[i];
// DEBUG: Print the generated K trees
// printGenerateTrees(ktrees);
return ktrees;
}
|
diff --git a/runtime/src/org/aspectj/lang/Aspects.java b/runtime/src/org/aspectj/lang/Aspects.java
index 2b0c8540c..2f6fa5329 100644
--- a/runtime/src/org/aspectj/lang/Aspects.java
+++ b/runtime/src/org/aspectj/lang/Aspects.java
@@ -1,92 +1,92 @@
/*******************************************************************************
* Copyright (c) 2005 Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* initial implementation Jonas Bon�r, Alexandre Vasseur
*******************************************************************************/
package org.aspectj.lang;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Handles generic aspectOf method when those are not available in the aspects but added later on
* thru load time weaving.
* <p/>
* Aspects.aspectOf(..) is doing reflective calls to the aspect aspectOf, so for better performance
* consider using preparation of the aspects.
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class Aspects {
private final static Class[] EMPTY_CLASS_ARRAY = new Class[0];
private final static Class[] PEROBJECT_CLASS_ARRAY = new Class[]{Object.class};
private final static Object[] EMPTY_OBJECT_ARRAY = new Object[0];
private final static String ASPECTOF = "aspectOf";
/**
* Returns the singleton aspect
*
* @param aspectClass
* @return
* @throws NoAspectBoundException if no such aspect
*/
public static Object aspectOf(Class aspectClass) throws NoAspectBoundException {
try {
return getSingletonAspectOf(aspectClass).invoke(null, EMPTY_OBJECT_ARRAY);
} catch (Exception e) {
throw new NoAspectBoundException(aspectClass.getName(), e);
}
}
/**
* Returns the perthis / pertarget aspect
* @param aspectClass
* @param perObject
* @return
* @throws NoAspectBoundException if no such aspect, or no aspect bound
*/
public static Object aspectOf(Class aspectClass, Object perObject) throws NoAspectBoundException {
try {
return getPerObjectAspectOf(aspectClass).invoke(null, new Object[]{perObject});
} catch (Exception e) {
throw new NoAspectBoundException(aspectClass.getName(), e);
}
}
public static Object aspectOf(Class aspectClass, Thread perThread) throws NoAspectBoundException {
//TODO - how to know it s a real per Thread ?
// if it is actually a singleton one, we will have it as well...
try {
return getSingletonAspectOf(aspectClass).invoke(null, EMPTY_OBJECT_ARRAY);
} catch (Exception e) {
throw new NoAspectBoundException(aspectClass.getName(), e);
}
}
private static Method getSingletonAspectOf(Class aspectClass) throws NoSuchMethodException {
Method method = aspectClass.getDeclaredMethod(ASPECTOF, EMPTY_CLASS_ARRAY);
return checkAspectOf(method, aspectClass);
}
private static Method getPerObjectAspectOf(Class aspectClass) throws NoSuchMethodException {
Method method = aspectClass.getDeclaredMethod(ASPECTOF, PEROBJECT_CLASS_ARRAY);
return checkAspectOf(method, aspectClass);
}
private static Method checkAspectOf(Method method, Class aspectClass)
throws NoSuchMethodException {
method.setAccessible(true);
if (!method.isAccessible()
|| !Modifier.isPublic(method.getModifiers())
|| !Modifier.isStatic(method.getModifiers())) {
- new NoSuchMethodException(aspectClass.getName() + ".aspectOf(..) is not accessible public static");
+ throw new NoSuchMethodException(aspectClass.getName() + ".aspectOf(..) is not accessible public static");
}
return method;
}
}
| true | true | private static Method checkAspectOf(Method method, Class aspectClass)
throws NoSuchMethodException {
method.setAccessible(true);
if (!method.isAccessible()
|| !Modifier.isPublic(method.getModifiers())
|| !Modifier.isStatic(method.getModifiers())) {
new NoSuchMethodException(aspectClass.getName() + ".aspectOf(..) is not accessible public static");
}
return method;
}
| private static Method checkAspectOf(Method method, Class aspectClass)
throws NoSuchMethodException {
method.setAccessible(true);
if (!method.isAccessible()
|| !Modifier.isPublic(method.getModifiers())
|| !Modifier.isStatic(method.getModifiers())) {
throw new NoSuchMethodException(aspectClass.getName() + ".aspectOf(..) is not accessible public static");
}
return method;
}
|
diff --git a/shell/ssh/src/main/java/org/apache/karaf/shell/ssh/ServerKeyVerifierImpl.java b/shell/ssh/src/main/java/org/apache/karaf/shell/ssh/ServerKeyVerifierImpl.java
index 61f1717e5..ab337cdcd 100644
--- a/shell/ssh/src/main/java/org/apache/karaf/shell/ssh/ServerKeyVerifierImpl.java
+++ b/shell/ssh/src/main/java/org/apache/karaf/shell/ssh/ServerKeyVerifierImpl.java
@@ -1,61 +1,61 @@
/*
* 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.karaf.shell.ssh;
import java.net.SocketAddress;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import org.apache.sshd.ClientSession;
import org.apache.sshd.client.ServerKeyVerifier;
public class ServerKeyVerifierImpl implements ServerKeyVerifier {
private final KnownHostsManager knownHostsManager;
public ServerKeyVerifierImpl(KnownHostsManager knownHostsManager) {
this.knownHostsManager = knownHostsManager;
}
@Override
public boolean verifyServerKey(ClientSession sshClientSession,
SocketAddress remoteAddress, PublicKey serverKey) {
PublicKey knownKey;
try {
knownKey = knownHostsManager.getKnownKey(remoteAddress, serverKey.getAlgorithm());
} catch (InvalidKeySpecException e) {
- System.out.println("Invalid key stored for host " + remoteAddress + ". Terminating session.");
+ System.err.println("Invalid key stored for host " + remoteAddress + ". Terminating session.");
return false;
}
if (knownKey == null) {
System.out.println("Connecting to this server for the first time. Storing the server key.");
knownHostsManager.storeKeyForHost(remoteAddress, serverKey);
return true;
}
boolean verifed = (knownKey.equals(serverKey));
if (!verifed) {
- System.out.println("Server key for host " + remoteAddress + " does not match the stored key !! Terminating session.");
+ System.err.println("Server key for host " + remoteAddress + " does not match the stored key !! Terminating session.");
}
return verifed;
}
}
| false | true | public boolean verifyServerKey(ClientSession sshClientSession,
SocketAddress remoteAddress, PublicKey serverKey) {
PublicKey knownKey;
try {
knownKey = knownHostsManager.getKnownKey(remoteAddress, serverKey.getAlgorithm());
} catch (InvalidKeySpecException e) {
System.out.println("Invalid key stored for host " + remoteAddress + ". Terminating session.");
return false;
}
if (knownKey == null) {
System.out.println("Connecting to this server for the first time. Storing the server key.");
knownHostsManager.storeKeyForHost(remoteAddress, serverKey);
return true;
}
boolean verifed = (knownKey.equals(serverKey));
if (!verifed) {
System.out.println("Server key for host " + remoteAddress + " does not match the stored key !! Terminating session.");
}
return verifed;
}
| public boolean verifyServerKey(ClientSession sshClientSession,
SocketAddress remoteAddress, PublicKey serverKey) {
PublicKey knownKey;
try {
knownKey = knownHostsManager.getKnownKey(remoteAddress, serverKey.getAlgorithm());
} catch (InvalidKeySpecException e) {
System.err.println("Invalid key stored for host " + remoteAddress + ". Terminating session.");
return false;
}
if (knownKey == null) {
System.out.println("Connecting to this server for the first time. Storing the server key.");
knownHostsManager.storeKeyForHost(remoteAddress, serverKey);
return true;
}
boolean verifed = (knownKey.equals(serverKey));
if (!verifed) {
System.err.println("Server key for host " + remoteAddress + " does not match the stored key !! Terminating session.");
}
return verifed;
}
|
diff --git a/code/src/at/photoselector/ui/MyApplicationWindow.java b/code/src/at/photoselector/ui/MyApplicationWindow.java
index 913922b..7468d65 100644
--- a/code/src/at/photoselector/ui/MyApplicationWindow.java
+++ b/code/src/at/photoselector/ui/MyApplicationWindow.java
@@ -1,57 +1,62 @@
package at.photoselector.ui;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Shell;
import at.photoselector.Settings;
public abstract class MyApplicationWindow extends ApplicationWindow implements
Runnable {
protected String control = null;
public MyApplicationWindow(Shell parentShell) {
super(null);
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
// restore window size and location
control = this.getClass().getSimpleName().replaceAll("s?Dialog$", "")
.toLowerCase();
Rectangle tmp = Settings.rememberWindowPosition(control);
shell.setLocation(tmp.x, tmp.y);
shell.setSize(tmp.width, tmp.height);
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
// memorize window location
/*
* FIXME dirty fix of swt but. shell.getLocation is not updated
* unless we hide it and show it again...
*/
getShell().setVisible(false);
getShell().setVisible(true);
+ if (((Shell) e.widget).getText().equals("PhotoSelector"))
+ getShell().setBounds(getShell().getBounds().x,
+ getShell().getBounds().y,
+ getShell().getBounds().width + 4,
+ getShell().getBounds().height + 4);
Settings.memorizeWindowPosition(control, getShell().getBounds());
}
});
}
public void run() {
// Don't return from open() until window closes
setBlockOnOpen(true);
// Open the main window
open();
}
public abstract void update();
}
| true | true | protected void configureShell(Shell shell) {
super.configureShell(shell);
// restore window size and location
control = this.getClass().getSimpleName().replaceAll("s?Dialog$", "")
.toLowerCase();
Rectangle tmp = Settings.rememberWindowPosition(control);
shell.setLocation(tmp.x, tmp.y);
shell.setSize(tmp.width, tmp.height);
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
// memorize window location
/*
* FIXME dirty fix of swt but. shell.getLocation is not updated
* unless we hide it and show it again...
*/
getShell().setVisible(false);
getShell().setVisible(true);
Settings.memorizeWindowPosition(control, getShell().getBounds());
}
});
}
| protected void configureShell(Shell shell) {
super.configureShell(shell);
// restore window size and location
control = this.getClass().getSimpleName().replaceAll("s?Dialog$", "")
.toLowerCase();
Rectangle tmp = Settings.rememberWindowPosition(control);
shell.setLocation(tmp.x, tmp.y);
shell.setSize(tmp.width, tmp.height);
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
// memorize window location
/*
* FIXME dirty fix of swt but. shell.getLocation is not updated
* unless we hide it and show it again...
*/
getShell().setVisible(false);
getShell().setVisible(true);
if (((Shell) e.widget).getText().equals("PhotoSelector"))
getShell().setBounds(getShell().getBounds().x,
getShell().getBounds().y,
getShell().getBounds().width + 4,
getShell().getBounds().height + 4);
Settings.memorizeWindowPosition(control, getShell().getBounds());
}
});
}
|
diff --git a/src/org/waveprotocol/wave/client/wavepanel/impl/toolbar/ToolbarSwitcher.java b/src/org/waveprotocol/wave/client/wavepanel/impl/toolbar/ToolbarSwitcher.java
index 0c8f12da..639f84d1 100644
--- a/src/org/waveprotocol/wave/client/wavepanel/impl/toolbar/ToolbarSwitcher.java
+++ b/src/org/waveprotocol/wave/client/wavepanel/impl/toolbar/ToolbarSwitcher.java
@@ -1,90 +1,90 @@
/**
* 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 org.waveprotocol.wave.client.wavepanel.impl.toolbar;
import org.waveprotocol.wave.client.editor.Editor;
import org.waveprotocol.wave.client.wavepanel.WavePanel;
import org.waveprotocol.wave.client.wavepanel.impl.edit.EditSession;
import org.waveprotocol.wave.client.wavepanel.view.BlipView;
/**
* Switches between two toolbars, a "view" and "edit" toolbar, as the client
* moves in and out of edit mode.
*
* @author [email protected] (Benjamin Kalman)
*/
public final class ToolbarSwitcher implements EditSession.Listener {
private final WavePanel panel;
private final EditSession editSession;
private final ViewToolbar viewToolbar;
private final EditToolbar editToolbar;
private ToolbarSwitcher(WavePanel panel, EditSession editSession,
ViewToolbar viewToolbar, EditToolbar editToolbar) {
this.panel = panel;
this.editSession = editSession;
this.viewToolbar = viewToolbar;
this.editToolbar = editToolbar;
}
/**
* Creates a new {@link ToolbarSwitcher} and initialises it.
*/
public static ToolbarSwitcher install(WavePanel panel, EditSession editSession,
ViewToolbar viewToolbar, EditToolbar editToolbar) {
ToolbarSwitcher switcher = new ToolbarSwitcher(panel, editSession, viewToolbar, editToolbar);
switcher.init();
return switcher;
}
private void init() {
viewToolbar.init();
editToolbar.init();
editSession.addListener(this);
if (editSession.isEditing()) {
startEditSession(editSession.getEditor());
- } else if(panel.hasContents()){
+ } else if (panel.hasContents()) {
startViewSession();
}
}
@Override
public void onSessionStart(Editor editor, BlipView blipUi) {
viewToolbar.getWidget().removeFromParent();
startEditSession(editor);
}
private void startEditSession(Editor editor) {
panel.getContents().setToolbar(editToolbar.getWidget().getElement());
panel.getGwtPanel().doAdopt(editToolbar.getWidget());
editToolbar.enable(editor);
}
@Override
public void onSessionEnd(Editor editor, BlipView blipUi) {
editToolbar.disable(editor);
editToolbar.getWidget().removeFromParent();
startViewSession();
}
private void startViewSession() {
panel.getContents().setToolbar(viewToolbar.getWidget().getElement());
panel.getGwtPanel().doAdopt(viewToolbar.getWidget());
}
}
| true | true | private void init() {
viewToolbar.init();
editToolbar.init();
editSession.addListener(this);
if (editSession.isEditing()) {
startEditSession(editSession.getEditor());
} else if(panel.hasContents()){
startViewSession();
}
}
| private void init() {
viewToolbar.init();
editToolbar.init();
editSession.addListener(this);
if (editSession.isEditing()) {
startEditSession(editSession.getEditor());
} else if (panel.hasContents()) {
startViewSession();
}
}
|
diff --git a/lucene/backwards/src/test/org/apache/lucene/index/TestIndexReader.java b/lucene/backwards/src/test/org/apache/lucene/index/TestIndexReader.java
index 0c0a2c3a..5330d0cf 100644
--- a/lucene/backwards/src/test/org/apache/lucene/index/TestIndexReader.java
+++ b/lucene/backwards/src/test/org/apache/lucene/index/TestIndexReader.java
@@ -1,1828 +1,1828 @@
package org.apache.lucene.index;
/**
* 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.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.SortedSet;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.SetBasedFieldSelector;
import org.apache.lucene.index.IndexReader.FieldOption;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.store.NoSuchDirectoryException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.LockReleaseFailedException;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
public class TestIndexReader extends LuceneTestCase {
public void testCommitUserData() throws Exception {
Directory d = newDirectory();
Map<String,String> commitUserData = new HashMap<String,String>();
commitUserData.put("foo", "fighters");
// set up writer
IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT))
.setMaxBufferedDocs(2));
for(int i=0;i<27;i++)
addDocumentWithFields(writer);
writer.close();
IndexReader r = IndexReader.open(d, false);
r.deleteDocument(5);
r.flush(commitUserData);
r.close();
SegmentInfos sis = new SegmentInfos();
sis.read(d);
IndexReader r2 = IndexReader.open(d, false);
IndexCommit c = r.getIndexCommit();
assertEquals(c.getUserData(), commitUserData);
assertEquals(sis.getCurrentSegmentFileName(), c.getSegmentsFileName());
assertTrue(c.equals(r.getIndexCommit()));
// Change the index
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(
OpenMode.APPEND).setMaxBufferedDocs(2));
for(int i=0;i<7;i++)
addDocumentWithFields(writer);
writer.close();
IndexReader r3 = r2.reopen();
assertFalse(c.equals(r3.getIndexCommit()));
assertFalse(r2.getIndexCommit().isOptimized());
r3.close();
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT))
.setOpenMode(OpenMode.APPEND));
writer.optimize();
writer.close();
r3 = r2.reopen();
assertTrue(r3.getIndexCommit().isOptimized());
r2.close();
r3.close();
d.close();
}
public void testIsCurrent() throws Exception {
Directory d = newDirectory();
IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
writer.close();
// set up reader:
IndexReader reader = IndexReader.open(d, false);
assertTrue(reader.isCurrent());
// modify index by adding another document:
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
addDocumentWithFields(writer);
writer.close();
assertFalse(reader.isCurrent());
// re-create index:
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
addDocumentWithFields(writer);
writer.close();
assertFalse(reader.isCurrent());
reader.close();
d.close();
}
/**
* Tests the IndexReader.getFieldNames implementation
* @throws Exception on error
*/
public void testGetFieldNames() throws Exception {
Directory d = newDirectory();
// set up writer
IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT)));
Document doc = new Document();
doc.add(new Field("keyword","test1", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("text","test1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("unindexed","test1", Field.Store.YES, Field.Index.NO));
doc.add(new Field("unstored","test1", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
writer.close();
// set up reader
IndexReader reader = IndexReader.open(d, false);
Collection<String> fieldNames = reader.getFieldNames(IndexReader.FieldOption.ALL);
assertTrue(fieldNames.contains("keyword"));
assertTrue(fieldNames.contains("text"));
assertTrue(fieldNames.contains("unindexed"));
assertTrue(fieldNames.contains("unstored"));
reader.close();
// add more documents
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
// want to get some more segments here
int mergeFactor = ((LogMergePolicy) writer.getConfig().getMergePolicy()).getMergeFactor();
for (int i = 0; i < 5*mergeFactor; i++) {
doc = new Document();
doc.add(new Field("keyword","test1", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("text","test1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("unindexed","test1", Field.Store.YES, Field.Index.NO));
doc.add(new Field("unstored","test1", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
// new fields are in some different segments (we hope)
for (int i = 0; i < 5*mergeFactor; i++) {
doc = new Document();
doc.add(new Field("keyword2","test1", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("text2","test1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("unindexed2","test1", Field.Store.YES, Field.Index.NO));
doc.add(new Field("unstored2","test1", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
// new termvector fields
for (int i = 0; i < 5*mergeFactor; i++) {
doc = new Document();
doc.add(new Field("tvnot","tvnot", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
doc.add(new Field("termvector","termvector", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
doc.add(new Field("tvoffset","tvoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
doc.add(new Field("tvposition","tvposition", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
doc.add(newField("tvpositionoffset","tvpositionoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
}
writer.close();
// verify fields again
reader = IndexReader.open(d, false);
fieldNames = reader.getFieldNames(IndexReader.FieldOption.ALL);
assertEquals(13, fieldNames.size()); // the following fields
assertTrue(fieldNames.contains("keyword"));
assertTrue(fieldNames.contains("text"));
assertTrue(fieldNames.contains("unindexed"));
assertTrue(fieldNames.contains("unstored"));
assertTrue(fieldNames.contains("keyword2"));
assertTrue(fieldNames.contains("text2"));
assertTrue(fieldNames.contains("unindexed2"));
assertTrue(fieldNames.contains("unstored2"));
assertTrue(fieldNames.contains("tvnot"));
assertTrue(fieldNames.contains("termvector"));
assertTrue(fieldNames.contains("tvposition"));
assertTrue(fieldNames.contains("tvoffset"));
assertTrue(fieldNames.contains("tvpositionoffset"));
// verify that only indexed fields were returned
fieldNames = reader.getFieldNames(IndexReader.FieldOption.INDEXED);
assertEquals(11, fieldNames.size()); // 6 original + the 5 termvector fields
assertTrue(fieldNames.contains("keyword"));
assertTrue(fieldNames.contains("text"));
assertTrue(fieldNames.contains("unstored"));
assertTrue(fieldNames.contains("keyword2"));
assertTrue(fieldNames.contains("text2"));
assertTrue(fieldNames.contains("unstored2"));
assertTrue(fieldNames.contains("tvnot"));
assertTrue(fieldNames.contains("termvector"));
assertTrue(fieldNames.contains("tvposition"));
assertTrue(fieldNames.contains("tvoffset"));
assertTrue(fieldNames.contains("tvpositionoffset"));
// verify that only unindexed fields were returned
fieldNames = reader.getFieldNames(IndexReader.FieldOption.UNINDEXED);
assertEquals(2, fieldNames.size()); // the following fields
assertTrue(fieldNames.contains("unindexed"));
assertTrue(fieldNames.contains("unindexed2"));
// verify index term vector fields
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR);
assertEquals(1, fieldNames.size()); // 1 field has term vector only
assertTrue(fieldNames.contains("termvector"));
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION);
assertEquals(1, fieldNames.size()); // 4 fields are indexed with term vectors
assertTrue(fieldNames.contains("tvposition"));
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET);
assertEquals(1, fieldNames.size()); // 4 fields are indexed with term vectors
assertTrue(fieldNames.contains("tvoffset"));
fieldNames = reader.getFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET);
assertEquals(1, fieldNames.size()); // 4 fields are indexed with term vectors
assertTrue(fieldNames.contains("tvpositionoffset"));
reader.close();
d.close();
}
public void testTermVectors() throws Exception {
Directory d = newDirectory();
// set up writer
IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT)));
// want to get some more segments here
// new termvector fields
int mergeFactor = ((LogMergePolicy) writer.getConfig().getMergePolicy()).getMergeFactor();
for (int i = 0; i < 5 * mergeFactor; i++) {
Document doc = new Document();
doc.add(new Field("tvnot","one two two three three three", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
doc.add(new Field("termvector","one two two three three three", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
doc.add(new Field("tvoffset","one two two three three three", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
doc.add(new Field("tvposition","one two two three three three", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
doc.add(new Field("tvpositionoffset","one two two three three three", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
}
writer.close();
IndexReader reader = IndexReader.open(d, false);
FieldSortedTermVectorMapper mapper = new FieldSortedTermVectorMapper(new TermVectorEntryFreqSortedComparator());
reader.getTermFreqVector(0, mapper);
Map<String,SortedSet<TermVectorEntry>> map = mapper.getFieldToTerms();
assertTrue("map is null and it shouldn't be", map != null);
assertTrue("map Size: " + map.size() + " is not: " + 4, map.size() == 4);
Set<TermVectorEntry> set = map.get("termvector");
for (Iterator<TermVectorEntry> iterator = set.iterator(); iterator.hasNext();) {
TermVectorEntry entry = iterator.next();
assertTrue("entry is null and it shouldn't be", entry != null);
if (VERBOSE) System.out.println("Entry: " + entry);
}
reader.close();
d.close();
}
private void assertTermDocsCount(String msg,
IndexReader reader,
Term term,
int expected)
throws IOException
{
TermDocs tdocs = null;
try {
tdocs = reader.termDocs(term);
assertNotNull(msg + ", null TermDocs", tdocs);
int count = 0;
while(tdocs.next()) {
count++;
}
assertEquals(msg + ", count mismatch", expected, count);
} finally {
if (tdocs != null)
tdocs.close();
}
}
public void testBasicDelete() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = null;
IndexReader reader = null;
Term searchTerm = new Term("content", "aaa");
// add 100 documents with term : aaa
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for (int i = 0; i < 100; i++) {
addDoc(writer, searchTerm.text());
}
writer.close();
// OPEN READER AT THIS POINT - this should fix the view of the
// index at the point of having 100 "aaa" documents and 0 "bbb"
reader = IndexReader.open(dir, false);
assertEquals("first docFreq", 100, reader.docFreq(searchTerm));
assertTermDocsCount("first reader", reader, searchTerm, 100);
reader.close();
// DELETE DOCUMENTS CONTAINING TERM: aaa
int deleted = 0;
reader = IndexReader.open(dir, false);
deleted = reader.deleteDocuments(searchTerm);
assertEquals("deleted count", 100, deleted);
assertEquals("deleted docFreq", 100, reader.docFreq(searchTerm));
assertTermDocsCount("deleted termDocs", reader, searchTerm, 0);
// open a 2nd reader to make sure first reader can
// commit its changes (.del) while second reader
// is open:
IndexReader reader2 = IndexReader.open(dir, false);
reader.close();
// CREATE A NEW READER and re-test
reader = IndexReader.open(dir, false);
assertEquals("deleted docFreq", 0, reader.docFreq(searchTerm));
assertTermDocsCount("deleted termDocs", reader, searchTerm, 0);
reader.close();
reader2.close();
dir.close();
}
public void testBinaryFields() throws IOException {
Directory dir = newDirectory();
byte[] bin = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for (int i = 0; i < 10; i++) {
addDoc(writer, "document number " + (i + 1));
addDocumentWithFields(writer);
addDocumentWithDifferentFields(writer);
addDocumentWithTermVectorFields(writer);
}
writer.close();
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
Document doc = new Document();
doc.add(new Field("bin1", bin));
doc.add(new Field("junk", "junk text", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
writer.close();
IndexReader reader = IndexReader.open(dir, false);
doc = reader.document(reader.maxDoc() - 1);
Field[] fields = doc.getFields("bin1");
assertNotNull(fields);
assertEquals(1, fields.length);
Field b1 = fields[0];
assertTrue(b1.isBinary());
byte[] data1 = b1.getBinaryValue();
assertEquals(bin.length, b1.getBinaryLength());
for (int i = 0; i < bin.length; i++) {
assertEquals(bin[i], data1[i + b1.getBinaryOffset()]);
}
Set<String> lazyFields = new HashSet<String>();
lazyFields.add("bin1");
FieldSelector sel = new SetBasedFieldSelector(new HashSet<String>(), lazyFields);
doc = reader.document(reader.maxDoc() - 1, sel);
Fieldable[] fieldables = doc.getFieldables("bin1");
assertNotNull(fieldables);
assertEquals(1, fieldables.length);
Fieldable fb1 = fieldables[0];
assertTrue(fb1.isBinary());
assertEquals(bin.length, fb1.getBinaryLength());
data1 = fb1.getBinaryValue();
assertEquals(bin.length, fb1.getBinaryLength());
for (int i = 0; i < bin.length; i++) {
assertEquals(bin[i], data1[i + fb1.getBinaryOffset()]);
}
reader.close();
// force optimize
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
writer.optimize();
writer.close();
reader = IndexReader.open(dir, false);
doc = reader.document(reader.maxDoc() - 1);
fields = doc.getFields("bin1");
assertNotNull(fields);
assertEquals(1, fields.length);
b1 = fields[0];
assertTrue(b1.isBinary());
data1 = b1.getBinaryValue();
assertEquals(bin.length, b1.getBinaryLength());
for (int i = 0; i < bin.length; i++) {
assertEquals(bin[i], data1[i + b1.getBinaryOffset()]);
}
reader.close();
dir.close();
}
// Make sure attempts to make changes after reader is
// closed throws IOException:
public void testChangesAfterClose() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = null;
IndexReader reader = null;
Term searchTerm = new Term("content", "aaa");
// add 11 documents with term : aaa
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for (int i = 0; i < 11; i++) {
addDoc(writer, searchTerm.text());
}
writer.close();
reader = IndexReader.open(dir, false);
// Close reader:
reader.close();
// Then, try to make changes:
try {
reader.deleteDocument(4);
fail("deleteDocument after close failed to throw IOException");
} catch (AlreadyClosedException e) {
// expected
}
try {
reader.setNorm(5, "aaa", 2.0f);
fail("setNorm after close failed to throw IOException");
} catch (AlreadyClosedException e) {
// expected
}
try {
reader.undeleteAll();
fail("undeleteAll after close failed to throw IOException");
} catch (AlreadyClosedException e) {
// expected
}
dir.close();
}
// Make sure we get lock obtain failed exception with 2 writers:
public void testLockObtainFailed() throws IOException {
Directory dir = newDirectory();
Term searchTerm = new Term("content", "aaa");
// add 11 documents with term : aaa
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
writer.commit();
for (int i = 0; i < 11; i++) {
addDoc(writer, searchTerm.text());
}
// Create reader:
IndexReader reader = IndexReader.open(dir, false);
// Try to make changes
try {
reader.deleteDocument(4);
fail("deleteDocument should have hit LockObtainFailedException");
} catch (LockObtainFailedException e) {
// expected
}
try {
reader.setNorm(5, "aaa", 2.0f);
fail("setNorm should have hit LockObtainFailedException");
} catch (LockObtainFailedException e) {
// expected
}
try {
reader.undeleteAll();
fail("undeleteAll should have hit LockObtainFailedException");
} catch (LockObtainFailedException e) {
// expected
}
writer.close();
reader.close();
dir.close();
}
// Make sure you can set norms & commit even if a reader
// is open against the index:
public void testWritingNorms() throws IOException {
Directory dir = newDirectory();
IndexWriter writer;
IndexReader reader;
Term searchTerm = new Term("content", "aaa");
// add 1 documents with term : aaa
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDoc(writer, searchTerm.text());
writer.close();
// now open reader & set norm for doc 0
reader = IndexReader.open(dir, false);
reader.setNorm(0, "content", (float) 2.0);
// we should be holding the write lock now:
assertTrue("locked", IndexWriter.isLocked(dir));
reader.commit();
// we should not be holding the write lock now:
assertTrue("not locked", !IndexWriter.isLocked(dir));
// open a 2nd reader:
IndexReader reader2 = IndexReader.open(dir, false);
// set norm again for doc 0
reader.setNorm(0, "content", (float) 3.0);
assertTrue("locked", IndexWriter.isLocked(dir));
reader.close();
// we should not be holding the write lock now:
assertTrue("not locked", !IndexWriter.isLocked(dir));
reader2.close();
dir.close();
}
// Make sure you can set norms & commit, and there are
// no extra norms files left:
public void testWritingNormsNoReader() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = null;
IndexReader reader = null;
Term searchTerm = new Term("content", "aaa");
// add 1 documents with term : aaa
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
((LogMergePolicy) writer.getConfig().getMergePolicy()).setUseCompoundFile(false);
addDoc(writer, searchTerm.text());
writer.close();
// now open reader & set norm for doc 0 (writes to
// _0_1.s0)
reader = IndexReader.open(dir, false);
reader.setNorm(0, "content", (float) 2.0);
reader.close();
// now open reader again & set norm for doc 0 (writes to _0_2.s0)
reader = IndexReader.open(dir, false);
reader.setNorm(0, "content", (float) 2.0);
reader.close();
assertFalse("failed to remove first generation norms file on writing second generation",
dir.fileExists("_0_1.s0"));
dir.close();
}
public void testDeleteReaderWriterConflictUnoptimized() throws IOException{
deleteReaderWriterConflict(false);
}
/* ??? public void testOpenEmptyDirectory() throws IOException{
String dirName = "test.empty";
File fileDirName = new File(dirName);
if (!fileDirName.exists()) {
fileDirName.mkdir();
}
try {
IndexReader.open(fileDirName);
fail("opening IndexReader on empty directory failed to produce FileNotFoundException");
} catch (FileNotFoundException e) {
// GOOD
}
rmDir(fileDirName);
}*/
public void testDeleteReaderWriterConflictOptimized() throws IOException{
deleteReaderWriterConflict(true);
}
private void deleteReaderWriterConflict(boolean optimize) throws IOException {
//Directory dir = new RAMDirectory();
Directory dir = newDirectory();
Term searchTerm = new Term("content", "aaa");
Term searchTerm2 = new Term("content", "bbb");
// add 100 documents with term : aaa
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
for (int i = 0; i < 100; i++) {
addDoc(writer, searchTerm.text());
}
writer.close();
// OPEN READER AT THIS POINT - this should fix the view of the
// index at the point of having 100 "aaa" documents and 0 "bbb"
IndexReader reader = IndexReader.open(dir, false);
assertEquals("first docFreq", 100, reader.docFreq(searchTerm));
assertEquals("first docFreq", 0, reader.docFreq(searchTerm2));
assertTermDocsCount("first reader", reader, searchTerm, 100);
assertTermDocsCount("first reader", reader, searchTerm2, 0);
// add 100 documents with term : bbb
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
for (int i = 0; i < 100; i++) {
addDoc(writer, searchTerm2.text());
}
// REQUEST OPTIMIZATION
// This causes a new segment to become current for all subsequent
// searchers. Because of this, deletions made via a previously open
// reader, which would be applied to that reader's segment, are lost
// for subsequent searchers/readers
if(optimize)
writer.optimize();
writer.close();
// The reader should not see the new data
assertEquals("first docFreq", 100, reader.docFreq(searchTerm));
assertEquals("first docFreq", 0, reader.docFreq(searchTerm2));
assertTermDocsCount("first reader", reader, searchTerm, 100);
assertTermDocsCount("first reader", reader, searchTerm2, 0);
// DELETE DOCUMENTS CONTAINING TERM: aaa
// NOTE: the reader was created when only "aaa" documents were in
int deleted = 0;
try {
deleted = reader.deleteDocuments(searchTerm);
fail("Delete allowed on an index reader with stale segment information");
} catch (StaleReaderException e) {
/* success */
}
// Re-open index reader and try again. This time it should see
// the new data.
reader.close();
reader = IndexReader.open(dir, false);
assertEquals("first docFreq", 100, reader.docFreq(searchTerm));
assertEquals("first docFreq", 100, reader.docFreq(searchTerm2));
assertTermDocsCount("first reader", reader, searchTerm, 100);
assertTermDocsCount("first reader", reader, searchTerm2, 100);
deleted = reader.deleteDocuments(searchTerm);
assertEquals("deleted count", 100, deleted);
assertEquals("deleted docFreq", 100, reader.docFreq(searchTerm));
assertEquals("deleted docFreq", 100, reader.docFreq(searchTerm2));
assertTermDocsCount("deleted termDocs", reader, searchTerm, 0);
assertTermDocsCount("deleted termDocs", reader, searchTerm2, 100);
reader.close();
// CREATE A NEW READER and re-test
reader = IndexReader.open(dir, false);
assertEquals("deleted docFreq", 100, reader.docFreq(searchTerm2));
assertTermDocsCount("deleted termDocs", reader, searchTerm, 0);
assertTermDocsCount("deleted termDocs", reader, searchTerm2, 100);
reader.close();
dir.close();
}
public void testFilesOpenClose() throws IOException {
// Create initial data set
File dirFile = _TestUtil.getTempDir("TestIndexReader.testFilesOpenClose");
Directory dir = newFSDirectory(dirFile);
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDoc(writer, "test");
writer.close();
dir.close();
// Try to erase the data - this ensures that the writer closed all files
_TestUtil.rmDir(dirFile);
dir = newFSDirectory(dirFile);
// Now create the data set again, just as before
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
addDoc(writer, "test");
writer.close();
dir.close();
// Now open existing directory and test that reader closes all files
dir = newFSDirectory(dirFile);
IndexReader reader1 = IndexReader.open(dir, false);
reader1.close();
dir.close();
// The following will fail if reader did not close
// all files
_TestUtil.rmDir(dirFile);
}
public void testLastModified() throws Exception {
for(int i=0;i<2;i++) {
final Directory dir = newDirectory();
assertFalse(IndexReader.indexExists(dir));
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
addDocumentWithFields(writer);
assertTrue(IndexWriter.isLocked(dir)); // writer open, so dir is locked
writer.close();
assertTrue(IndexReader.indexExists(dir));
IndexReader reader = IndexReader.open(dir, false);
assertFalse(IndexWriter.isLocked(dir)); // reader only, no lock
long version = IndexReader.lastModified(dir);
if (i == 1) {
long version2 = IndexReader.lastModified(dir);
assertEquals(version, version2);
}
reader.close();
// modify index and check version has been
// incremented:
Thread.sleep(1000);
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
addDocumentWithFields(writer);
writer.close();
reader = IndexReader.open(dir, false);
assertTrue("old lastModified is " + version + "; new lastModified is " + IndexReader.lastModified(dir), version <= IndexReader.lastModified(dir));
reader.close();
dir.close();
}
}
public void testVersion() throws IOException {
Directory dir = newDirectory();
assertFalse(IndexReader.indexExists(dir));
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
assertTrue(IndexWriter.isLocked(dir)); // writer open, so dir is locked
writer.close();
assertTrue(IndexReader.indexExists(dir));
IndexReader reader = IndexReader.open(dir, false);
assertFalse(IndexWriter.isLocked(dir)); // reader only, no lock
long version = IndexReader.getCurrentVersion(dir);
reader.close();
// modify index and check version has been
// incremented:
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
addDocumentWithFields(writer);
writer.close();
reader = IndexReader.open(dir, false);
assertTrue("old version is " + version + "; new version is " + IndexReader.getCurrentVersion(dir), version < IndexReader.getCurrentVersion(dir));
reader.close();
dir.close();
}
public void testLock() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
writer.close();
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
IndexReader reader = IndexReader.open(dir, false);
try {
reader.deleteDocument(0);
fail("expected lock");
} catch(IOException e) {
// expected exception
}
try {
IndexWriter.unlock(dir); // this should not be done in the real world!
} catch (LockReleaseFailedException lrfe) {
writer.close();
}
reader.deleteDocument(0);
reader.close();
writer.close();
dir.close();
}
public void testUndeleteAll() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
addDocumentWithFields(writer);
writer.close();
IndexReader reader = IndexReader.open(dir, false);
reader.deleteDocument(0);
reader.deleteDocument(1);
reader.undeleteAll();
reader.close();
reader = IndexReader.open(dir, false);
assertEquals(2, reader.numDocs()); // nothing has really been deleted thanks to undeleteAll()
reader.close();
dir.close();
}
public void testUndeleteAllAfterClose() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
addDocumentWithFields(writer);
writer.close();
IndexReader reader = IndexReader.open(dir, false);
reader.deleteDocument(0);
reader.close();
reader = IndexReader.open(dir, false);
reader.undeleteAll();
assertEquals(2, reader.numDocs()); // nothing has really been deleted thanks to undeleteAll()
reader.close();
dir.close();
}
public void testUndeleteAllAfterCloseThenReopen() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
addDocumentWithFields(writer);
writer.close();
IndexReader reader = IndexReader.open(dir, false);
reader.deleteDocument(0);
reader.close();
reader = IndexReader.open(dir, false);
reader.undeleteAll();
reader.close();
reader = IndexReader.open(dir, false);
assertEquals(2, reader.numDocs()); // nothing has really been deleted thanks to undeleteAll()
reader.close();
dir.close();
}
public void testDeleteReaderReaderConflictUnoptimized() throws IOException{
deleteReaderReaderConflict(false);
}
public void testDeleteReaderReaderConflictOptimized() throws IOException{
deleteReaderReaderConflict(true);
}
/**
* Make sure if reader tries to commit but hits disk
* full that reader remains consistent and usable.
*/
public void testDiskFull() throws IOException {
Term searchTerm = new Term("content", "aaa");
int START_COUNT = 157;
int END_COUNT = 144;
// First build up a starting index:
MockDirectoryWrapper startDir = newDirectory();
IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for(int i=0;i<157;i++) {
Document d = new Document();
d.add(newField("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
d.add(newField("content", "aaa " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(d);
}
writer.close();
long diskUsage = startDir.getRecomputedActualSizeInBytes();
long diskFree = diskUsage+100;
IOException err = null;
boolean done = false;
// Iterate w/ ever increasing free disk space:
while(!done) {
MockDirectoryWrapper dir = new MockDirectoryWrapper(random, new RAMDirectory(startDir));
// If IndexReader hits disk full, it can write to
// the same files again.
dir.setPreventDoubleWrite(false);
IndexReader reader = IndexReader.open(dir, false);
// For each disk size, first try to commit against
// dir that will hit random IOExceptions & disk
// full; after, give it infinite disk space & turn
// off random IOExceptions & retry w/ same reader:
boolean success = false;
for(int x=0;x<2;x++) {
double rate = 0.05;
double diskRatio = ((double) diskFree)/diskUsage;
long thisDiskFree;
String testName;
if (0 == x) {
thisDiskFree = diskFree;
if (diskRatio >= 2.0) {
rate /= 2;
}
if (diskRatio >= 4.0) {
rate /= 2;
}
if (diskRatio >= 6.0) {
rate = 0.0;
}
if (VERBOSE) {
System.out.println("\ncycle: " + diskFree + " bytes");
}
testName = "disk full during reader.close() @ " + thisDiskFree + " bytes";
} else {
thisDiskFree = 0;
rate = 0.0;
if (VERBOSE) {
System.out.println("\ncycle: same writer: unlimited disk space");
}
testName = "reader re-use after disk full";
}
dir.setMaxSizeInBytes(thisDiskFree);
dir.setRandomIOExceptionRate(rate);
try {
if (0 == x) {
int docId = 12;
for(int i=0;i<13;i++) {
reader.deleteDocument(docId);
- reader.setNorm(docId, "contents", (float) 2.0);
+ reader.setNorm(docId, "content", (float) 2.0);
docId += 12;
}
}
reader.close();
success = true;
if (0 == x) {
done = true;
}
} catch (IOException e) {
if (VERBOSE) {
System.out.println(" hit IOException: " + e);
e.printStackTrace(System.out);
}
err = e;
if (1 == x) {
e.printStackTrace();
fail(testName + " hit IOException after disk space was freed up");
}
}
// Finally, verify index is not corrupt, and, if
// we succeeded, we see all docs changed, and if
// we failed, we see either all docs or no docs
// changed (transactional semantics):
IndexReader newReader = null;
try {
newReader = IndexReader.open(dir, false);
} catch (IOException e) {
e.printStackTrace();
fail(testName + ":exception when creating IndexReader after disk full during close: " + e);
}
/*
int result = newReader.docFreq(searchTerm);
if (success) {
if (result != END_COUNT) {
fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + END_COUNT);
}
} else {
// On hitting exception we still may have added
// all docs:
if (result != START_COUNT && result != END_COUNT) {
err.printStackTrace();
fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT);
}
}
*/
IndexSearcher searcher = newSearcher(newReader);
ScoreDoc[] hits = null;
try {
hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
} catch (IOException e) {
e.printStackTrace();
fail(testName + ": exception when searching: " + e);
}
int result2 = hits.length;
if (success) {
if (result2 != END_COUNT) {
fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + END_COUNT);
}
} else {
// On hitting exception we still may have added
// all docs:
if (result2 != START_COUNT && result2 != END_COUNT) {
err.printStackTrace();
fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + START_COUNT);
}
}
searcher.close();
newReader.close();
if (result2 == END_COUNT) {
break;
}
}
dir.close();
// Try again with 10 more bytes of free space:
diskFree += 10;
}
startDir.close();
}
public void testDocsOutOfOrderJIRA140() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for(int i=0;i<11;i++) {
addDoc(writer, "aaa");
}
writer.close();
IndexReader reader = IndexReader.open(dir, false);
// Try to delete an invalid docId, yet, within range
// of the final bits of the BitVector:
boolean gotException = false;
try {
reader.deleteDocument(11);
} catch (ArrayIndexOutOfBoundsException e) {
gotException = true;
}
reader.close();
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.APPEND));
// We must add more docs to get a new segment written
for(int i=0;i<11;i++) {
addDoc(writer, "aaa");
}
// Without the fix for LUCENE-140 this call will
// [incorrectly] hit a "docs out of order"
// IllegalStateException because above out-of-bounds
// deleteDocument corrupted the index:
writer.optimize();
writer.close();
if (!gotException) {
fail("delete of out-of-bounds doc number failed to hit exception");
}
dir.close();
}
public void testExceptionReleaseWriteLockJIRA768() throws IOException {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
addDoc(writer, "aaa");
writer.close();
IndexReader reader = IndexReader.open(dir, false);
try {
reader.deleteDocument(1);
fail("did not hit exception when deleting an invalid doc number");
} catch (ArrayIndexOutOfBoundsException e) {
// expected
}
reader.close();
if (IndexWriter.isLocked(dir)) {
fail("write lock is still held after close");
}
reader = IndexReader.open(dir, false);
try {
reader.setNorm(1, "content", (float) 2.0);
fail("did not hit exception when calling setNorm on an invalid doc number");
} catch (ArrayIndexOutOfBoundsException e) {
// expected
}
reader.close();
if (IndexWriter.isLocked(dir)) {
fail("write lock is still held after close");
}
dir.close();
}
private String arrayToString(String[] l) {
String s = "";
for(int i=0;i<l.length;i++) {
if (i > 0) {
s += "\n ";
}
s += l[i];
}
return s;
}
public void testOpenReaderAfterDelete() throws IOException {
File dirFile = _TestUtil.getTempDir("deletetest");
Directory dir = newFSDirectory(dirFile);
try {
IndexReader.open(dir, false);
fail("expected FileNotFoundException");
} catch (FileNotFoundException e) {
// expected
}
dirFile.delete();
// Make sure we still get a CorruptIndexException (not NPE):
try {
IndexReader.open(dir, false);
fail("expected FileNotFoundException");
} catch (FileNotFoundException e) {
// expected
}
dir.close();
}
private void deleteReaderReaderConflict(boolean optimize) throws IOException {
Directory dir = newDirectory();
Term searchTerm1 = new Term("content", "aaa");
Term searchTerm2 = new Term("content", "bbb");
Term searchTerm3 = new Term("content", "ccc");
// add 100 documents with term : aaa
// add 100 documents with term : bbb
// add 100 documents with term : ccc
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE));
for (int i = 0; i < 100; i++) {
addDoc(writer, searchTerm1.text());
addDoc(writer, searchTerm2.text());
addDoc(writer, searchTerm3.text());
}
if(optimize)
writer.optimize();
writer.close();
// OPEN TWO READERS
// Both readers get segment info as exists at this time
IndexReader reader1 = IndexReader.open(dir, false);
assertEquals("first opened", 100, reader1.docFreq(searchTerm1));
assertEquals("first opened", 100, reader1.docFreq(searchTerm2));
assertEquals("first opened", 100, reader1.docFreq(searchTerm3));
assertTermDocsCount("first opened", reader1, searchTerm1, 100);
assertTermDocsCount("first opened", reader1, searchTerm2, 100);
assertTermDocsCount("first opened", reader1, searchTerm3, 100);
IndexReader reader2 = IndexReader.open(dir, false);
assertEquals("first opened", 100, reader2.docFreq(searchTerm1));
assertEquals("first opened", 100, reader2.docFreq(searchTerm2));
assertEquals("first opened", 100, reader2.docFreq(searchTerm3));
assertTermDocsCount("first opened", reader2, searchTerm1, 100);
assertTermDocsCount("first opened", reader2, searchTerm2, 100);
assertTermDocsCount("first opened", reader2, searchTerm3, 100);
// DELETE DOCS FROM READER 2 and CLOSE IT
// delete documents containing term: aaa
// when the reader is closed, the segment info is updated and
// the first reader is now stale
reader2.deleteDocuments(searchTerm1);
assertEquals("after delete 1", 100, reader2.docFreq(searchTerm1));
assertEquals("after delete 1", 100, reader2.docFreq(searchTerm2));
assertEquals("after delete 1", 100, reader2.docFreq(searchTerm3));
assertTermDocsCount("after delete 1", reader2, searchTerm1, 0);
assertTermDocsCount("after delete 1", reader2, searchTerm2, 100);
assertTermDocsCount("after delete 1", reader2, searchTerm3, 100);
reader2.close();
// Make sure reader 1 is unchanged since it was open earlier
assertEquals("after delete 1", 100, reader1.docFreq(searchTerm1));
assertEquals("after delete 1", 100, reader1.docFreq(searchTerm2));
assertEquals("after delete 1", 100, reader1.docFreq(searchTerm3));
assertTermDocsCount("after delete 1", reader1, searchTerm1, 100);
assertTermDocsCount("after delete 1", reader1, searchTerm2, 100);
assertTermDocsCount("after delete 1", reader1, searchTerm3, 100);
// ATTEMPT TO DELETE FROM STALE READER
// delete documents containing term: bbb
try {
reader1.deleteDocuments(searchTerm2);
fail("Delete allowed from a stale index reader");
} catch (IOException e) {
/* success */
}
// RECREATE READER AND TRY AGAIN
reader1.close();
reader1 = IndexReader.open(dir, false);
assertEquals("reopened", 100, reader1.docFreq(searchTerm1));
assertEquals("reopened", 100, reader1.docFreq(searchTerm2));
assertEquals("reopened", 100, reader1.docFreq(searchTerm3));
assertTermDocsCount("reopened", reader1, searchTerm1, 0);
assertTermDocsCount("reopened", reader1, searchTerm2, 100);
assertTermDocsCount("reopened", reader1, searchTerm3, 100);
reader1.deleteDocuments(searchTerm2);
assertEquals("deleted 2", 100, reader1.docFreq(searchTerm1));
assertEquals("deleted 2", 100, reader1.docFreq(searchTerm2));
assertEquals("deleted 2", 100, reader1.docFreq(searchTerm3));
assertTermDocsCount("deleted 2", reader1, searchTerm1, 0);
assertTermDocsCount("deleted 2", reader1, searchTerm2, 0);
assertTermDocsCount("deleted 2", reader1, searchTerm3, 100);
reader1.close();
// Open another reader to confirm that everything is deleted
reader2 = IndexReader.open(dir, false);
assertTermDocsCount("reopened 2", reader2, searchTerm1, 0);
assertTermDocsCount("reopened 2", reader2, searchTerm2, 0);
assertTermDocsCount("reopened 2", reader2, searchTerm3, 100);
reader2.close();
dir.close();
}
private void addDocumentWithFields(IndexWriter writer) throws IOException
{
Document doc = new Document();
doc.add(newField("keyword","test1", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(newField("text","test1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(newField("unindexed","test1", Field.Store.YES, Field.Index.NO));
doc.add(newField("unstored","test1", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
private void addDocumentWithDifferentFields(IndexWriter writer) throws IOException
{
Document doc = new Document();
doc.add(newField("keyword2","test1", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(newField("text2","test1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(newField("unindexed2","test1", Field.Store.YES, Field.Index.NO));
doc.add(newField("unstored2","test1", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
private void addDocumentWithTermVectorFields(IndexWriter writer) throws IOException
{
Document doc = new Document();
doc.add(newField("tvnot","tvnot", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.NO));
doc.add(newField("termvector","termvector", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.YES));
doc.add(newField("tvoffset","tvoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
doc.add(newField("tvposition","tvposition", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
doc.add(newField("tvpositionoffset","tvpositionoffset", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);
}
private void addDoc(IndexWriter writer, String value) throws IOException {
Document doc = new Document();
doc.add(newField("content", value, Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
public static void assertIndexEquals(IndexReader index1, IndexReader index2) throws IOException {
assertEquals("IndexReaders have different values for numDocs.", index1.numDocs(), index2.numDocs());
assertEquals("IndexReaders have different values for maxDoc.", index1.maxDoc(), index2.maxDoc());
assertEquals("Only one IndexReader has deletions.", index1.hasDeletions(), index2.hasDeletions());
assertEquals("Only one index is optimized.", index1.isOptimized(), index2.isOptimized());
// check field names
Collection<String> fields1 = index1.getFieldNames(FieldOption.ALL);
Collection<String> fields2 = index1.getFieldNames(FieldOption.ALL);
assertEquals("IndexReaders have different numbers of fields.", fields1.size(), fields2.size());
Iterator<String> it1 = fields1.iterator();
Iterator<String> it2 = fields1.iterator();
while (it1.hasNext()) {
assertEquals("Different field names.", it1.next(), it2.next());
}
// check norms
it1 = fields1.iterator();
while (it1.hasNext()) {
String curField = it1.next();
byte[] norms1 = index1.norms(curField);
byte[] norms2 = index2.norms(curField);
if (norms1 != null && norms2 != null)
{
assertEquals(norms1.length, norms2.length);
for (int i = 0; i < norms1.length; i++) {
assertEquals("Norm different for doc " + i + " and field '" + curField + "'.", norms1[i], norms2[i]);
}
}
else
{
assertSame(norms1, norms2);
}
}
// check deletions
for (int i = 0; i < index1.maxDoc(); i++) {
assertEquals("Doc " + i + " only deleted in one index.", index1.isDeleted(i), index2.isDeleted(i));
}
// check stored fields
for (int i = 0; i < index1.maxDoc(); i++) {
if (!index1.isDeleted(i)) {
Document doc1 = index1.document(i);
Document doc2 = index2.document(i);
List<Fieldable> fieldable1 = doc1.getFields();
List<Fieldable> fieldable2 = doc2.getFields();
assertEquals("Different numbers of fields for doc " + i + ".", fieldable1.size(), fieldable2.size());
Iterator<Fieldable> itField1 = fieldable1.iterator();
Iterator<Fieldable> itField2 = fieldable2.iterator();
while (itField1.hasNext()) {
Field curField1 = (Field) itField1.next();
Field curField2 = (Field) itField2.next();
assertEquals("Different fields names for doc " + i + ".", curField1.name(), curField2.name());
assertEquals("Different field values for doc " + i + ".", curField1.stringValue(), curField2.stringValue());
}
}
}
// check dictionary and posting lists
TermEnum enum1 = index1.terms();
TermEnum enum2 = index2.terms();
TermPositions tp1 = index1.termPositions();
TermPositions tp2 = index2.termPositions();
while(enum1.next()) {
assertTrue(enum2.next());
assertEquals("Different term in dictionary.", enum1.term(), enum2.term());
tp1.seek(enum1.term());
tp2.seek(enum1.term());
while(tp1.next()) {
assertTrue(tp2.next());
assertEquals("Different doc id in postinglist of term " + enum1.term() + ".", tp1.doc(), tp2.doc());
assertEquals("Different term frequence in postinglist of term " + enum1.term() + ".", tp1.freq(), tp2.freq());
for (int i = 0; i < tp1.freq(); i++) {
assertEquals("Different positions in postinglist of term " + enum1.term() + ".", tp1.nextPosition(), tp2.nextPosition());
}
}
}
}
public void testGetIndexCommit() throws IOException {
Directory d = newDirectory();
// set up writer
IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT))
.setMaxBufferedDocs(2));
((LogMergePolicy) writer.getMergePolicy()).setMergeFactor(10);
for(int i=0;i<27;i++)
addDocumentWithFields(writer);
writer.close();
SegmentInfos sis = new SegmentInfos();
sis.read(d);
IndexReader r = IndexReader.open(d, false);
IndexCommit c = r.getIndexCommit();
assertEquals(sis.getCurrentSegmentFileName(), c.getSegmentsFileName());
assertTrue(c.equals(r.getIndexCommit()));
// Change the index
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(
OpenMode.APPEND).setMaxBufferedDocs(2));
((LogMergePolicy) writer.getMergePolicy()).setMergeFactor(10);
for(int i=0;i<7;i++)
addDocumentWithFields(writer);
writer.close();
IndexReader r2 = r.reopen();
assertFalse(c.equals(r2.getIndexCommit()));
assertFalse(r2.getIndexCommit().isOptimized());
r2.close();
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT))
.setOpenMode(OpenMode.APPEND));
writer.optimize();
writer.close();
r2 = r.reopen();
assertTrue(r2.getIndexCommit().isOptimized());
r.close();
r2.close();
d.close();
}
public void testReadOnly() throws Throwable {
Directory d = newDirectory();
IndexWriter writer = new IndexWriter(d, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT)));
addDocumentWithFields(writer);
writer.commit();
addDocumentWithFields(writer);
writer.close();
IndexReader r = IndexReader.open(d, true);
try {
r.deleteDocument(0);
fail();
} catch (UnsupportedOperationException uoe) {
// expected
}
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT))
.setOpenMode(OpenMode.APPEND));
((LogMergePolicy) writer.getMergePolicy()).setMergeFactor(10);
addDocumentWithFields(writer);
writer.close();
// Make sure reopen is still readonly:
IndexReader r2 = r.reopen();
r.close();
assertFalse(r == r2);
try {
r2.deleteDocument(0);
fail();
} catch (UnsupportedOperationException uoe) {
// expected
}
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT))
.setOpenMode(OpenMode.APPEND));
writer.optimize();
writer.close();
// Make sure reopen to a single segment is still readonly:
IndexReader r3 = r2.reopen();
assertFalse(r3 == r2);
r2.close();
assertFalse(r == r2);
try {
r3.deleteDocument(0);
fail();
} catch (UnsupportedOperationException uoe) {
// expected
}
// Make sure write lock isn't held
writer = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT,
new StandardAnalyzer(TEST_VERSION_CURRENT))
.setOpenMode(OpenMode.APPEND));
writer.close();
r3.close();
d.close();
}
// LUCENE-1474
public void testIndexReader() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT)));
writer.addDocument(createDocument("a"));
writer.addDocument(createDocument("b"));
writer.addDocument(createDocument("c"));
writer.close();
IndexReader reader = IndexReader.open(dir, false);
reader.deleteDocuments(new Term("id", "a"));
reader.flush();
reader.deleteDocuments(new Term("id", "b"));
reader.close();
IndexReader.open(dir,true).close();
dir.close();
}
// LUCENE-1647
public void testIndexReaderUnDeleteAll() throws Exception {
MockDirectoryWrapper dir = newDirectory();
dir.setPreventDoubleWrite(false);
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT)));
writer.addDocument(createDocument("a"));
writer.addDocument(createDocument("b"));
writer.addDocument(createDocument("c"));
writer.close();
IndexReader reader = IndexReader.open(dir, false);
reader.deleteDocuments(new Term("id", "a"));
reader.flush();
reader.deleteDocuments(new Term("id", "b"));
reader.undeleteAll();
reader.deleteDocuments(new Term("id", "b"));
reader.close();
IndexReader.open(dir,true).close();
dir.close();
}
private Document createDocument(String id) {
Document doc = new Document();
doc.add(newField("id", id, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
return doc;
}
// LUCENE-1468 -- make sure on attempting to open an
// IndexReader on a non-existent directory, you get a
// good exception
public void testNoDir() throws Throwable {
Directory dir = newFSDirectory(_TestUtil.getTempDir("doesnotexist"));
try {
IndexReader.open(dir, true);
fail("did not hit expected exception");
} catch (NoSuchDirectoryException nsde) {
// expected
}
dir.close();
}
// LUCENE-1509
public void testNoDupCommitFileNames() throws Throwable {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new StandardAnalyzer(TEST_VERSION_CURRENT))
.setMaxBufferedDocs(2));
writer.addDocument(createDocument("a"));
writer.addDocument(createDocument("a"));
writer.addDocument(createDocument("a"));
writer.close();
Collection<IndexCommit> commits = IndexReader.listCommits(dir);
for (final IndexCommit commit : commits) {
Collection<String> files = commit.getFileNames();
HashSet<String> seen = new HashSet<String>();
for (final String fileName : files) {
assertTrue("file " + fileName + " was duplicated", !seen.contains(fileName));
seen.add(fileName);
}
}
dir.close();
}
// LUCENE-1579: Ensure that on a cloned reader, segments
// reuse the doc values arrays in FieldCache
public void testFieldCacheReuseAfterClone() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
Document doc = new Document();
doc.add(newField("number", "17", Field.Store.NO, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
writer.close();
// Open reader
IndexReader r = SegmentReader.getOnlySegmentReader(dir);
final int[] ints = FieldCache.DEFAULT.getInts(r, "number");
assertEquals(1, ints.length);
assertEquals(17, ints[0]);
// Clone reader
IndexReader r2 = (IndexReader) r.clone();
r.close();
assertTrue(r2 != r);
final int[] ints2 = FieldCache.DEFAULT.getInts(r2, "number");
r2.close();
assertEquals(1, ints2.length);
assertEquals(17, ints2[0]);
assertTrue(ints == ints2);
dir.close();
}
// LUCENE-1579: Ensure that on a reopened reader, that any
// shared segments reuse the doc values arrays in
// FieldCache
public void testFieldCacheReuseAfterReopen() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
Document doc = new Document();
doc.add(newField("number", "17", Field.Store.NO, Field.Index.NOT_ANALYZED));
((LogMergePolicy) writer.getMergePolicy()).setMergeFactor(10);
writer.addDocument(doc);
writer.commit();
// Open reader1
IndexReader r = IndexReader.open(dir, false);
IndexReader r1 = SegmentReader.getOnlySegmentReader(r);
final int[] ints = FieldCache.DEFAULT.getInts(r1, "number");
assertEquals(1, ints.length);
assertEquals(17, ints[0]);
// Add new segment
writer.addDocument(doc);
writer.commit();
// Reopen reader1 --> reader2
IndexReader r2 = r.reopen();
r.close();
IndexReader sub0 = r2.getSequentialSubReaders()[0];
final int[] ints2 = FieldCache.DEFAULT.getInts(sub0, "number");
r2.close();
assertTrue(ints == ints2);
dir.close();
}
// LUCENE-1579: Make sure all SegmentReaders are new when
// reopen switches readOnly
public void testReopenChangeReadonly() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setMaxBufferedDocs(-1));
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(10);
Document doc = new Document();
doc.add(newField("number", "17", Field.Store.NO, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
writer.commit();
// Open reader1
IndexReader r = IndexReader.open(dir, false);
assertTrue(r instanceof DirectoryReader);
IndexReader r1 = SegmentReader.getOnlySegmentReader(r);
final int[] ints = FieldCache.DEFAULT.getInts(r1, "number");
assertEquals(1, ints.length);
assertEquals(17, ints[0]);
// Reopen to readonly w/ no chnages
IndexReader r3 = r.reopen(true);
assertTrue(r3 instanceof ReadOnlyDirectoryReader);
r3.close();
// Add new segment
writer.addDocument(doc);
writer.commit();
// Reopen reader1 --> reader2
IndexReader r2 = r.reopen(true);
r.close();
assertTrue(r2 instanceof ReadOnlyDirectoryReader);
IndexReader[] subs = r2.getSequentialSubReaders();
final int[] ints2 = FieldCache.DEFAULT.getInts(subs[0], "number");
r2.close();
assertTrue(subs[0] instanceof ReadOnlySegmentReader);
assertTrue(subs[1] instanceof ReadOnlySegmentReader);
assertTrue(ints == ints2);
dir.close();
}
// LUCENE-1586: getUniqueTermCount
public void testUniqueTermCount() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
Document doc = new Document();
doc.add(newField("field", "a b c d e f g h i j k l m n o p q r s t u v w x y z", Field.Store.NO, Field.Index.ANALYZED));
doc.add(newField("number", "0 1 2 3 4 5 6 7 8 9", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
writer.addDocument(doc);
writer.commit();
IndexReader r = IndexReader.open(dir, false);
IndexReader r1 = SegmentReader.getOnlySegmentReader(r);
assertEquals(36, r1.getUniqueTermCount());
writer.addDocument(doc);
writer.commit();
IndexReader r2 = r.reopen();
r.close();
try {
r2.getUniqueTermCount();
fail("expected exception");
} catch (UnsupportedOperationException uoe) {
// expected
}
IndexReader[] subs = r2.getSequentialSubReaders();
for(int i=0;i<subs.length;i++) {
assertEquals(36, subs[i].getUniqueTermCount());
}
r2.close();
writer.close();
dir.close();
}
// LUCENE-1609: don't load terms index
public void testNoTermsIndex() throws Throwable {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
Document doc = new Document();
doc.add(newField("field", "a b c d e f g h i j k l m n o p q r s t u v w x y z", Field.Store.NO, Field.Index.ANALYZED));
doc.add(newField("number", "0 1 2 3 4 5 6 7 8 9", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
writer.addDocument(doc);
writer.close();
IndexReader r = IndexReader.open(dir, null, true, -1);
try {
r.docFreq(new Term("field", "f"));
fail("did not hit expected exception");
} catch (IllegalStateException ise) {
// expected
}
assertFalse(((SegmentReader) r.getSequentialSubReaders()[0]).termsIndexLoaded());
assertEquals(-1, ((SegmentReader) r.getSequentialSubReaders()[0]).getTermInfosIndexDivisor());
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
((LogMergePolicy) writer.getMergePolicy()).setMergeFactor(10);
writer.addDocument(doc);
writer.close();
// LUCENE-1718: ensure re-open carries over no terms index:
IndexReader r2 = r.reopen();
r.close();
IndexReader[] subReaders = r2.getSequentialSubReaders();
assertEquals(2, subReaders.length);
for(int i=0;i<2;i++) {
assertFalse(((SegmentReader) subReaders[i]).termsIndexLoaded());
}
r2.close();
dir.close();
}
// LUCENE-2046
public void testPrepareCommitIsCurrent() throws Throwable {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
writer.commit();
Document doc = new Document();
writer.addDocument(doc);
IndexReader r = IndexReader.open(dir, true);
assertTrue(r.isCurrent());
writer.addDocument(doc);
writer.prepareCommit();
assertTrue(r.isCurrent());
IndexReader r2 = r.reopen();
assertTrue(r == r2);
writer.commit();
assertFalse(r.isCurrent());
writer.close();
r.close();
dir.close();
}
// LUCENE-2753
public void testListCommits() throws Exception {
Directory dir = newDirectory();
SnapshotDeletionPolicy sdp = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setIndexDeletionPolicy(sdp));
writer.addDocument(new Document());
writer.commit();
sdp.snapshot("c1");
writer.addDocument(new Document());
writer.commit();
sdp.snapshot("c2");
writer.addDocument(new Document());
writer.commit();
sdp.snapshot("c3");
writer.close();
long currentGen = 0;
for (IndexCommit ic : IndexReader.listCommits(dir)) {
assertTrue("currentGen=" + currentGen + " commitGen=" + ic.getGeneration(), currentGen < ic.getGeneration());
currentGen = ic.getGeneration();
}
dir.close();
}
// LUCENE-2812
public void testIndexExists() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
writer.addDocument(new Document());
writer.prepareCommit();
assertFalse(IndexReader.indexExists(dir));
writer.close();
assertTrue(IndexReader.indexExists(dir));
dir.close();
}
// LUCENE-2474
public void testReaderFinishedListener() throws Exception {
Directory dir = newDirectory();
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(3);
writer.setInfoStream(VERBOSE ? System.out : null);
writer.addDocument(new Document());
writer.commit();
writer.addDocument(new Document());
writer.commit();
final IndexReader reader = writer.getReader();
final int[] closeCount = new int[1];
final IndexReader.ReaderFinishedListener listener = new IndexReader.ReaderFinishedListener() {
public void finished(IndexReader reader) {
closeCount[0]++;
}
};
reader.addReaderFinishedListener(listener);
reader.close();
// Just the top reader
assertEquals(1, closeCount[0]);
writer.close();
// Now also the subs
assertEquals(3, closeCount[0]);
IndexReader reader2 = IndexReader.open(dir);
reader2.addReaderFinishedListener(listener);
closeCount[0] = 0;
reader2.close();
assertEquals(3, closeCount[0]);
dir.close();
}
}
| true | true | public void testDiskFull() throws IOException {
Term searchTerm = new Term("content", "aaa");
int START_COUNT = 157;
int END_COUNT = 144;
// First build up a starting index:
MockDirectoryWrapper startDir = newDirectory();
IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for(int i=0;i<157;i++) {
Document d = new Document();
d.add(newField("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
d.add(newField("content", "aaa " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(d);
}
writer.close();
long diskUsage = startDir.getRecomputedActualSizeInBytes();
long diskFree = diskUsage+100;
IOException err = null;
boolean done = false;
// Iterate w/ ever increasing free disk space:
while(!done) {
MockDirectoryWrapper dir = new MockDirectoryWrapper(random, new RAMDirectory(startDir));
// If IndexReader hits disk full, it can write to
// the same files again.
dir.setPreventDoubleWrite(false);
IndexReader reader = IndexReader.open(dir, false);
// For each disk size, first try to commit against
// dir that will hit random IOExceptions & disk
// full; after, give it infinite disk space & turn
// off random IOExceptions & retry w/ same reader:
boolean success = false;
for(int x=0;x<2;x++) {
double rate = 0.05;
double diskRatio = ((double) diskFree)/diskUsage;
long thisDiskFree;
String testName;
if (0 == x) {
thisDiskFree = diskFree;
if (diskRatio >= 2.0) {
rate /= 2;
}
if (diskRatio >= 4.0) {
rate /= 2;
}
if (diskRatio >= 6.0) {
rate = 0.0;
}
if (VERBOSE) {
System.out.println("\ncycle: " + diskFree + " bytes");
}
testName = "disk full during reader.close() @ " + thisDiskFree + " bytes";
} else {
thisDiskFree = 0;
rate = 0.0;
if (VERBOSE) {
System.out.println("\ncycle: same writer: unlimited disk space");
}
testName = "reader re-use after disk full";
}
dir.setMaxSizeInBytes(thisDiskFree);
dir.setRandomIOExceptionRate(rate);
try {
if (0 == x) {
int docId = 12;
for(int i=0;i<13;i++) {
reader.deleteDocument(docId);
reader.setNorm(docId, "contents", (float) 2.0);
docId += 12;
}
}
reader.close();
success = true;
if (0 == x) {
done = true;
}
} catch (IOException e) {
if (VERBOSE) {
System.out.println(" hit IOException: " + e);
e.printStackTrace(System.out);
}
err = e;
if (1 == x) {
e.printStackTrace();
fail(testName + " hit IOException after disk space was freed up");
}
}
// Finally, verify index is not corrupt, and, if
// we succeeded, we see all docs changed, and if
// we failed, we see either all docs or no docs
// changed (transactional semantics):
IndexReader newReader = null;
try {
newReader = IndexReader.open(dir, false);
} catch (IOException e) {
e.printStackTrace();
fail(testName + ":exception when creating IndexReader after disk full during close: " + e);
}
/*
int result = newReader.docFreq(searchTerm);
if (success) {
if (result != END_COUNT) {
fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + END_COUNT);
}
} else {
// On hitting exception we still may have added
// all docs:
if (result != START_COUNT && result != END_COUNT) {
err.printStackTrace();
fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT);
}
}
*/
IndexSearcher searcher = newSearcher(newReader);
ScoreDoc[] hits = null;
try {
hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
} catch (IOException e) {
e.printStackTrace();
fail(testName + ": exception when searching: " + e);
}
int result2 = hits.length;
if (success) {
if (result2 != END_COUNT) {
fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + END_COUNT);
}
} else {
// On hitting exception we still may have added
// all docs:
if (result2 != START_COUNT && result2 != END_COUNT) {
err.printStackTrace();
fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + START_COUNT);
}
}
searcher.close();
newReader.close();
if (result2 == END_COUNT) {
break;
}
}
dir.close();
// Try again with 10 more bytes of free space:
diskFree += 10;
}
startDir.close();
}
| public void testDiskFull() throws IOException {
Term searchTerm = new Term("content", "aaa");
int START_COUNT = 157;
int END_COUNT = 144;
// First build up a starting index:
MockDirectoryWrapper startDir = newDirectory();
IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)));
for(int i=0;i<157;i++) {
Document d = new Document();
d.add(newField("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED));
d.add(newField("content", "aaa " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(d);
}
writer.close();
long diskUsage = startDir.getRecomputedActualSizeInBytes();
long diskFree = diskUsage+100;
IOException err = null;
boolean done = false;
// Iterate w/ ever increasing free disk space:
while(!done) {
MockDirectoryWrapper dir = new MockDirectoryWrapper(random, new RAMDirectory(startDir));
// If IndexReader hits disk full, it can write to
// the same files again.
dir.setPreventDoubleWrite(false);
IndexReader reader = IndexReader.open(dir, false);
// For each disk size, first try to commit against
// dir that will hit random IOExceptions & disk
// full; after, give it infinite disk space & turn
// off random IOExceptions & retry w/ same reader:
boolean success = false;
for(int x=0;x<2;x++) {
double rate = 0.05;
double diskRatio = ((double) diskFree)/diskUsage;
long thisDiskFree;
String testName;
if (0 == x) {
thisDiskFree = diskFree;
if (diskRatio >= 2.0) {
rate /= 2;
}
if (diskRatio >= 4.0) {
rate /= 2;
}
if (diskRatio >= 6.0) {
rate = 0.0;
}
if (VERBOSE) {
System.out.println("\ncycle: " + diskFree + " bytes");
}
testName = "disk full during reader.close() @ " + thisDiskFree + " bytes";
} else {
thisDiskFree = 0;
rate = 0.0;
if (VERBOSE) {
System.out.println("\ncycle: same writer: unlimited disk space");
}
testName = "reader re-use after disk full";
}
dir.setMaxSizeInBytes(thisDiskFree);
dir.setRandomIOExceptionRate(rate);
try {
if (0 == x) {
int docId = 12;
for(int i=0;i<13;i++) {
reader.deleteDocument(docId);
reader.setNorm(docId, "content", (float) 2.0);
docId += 12;
}
}
reader.close();
success = true;
if (0 == x) {
done = true;
}
} catch (IOException e) {
if (VERBOSE) {
System.out.println(" hit IOException: " + e);
e.printStackTrace(System.out);
}
err = e;
if (1 == x) {
e.printStackTrace();
fail(testName + " hit IOException after disk space was freed up");
}
}
// Finally, verify index is not corrupt, and, if
// we succeeded, we see all docs changed, and if
// we failed, we see either all docs or no docs
// changed (transactional semantics):
IndexReader newReader = null;
try {
newReader = IndexReader.open(dir, false);
} catch (IOException e) {
e.printStackTrace();
fail(testName + ":exception when creating IndexReader after disk full during close: " + e);
}
/*
int result = newReader.docFreq(searchTerm);
if (success) {
if (result != END_COUNT) {
fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + END_COUNT);
}
} else {
// On hitting exception we still may have added
// all docs:
if (result != START_COUNT && result != END_COUNT) {
err.printStackTrace();
fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT);
}
}
*/
IndexSearcher searcher = newSearcher(newReader);
ScoreDoc[] hits = null;
try {
hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
} catch (IOException e) {
e.printStackTrace();
fail(testName + ": exception when searching: " + e);
}
int result2 = hits.length;
if (success) {
if (result2 != END_COUNT) {
fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + END_COUNT);
}
} else {
// On hitting exception we still may have added
// all docs:
if (result2 != START_COUNT && result2 != END_COUNT) {
err.printStackTrace();
fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + START_COUNT);
}
}
searcher.close();
newReader.close();
if (result2 == END_COUNT) {
break;
}
}
dir.close();
// Try again with 10 more bytes of free space:
diskFree += 10;
}
startDir.close();
}
|
diff --git a/web/src/main/java/org/alx/stripestemplate/stripes/ext/HibernateTxInterceptor.java b/web/src/main/java/org/alx/stripestemplate/stripes/ext/HibernateTxInterceptor.java
index 47f56b9..ed945da 100644
--- a/web/src/main/java/org/alx/stripestemplate/stripes/ext/HibernateTxInterceptor.java
+++ b/web/src/main/java/org/alx/stripestemplate/stripes/ext/HibernateTxInterceptor.java
@@ -1,73 +1,73 @@
package org.alx.stripestemplate.stripes.ext;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;
import org.alx.stripestemplate.persistence.HibernateStore;
import org.alx.stripestemplate.stripes.noext.MyInitListener;
import org.alx.stripestemplate.stripes.noext.MyInitListener;
import org.alx.stripestemplate.util.MLogger;
import org.alx.stripestemplate.stripes.noext.MyInitListener;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/**
* @author Alexis Boissonnat - alexis.boissonnat 'at' gmail.com
*/
@Intercepts({LifecycleStage.RequestInit , LifecycleStage.RequestComplete})
public class HibernateTxInterceptor implements net.sourceforge.stripes.controller.Interceptor {
private static final MLogger log = MLogger.getLogger(HibernateTxInterceptor.class);
private SessionFactory getSessionFactory(ExecutionContext context) {
HibernateStore store = (HibernateStore) context.getActionBeanContext().getServletContext().getAttribute(MyInitListener.CTX_STORE_KEY);
return store.getSessionFactory();
}
public Resolution intercept(ExecutionContext context) throws Exception {
LifecycleStage stage = context.getLifecycleStage();
if (stage==LifecycleStage.RequestInit) {
Transaction tx = getSessionFactory(context).getCurrentSession().beginTransaction();
log.debug("Started transaction : " + tx);
} else if (stage.equals(LifecycleStage.RequestComplete)) {
Transaction tx = getSessionFactory(context).getCurrentSession().getTransaction();
if (tx==null) {
log.debug("No transaction found, nothing to do.");
} else {
try {
log.debug("Commiting transaction " + tx);
tx.commit();
} catch(Exception e) {
- log.error("Commit error : $e", e);
+ log.error("Commit error : ", e);
tx.rollback();
throw e;
}
}
}
try {
return context.proceed();
} catch(Exception e) {
log.error("Exception while proceeding with context, rollbacking transaction if any, exception will be rethrown", e);
Session session = getSessionFactory(context).getCurrentSession();
if (session!=null) {
Transaction tx = session.getTransaction();
if (tx!=null) {
try {
tx.rollback();
} catch(Exception e2) {
log.error("Exception while rollbacking", e2);
}
}
}
// re-throw exception
throw e;
}
}
}
| true | true | public Resolution intercept(ExecutionContext context) throws Exception {
LifecycleStage stage = context.getLifecycleStage();
if (stage==LifecycleStage.RequestInit) {
Transaction tx = getSessionFactory(context).getCurrentSession().beginTransaction();
log.debug("Started transaction : " + tx);
} else if (stage.equals(LifecycleStage.RequestComplete)) {
Transaction tx = getSessionFactory(context).getCurrentSession().getTransaction();
if (tx==null) {
log.debug("No transaction found, nothing to do.");
} else {
try {
log.debug("Commiting transaction " + tx);
tx.commit();
} catch(Exception e) {
log.error("Commit error : $e", e);
tx.rollback();
throw e;
}
}
}
try {
return context.proceed();
} catch(Exception e) {
log.error("Exception while proceeding with context, rollbacking transaction if any, exception will be rethrown", e);
Session session = getSessionFactory(context).getCurrentSession();
if (session!=null) {
Transaction tx = session.getTransaction();
if (tx!=null) {
try {
tx.rollback();
} catch(Exception e2) {
log.error("Exception while rollbacking", e2);
}
}
}
// re-throw exception
throw e;
}
}
| public Resolution intercept(ExecutionContext context) throws Exception {
LifecycleStage stage = context.getLifecycleStage();
if (stage==LifecycleStage.RequestInit) {
Transaction tx = getSessionFactory(context).getCurrentSession().beginTransaction();
log.debug("Started transaction : " + tx);
} else if (stage.equals(LifecycleStage.RequestComplete)) {
Transaction tx = getSessionFactory(context).getCurrentSession().getTransaction();
if (tx==null) {
log.debug("No transaction found, nothing to do.");
} else {
try {
log.debug("Commiting transaction " + tx);
tx.commit();
} catch(Exception e) {
log.error("Commit error : ", e);
tx.rollback();
throw e;
}
}
}
try {
return context.proceed();
} catch(Exception e) {
log.error("Exception while proceeding with context, rollbacking transaction if any, exception will be rethrown", e);
Session session = getSessionFactory(context).getCurrentSession();
if (session!=null) {
Transaction tx = session.getTransaction();
if (tx!=null) {
try {
tx.rollback();
} catch(Exception e2) {
log.error("Exception while rollbacking", e2);
}
}
}
// re-throw exception
throw e;
}
}
|
diff --git a/NAKJava/src/de/nordakademie/nakjava/gamelogic/cards/zauberlabor/Weihnachtsmann.java b/NAKJava/src/de/nordakademie/nakjava/gamelogic/cards/zauberlabor/Weihnachtsmann.java
index 20cf82c..ac6aa66 100644
--- a/NAKJava/src/de/nordakademie/nakjava/gamelogic/cards/zauberlabor/Weihnachtsmann.java
+++ b/NAKJava/src/de/nordakademie/nakjava/gamelogic/cards/zauberlabor/Weihnachtsmann.java
@@ -1,48 +1,51 @@
package de.nordakademie.nakjava.gamelogic.cards.zauberlabor;
import java.util.Map;
import de.nordakademie.nakjava.gamelogic.cards.impl.AbstractCard;
import de.nordakademie.nakjava.gamelogic.cards.impl.ArtifactEffect;
import de.nordakademie.nakjava.gamelogic.cards.impl.Card;
import de.nordakademie.nakjava.gamelogic.cards.impl.CardLibrary;
import de.nordakademie.nakjava.gamelogic.cards.impl.Target;
import de.nordakademie.nakjava.gamelogic.shared.artifacts.ressources.Kristalle;
import de.nordakademie.nakjava.gamelogic.shared.artifacts.ressources.Monster;
import de.nordakademie.nakjava.gamelogic.shared.artifacts.ressources.Ziegel;
import de.nordakademie.nakjava.gamelogic.shared.cards.CardType;
import de.nordakademie.nakjava.gamelogic.shared.playerstate.CardSet;
import de.nordakademie.nakjava.gamelogic.shared.playerstate.PlayerState;
import de.nordakademie.nakjava.server.internal.model.InGameSpecificModel;
@Card(name = "Weihnachtsmann",
type = CardType.ZAUBERLABOR,
artifactEffects = { @ArtifactEffect(artifact = Ziegel.class,
count = 5,
target = Target.SELF),
@ArtifactEffect(artifact = Monster.class,
count = 5,
target = Target.SELF),
@ArtifactEffect(artifact = Kristalle.class,
count = 5,
target = Target.SELF) },
additionalDescription = "Zufällige Karte mit Kosten>14 vom Vorratsstapel oder Kartenfriedhof auf die Hand.")
public class Weihnachtsmann extends AbstractCard {
@Override
protected void performAction(Map<Target, PlayerState> states) {
super.performAction(states);
CardSet selfCards = ((InGameSpecificModel) states.get(Target.SELF)
.getStateSpecificModel()).getCards();
int passedCards = 0;
String drawnCard;
- while (passedCards < selfCards.getCardSetSize()) {
+ boolean cardFound = false;
+ while (!cardFound && passedCards < selfCards.getCardSetSize()) {
drawnCard = selfCards.drawCardFromDeck();
passedCards++;
if (CardLibrary.get().getCardForName(drawnCard).getTotalCosts() < 15) {
selfCards.discardCardFromHand(drawnCard);
+ } else {
+ cardFound = true;
}
}
}
}
| false | true | protected void performAction(Map<Target, PlayerState> states) {
super.performAction(states);
CardSet selfCards = ((InGameSpecificModel) states.get(Target.SELF)
.getStateSpecificModel()).getCards();
int passedCards = 0;
String drawnCard;
while (passedCards < selfCards.getCardSetSize()) {
drawnCard = selfCards.drawCardFromDeck();
passedCards++;
if (CardLibrary.get().getCardForName(drawnCard).getTotalCosts() < 15) {
selfCards.discardCardFromHand(drawnCard);
}
}
}
| protected void performAction(Map<Target, PlayerState> states) {
super.performAction(states);
CardSet selfCards = ((InGameSpecificModel) states.get(Target.SELF)
.getStateSpecificModel()).getCards();
int passedCards = 0;
String drawnCard;
boolean cardFound = false;
while (!cardFound && passedCards < selfCards.getCardSetSize()) {
drawnCard = selfCards.drawCardFromDeck();
passedCards++;
if (CardLibrary.get().getCardForName(drawnCard).getTotalCosts() < 15) {
selfCards.discardCardFromHand(drawnCard);
} else {
cardFound = true;
}
}
}
|
diff --git a/src/logicamente/drawer/SyntaxTreeDrawer.java b/src/logicamente/drawer/SyntaxTreeDrawer.java
index 31f710f..e9d7db6 100644
--- a/src/logicamente/drawer/SyntaxTreeDrawer.java
+++ b/src/logicamente/drawer/SyntaxTreeDrawer.java
@@ -1,487 +1,487 @@
package logicamente.drawer;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import logicamente.formulas.AtomicFormula;
import logicamente.formulas.CompositeFormula;
import logicamente.formulas.Formula;
import logicamente.parser.ParseResult;
import logicamente.parser.Parser;
public class SyntaxTreeDrawer extends JFrame implements ActionListener {
private static final long serialVersionUID = 4393288660576735767L;
private int width;
private int height;
private Parser parser;
private Formula formula;
private DrawingGrid grid;
private Map<String, String> connectiveSymbolsMap;
private JPanel drawingPanel;
private JPanel topPanel;
private JPanel infoPanel;
private JLabel errorPanel;
private JPanel formulaInfoPanel;
private JTextField complexityTextField;
private JTextField heightTextField;
private JTextField negativesTextField;
private javax.swing.JLabel inputFormulaLabel;
private javax.swing.JTextField inputFormulaTextField;
private javax.swing.JButton btnAnd;
private javax.swing.JButton btnImplies;
private javax.swing.JButton btnNot;
private javax.swing.JButton btnOr;
private boolean showGridLines = false;
public static void main(String[] args) {
SyntaxTreeDrawer std = new SyntaxTreeDrawer();
// System.out.println(args.length);
if (args.length >= 1) {
initFromCommandLine(args, std);
}
}
private static void initFromCommandLine(String[] args, SyntaxTreeDrawer std) {
String formula;
if (args.length == 1) {
formula = args[0];
std = new SyntaxTreeDrawer();
std.setFormula(formula);
} else {
showCommandLineComments();
}
}
private static void showCommandLineComments() {
System.out
.println("Usage: java -jar logicamente-utfpr.jar '<formula>'");
System.out.println();
System.out.println("Some examples:");
System.out.println("java -jar logicamente-utfpr.jar 'A'");
System.out.println("java -jar logicamente-utfpr.jar 'A->B'");
System.out.println("java -jar logicamente-utfpr.jar 'A->B->C'");
System.out
.println("java -jar logicamente-utfpr.jar 'A->B->C->D->E->F->G'");
System.out
.println("java -jar logicamente-utfpr.jar '(!A->B->!!C)->D->E->F->G'");
System.out.println();
System.out
.println("More information at http://github.com/adolfont/Logicamente-UTFPR/");
System.exit(0);
}
public SyntaxTreeDrawer() {
parser = new Parser();
this.width = 700;
this.height = 500;
this.setBounds(300, 100, width, height);
setTitle("Logicamente-UTFPR - Syntax Tree Drawer");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// The symbols came from
// http://en.wikipedia.org/wiki/List_of_logic_symbols
connectiveSymbolsMap = new HashMap<String, String>();
connectiveSymbolsMap.put(Formula.NOT, "¬");
connectiveSymbolsMap.put(Formula.AND, "∧");
connectiveSymbolsMap.put(Formula.OR, "∨");
connectiveSymbolsMap.put(Formula.IMPLIES, "→");
drawScreen();
setVisible(true);
}
private void btnClick(String st) {
inputFormulaTextField.setText(inputFormulaTextField.getText() + st);
inputFormulaTextField.grabFocus();
}
private void drawScreen() {
if (drawingPanel == null) {
drawingPanel = new JPanel();
}
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
topPanel = new JPanel();
includeFormulaInputArea();
addConnectiveButtons();
setTopAndDrawingPanelProperties();
includeFormulaInfoPanel();
includeTopLevelInfoPanel();
JPanel topLevelPanel = createComplexLayout();
getContentPane().add(topLevelPanel, BorderLayout.CENTER);
getContentPane().add(infoPanel, BorderLayout.SOUTH);
}
private void setTopAndDrawingPanelProperties() {
topPanel.setLayout(new GridLayout(2, 1));
topPanel.add(inputFormulaLabel);
topPanel.add(inputFormulaTextField);
topPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
drawingPanel.setBounds(0, 0, 500, 500);
}
private void includeTopLevelInfoPanel() {
infoPanel = new JPanel();
errorPanel = new JLabel("", JLabel.CENTER);
errorPanel.setFont(infoPanel.getFont().deriveFont((float) 30.0));
infoPanel.setLayout(new GridLayout(2, 1));
infoPanel.add(errorPanel);
infoPanel.add(formulaInfoPanel);
}
private JPanel createComplexLayout() {
GroupLayout topPanelLayout = new GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(topPanelLayout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
topPanelLayout.createSequentialGroup().addComponent(
inputFormulaLabel)
.addContainerGap(551, Short.MAX_VALUE)).addComponent(
inputFormulaTextField, GroupLayout.DEFAULT_SIZE, 632,
Short.MAX_VALUE).addGroup(
topPanelLayout.createSequentialGroup().addGap(191, 191, 191)
.addComponent(btnImplies, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addPreferredGap(
ComponentPlacement.RELATED).addComponent(
btnAnd, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addPreferredGap(
ComponentPlacement.RELATED).addComponent(btnOr,
GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNot, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addContainerGap(203,
Short.MAX_VALUE)));
topPanelLayout.setVerticalGroup(topPanelLayout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
topPanelLayout.createSequentialGroup().addComponent(
inputFormulaLabel).addPreferredGap(
ComponentPlacement.RELATED).addComponent(
inputFormulaTextField, GroupLayout.PREFERRED_SIZE, 42,
GroupLayout.PREFERRED_SIZE).addPreferredGap(
ComponentPlacement.RELATED).addGroup(
topPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNot,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnOr,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnAnd,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnImplies,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE))
.addContainerGap(GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
- drawingPanel.setBorder(BorderFactory
- .createLineBorder(new java.awt.Color(0, 0, 0)));
+// drawingPanel.setBorder(BorderFactory
+// .createLineBorder(new java.awt.Color(0, 0, 0)));
GroupLayout drawingPanelLayout = new javax.swing.GroupLayout(
drawingPanel);
drawingPanel.setLayout(drawingPanelLayout);
JPanel topLevelPanel = new JPanel();
GroupLayout layout = new GroupLayout(topLevelPanel);
topLevelPanel.setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(
GroupLayout.Alignment.LEADING).addComponent(topPanel,
GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE).addComponent(drawingPanel,
GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup().addComponent(topPanel,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED).addComponent(
drawingPanel, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
return topLevelPanel;
}
private void addConnectiveButtons() {
btnAnd = new JButton();
btnOr = new JButton();
btnNot = new JButton();
btnImplies = new JButton();
btnImplies.setToolTipText("Implies");
btnAnd.setToolTipText("And");
btnOr.setToolTipText("Or");
btnNot.setToolTipText("Not");
// btnAnd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btnAnd.setText(connectiveSymbolsMap.get(Formula.AND));
btnAnd.setAlignmentY(0.0F);
btnAnd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btnAnd.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
btnClick(Formula.AND);
}
});
// btnOr.setFont(new java.awt.Font("Tahoma", 1, 11));
btnOr.setText(connectiveSymbolsMap.get(Formula.OR));
btnOr.setAlignmentY(0.0F);
btnOr.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btnOr.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
btnClick(Formula.OR);
}
});
// btnNot.setFont(new java.awt.Font("Tahoma", 1, 11));
btnNot.setText(connectiveSymbolsMap.get(Formula.NOT));
btnNot.setAlignmentY(0.0F);
btnNot.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btnNot.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
btnClick(Formula.NOT);
}
});
// btnImplies.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btnImplies.setText(connectiveSymbolsMap.get(Formula.IMPLIES));
btnImplies.setAlignmentY(0.0F);
btnImplies.setBorder(javax.swing.BorderFactory.createEtchedBorder());
btnImplies.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
btnClick(Formula.IMPLIES);
}
});
}
private void includeFormulaInputArea() {
inputFormulaLabel = new JLabel();
// inputFormulaLabel.setFont(inputFormulaLabel.getFont().deriveFont((float)
// 30.0));
inputFormulaLabel.setFont(new java.awt.Font("Tahoma", 1, 18));
inputFormulaLabel.setText("Fórmula: ");
inputFormulaTextField = new JTextField(30);
// inputFormulaTextField.setFont(inputFormulaTextField.getFont().deriveFont((float)
// 30.0));
inputFormulaTextField.setFont(new java.awt.Font("Verdana", 1, 24));
inputFormulaTextField.addActionListener(this);
inputFormulaTextField.setText("");
inputFormulaTextField
.setToolTipText("Press Enter key to generate a tree!");
}
private void includeFormulaInfoPanel() {
formulaInfoPanel = new JPanel();
formulaInfoPanel.setLayout(new GridLayout(1, 6));
JLabel negativesLabel = new JLabel("Negações: ", JLabel.CENTER);
negativesTextField = new JTextField(4);
negativesTextField.setEditable(false);
JLabel heightLabel = new JLabel("Altura: ", JLabel.CENTER);
heightTextField = new JTextField(4);
heightTextField.setEditable(false);
JLabel complexityLabel = new JLabel("Complexidade: ", JLabel.CENTER);
complexityTextField = new JTextField(4);
complexityTextField.setEditable(false);
formulaInfoPanel.add(negativesLabel);
formulaInfoPanel.add(negativesTextField);
formulaInfoPanel.add(heightLabel);
formulaInfoPanel.add(heightTextField);
formulaInfoPanel.add(complexityLabel);
formulaInfoPanel.add(complexityTextField);
}
public void setFormula(String string) {
ParseResult result = parser.parse(string);
// System.out.println(result.parseCorrect());
if (result.parseCorrect()) {
formula = result.getFormula();
// System.out.println(formula);
errorPanel.setText("");
} else {
formula = null;
if (grid != null)
grid.clear();
errorPanel.setText("Syntax error");
}
}
private void showInfoValues() {
if (formula != null) {
complexityTextField.setText("" + formula.getComplexity());
heightTextField.setText("" + formula.getHeight());
negativesTextField.setText("" + formula.getNegationDegree());
} else {
complexityTextField.setText("");
heightTextField.setText("");
negativesTextField.setText("");
}
}
public void paint(Graphics g) {
if (formula != null) {
paintSyntaxTree();
} else {
drawingPanel.repaint();
}
showInfoValues();
topPanel.repaint();
infoPanel.repaint();
errorPanel.repaint();
formulaInfoPanel.repaint();
}
public void calculatePositionOfTreeNodes() {
grid = new DrawingGrid(drawingPanel.getGraphics());
drawingPanel.getGraphics()
.clearRect(0, 0, drawingPanel.getBounds().width,
drawingPanel.getBounds().height);
grid.setBounds(drawingPanel.getBounds().width,
drawingPanel.getBounds().height);
grid.setNodeDiameter(50);
grid.setGrid(formula.getComplexity() - formula.getNegationDegree(),
formula.getHeight() + 1);
if (showGridLines)
grid.drawGridLines();
Interval xInterval = new Interval(1, formula.getComplexity()
- formula.getNegationDegree());
drawSyntaxTree(null, formula, xInterval, 1);
}
private void paintSyntaxTree() {
calculatePositionOfTreeNodes();
grid.drawTree();
}
private void drawSyntaxTree(GridNode parent, Formula formula,
Interval xInterval, int y) {
int x = xInterval.getXLeft() + getLeftSize(formula);
GridNode currentNode = new GridNode(x, y, getCurrentSymbol(formula));
currentNode.setParent(parent);
grid.add(currentNode);
drawSyntaxTree_leftSubformula(currentNode, formula, xInterval, x, y);
drawSyntaxTree_rightSubformula(currentNode, formula, xInterval, x, y);
}
private void drawSyntaxTree_leftSubformula(GridNode parentNode,
Formula formula, Interval interval, int x, int y) {
// poe na esquerda
if (formula instanceof CompositeFormula) {
CompositeFormula cf = (CompositeFormula) formula;
String connective = cf.getConnective();
if (connective == Formula.NOT) {
// xLeft = o mesmo
// xRight= o mesmo
} else {
// xLeft = o mesmo
// xRight = x onde foi colocado o conectivo - 1
interval.setXRight(x - 1);
}
drawSyntaxTree(parentNode, cf.getLeftFormula(), interval, y + 1);
} else {
// nao faz nada. Já fez o que tinha de fazer antes
}
}
private void drawSyntaxTree_rightSubformula(GridNode parentNode,
Formula formula, Interval interval, int x, int y) {
// poe na direita
if (formula instanceof CompositeFormula) {
CompositeFormula cf = (CompositeFormula) formula;
String connective = cf.getConnective();
if (connective == Formula.NOT) {
// ja fez o que tinha de fazer
} else {
// xLeft = x onde foi colocado o conectivo + 1
interval.setXLeft(x + 1);
// xRight = o mesmo
drawSyntaxTree(parentNode, cf.getRightFormula(), interval,
y + 1);
}
} else {
// nao faz nada. Já fez o que tinha de fazer antes
}
}
private String getCurrentSymbol(Formula formula) {
if (formula instanceof AtomicFormula) {
return formula.toString();
} else {
return getConnectiveSymbol(((CompositeFormula) formula)
.getConnective());
}
}
private String getConnectiveSymbol(String connective) {
return connectiveSymbolsMap.get(connective);
}
public static int getLeftSize(Formula f) {
if (f instanceof AtomicFormula) {
return 0;
} else {
CompositeFormula cf = (CompositeFormula) f;
if (cf.getConnective() == Formula.NOT) {
return getLeftSize(cf.getLeftFormula());
}
return cf.getLeftFormula().getComplexity()
- cf.getLeftFormula().getNegationDegree();
}
}
public List<GridNode> getTreeNodes() {
return grid.getNodes();
}
@Override
public void actionPerformed(ActionEvent e) {
setFormula(e.getActionCommand());
repaint();
}
}
| true | true | private JPanel createComplexLayout() {
GroupLayout topPanelLayout = new GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(topPanelLayout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
topPanelLayout.createSequentialGroup().addComponent(
inputFormulaLabel)
.addContainerGap(551, Short.MAX_VALUE)).addComponent(
inputFormulaTextField, GroupLayout.DEFAULT_SIZE, 632,
Short.MAX_VALUE).addGroup(
topPanelLayout.createSequentialGroup().addGap(191, 191, 191)
.addComponent(btnImplies, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addPreferredGap(
ComponentPlacement.RELATED).addComponent(
btnAnd, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addPreferredGap(
ComponentPlacement.RELATED).addComponent(btnOr,
GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNot, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addContainerGap(203,
Short.MAX_VALUE)));
topPanelLayout.setVerticalGroup(topPanelLayout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
topPanelLayout.createSequentialGroup().addComponent(
inputFormulaLabel).addPreferredGap(
ComponentPlacement.RELATED).addComponent(
inputFormulaTextField, GroupLayout.PREFERRED_SIZE, 42,
GroupLayout.PREFERRED_SIZE).addPreferredGap(
ComponentPlacement.RELATED).addGroup(
topPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNot,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnOr,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnAnd,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnImplies,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE))
.addContainerGap(GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
drawingPanel.setBorder(BorderFactory
.createLineBorder(new java.awt.Color(0, 0, 0)));
GroupLayout drawingPanelLayout = new javax.swing.GroupLayout(
drawingPanel);
drawingPanel.setLayout(drawingPanelLayout);
JPanel topLevelPanel = new JPanel();
GroupLayout layout = new GroupLayout(topLevelPanel);
topLevelPanel.setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(
GroupLayout.Alignment.LEADING).addComponent(topPanel,
GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE).addComponent(drawingPanel,
GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup().addComponent(topPanel,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED).addComponent(
drawingPanel, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
return topLevelPanel;
}
| private JPanel createComplexLayout() {
GroupLayout topPanelLayout = new GroupLayout(topPanel);
topPanel.setLayout(topPanelLayout);
topPanelLayout.setHorizontalGroup(topPanelLayout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
topPanelLayout.createSequentialGroup().addComponent(
inputFormulaLabel)
.addContainerGap(551, Short.MAX_VALUE)).addComponent(
inputFormulaTextField, GroupLayout.DEFAULT_SIZE, 632,
Short.MAX_VALUE).addGroup(
topPanelLayout.createSequentialGroup().addGap(191, 191, 191)
.addComponent(btnImplies, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addPreferredGap(
ComponentPlacement.RELATED).addComponent(
btnAnd, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addPreferredGap(
ComponentPlacement.RELATED).addComponent(btnOr,
GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNot, GroupLayout.DEFAULT_SIZE, 54,
Short.MAX_VALUE).addContainerGap(203,
Short.MAX_VALUE)));
topPanelLayout.setVerticalGroup(topPanelLayout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
topPanelLayout.createSequentialGroup().addComponent(
inputFormulaLabel).addPreferredGap(
ComponentPlacement.RELATED).addComponent(
inputFormulaTextField, GroupLayout.PREFERRED_SIZE, 42,
GroupLayout.PREFERRED_SIZE).addPreferredGap(
ComponentPlacement.RELATED).addGroup(
topPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNot,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnOr,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnAnd,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE)
.addComponent(btnImplies,
GroupLayout.PREFERRED_SIZE, 35,
GroupLayout.PREFERRED_SIZE))
.addContainerGap(GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
// drawingPanel.setBorder(BorderFactory
// .createLineBorder(new java.awt.Color(0, 0, 0)));
GroupLayout drawingPanelLayout = new javax.swing.GroupLayout(
drawingPanel);
drawingPanel.setLayout(drawingPanelLayout);
JPanel topLevelPanel = new JPanel();
GroupLayout layout = new GroupLayout(topLevelPanel);
topLevelPanel.setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(
GroupLayout.Alignment.LEADING).addComponent(topPanel,
GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE).addComponent(drawingPanel,
GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(
GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup().addComponent(topPanel,
GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED).addComponent(
drawingPanel, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
return topLevelPanel;
}
|
diff --git a/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/InquiryServiceImpl.java b/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/InquiryServiceImpl.java
index a552167bd..79235351a 100644
--- a/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/InquiryServiceImpl.java
+++ b/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/InquiryServiceImpl.java
@@ -1,225 +1,227 @@
/*
* Copyright 2001-2009 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.juddi.portlets.server.service;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.juddi.ClassUtil;
import org.apache.juddi.portlets.client.model.Business;
import org.apache.juddi.portlets.client.model.Service;
import org.apache.juddi.portlets.client.model.ServiceBinding;
import org.apache.juddi.portlets.client.service.InquiryResponse;
import org.apache.juddi.portlets.client.service.InquiryService;
import org.apache.juddi.v3.client.config.UDDIClerkManager;
import org.apache.juddi.v3.client.config.UDDIClientContainer;
import org.apache.juddi.portlets.client.service.SearchResponse;
import org.apache.juddi.v3.client.i18n.EntityForLang;
import org.apache.juddi.v3.client.transport.Transport;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.Loader;
import org.uddi.api_v3.BindingTemplate;
import org.uddi.api_v3.BusinessDetail;
import org.uddi.api_v3.BusinessEntity;
import org.uddi.api_v3.BusinessService;
import org.uddi.api_v3.GetBusinessDetail;
import org.uddi.api_v3.GetServiceDetail;
import org.uddi.api_v3.GetTModelDetail;
import org.uddi.api_v3.ServiceDetail;
import org.uddi.api_v3.TModel;
import org.uddi.api_v3.TModelDetail;
import org.uddi.v3_service.UDDIInquiryPortType;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
*
* @author <a href="mailto:[email protected]">Kurt T Stam</a>
*
*/
public class InquiryServiceImpl extends RemoteServiceServlet implements InquiryService {
private static final long serialVersionUID = 8509627428299232161L;
private Logger logger = Logger.getLogger(this.getClass());
private Transport transport = null;
public InquiryServiceImpl() {
super();
}
private Transport getTransport()
throws ConfigurationException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
if (transport==null) {
UDDIClerkManager manager = UDDIClientContainer.getUDDIClerkManager(Constants.MANAGER_NAME);
String clazz = manager.getClientConfig().getUDDINode(Constants.NODE_NAME).getProxyTransport();
Class<?> transportClass = ClassUtil.forName(clazz, Transport.class);
transport = (Transport) transportClass.getConstructor(String.class).newInstance(Constants.NODE_NAME);
}
return transport;
}
public SearchResponse queryJUDDI(String query) {
SearchResponse response = new SearchResponse();
try {
UDDIInquiryPortType inquiryService = getTransport().getUDDIInquiryService();
org.apache.juddi.v3.client.transport.wrapper.UDDIInquiryService uis =
new org.apache.juddi.v3.client.transport.wrapper.UDDIInquiryService();
String reply = uis.inquire(inquiryService, query);
response.setMessage(reply);
response.setSuccess(true);
} catch (Exception e) {
logger.error("Could not obtain token. " + e.getMessage(), e);
response.setSuccess(false);
response.setMessage(e.getMessage());
response.setErrorCode("102");
} catch (Throwable t) {
logger.error("Could not obtain token. " + t.getMessage(), t);
response.setSuccess(false);
response.setMessage(t.getMessage());
response.setErrorCode("102");
}
return response;
}
public InquiryResponse getTModelDetail(String authToken, String tModelKey)
{
//HttpServletRequest request = this.getThreadLocalRequest();
//HttpSession session = request.getSession();
GetTModelDetail getTModelDetail = new GetTModelDetail();
getTModelDetail.setAuthInfo(authToken);
getTModelDetail.getTModelKey().add(tModelKey);
InquiryResponse response = new InquiryResponse();
logger.debug("TModelDetail " + getTModelDetail + " sending tmodelDetail request..");
Map<String,String> tmodelDetailMap = new HashMap<String,String>();
try {
UDDIInquiryPortType inquiryService = getTransport().getUDDIInquiryService();
TModelDetail tmodelDetail = inquiryService.getTModelDetail(getTModelDetail);
//demo code fix up what to return for real.
for (TModel tmodel : tmodelDetail.getTModel()) {
tmodelDetailMap.put("name",tmodel.getName().getValue());
}
response.setSuccess(true);
} catch (Exception e) {
logger.error("Could not obtain token. " + e.getMessage(), e);
response.setSuccess(false);
response.setMessage(e.getMessage());
response.setErrorCode("102");
} catch (Throwable t) {
logger.error("Could not obtain token. " + t.getMessage(), t);
response.setSuccess(false);
response.setMessage(t.getMessage());
response.setErrorCode("102");
}
return response;
}
public InquiryResponse getBusinessDetail(String authToken, String businessKey)
{
HttpServletRequest request = this.getThreadLocalRequest();
String lang = request.getLocale().getLanguage();
GetBusinessDetail getBusinessDetail = new GetBusinessDetail();
getBusinessDetail.setAuthInfo(authToken);
getBusinessDetail.getBusinessKey().add(businessKey);
InquiryResponse response = new InquiryResponse();
logger.debug("BusinessDetail " + getBusinessDetail + " sending businessDetail request..");
try {
UDDIInquiryPortType inquiryService = getTransport().getUDDIInquiryService();
BusinessDetail businessDetail = inquiryService.getBusinessDetail(getBusinessDetail);
for (BusinessEntity businessEntity : businessDetail.getBusinessEntity()) {
Business business = new Business(
businessEntity.getBusinessKey(),
EntityForLang.getName(businessEntity.getName(),lang).getValue(),
EntityForLang.getDescription(businessEntity.getDescription(),lang).getValue());
- for (BusinessService businessService : businessEntity.getBusinessServices().getBusinessService()) {
- Service service = new Service(
- businessService.getServiceKey(),
- EntityForLang.getName(businessService.getName(),lang).getValue(),
- EntityForLang.getDescription(businessService.getDescription(),lang).getValue());
- business.getServices().add(service);
+ if (businessEntity.getBusinessServices()!=null) {
+ for (BusinessService businessService : businessEntity.getBusinessServices().getBusinessService()) {
+ Service service = new Service(
+ businessService.getServiceKey(),
+ EntityForLang.getName(businessService.getName(),lang).getValue(),
+ EntityForLang.getDescription(businessService.getDescription(),lang).getValue());
+ business.getServices().add(service);
+ }
}
//for (Contact contact : businessEntity.getContacts().getContact()) {
//contact.get
//}
response.setBusiness(business);
}
response.setSuccess(true);
} catch (Exception e) {
logger.error("Could not obtain token. " + e.getMessage(), e);
response.setSuccess(false);
response.setMessage(e.getMessage());
response.setErrorCode("102");
} catch (Throwable t) {
logger.error("Could not obtain token. " + t.getMessage(), t);
response.setSuccess(false);
response.setMessage(t.getMessage());
response.setErrorCode("102");
}
return response;
}
public InquiryResponse getServiceDetail(String authToken, String serviceKey)
{
HttpServletRequest request = this.getThreadLocalRequest();
String lang = request.getLocale().getLanguage();
GetServiceDetail getServiceDetail = new GetServiceDetail();
getServiceDetail.setAuthInfo(authToken);
getServiceDetail.getServiceKey().add(serviceKey);
InquiryResponse response = new InquiryResponse();
logger.debug("ServiceDetail " + getServiceDetail + " sending serviceDetail request..");
try {
UDDIInquiryPortType inquiryService = getTransport().getUDDIInquiryService();
ServiceDetail serviceDetail = inquiryService.getServiceDetail(getServiceDetail);
for (BusinessService businessService : serviceDetail.getBusinessService()) {
Service service = new Service(
businessService.getServiceKey(),
EntityForLang.getName(businessService.getName(),lang).getValue(),
EntityForLang.getDescription(businessService.getDescription(),lang).getValue());
for (BindingTemplate bindingTemplate : businessService.getBindingTemplates().getBindingTemplate()) {
ServiceBinding serviceBinding = new ServiceBinding(
bindingTemplate.getBindingKey(),
bindingTemplate.getAccessPoint().getValue(),
EntityForLang.getDescription(bindingTemplate.getDescription(),lang).getValue(),
bindingTemplate.getAccessPoint().getUseType());
service.getServiceBindings().add(serviceBinding);
}
response.setService(service);
}
response.setSuccess(true);
} catch (Exception e) {
logger.error("Could not obtain token. " + e.getMessage(), e);
response.setSuccess(false);
response.setMessage(e.getMessage());
response.setErrorCode("102");
} catch (Throwable t) {
logger.error("Could not obtain token. " + t.getMessage(), t);
response.setSuccess(false);
response.setMessage(t.getMessage());
response.setErrorCode("102");
}
return response;
}
}
| true | true | public InquiryResponse getBusinessDetail(String authToken, String businessKey)
{
HttpServletRequest request = this.getThreadLocalRequest();
String lang = request.getLocale().getLanguage();
GetBusinessDetail getBusinessDetail = new GetBusinessDetail();
getBusinessDetail.setAuthInfo(authToken);
getBusinessDetail.getBusinessKey().add(businessKey);
InquiryResponse response = new InquiryResponse();
logger.debug("BusinessDetail " + getBusinessDetail + " sending businessDetail request..");
try {
UDDIInquiryPortType inquiryService = getTransport().getUDDIInquiryService();
BusinessDetail businessDetail = inquiryService.getBusinessDetail(getBusinessDetail);
for (BusinessEntity businessEntity : businessDetail.getBusinessEntity()) {
Business business = new Business(
businessEntity.getBusinessKey(),
EntityForLang.getName(businessEntity.getName(),lang).getValue(),
EntityForLang.getDescription(businessEntity.getDescription(),lang).getValue());
for (BusinessService businessService : businessEntity.getBusinessServices().getBusinessService()) {
Service service = new Service(
businessService.getServiceKey(),
EntityForLang.getName(businessService.getName(),lang).getValue(),
EntityForLang.getDescription(businessService.getDescription(),lang).getValue());
business.getServices().add(service);
}
//for (Contact contact : businessEntity.getContacts().getContact()) {
//contact.get
//}
response.setBusiness(business);
}
response.setSuccess(true);
} catch (Exception e) {
logger.error("Could not obtain token. " + e.getMessage(), e);
response.setSuccess(false);
response.setMessage(e.getMessage());
response.setErrorCode("102");
} catch (Throwable t) {
logger.error("Could not obtain token. " + t.getMessage(), t);
response.setSuccess(false);
response.setMessage(t.getMessage());
response.setErrorCode("102");
}
return response;
}
| public InquiryResponse getBusinessDetail(String authToken, String businessKey)
{
HttpServletRequest request = this.getThreadLocalRequest();
String lang = request.getLocale().getLanguage();
GetBusinessDetail getBusinessDetail = new GetBusinessDetail();
getBusinessDetail.setAuthInfo(authToken);
getBusinessDetail.getBusinessKey().add(businessKey);
InquiryResponse response = new InquiryResponse();
logger.debug("BusinessDetail " + getBusinessDetail + " sending businessDetail request..");
try {
UDDIInquiryPortType inquiryService = getTransport().getUDDIInquiryService();
BusinessDetail businessDetail = inquiryService.getBusinessDetail(getBusinessDetail);
for (BusinessEntity businessEntity : businessDetail.getBusinessEntity()) {
Business business = new Business(
businessEntity.getBusinessKey(),
EntityForLang.getName(businessEntity.getName(),lang).getValue(),
EntityForLang.getDescription(businessEntity.getDescription(),lang).getValue());
if (businessEntity.getBusinessServices()!=null) {
for (BusinessService businessService : businessEntity.getBusinessServices().getBusinessService()) {
Service service = new Service(
businessService.getServiceKey(),
EntityForLang.getName(businessService.getName(),lang).getValue(),
EntityForLang.getDescription(businessService.getDescription(),lang).getValue());
business.getServices().add(service);
}
}
//for (Contact contact : businessEntity.getContacts().getContact()) {
//contact.get
//}
response.setBusiness(business);
}
response.setSuccess(true);
} catch (Exception e) {
logger.error("Could not obtain token. " + e.getMessage(), e);
response.setSuccess(false);
response.setMessage(e.getMessage());
response.setErrorCode("102");
} catch (Throwable t) {
logger.error("Could not obtain token. " + t.getMessage(), t);
response.setSuccess(false);
response.setMessage(t.getMessage());
response.setErrorCode("102");
}
return response;
}
|
diff --git a/src/backend/Backend.java b/src/backend/Backend.java
index dd25b7d..be0c7c7 100644
--- a/src/backend/Backend.java
+++ b/src/backend/Backend.java
@@ -1,58 +1,58 @@
package backend;
import intermediate.IntermediateCode;
import intermediate.SymbolTable;
import intermediate.SymbolTableEntry;
import intermediate.SymbolTableStack;
import java.io.IOException;
import java.util.ArrayList;
public class Backend {
public void process(ArrayList<IntermediateCode> intermediateCodes,
SymbolTableStack symbolTableStack) throws IOException
{
System.out.println("\n----------Printing Parse Tree---------\n");
for(IntermediateCode iCode : intermediateCodes) {
printParseTree(iCode);
System.out.println();
}
System.out.println("\n----------Printing Symbol Table---------\n");
printSymbolTableStack(symbolTableStack);
}
public void printParseTree(IntermediateCode intermediateCode) {
if (intermediateCode == null) {
return;
}
if (intermediateCode.getText() != null) {
if (intermediateCode.getText().compareTo("'") == 0) {
System.out.print(intermediateCode.getText());
}
else {
System.out.print(intermediateCode.getText() + ' ');
}
}
else {
System.out.print('(');
}
printParseTree(intermediateCode.getCar());
printParseTree(intermediateCode.getCdr());
- if (intermediateCode.getCar() == null && intermediateCode.getCdr()==null) {
+ if (intermediateCode.getCdr() == null) {
System.out.println(')');
}
}
public void printSymbolTableStack(SymbolTableStack symbolTableStack) {
for (SymbolTable table : symbolTableStack) {
for (SymbolTableEntry entry : table.values()) {
System.out.println(entry);
}
}
}
}
| true | true | public void printParseTree(IntermediateCode intermediateCode) {
if (intermediateCode == null) {
return;
}
if (intermediateCode.getText() != null) {
if (intermediateCode.getText().compareTo("'") == 0) {
System.out.print(intermediateCode.getText());
}
else {
System.out.print(intermediateCode.getText() + ' ');
}
}
else {
System.out.print('(');
}
printParseTree(intermediateCode.getCar());
printParseTree(intermediateCode.getCdr());
if (intermediateCode.getCar() == null && intermediateCode.getCdr()==null) {
System.out.println(')');
}
}
| public void printParseTree(IntermediateCode intermediateCode) {
if (intermediateCode == null) {
return;
}
if (intermediateCode.getText() != null) {
if (intermediateCode.getText().compareTo("'") == 0) {
System.out.print(intermediateCode.getText());
}
else {
System.out.print(intermediateCode.getText() + ' ');
}
}
else {
System.out.print('(');
}
printParseTree(intermediateCode.getCar());
printParseTree(intermediateCode.getCdr());
if (intermediateCode.getCdr() == null) {
System.out.println(')');
}
}
|
diff --git a/modules/webutil/src/com/caucho/xtpdoc/Figure.java b/modules/webutil/src/com/caucho/xtpdoc/Figure.java
index 11b7e88e3..fdb35e859 100644
--- a/modules/webutil/src/com/caucho/xtpdoc/Figure.java
+++ b/modules/webutil/src/com/caucho/xtpdoc/Figure.java
@@ -1,220 +1,220 @@
/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Emil Ong
*/
package com.caucho.xtpdoc;
import javax.imageio.ImageIO;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import com.caucho.config.ConfigException;
public class Figure implements ContentItem {
private int _height = -1;
private int _width = -1;
private String _source;
private String _title;
private Document _document;
public Figure(Document document)
{
_document = document;
}
public Document getDocument()
{
return _document;
}
public void setHeight(int height)
{
_height = height;
}
public void setWidth(int width)
{
_width = width;
}
public void setSrc(String source)
{
_source = source;
}
public void setTitle(String title)
{
_title = title;
}
public void writeHtml(XMLStreamWriter out)
throws XMLStreamException
{
out.writeStartElement("center");
out.writeEmptyElement("img");
out.writeAttribute("border", "0");
if (_height >= 0)
out.writeAttribute("height", Integer.toString(_height));
if (_title != null)
out.writeAttribute("title", _title);
if (_width >= 0)
out.writeAttribute("width", Integer.toString(_width));
out.writeAttribute("src",
_document.getContextPath() + "/images/" + _source);
out.writeEndElement(); // center
}
public void writeLaTeXVerbatim(PrintWriter out)
throws IOException
{
throw new ConfigException("<figure> not allowed in a verbatim context");
}
public void writeLaTeX(PrintWriter out)
throws IOException
{
int dot = _source.lastIndexOf('.');
String basename = _source.substring(0, dot);
int lastSlash = basename.lastIndexOf('/');
if (lastSlash >= 0)
basename = basename.substring(lastSlash + 1);
out.println();
out.println();
out.println("\\noindent");
out.println("\\epsfig{file=../images/" + basename + ",width=\\linewidth}");
out.println();
out.println();
}
public void writeLaTeXEnclosed(PrintWriter out)
throws IOException
{
writeLaTeX(out);
}
public void writeLaTeXTop(PrintWriter out)
throws IOException
{
writeLaTeX(out);
}
@Override
public void writeAsciiDoc(PrintWriter out)
throws IOException
{
int dot = _source.lastIndexOf('.');
- String basename = _source.substring(0, dot);
+ String baseName = _source.substring(0, dot);
out.println();
out.println();
String pdfName = baseName + ".pdf";
boolean isPdf = false;
if (new File(pdfName).exists()) {
out.print("image::images/" + pdfName + "[alt=\"" + _source + "\"");
isPdf = true;
}
else {
out.print("image::images/" + _source + "[alt=\"" + _source + "\"");
}
int width = getWidth(_source);
/*
if (width > 0)
out.print(",width=" + width);
int height = getHeight(_source);
if (height > 0)
out.print(",height=" + height);
out.print(",align=center");
*/
//if (width > 0)
// out.print(",scaledwidth=" + width);
if (! isPdf) {
out.print(",scaledwidth=\"100%\"");
out.print(",height=\"100%\"");
}
out.print(",align=center");
out.println("]");
}
public static int getWidth(String source)
{
try {
Toolkit toolkit = Toolkit.getDefaultToolkit();
File file = new File("images/" + source);
java.awt.Image image = ImageIO.read(file);
return image.getWidth(null);
} catch (Exception e) {
// log.log(Level.FINER, e.toString(), e);
return -1;
}
}
public static int getHeight(String source)
{
try {
Toolkit toolkit = Toolkit.getDefaultToolkit();
File file = new File("images/" + source);
java.awt.Image image = ImageIO.read(file);
return image.getHeight(null);
} catch (Exception e) {
// log.log(Level.FINER, e.toString(), e);
return -1;
}
}
}
| true | true | public void writeAsciiDoc(PrintWriter out)
throws IOException
{
int dot = _source.lastIndexOf('.');
String basename = _source.substring(0, dot);
out.println();
out.println();
String pdfName = baseName + ".pdf";
boolean isPdf = false;
if (new File(pdfName).exists()) {
out.print("image::images/" + pdfName + "[alt=\"" + _source + "\"");
isPdf = true;
}
else {
out.print("image::images/" + _source + "[alt=\"" + _source + "\"");
}
int width = getWidth(_source);
/*
if (width > 0)
out.print(",width=" + width);
int height = getHeight(_source);
if (height > 0)
out.print(",height=" + height);
out.print(",align=center");
*/
//if (width > 0)
// out.print(",scaledwidth=" + width);
if (! isPdf) {
out.print(",scaledwidth=\"100%\"");
out.print(",height=\"100%\"");
}
out.print(",align=center");
out.println("]");
}
| public void writeAsciiDoc(PrintWriter out)
throws IOException
{
int dot = _source.lastIndexOf('.');
String baseName = _source.substring(0, dot);
out.println();
out.println();
String pdfName = baseName + ".pdf";
boolean isPdf = false;
if (new File(pdfName).exists()) {
out.print("image::images/" + pdfName + "[alt=\"" + _source + "\"");
isPdf = true;
}
else {
out.print("image::images/" + _source + "[alt=\"" + _source + "\"");
}
int width = getWidth(_source);
/*
if (width > 0)
out.print(",width=" + width);
int height = getHeight(_source);
if (height > 0)
out.print(",height=" + height);
out.print(",align=center");
*/
//if (width > 0)
// out.print(",scaledwidth=" + width);
if (! isPdf) {
out.print(",scaledwidth=\"100%\"");
out.print(",height=\"100%\"");
}
out.print(",align=center");
out.println("]");
}
|
diff --git a/src/nuthatch/engine/impl/EnvEngine.java b/src/nuthatch/engine/impl/EnvEngine.java
index 40feaa0..1f31c71 100644
--- a/src/nuthatch/engine/impl/EnvEngine.java
+++ b/src/nuthatch/engine/impl/EnvEngine.java
@@ -1,121 +1,123 @@
package nuthatch.engine.impl;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import nuthatch.pattern.Environment;
import nuthatch.pattern.EnvironmentFactory;
import nuthatch.pattern.VarName;
import nuthatch.strategy.Strategy;
import nuthatch.tree.TreeCursor;
import nuthatch.tree.errors.BranchNotFoundError;
import nuthatch.tree.util.BranchUtil;
public class EnvEngine<Value, Type, E extends EnvEngine<Value, Type, E>> extends RegisteredEngine<Value, Type, E> {
private Environment<Object> env = null;
private List<Map<String, Object>> subtreeScoping;
private Map<String, Object> subtreeVars;
private Map<String, Object> globalVars;
public EnvEngine(TreeCursor<Value, Type> cursor, Strategy<E> strat) {
super(cursor, strat);
clear();
}
public void clear() {
env = EnvironmentFactory.env();
globalVars = new IdentityHashMap<String, Object>();
subtreeVars = new IdentityHashMap<String, Object>();
subtreeScoping = new ArrayList<Map<String, Object>>();
}
@Override
public void engage() {
super.engage();
}
public void enterScope() {
env.enterScope();
}
public void exitScope() {
env.exitScope();
}
public <T> T getGlobalVar(VarName<T> name) {
return (T) globalVars.get(name.getName());
}
public <T> T getScopedVar(VarName<T> name) {
return (T) env.get(name.getName());
}
public <T> T getSubtreeVar(VarName<T> name) {
return (T) subtreeVars.get(name.getName());
}
@Override
public TreeCursor<Value, Type> go(int i) throws BranchNotFoundError {
int j = BranchUtil.normalBranch(i, getNumChildren());
if(j == 0) {
int k = subtreeScoping.size();
- Map<String, Object> map = subtreeScoping.remove(k - 1);
- if(map != null) {
- for(Entry<String, Object> entry : map.entrySet()) {
- if(entry.getValue() == null) {
- subtreeVars.remove(entry.getKey());
- }
- else {
- subtreeVars.put(entry.getKey(), entry.getValue());
+ if(k > 0) {
+ Map<String, Object> map = subtreeScoping.remove(k - 1);
+ if(map != null) {
+ for(Entry<String, Object> entry : map.entrySet()) {
+ if(entry.getValue() == null) {
+ subtreeVars.remove(entry.getKey());
+ }
+ else {
+ subtreeVars.put(entry.getKey(), entry.getValue());
+ }
}
}
}
}
else if(j > 0) {
subtreeScoping.add(null);
}
else {
throw new BranchNotFoundError(Integer.toString(i));
}
return super.go(j);
}
public <T> void setGlobalVar(VarName<T> name, T value) {
globalVars.put(name.getName(), value);
}
public <T> void setScopedVar(VarName<T> name, T value) {
env.put(name.getName(), value);
}
public <T> void setSubtreeVar(VarName<T> name, T value) {
Map<String, Object> map = subtreeScoping.get(subtreeScoping.size() - 1);
String n = name.getName();
if(map == null) {
map = new IdentityHashMap<>();
subtreeScoping.set(subtreeScoping.size() - 1, map);
}
if(!map.containsKey(n)) {
// store old value if this is a new variable at this subtree
map.put(n, subtreeVars.get(n));
}
subtreeVars.put(name.getName(), value);
}
}
| true | true | public TreeCursor<Value, Type> go(int i) throws BranchNotFoundError {
int j = BranchUtil.normalBranch(i, getNumChildren());
if(j == 0) {
int k = subtreeScoping.size();
Map<String, Object> map = subtreeScoping.remove(k - 1);
if(map != null) {
for(Entry<String, Object> entry : map.entrySet()) {
if(entry.getValue() == null) {
subtreeVars.remove(entry.getKey());
}
else {
subtreeVars.put(entry.getKey(), entry.getValue());
}
}
}
}
else if(j > 0) {
subtreeScoping.add(null);
}
else {
throw new BranchNotFoundError(Integer.toString(i));
}
return super.go(j);
}
| public TreeCursor<Value, Type> go(int i) throws BranchNotFoundError {
int j = BranchUtil.normalBranch(i, getNumChildren());
if(j == 0) {
int k = subtreeScoping.size();
if(k > 0) {
Map<String, Object> map = subtreeScoping.remove(k - 1);
if(map != null) {
for(Entry<String, Object> entry : map.entrySet()) {
if(entry.getValue() == null) {
subtreeVars.remove(entry.getKey());
}
else {
subtreeVars.put(entry.getKey(), entry.getValue());
}
}
}
}
}
else if(j > 0) {
subtreeScoping.add(null);
}
else {
throw new BranchNotFoundError(Integer.toString(i));
}
return super.go(j);
}
|
diff --git a/src/jaxrs/java/org/codehaus/jackson/jaxrs/MapperConfigurator.java b/src/jaxrs/java/org/codehaus/jackson/jaxrs/MapperConfigurator.java
index 11d1e5b1..0ead76c3 100644
--- a/src/jaxrs/java/org/codehaus/jackson/jaxrs/MapperConfigurator.java
+++ b/src/jaxrs/java/org/codehaus/jackson/jaxrs/MapperConfigurator.java
@@ -1,180 +1,179 @@
package org.codehaus.jackson.jaxrs;
import java.util.*;
import org.codehaus.jackson.*;
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
/**
* Helper class used to encapsulate details of configuring an
* {@link ObjectMapper} instance to be used for data binding, as
* well as accessing it.
*/
public class MapperConfigurator
{
/**
* Mapper provider was constructed with if any, or that was constructed
* due to a call to explicitly configure mapper.
* If defined (explicitly or implicitly) it will be used, instead
* of using provider-based lookup.
*/
protected ObjectMapper _mapper;
/**
* If no mapper was specified when constructed, and no configuration
* calls are made, a default mapper is constructed. The difference
* between default mapper and regular one is that default mapper
* is only used if no mapper is found via provider lookup.
*/
protected ObjectMapper _defaultMapper;
/**
* Annotations set to use by default; overridden by explicit call
* to {@link #setAnnotationsToUse}
*/
protected Annotations[] _defaultAnnotationsToUse;
/**
* To support optional dependency to Jackson-XC module (needed if and
* when JAXB annotations are used for configuration)
*/
protected Class<? extends AnnotationIntrospector> _jaxbIntrospectorClass;
/*
***********************************************************
* Construction
***********************************************************
*/
public MapperConfigurator(ObjectMapper mapper, Annotations[] defAnnotations)
{
_mapper = mapper;
_defaultAnnotationsToUse = defAnnotations;
}
/**
* Method that locates, configures and returns {@link ObjectMapper} to use
*/
public synchronized ObjectMapper getConfiguredMapper() {
/* important: should NOT call mapper(); needs to return null
* if no instance has been passed or constructed
*/
return _mapper;
}
public synchronized ObjectMapper getDefaultMapper() {
if (_defaultMapper == null) {
_defaultMapper = new ObjectMapper();
_setAnnotations(_defaultMapper, _defaultAnnotationsToUse);
}
return _defaultMapper;
}
/*
***********************************************************
* Configuration methods
***********************************************************
*/
public synchronized void setMapper(ObjectMapper m) {
_mapper = m;
}
public synchronized void setAnnotationsToUse(Annotations[] annotationsToUse) {
_setAnnotations(mapper(), annotationsToUse);
}
public synchronized void configure(DeserializationConfig.Feature f, boolean state) {
mapper().configure(f, state);
}
public synchronized void configure(SerializationConfig.Feature f, boolean state) {
mapper().configure(f, state);
}
public synchronized void configure(JsonParser.Feature f, boolean state) {
mapper().configure(f, state);
}
public synchronized void configure(JsonGenerator.Feature f, boolean state) {
mapper().configure(f, state);
}
/*
***********************************************************
* Internal methods
***********************************************************
*/
/**
* Helper method that will ensure that there is a configurable non-default
* mapper (constructing an instance if one didn't yet exit), and return
* that mapper.
*/
protected ObjectMapper mapper()
{
if (_mapper == null) {
_mapper = new ObjectMapper();
_setAnnotations(_mapper, _defaultAnnotationsToUse);
}
return _mapper;
}
protected void _setAnnotations(ObjectMapper mapper, Annotations[] annotationsToUse)
{
AnnotationIntrospector intr;
if (annotationsToUse == null || annotationsToUse.length == 0) {
intr = AnnotationIntrospector.nopInstance();
} else {
intr = _resolveIntrospectors(annotationsToUse);
}
mapper.getDeserializationConfig().setAnnotationIntrospector(intr);
mapper.getSerializationConfig().setAnnotationIntrospector(intr);
}
protected AnnotationIntrospector _resolveIntrospectors(Annotations[] annotationsToUse)
{
// Let's ensure there are no dups there first, filter out nulls
ArrayList<AnnotationIntrospector> intr = new ArrayList<AnnotationIntrospector>();
for (Annotations a : annotationsToUse) {
if (a != null) {
intr.add(_resolveIntrospector(a));
}
}
int count = intr.size();
if (count == 0) {
return AnnotationIntrospector.nopInstance();
}
AnnotationIntrospector curr = intr.get(0);
for (int i = 1, len = intr.size(); i < len; ++i) {
curr = AnnotationIntrospector.pair(curr, intr.get(i));
}
return curr;
}
protected AnnotationIntrospector _resolveIntrospector(Annotations ann)
{
-System.err.println("Resolve: "+ann);
switch (ann) {
case JACKSON:
return new JacksonAnnotationIntrospector();
case JAXB:
/* For this, need to use indirection just so that error occurs
* when we get here, and not when this call is being loaded
*/
try {
if (_jaxbIntrospectorClass == null) {
_jaxbIntrospectorClass = JaxbAnnotationIntrospector.class;
}
return _jaxbIntrospectorClass.newInstance();
} catch (Exception e) {
throw new IllegalStateException("Failed to instantiate JaxbAnnotationIntrospector: "+e.getMessage(), e);
}
default:
throw new IllegalStateException();
}
}
}
| true | true | protected AnnotationIntrospector _resolveIntrospector(Annotations ann)
{
System.err.println("Resolve: "+ann);
switch (ann) {
case JACKSON:
return new JacksonAnnotationIntrospector();
case JAXB:
/* For this, need to use indirection just so that error occurs
* when we get here, and not when this call is being loaded
*/
try {
if (_jaxbIntrospectorClass == null) {
_jaxbIntrospectorClass = JaxbAnnotationIntrospector.class;
}
return _jaxbIntrospectorClass.newInstance();
} catch (Exception e) {
throw new IllegalStateException("Failed to instantiate JaxbAnnotationIntrospector: "+e.getMessage(), e);
}
default:
throw new IllegalStateException();
}
}
| protected AnnotationIntrospector _resolveIntrospector(Annotations ann)
{
switch (ann) {
case JACKSON:
return new JacksonAnnotationIntrospector();
case JAXB:
/* For this, need to use indirection just so that error occurs
* when we get here, and not when this call is being loaded
*/
try {
if (_jaxbIntrospectorClass == null) {
_jaxbIntrospectorClass = JaxbAnnotationIntrospector.class;
}
return _jaxbIntrospectorClass.newInstance();
} catch (Exception e) {
throw new IllegalStateException("Failed to instantiate JaxbAnnotationIntrospector: "+e.getMessage(), e);
}
default:
throw new IllegalStateException();
}
}
|
diff --git a/src/com/edinarobotics/zephyr/Components.java b/src/com/edinarobotics/zephyr/Components.java
index a1d4e29..e2f83fc 100644
--- a/src/com/edinarobotics/zephyr/Components.java
+++ b/src/com/edinarobotics/zephyr/Components.java
@@ -1,47 +1,48 @@
package com.edinarobotics.zephyr;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.RobotDrive;
/**
*
*/
public class Components {
//PORT NUMBERS HERE!
private static final int LEFT_JAGUAR_PORT = 1;
private static final int RIGHT_JAGUAR_PORT = 2;
private static final int SHOOTER_JAGUAR_PORT = 3;
private static final int COMPRESSOR_PRESSURE_SENSOR = 1;
private static final int COMPRESSOR_SPIKE = 1;
private static final int BALL_LOAD_PISTON_SPIKE = 2;
private static Components instance;
public Jaguar leftJaguar;
public Jaguar rightJaguar;
public Jaguar shooterJaguar;
public RobotDrive driveControl;
public Compressor compressor;
public Relay ballLoadPiston;
public DriverStationLCD textOutput;
private Components(){
leftJaguar = new Jaguar(LEFT_JAGUAR_PORT);
rightJaguar = new Jaguar(RIGHT_JAGUAR_PORT);
shooterJaguar = new Jaguar(SHOOTER_JAGUAR_PORT);
driveControl = new RobotDrive(leftJaguar,rightJaguar);
compressor = new Compressor(COMPRESSOR_PRESSURE_SENSOR,COMPRESSOR_SPIKE);
+ compressor.start();
ballLoadPiston = new Relay(BALL_LOAD_PISTON_SPIKE);
textOutput = DriverStationLCD.getInstance();
}
public static Components getInstance(){
if(instance == null){
instance = new Components();
}
return instance;
}
}
| true | true | private Components(){
leftJaguar = new Jaguar(LEFT_JAGUAR_PORT);
rightJaguar = new Jaguar(RIGHT_JAGUAR_PORT);
shooterJaguar = new Jaguar(SHOOTER_JAGUAR_PORT);
driveControl = new RobotDrive(leftJaguar,rightJaguar);
compressor = new Compressor(COMPRESSOR_PRESSURE_SENSOR,COMPRESSOR_SPIKE);
ballLoadPiston = new Relay(BALL_LOAD_PISTON_SPIKE);
textOutput = DriverStationLCD.getInstance();
}
| private Components(){
leftJaguar = new Jaguar(LEFT_JAGUAR_PORT);
rightJaguar = new Jaguar(RIGHT_JAGUAR_PORT);
shooterJaguar = new Jaguar(SHOOTER_JAGUAR_PORT);
driveControl = new RobotDrive(leftJaguar,rightJaguar);
compressor = new Compressor(COMPRESSOR_PRESSURE_SENSOR,COMPRESSOR_SPIKE);
compressor.start();
ballLoadPiston = new Relay(BALL_LOAD_PISTON_SPIKE);
textOutput = DriverStationLCD.getInstance();
}
|
diff --git a/src/com/chess/genesis/widget/RegGameState.java b/src/com/chess/genesis/widget/RegGameState.java
index 1626e2e..89e2418 100644
--- a/src/com/chess/genesis/widget/RegGameState.java
+++ b/src/com/chess/genesis/widget/RegGameState.java
@@ -1,407 +1,407 @@
/* GenesisChess, an Android chess application
Copyright 2012, Justin Madru ([email protected])
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://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.chess.genesis;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Toast;
class RegGameState extends GameState
{
private final ObjectArray<MoveFlags> flagsHistory;
private final Handler xhandle = new Handler()
{
public void handleMessage(final Message msg)
{
switch (msg.what) {
case RegEngine.MSG:
final Bundle bundle = (Bundle) msg.obj;
if (bundle.getLong("time") == 0) {
cpu.setBoard((RegBoard) board);
(new Thread(cpu)).start();
return;
}
currentMove();
final RegMove tmove = bundle.getParcelable("move");
final RegMove move = new RegMove();
if (board.validMove(tmove, move))
applyMove(move, true, true);
break;
default:
handleOther(msg);
break;
}
}
};
public RegGameState(final Activity _activity, final GameFrag _game, final Bundle _settings)
{
activity = _activity;
game = _game;
settings = _settings;
handle = xhandle;
callstack = new IntArray();
flagsHistory = new ObjectArray<MoveFlags>();
history = new ObjectArray<Move>();
board = new RegBoard();
progress = new ProgressMsg(activity);
type = settings.getInt("type", Enums.ONLINE_GAME);
switch (type) {
case Enums.LOCAL_GAME:
default:
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(activity);
cpu = new RegEngine(handle);
cpu.setTime(pref.getInt("cputime", cpu.getTime()));
oppType = Integer.valueOf(settings.getString("opponent"));
net = null;
ycol = (oppType == Enums.CPU_WHITE_OPPONENT)? Piece.BLACK : Piece.WHITE;
break;
case Enums.ONLINE_GAME:
case Enums.ARCHIVE_GAME:
oppType = Enums.HUMAN_OPPONENT;
cpu = null;
net = new NetworkClient(activity, handle);
ycol = settings.getString("username").equals(settings.getString("white"))? Piece.WHITE : Piece.BLACK;
break;
}
final String tmp = settings.getString("history");
if (tmp == null || tmp.length() < 3) {
check_endgame();
return;
}
final String[] movehistory = tmp.trim().split(" +");
for (int i = 0; i < movehistory.length; i++) {
final RegMove move = new RegMove();
move.parse(movehistory[i]);
if (board.validMove(move) != Move.VALID_MOVE)
break;
flagsHistory.push(board.getMoveFlags());
history.push(move);
board.make(move);
hindex++;
}
check_endgame();
}
public void setBoard()
{
// set dead piece counts
setBoard(board.getPieceCounts(Piece.DEAD));
}
protected boolean runCPU()
{
// Start computer player
if (oppType == Enums.HUMAN_OPPONENT)
return false;
else if (hindex + 1 < history.size())
return false;
else if (board.getStm() == ycol)
return false;
if (cpu.isActive()) {
cpu.stop();
return true;
}
cpu.setBoard((RegBoard) board);
(new Thread(cpu)).start();
return true;
}
protected void applyRemoteMove(final String hist)
{
if (hist == null || hist.length() < 3)
return;
final String[] movehistory = hist.trim().split(" +");
if (movehistory[movehistory.length - 1].equals(history.top().toString()))
return;
// must be on most current move to apply it
currentMove();
Toast.makeText(activity, "New move loaded...", Toast.LENGTH_LONG).show();
final RegMove move = new RegMove();
move.parse(movehistory[movehistory.length - 1]);
if (board.validMove(move) != Move.VALID_MOVE)
return;
applyMove(move, true, false);
}
public void reset()
{
super.reset();
history.clear();
flagsHistory.clear();
board.reset();
}
public void backMove()
{
if (hindex < 0)
return;
final RegMove move = (RegMove) history.get(hindex);
revertMove(move);
}
public void forwardMove()
{
if (hindex + 1 >= history.size())
return;
final RegMove move = (RegMove) history.get(hindex + 1);
applyMove(move, false, true);
}
public void currentMove()
{
while (hindex + 1 < history.size()) {
final RegMove move = (RegMove) history.get(hindex + 1);
applyMove(move, false, true);
}
}
public void firstMove()
{
while (hindex > 0) {
final RegMove move = (RegMove) history.get(hindex);
revertMove(move);
}
}
public void undoMove()
{
if (hindex < 0)
return;
final RegMove move = (RegMove) history.get(hindex);
revertMove(move);
history.pop();
flagsHistory.pop();
}
private void handleMove()
{
if (type == Enums.ONLINE_GAME) {
// you can't edit the past in online games
if (hindex + 1 < history.size()) {
callstack.pop();
return;
}
} else if (type == Enums.ARCHIVE_GAME) {
return;
}
final RegMove move = new RegMove();
move.from = callstack.get(0);
move.to = callstack.get(1);
// return if move isn't valid
if (board.validMove(move) != Move.VALID_MOVE) {
callstack.pop();
return;
}
callstack.clear();
applyMove(move, true, true);
}
private void applyMove(final RegMove move, final boolean erase, final boolean localmove)
{
if (hindex >= 0) {
// undo last move highlight
final BoardButton to = (BoardButton) activity.findViewById(history.get(hindex).to);
to.setLast(false);
if (hindex > 1) {
// legal move always ends with king not in check
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(false);
}
}
final BoardButton from = (BoardButton) activity.findViewById(move.from);
final BoardButton to = (BoardButton) activity.findViewById(move.to);
to.setPiece(from.getPiece());
to.setLast(true);
from.setPiece(0);
from.setHighlight(false);
if (move.xindex != Piece.NONE) {
final PlaceButton piece = (PlaceButton) activity.findViewById(board.PieceType(move.xindex) + 1000);
piece.plusPiece();
}
if (move.getCastle() != 0) {
final boolean left = (move.getCastle() == Move.CASTLE_QS);
final int castleTo = move.to + (left? 1 : -1),
castleFrom = (left? 0:7) + ((board.getStm() == Piece.WHITE)? Piece.A1 : Piece.A8);
BoardButton castle = (BoardButton) activity.findViewById(castleFrom);
castle.setPiece(Piece.EMPTY);
castle = (BoardButton) activity.findViewById(castleTo);
castle.setPiece(Piece.ROOK * board.getStm());
} else if (move.getPromote() != 0) {
final BoardButton pawn = (BoardButton) activity.findViewById(move.to);
- pawn.setPiece(Piece.QUEEN * board.getStm());
+ pawn.setPiece(move.getPromote() * board.getStm());
} else if (move.getEnPassant()) {
final BoardButton pawn = (BoardButton) activity.findViewById(board.Piece(move.xindex));
pawn.setPiece(Piece.EMPTY);
}
// get copy of board flags
final MoveFlags flags = board.getMoveFlags();
// apply move to board
board.make(move);
// update hindex, history
hindex++;
if (erase) {
if (hindex < history.size()) {
history.resize(hindex);
flagsHistory.resize(hindex);
}
history.push(move);
flagsHistory.push(flags);
if (localmove)
save(activity, false);
}
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
private void revertMove(final RegMove move)
{
// legal move always ends with king not in check
if (hindex > 1) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(false);
}
final BoardButton from = (BoardButton) activity.findViewById(move.from);
final BoardButton to = (BoardButton) activity.findViewById(move.to);
from.setPiece(to.getPiece());
to.setLast(false);
if (move.xindex == Piece.NONE) {
to.setPiece(Piece.EMPTY);
} else if (move.getEnPassant()) {
final int loc = move.to + ((move.to - move.from > 0)? -16 : 16);
final BoardButton pawn = (BoardButton) activity.findViewById(loc);
pawn.setPiece(Piece.PAWN * board.getStm());
to.setPiece(Piece.EMPTY);
} else {
to.setPiece(board.PieceType(move.xindex));
}
if (move.xindex != Piece.NONE) {
final PlaceButton piece = (PlaceButton) activity.findViewById(board.PieceType(move.xindex) + 1000);
piece.minusPiece();
}
if (move.getCastle() != 0) {
final boolean left = (move.getCastle() == Move.CASTLE_QS);
final int castleTo = move.to + (left? 1 : -1),
castleFrom = (left? 0:7) + ((board.getStm() == Piece.BLACK)? Piece.A1 : Piece.A8);
BoardButton castle = (BoardButton) activity.findViewById(castleFrom);
castle.setPiece(Piece.ROOK * -board.getStm());
castle = (BoardButton) activity.findViewById(castleTo);
castle.setPiece(Piece.EMPTY);
} else if (move.getPromote() != 0) {
final BoardButton pawn = (BoardButton) activity.findViewById(move.from);
pawn.setPiece(Piece.PAWN * -board.getStm());
}
board.unmake(move, flagsHistory.get(hindex));
hindex--;
if (hindex >= 0) {
// redo last move highlight
final BoardButton hto = (BoardButton) activity.findViewById(history.get(hindex).to);
hto.setLast(true);
}
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
public void boardClick(final View v)
{
final BoardButton to = (BoardButton) v;
final int index = to.getIndex();
final int col = yourColor();
if (callstack.size() == 0) {
// No active clicks
// first click must be non empty and your own
if (to.getPiece() * col <= 0)
return;
callstack.push(index);
to.setHighlight(true);
return;
} else if (callstack.get(0) == index) {
// clicking the same square
callstack.clear();
to.setHighlight(false);
return;
} else {
// piece move action
final BoardButton from = (BoardButton) activity.findViewById(callstack.get(0));
// capturing your own piece (switch to piece)
if (from.getPiece() * to.getPiece() > 0) {
from.setHighlight(false);
to.setHighlight(true);
callstack.set(0, index);
return;
}
}
callstack.push(index);
handleMove();
}
public void placeClick(final View v)
{
// Required because GameState calls this function
}
}
| true | true | private void applyMove(final RegMove move, final boolean erase, final boolean localmove)
{
if (hindex >= 0) {
// undo last move highlight
final BoardButton to = (BoardButton) activity.findViewById(history.get(hindex).to);
to.setLast(false);
if (hindex > 1) {
// legal move always ends with king not in check
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(false);
}
}
final BoardButton from = (BoardButton) activity.findViewById(move.from);
final BoardButton to = (BoardButton) activity.findViewById(move.to);
to.setPiece(from.getPiece());
to.setLast(true);
from.setPiece(0);
from.setHighlight(false);
if (move.xindex != Piece.NONE) {
final PlaceButton piece = (PlaceButton) activity.findViewById(board.PieceType(move.xindex) + 1000);
piece.plusPiece();
}
if (move.getCastle() != 0) {
final boolean left = (move.getCastle() == Move.CASTLE_QS);
final int castleTo = move.to + (left? 1 : -1),
castleFrom = (left? 0:7) + ((board.getStm() == Piece.WHITE)? Piece.A1 : Piece.A8);
BoardButton castle = (BoardButton) activity.findViewById(castleFrom);
castle.setPiece(Piece.EMPTY);
castle = (BoardButton) activity.findViewById(castleTo);
castle.setPiece(Piece.ROOK * board.getStm());
} else if (move.getPromote() != 0) {
final BoardButton pawn = (BoardButton) activity.findViewById(move.to);
pawn.setPiece(Piece.QUEEN * board.getStm());
} else if (move.getEnPassant()) {
final BoardButton pawn = (BoardButton) activity.findViewById(board.Piece(move.xindex));
pawn.setPiece(Piece.EMPTY);
}
// get copy of board flags
final MoveFlags flags = board.getMoveFlags();
// apply move to board
board.make(move);
// update hindex, history
hindex++;
if (erase) {
if (hindex < history.size()) {
history.resize(hindex);
flagsHistory.resize(hindex);
}
history.push(move);
flagsHistory.push(flags);
if (localmove)
save(activity, false);
}
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
| private void applyMove(final RegMove move, final boolean erase, final boolean localmove)
{
if (hindex >= 0) {
// undo last move highlight
final BoardButton to = (BoardButton) activity.findViewById(history.get(hindex).to);
to.setLast(false);
if (hindex > 1) {
// legal move always ends with king not in check
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(false);
}
}
final BoardButton from = (BoardButton) activity.findViewById(move.from);
final BoardButton to = (BoardButton) activity.findViewById(move.to);
to.setPiece(from.getPiece());
to.setLast(true);
from.setPiece(0);
from.setHighlight(false);
if (move.xindex != Piece.NONE) {
final PlaceButton piece = (PlaceButton) activity.findViewById(board.PieceType(move.xindex) + 1000);
piece.plusPiece();
}
if (move.getCastle() != 0) {
final boolean left = (move.getCastle() == Move.CASTLE_QS);
final int castleTo = move.to + (left? 1 : -1),
castleFrom = (left? 0:7) + ((board.getStm() == Piece.WHITE)? Piece.A1 : Piece.A8);
BoardButton castle = (BoardButton) activity.findViewById(castleFrom);
castle.setPiece(Piece.EMPTY);
castle = (BoardButton) activity.findViewById(castleTo);
castle.setPiece(Piece.ROOK * board.getStm());
} else if (move.getPromote() != 0) {
final BoardButton pawn = (BoardButton) activity.findViewById(move.to);
pawn.setPiece(move.getPromote() * board.getStm());
} else if (move.getEnPassant()) {
final BoardButton pawn = (BoardButton) activity.findViewById(board.Piece(move.xindex));
pawn.setPiece(Piece.EMPTY);
}
// get copy of board flags
final MoveFlags flags = board.getMoveFlags();
// apply move to board
board.make(move);
// update hindex, history
hindex++;
if (erase) {
if (hindex < history.size()) {
history.resize(hindex);
flagsHistory.resize(hindex);
}
history.push(move);
flagsHistory.push(flags);
if (localmove)
save(activity, false);
}
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) activity.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
|
diff --git a/plugins/org.jboss.tools.jst.firstrun/src/org/jboss/tools/jst/firstrun/JBossASAdapterInitializer.java b/plugins/org.jboss.tools.jst.firstrun/src/org/jboss/tools/jst/firstrun/JBossASAdapterInitializer.java
index f34fa7e7..8f91824e 100644
--- a/plugins/org.jboss.tools.jst.firstrun/src/org/jboss/tools/jst/firstrun/JBossASAdapterInitializer.java
+++ b/plugins/org.jboss.tools.jst.firstrun/src/org/jboss/tools/jst/firstrun/JBossASAdapterInitializer.java
@@ -1,234 +1,234 @@
/*******************************************************************************
* Copyright (c) 2007 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.jst.firstrun;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.datatools.connectivity.ConnectionProfileConstants;
import org.eclipse.datatools.connectivity.ConnectionProfileException;
import org.eclipse.datatools.connectivity.ProfileManager;
import org.eclipse.datatools.connectivity.db.generic.IDBConnectionProfileConstants;
import org.eclipse.datatools.connectivity.db.generic.IDBDriverDefinitionConstants;
import org.eclipse.datatools.connectivity.drivers.DriverInstance;
import org.eclipse.datatools.connectivity.drivers.DriverManager;
import org.eclipse.datatools.connectivity.drivers.IDriverMgmtConstants;
import org.eclipse.datatools.connectivity.drivers.IPropertySet;
import org.eclipse.datatools.connectivity.drivers.PropertySetImpl;
import org.eclipse.datatools.connectivity.drivers.models.TemplateDescriptor;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.ui.IStartup;
import org.eclipse.wst.server.core.IRuntime;
import org.eclipse.wst.server.core.IRuntimeType;
import org.eclipse.wst.server.core.IRuntimeWorkingCopy;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.IServerType;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.ServerCore;
import org.eclipse.wst.server.core.ServerUtil;
import org.eclipse.wst.server.core.internal.RuntimeWorkingCopy;
/**
* @author eskimo
*
*/
public class JBossASAdapterInitializer implements IStartup {
public static final String JBOSS_AS_HOME = "../../../../jboss-eap/jboss-as"; // JBoss AS home directory (relative to plugin)- <RHDS_HOME>/jbossas.
public static final String JBOSS_AS_RUNTIME_TYPE_ID
= "org.jboss.ide.eclipse.as.runtime.42";
public static final String JBOSS_AS_TYPE_ID = "org.jboss.ide.eclipse.as.42";
public static final String JBOSS_AS_NAME = "JBoss Application Server 4.2";
public static final String JBOSS_AS_HOST = "localhost";
public static final String JBOSS_AS_DEFAULT_CONFIGURATION_NAME = "default";
public static final String FIRST_START_PREFERENCE_NAME = "FIRST_START";
public static final String HSQL_DRIVER_DEFINITION_ID
= "DriverDefn.Hypersonic DB";
public static final String HSQL_DRIVER_NAME = "Hypersonic DB";
public static final String HSQL_DRIVER_TEMPLATE_ID
= "org.eclipse.datatools.enablement.hsqldb.1_8.driver";
public static final String DTP_DB_URL_PROPERTY_ID
= "org.eclipse.datatools.connectivity.db.URL";
/**
* @see org.eclipse.ui.IStartup#earlyStartup()
*/
public void earlyStartup() {
try {
JstFirstRunPlugin.getDefault().getPreferenceStore().setDefault(FIRST_START_PREFERENCE_NAME, true);
boolean firstStart = JstFirstRunPlugin.getDefault().getPreferenceStore().getBoolean(FIRST_START_PREFERENCE_NAME);
if(!firstStart) {
return;
}
JstFirstRunPlugin.getDefault().getPreferenceStore().setValue(FIRST_START_PREFERENCE_NAME, false);
String jbossASLocation = null;
String pluginLocation = FileLocator.resolve(JstFirstRunPlugin.getDefault().getBundle().getEntry("/")).getPath();
File jbossASDir = new File(pluginLocation, JBOSS_AS_HOME);
if(jbossASDir.isDirectory()) {
jbossASLocation = jbossASDir.getAbsolutePath();
} else {
return;
}
IPath jbossAsLocationPath = new Path(jbossASLocation);
String type = null;
String version = null;
IServer[] servers = ServerCore.getServers();
for(int i=0; i<servers.length; i++) {
IRuntime runtime = servers[i].getRuntime();
if(runtime!=null && runtime.getLocation().equals(jbossAsLocationPath)) {
return;
}
}
IRuntimeWorkingCopy runtime = null;
IRuntime[] runtimes = ServerCore.getRuntimes();
String runtimeId = null;
for(int i=0; i<runtimes.length; i++) {
if(runtimes[0].getLocation().equals(jbossASLocation)) {
runtime = runtimes[0].createWorkingCopy();
runtimeId = null;
break;
}
}
IProgressMonitor progressMonitor = new NullProgressMonitor();
if(runtime==null) {
IRuntimeType[] runtimeTypes = ServerUtil.getRuntimeTypes(type, version, JBOSS_AS_RUNTIME_TYPE_ID);
if(runtimeTypes.length>0) {
runtime = runtimeTypes[0].createRuntime(runtimeId, progressMonitor);
runtime.setLocation(jbossAsLocationPath);
IVMInstall defaultVM = JavaRuntime.getDefaultVMInstall();
// IJBossServerRuntime.PROPERTY_VM_ID
((RuntimeWorkingCopy)runtime).setAttribute("PROPERTY_VM_ID", defaultVM.getId());
// IJBossServerRuntime.PROPERTY_VM_TYPE_ID
((RuntimeWorkingCopy)runtime).setAttribute("PROPERTY_VM_TYPE_ID", defaultVM.getVMInstallType().getId());
// IJBossServerRuntime.PROPERTY_CONFIGURATION_NAME
((RuntimeWorkingCopy)runtime).setAttribute("org.jboss.ide.eclipse.as.core.runtime.configurationName", JBOSS_AS_DEFAULT_CONFIGURATION_NAME);
runtime.save(false, progressMonitor);
}
}
if(runtime!=null) {
IServerType serverType = ServerCore.findServerType(JBOSS_AS_TYPE_ID);
IServerWorkingCopy server = serverType.createServer(null, null, runtime, progressMonitor);
server.setHost(JBOSS_AS_HOST);
server.setName(JBOSS_AS_NAME);
server.save(false, progressMonitor);
}
DriverInstance driver = DriverManager.getInstance()
.getDriverInstanceByName(HSQL_DRIVER_NAME);
if(driver==null) {
TemplateDescriptor descr = TemplateDescriptor
.getDriverTemplateDescriptor(HSQL_DRIVER_TEMPLATE_ID);
IPropertySet instance = new PropertySetImpl(
HSQL_DRIVER_NAME,HSQL_DRIVER_DEFINITION_ID);
instance.setName(HSQL_DRIVER_NAME);
instance.setID(HSQL_DRIVER_DEFINITION_ID);
Properties props = new Properties();
IConfigurationElement[] template = descr.getProperties();
for (int i = 0; i < template.length; i++) {
IConfigurationElement prop = template[i];
String id = prop.getAttribute("id"); //$NON-NLS-1$
String value = prop.getAttribute("value"); //$NON-NLS-1$
- props.setProperty(id, value == null ? new String()
+ props.setProperty(id, value == null ? ""
: value);
}
props.setProperty(DTP_DB_URL_PROPERTY_ID, "jdbc:hsqldb:.");
props.setProperty(IDriverMgmtConstants.PROP_DEFN_TYPE,
descr.getId());
props.setProperty(IDriverMgmtConstants.PROP_DEFN_JARLIST,
jbossASLocation+"/server/default/lib/hsqldb.jar");
instance.setBaseProperties(props);
DriverManager.getInstance().removeDriverInstance(instance.getID());
System.gc();
DriverManager.getInstance().addDriverInstance(instance);
}
driver = DriverManager.getInstance().getDriverInstanceByName(HSQL_DRIVER_NAME);
if(driver!=null) {
// create profile
Properties props = new Properties();
props.setProperty(ConnectionProfileConstants.PROP_DRIVER_DEFINITION_ID,
HSQL_DRIVER_DEFINITION_ID);
props.setProperty(
IDBConnectionProfileConstants.CONNECTION_PROPERTIES_PROP_ID,
"");
props.setProperty(IDBDriverDefinitionConstants.DRIVER_CLASS_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DRIVER_CLASS_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_VENDOR_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DATABASE_VENDOR_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_VERSION_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DATABASE_VERSION_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_NAME_PROP_ID,
"Default");
props.setProperty(IDBDriverDefinitionConstants.PASSWORD_PROP_ID, "");
props.setProperty(
IDBConnectionProfileConstants.SAVE_PASSWORD_PROP_ID, "false");
props.setProperty(IDBDriverDefinitionConstants.USERNAME_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.USERNAME_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.URL_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.URL_PROP_ID));
ProfileManager.getInstance().createProfile(
"DefaultDS",
"The JBoss AS Hypersonic embedded database",
IDBConnectionProfileConstants.CONNECTION_PROFILE_ID,
props,
"", false);
}
} catch (CoreException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new JBoss Server", e));
} catch (IOException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new JBoss Server", e));
} catch (ConnectionProfileException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new DTP " +
"Connection Profile for JBoss AS Hypersonic embedded database", e));
}
}
}
| true | true | public void earlyStartup() {
try {
JstFirstRunPlugin.getDefault().getPreferenceStore().setDefault(FIRST_START_PREFERENCE_NAME, true);
boolean firstStart = JstFirstRunPlugin.getDefault().getPreferenceStore().getBoolean(FIRST_START_PREFERENCE_NAME);
if(!firstStart) {
return;
}
JstFirstRunPlugin.getDefault().getPreferenceStore().setValue(FIRST_START_PREFERENCE_NAME, false);
String jbossASLocation = null;
String pluginLocation = FileLocator.resolve(JstFirstRunPlugin.getDefault().getBundle().getEntry("/")).getPath();
File jbossASDir = new File(pluginLocation, JBOSS_AS_HOME);
if(jbossASDir.isDirectory()) {
jbossASLocation = jbossASDir.getAbsolutePath();
} else {
return;
}
IPath jbossAsLocationPath = new Path(jbossASLocation);
String type = null;
String version = null;
IServer[] servers = ServerCore.getServers();
for(int i=0; i<servers.length; i++) {
IRuntime runtime = servers[i].getRuntime();
if(runtime!=null && runtime.getLocation().equals(jbossAsLocationPath)) {
return;
}
}
IRuntimeWorkingCopy runtime = null;
IRuntime[] runtimes = ServerCore.getRuntimes();
String runtimeId = null;
for(int i=0; i<runtimes.length; i++) {
if(runtimes[0].getLocation().equals(jbossASLocation)) {
runtime = runtimes[0].createWorkingCopy();
runtimeId = null;
break;
}
}
IProgressMonitor progressMonitor = new NullProgressMonitor();
if(runtime==null) {
IRuntimeType[] runtimeTypes = ServerUtil.getRuntimeTypes(type, version, JBOSS_AS_RUNTIME_TYPE_ID);
if(runtimeTypes.length>0) {
runtime = runtimeTypes[0].createRuntime(runtimeId, progressMonitor);
runtime.setLocation(jbossAsLocationPath);
IVMInstall defaultVM = JavaRuntime.getDefaultVMInstall();
// IJBossServerRuntime.PROPERTY_VM_ID
((RuntimeWorkingCopy)runtime).setAttribute("PROPERTY_VM_ID", defaultVM.getId());
// IJBossServerRuntime.PROPERTY_VM_TYPE_ID
((RuntimeWorkingCopy)runtime).setAttribute("PROPERTY_VM_TYPE_ID", defaultVM.getVMInstallType().getId());
// IJBossServerRuntime.PROPERTY_CONFIGURATION_NAME
((RuntimeWorkingCopy)runtime).setAttribute("org.jboss.ide.eclipse.as.core.runtime.configurationName", JBOSS_AS_DEFAULT_CONFIGURATION_NAME);
runtime.save(false, progressMonitor);
}
}
if(runtime!=null) {
IServerType serverType = ServerCore.findServerType(JBOSS_AS_TYPE_ID);
IServerWorkingCopy server = serverType.createServer(null, null, runtime, progressMonitor);
server.setHost(JBOSS_AS_HOST);
server.setName(JBOSS_AS_NAME);
server.save(false, progressMonitor);
}
DriverInstance driver = DriverManager.getInstance()
.getDriverInstanceByName(HSQL_DRIVER_NAME);
if(driver==null) {
TemplateDescriptor descr = TemplateDescriptor
.getDriverTemplateDescriptor(HSQL_DRIVER_TEMPLATE_ID);
IPropertySet instance = new PropertySetImpl(
HSQL_DRIVER_NAME,HSQL_DRIVER_DEFINITION_ID);
instance.setName(HSQL_DRIVER_NAME);
instance.setID(HSQL_DRIVER_DEFINITION_ID);
Properties props = new Properties();
IConfigurationElement[] template = descr.getProperties();
for (int i = 0; i < template.length; i++) {
IConfigurationElement prop = template[i];
String id = prop.getAttribute("id"); //$NON-NLS-1$
String value = prop.getAttribute("value"); //$NON-NLS-1$
props.setProperty(id, value == null ? new String()
: value);
}
props.setProperty(DTP_DB_URL_PROPERTY_ID, "jdbc:hsqldb:.");
props.setProperty(IDriverMgmtConstants.PROP_DEFN_TYPE,
descr.getId());
props.setProperty(IDriverMgmtConstants.PROP_DEFN_JARLIST,
jbossASLocation+"/server/default/lib/hsqldb.jar");
instance.setBaseProperties(props);
DriverManager.getInstance().removeDriverInstance(instance.getID());
System.gc();
DriverManager.getInstance().addDriverInstance(instance);
}
driver = DriverManager.getInstance().getDriverInstanceByName(HSQL_DRIVER_NAME);
if(driver!=null) {
// create profile
Properties props = new Properties();
props.setProperty(ConnectionProfileConstants.PROP_DRIVER_DEFINITION_ID,
HSQL_DRIVER_DEFINITION_ID);
props.setProperty(
IDBConnectionProfileConstants.CONNECTION_PROPERTIES_PROP_ID,
"");
props.setProperty(IDBDriverDefinitionConstants.DRIVER_CLASS_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DRIVER_CLASS_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_VENDOR_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DATABASE_VENDOR_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_VERSION_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DATABASE_VERSION_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_NAME_PROP_ID,
"Default");
props.setProperty(IDBDriverDefinitionConstants.PASSWORD_PROP_ID, "");
props.setProperty(
IDBConnectionProfileConstants.SAVE_PASSWORD_PROP_ID, "false");
props.setProperty(IDBDriverDefinitionConstants.USERNAME_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.USERNAME_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.URL_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.URL_PROP_ID));
ProfileManager.getInstance().createProfile(
"DefaultDS",
"The JBoss AS Hypersonic embedded database",
IDBConnectionProfileConstants.CONNECTION_PROFILE_ID,
props,
"", false);
}
} catch (CoreException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new JBoss Server", e));
} catch (IOException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new JBoss Server", e));
} catch (ConnectionProfileException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new DTP " +
"Connection Profile for JBoss AS Hypersonic embedded database", e));
}
}
| public void earlyStartup() {
try {
JstFirstRunPlugin.getDefault().getPreferenceStore().setDefault(FIRST_START_PREFERENCE_NAME, true);
boolean firstStart = JstFirstRunPlugin.getDefault().getPreferenceStore().getBoolean(FIRST_START_PREFERENCE_NAME);
if(!firstStart) {
return;
}
JstFirstRunPlugin.getDefault().getPreferenceStore().setValue(FIRST_START_PREFERENCE_NAME, false);
String jbossASLocation = null;
String pluginLocation = FileLocator.resolve(JstFirstRunPlugin.getDefault().getBundle().getEntry("/")).getPath();
File jbossASDir = new File(pluginLocation, JBOSS_AS_HOME);
if(jbossASDir.isDirectory()) {
jbossASLocation = jbossASDir.getAbsolutePath();
} else {
return;
}
IPath jbossAsLocationPath = new Path(jbossASLocation);
String type = null;
String version = null;
IServer[] servers = ServerCore.getServers();
for(int i=0; i<servers.length; i++) {
IRuntime runtime = servers[i].getRuntime();
if(runtime!=null && runtime.getLocation().equals(jbossAsLocationPath)) {
return;
}
}
IRuntimeWorkingCopy runtime = null;
IRuntime[] runtimes = ServerCore.getRuntimes();
String runtimeId = null;
for(int i=0; i<runtimes.length; i++) {
if(runtimes[0].getLocation().equals(jbossASLocation)) {
runtime = runtimes[0].createWorkingCopy();
runtimeId = null;
break;
}
}
IProgressMonitor progressMonitor = new NullProgressMonitor();
if(runtime==null) {
IRuntimeType[] runtimeTypes = ServerUtil.getRuntimeTypes(type, version, JBOSS_AS_RUNTIME_TYPE_ID);
if(runtimeTypes.length>0) {
runtime = runtimeTypes[0].createRuntime(runtimeId, progressMonitor);
runtime.setLocation(jbossAsLocationPath);
IVMInstall defaultVM = JavaRuntime.getDefaultVMInstall();
// IJBossServerRuntime.PROPERTY_VM_ID
((RuntimeWorkingCopy)runtime).setAttribute("PROPERTY_VM_ID", defaultVM.getId());
// IJBossServerRuntime.PROPERTY_VM_TYPE_ID
((RuntimeWorkingCopy)runtime).setAttribute("PROPERTY_VM_TYPE_ID", defaultVM.getVMInstallType().getId());
// IJBossServerRuntime.PROPERTY_CONFIGURATION_NAME
((RuntimeWorkingCopy)runtime).setAttribute("org.jboss.ide.eclipse.as.core.runtime.configurationName", JBOSS_AS_DEFAULT_CONFIGURATION_NAME);
runtime.save(false, progressMonitor);
}
}
if(runtime!=null) {
IServerType serverType = ServerCore.findServerType(JBOSS_AS_TYPE_ID);
IServerWorkingCopy server = serverType.createServer(null, null, runtime, progressMonitor);
server.setHost(JBOSS_AS_HOST);
server.setName(JBOSS_AS_NAME);
server.save(false, progressMonitor);
}
DriverInstance driver = DriverManager.getInstance()
.getDriverInstanceByName(HSQL_DRIVER_NAME);
if(driver==null) {
TemplateDescriptor descr = TemplateDescriptor
.getDriverTemplateDescriptor(HSQL_DRIVER_TEMPLATE_ID);
IPropertySet instance = new PropertySetImpl(
HSQL_DRIVER_NAME,HSQL_DRIVER_DEFINITION_ID);
instance.setName(HSQL_DRIVER_NAME);
instance.setID(HSQL_DRIVER_DEFINITION_ID);
Properties props = new Properties();
IConfigurationElement[] template = descr.getProperties();
for (int i = 0; i < template.length; i++) {
IConfigurationElement prop = template[i];
String id = prop.getAttribute("id"); //$NON-NLS-1$
String value = prop.getAttribute("value"); //$NON-NLS-1$
props.setProperty(id, value == null ? ""
: value);
}
props.setProperty(DTP_DB_URL_PROPERTY_ID, "jdbc:hsqldb:.");
props.setProperty(IDriverMgmtConstants.PROP_DEFN_TYPE,
descr.getId());
props.setProperty(IDriverMgmtConstants.PROP_DEFN_JARLIST,
jbossASLocation+"/server/default/lib/hsqldb.jar");
instance.setBaseProperties(props);
DriverManager.getInstance().removeDriverInstance(instance.getID());
System.gc();
DriverManager.getInstance().addDriverInstance(instance);
}
driver = DriverManager.getInstance().getDriverInstanceByName(HSQL_DRIVER_NAME);
if(driver!=null) {
// create profile
Properties props = new Properties();
props.setProperty(ConnectionProfileConstants.PROP_DRIVER_DEFINITION_ID,
HSQL_DRIVER_DEFINITION_ID);
props.setProperty(
IDBConnectionProfileConstants.CONNECTION_PROPERTIES_PROP_ID,
"");
props.setProperty(IDBDriverDefinitionConstants.DRIVER_CLASS_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DRIVER_CLASS_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_VENDOR_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DATABASE_VENDOR_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_VERSION_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.DATABASE_VERSION_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.DATABASE_NAME_PROP_ID,
"Default");
props.setProperty(IDBDriverDefinitionConstants.PASSWORD_PROP_ID, "");
props.setProperty(
IDBConnectionProfileConstants.SAVE_PASSWORD_PROP_ID, "false");
props.setProperty(IDBDriverDefinitionConstants.USERNAME_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.USERNAME_PROP_ID));
props.setProperty(IDBDriverDefinitionConstants.URL_PROP_ID,
driver.getProperty(IDBDriverDefinitionConstants.URL_PROP_ID));
ProfileManager.getInstance().createProfile(
"DefaultDS",
"The JBoss AS Hypersonic embedded database",
IDBConnectionProfileConstants.CONNECTION_PROFILE_ID,
props,
"", false);
}
} catch (CoreException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new JBoss Server", e));
} catch (IOException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new JBoss Server", e));
} catch (ConnectionProfileException e) {
JstFirstRunPlugin.getPluginLog().log(new Status(IStatus.ERROR,
JstFirstRunPlugin.PLUGIN_ID,"Can't create new DTP " +
"Connection Profile for JBoss AS Hypersonic embedded database", e));
}
}
|
diff --git a/src/main/java/org/makersoft/shards/strategy/exit/impl/ExitOperationsSelectOneCollector.java b/src/main/java/org/makersoft/shards/strategy/exit/impl/ExitOperationsSelectOneCollector.java
index b91fa97..e0066a6 100644
--- a/src/main/java/org/makersoft/shards/strategy/exit/impl/ExitOperationsSelectOneCollector.java
+++ b/src/main/java/org/makersoft/shards/strategy/exit/impl/ExitOperationsSelectOneCollector.java
@@ -1,42 +1,42 @@
package org.makersoft.shards.strategy.exit.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSessionFactory;
import org.makersoft.shards.strategy.exit.ExitOperationsCollector;
/**
*
*/
public class ExitOperationsSelectOneCollector implements ExitOperationsCollector {
private final String statement;
public ExitOperationsSelectOneCollector(String statement){
this.statement = statement;
}
@Override
public List<Object> apply(List<Object> result) {
if(statement.endsWith("count")){
- return new AggregateExitOperation("sum").apply(result);
+ return new RowCountExitOperation().apply(result);
}else if(statement.endsWith("sum")){
return new AggregateExitOperation("sum").apply(result);
}else if(statement.endsWith("min")){
return new AggregateExitOperation("min").apply(result);
}else if(statement.endsWith("max")){
return new AggregateExitOperation("max").apply(result);
}else if(statement.endsWith("avg")){
return new AvgResultsExitOperation().apply(result);
}
- throw new UnsupportedOperationException();
+ return result;
}
@Override
public void setSqlSessionFactory(SqlSessionFactory sessionFactory) {
}
}
| false | true | public List<Object> apply(List<Object> result) {
if(statement.endsWith("count")){
return new AggregateExitOperation("sum").apply(result);
}else if(statement.endsWith("sum")){
return new AggregateExitOperation("sum").apply(result);
}else if(statement.endsWith("min")){
return new AggregateExitOperation("min").apply(result);
}else if(statement.endsWith("max")){
return new AggregateExitOperation("max").apply(result);
}else if(statement.endsWith("avg")){
return new AvgResultsExitOperation().apply(result);
}
throw new UnsupportedOperationException();
}
| public List<Object> apply(List<Object> result) {
if(statement.endsWith("count")){
return new RowCountExitOperation().apply(result);
}else if(statement.endsWith("sum")){
return new AggregateExitOperation("sum").apply(result);
}else if(statement.endsWith("min")){
return new AggregateExitOperation("min").apply(result);
}else if(statement.endsWith("max")){
return new AggregateExitOperation("max").apply(result);
}else if(statement.endsWith("avg")){
return new AvgResultsExitOperation().apply(result);
}
return result;
}
|
diff --git a/plugins/org.eclipse.m2m.atl.core.ui/src/org/eclipse/m2m/atl/core/ui/launch/AdvancedTab.java b/plugins/org.eclipse.m2m.atl.core.ui/src/org/eclipse/m2m/atl/core/ui/launch/AdvancedTab.java
index 8bb9a828..a53a7e02 100644
--- a/plugins/org.eclipse.m2m.atl.core.ui/src/org/eclipse/m2m/atl/core/ui/launch/AdvancedTab.java
+++ b/plugins/org.eclipse.m2m.atl.core.ui/src/org/eclipse/m2m/atl/core/ui/launch/AdvancedTab.java
@@ -1,447 +1,448 @@
/*******************************************************************************
* Copyright (c) 2004 INRIA.
* 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:
* INRIA - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.core.ui.launch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.m2m.atl.common.ATLLogger;
import org.eclipse.m2m.atl.core.service.CoreService;
import org.eclipse.m2m.atl.core.ui.ATLCoreUIPlugin;
import org.eclipse.m2m.atl.core.ui.Messages;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* The "advanced" tab in ATL configurations.
*
* @author <a href="mailto:[email protected]">Freddy Allilaire</a>
*/
public class AdvancedTab extends AbstractLaunchConfigurationTab {
static final String SUPERIMPOSE = "SUPERIMPOSE"; //$NON-NLS-1$
private Composite container;
private Group groupSuperimpose;
private Table tableSuperimpose;
private Button buttonSuperimpose;
private Button buttonRemoveSuperimpose;
private Group groupOthersInformation;
private Combo atlVMs;
private Map<String, Button> buttonArray = new HashMap<String, Button>();;
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NULL);
groupSuperimpose = new Group(container, SWT.NULL);
buttonSuperimpose = new Button(groupSuperimpose, SWT.CENTER);
tableSuperimpose = new Table(groupSuperimpose, SWT.FULL_SELECTION | SWT.BORDER);
buttonRemoveSuperimpose = new Button(groupSuperimpose, SWT.CENTER);
groupOthersInformation = new Group(container, SWT.NULL);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.makeColumnsEqualWidth = true;
GridData gd3 = new GridData(GridData.FILL_HORIZONTAL);
groupOthersInformation.setLayoutData(gd3);
container.setLayout(layout);
groupSuperimpose.setLayoutData(new GridData(GridData.FILL_BOTH));
/*****************************************************************************************************
* GroupSuperimpose
****************************************************************************************************/
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 4;
groupLayout.makeColumnsEqualWidth = true;
groupSuperimpose.setLayout(groupLayout);
groupSuperimpose.setText(Messages.getString("AdvancedTab.SUPERIMPOSE")); //$NON-NLS-1$
buttonSuperimpose.setText(Messages.getString("AdvancedTab.ADD")); //$NON-NLS-1$
buttonSuperimpose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
addPath(AdvancedTab.SUPERIMPOSE, tableSuperimpose);
updateLaunchConfigurationDialog();
}
});
buttonRemoveSuperimpose.setText(Messages.getString("AdvancedTab.REMOVE")); //$NON-NLS-1$
buttonRemoveSuperimpose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
removePath(tableSuperimpose);
updateLaunchConfigurationDialog();
}
});
TableLayout tableLayout = new TableLayout();
tableSuperimpose.setLayout(tableLayout);
tableLayout.addColumnData(new ColumnWeightData(100));
tableSuperimpose.setLinesVisible(true);
tableSuperimpose.setHeaderVisible(true);
// ModelChoiceTab.TABLELIBNAME
TableColumn superimposeName = new TableColumn(tableSuperimpose, SWT.LEFT);
superimposeName.setText(Messages.getString("AdvancedTab.SUPERIMPOSE")); //$NON-NLS-1$
buttonSuperimpose.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
buttonRemoveSuperimpose.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_BEGINNING));
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 3;
gd.verticalSpan = 3;
tableSuperimpose.setLayoutData(gd);
/** ***************************************** */
/*****************************************************************************************************
* Components of group3
****************************************************************************************************/
groupOthersInformation.setText(Messages.getString("MainAtlTab.OTHERSPARAMETERS")); //$NON-NLS-1$
Composite groupATLVMs = new Composite(groupOthersInformation, SWT.SHADOW_NONE);
Label atlVMLabel = new Label(groupATLVMs, SWT.NULL);
atlVMLabel.setText(Messages.getString("AdvancedTab.ATLVM")); //$NON-NLS-1$
atlVMLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
atlVMs = new Combo(groupATLVMs, SWT.NULL | SWT.READ_ONLY);
atlVMs.setItems(CoreService.getLaunchersNames());
atlVMs.select(0);
atlVMs.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
atlVMs.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
clearCheckButtons();
buildCheckButtons();
+ container.layout();
updateLaunchConfigurationDialog();
}
});
groupATLVMs.setLayout(new GridLayout(2, false));
buildCheckButtons();
groupLayout = new GridLayout();
groupLayout.numColumns = 1;
groupLayout.makeColumnsEqualWidth = true;
groupOthersInformation.setLayout(groupLayout);
container.layout();
container.pack();
setControl(container);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#updateLaunchConfigurationDialog()
*/
@Override
protected void updateLaunchConfigurationDialog() {
if (getLaunchConfigurationDialog() != null) {
ILaunchConfigurationTab[] tabs = getLaunchConfigurationDialog().getTabs();
for (int i = 0; i < tabs.length; i++) {
if (tabs[i] instanceof MainAtlTab) {
MainAtlTab mainTab = (MainAtlTab)tabs[i];
mainTab.launcherNameChanged(getLauncherName());
mainTab.superimposedChanged(createSuperimposedList());
}
}
}
super.updateLaunchConfigurationDialog();
}
private Map<String, String> getCheckButtonsValues() {
Map<String, String> options = new HashMap<String, String>();
for (Iterator<String> iterator = buttonArray.keySet().iterator(); iterator.hasNext();) {
String optionId = iterator.next();
String optionValue = new Boolean(buttonArray.get(optionId).getSelection()).toString();
options.put(optionId, optionValue);
}
return options;
}
private void clearCheckButtons() {
for (Iterator<Button> iterator = buttonArray.values().iterator(); iterator.hasNext();) {
iterator.next().dispose();
}
buttonArray = new HashMap<String, Button>();
}
private void buildCheckButtons() {
Map<String, String> options = CoreService.getLauncherOptions(atlVMs.getItem(atlVMs
.getSelectionIndex()));
for (Iterator<Map.Entry<String, String>> iterator = options.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> option = iterator.next();
final Button newCheckButton = new Button(groupOthersInformation, SWT.CHECK);
newCheckButton.setLayoutData(new GridData(GridData.FILL_BOTH));
newCheckButton.setText(option.getValue());
newCheckButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateLaunchConfigurationDialog();
}
});
buttonArray.put(option.getKey(), newCheckButton);
}
}
@SuppressWarnings("unchecked")
private void initCheckButtons(ILaunchConfiguration configuration) throws CoreException {
Map<String, String> options = configuration.getAttribute(ATLLaunchConstants.OPTIONS, Collections
.<String, String> emptyMap());
for (Iterator<String> it = buttonArray.keySet().iterator(); it.hasNext();) {
String currentButtonName = it.next();
Button currentButton = buttonArray.get(currentButtonName);
currentButton.setSelection(new Boolean(options.get(currentButtonName)).booleanValue());
}
}
public String getName() {
return ATLLaunchConstants.ADVANCED_TAB_NAME;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration)
*/
public void initializeFrom(ILaunchConfiguration configuration) {
try {
List<?> superimpose = configuration.getAttribute(ATLLaunchConstants.SUPERIMPOSE,
Collections.EMPTY_LIST);
tableSuperimpose.removeAll();
for (Iterator<?> i = superimpose.iterator(); i.hasNext();) {
String mName = (String)i.next();
TableItem item = new TableItem(tableSuperimpose, SWT.NONE);
item.setText(mName);
}
for (int item = 0; item < atlVMs.getItems().length; item++) {
if (atlVMs.getItem(item).equals(
configuration.getAttribute(ATLLaunchConstants.ATL_VM,
ATLLaunchConstants.REGULAR_VM_NAME))) {
atlVMs.select(item);
}
}
initCheckButtons(configuration);
} catch (CoreException e) {
tableSuperimpose.removeAll();
ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
private List<String> createSuperimposedList() {
List<String> superimpose = new ArrayList<String>();
for (int i = 0; i < tableSuperimpose.getItemCount(); i++) {
TableItem ti = tableSuperimpose.getItem(i);
superimpose.add(ti.getText());
}
return superimpose;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
*/
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(ATLLaunchConstants.SUPERIMPOSE, createSuperimposedList());
configuration.setAttribute(ATLLaunchConstants.OPTIONS, getCheckButtonsValues());
configuration.setAttribute(ATLLaunchConstants.ATL_VM, atlVMs.getItem(atlVMs.getSelectionIndex()));
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
*/
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#canSave()
*/
@Override
public boolean canSave() {
if (tableSuperimpose.getItemCount() != 0) {
for (int i = 0; i < tableSuperimpose.getItemCount(); i++) {
if (tableSuperimpose.getItem(i).getText().equals("")) { //$NON-NLS-1$
this.setErrorMessage(Messages.getString("AdvancedTab.GIVEPATHSUPERIMPOSE")); //$NON-NLS-1$
return false;
}
}
}
this.setErrorMessage(null);
return true;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#getImage()
*/
@Override
public Image getImage() {
return ATLCoreUIPlugin.createImage(ATLLaunchConstants.ATL_ICON_PATH);
}
/**
* This method adds a path to the given table. The path corresponds to a file in the workspace
*
* @param type
* @param table
*/
private void addPath(final String type, Table table) {
ElementTreeSelectionDialog elementTreeSelectionDialog = new ElementTreeSelectionDialog(getShell(),
new WorkbenchLabelProvider(), new WorkbenchContentProvider());
elementTreeSelectionDialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
elementTreeSelectionDialog.setMessage(Messages.getString("AdvancedTab.CHOOSE") + type); //$NON-NLS-1$
elementTreeSelectionDialog.setAllowMultiple(false);
elementTreeSelectionDialog.setDoubleClickSelects(true);
elementTreeSelectionDialog.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
boolean ret = false;
if (element instanceof IContainer) {
ret = true;
} else if (element instanceof IFile) {
IFile currentFile = (IFile)element;
if (currentFile.getFileExtension() == null) {
return false;
}
if (type == AdvancedTab.SUPERIMPOSE) {
ret = (currentFile.getFileExtension().toUpperCase()).equals("ASM"); //$NON-NLS-1$
} else {
ret = true;
}
}
return ret;
}
});
elementTreeSelectionDialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
IStatus ret = Status.CANCEL_STATUS;
if (selection.length == 1) {
if (selection[0] instanceof IFile) { // no need to verify again extension here
ret = Status.OK_STATUS;
}
}
return ret;
}
});
elementTreeSelectionDialog.open();
Object result = elementTreeSelectionDialog.getFirstResult();
if ((result != null) && (result instanceof IFile)) {
IFile currentFile = (IFile)result;
TableItem item = new TableItem(table, SWT.NONE);
item.setText(currentFile.getFullPath().toString());
}
}
/**
* Delete a path in the table.
*
* @param table
*/
private void removePath(Table table) {
int index = table.getSelectionIndex();
if (index == -1) {
messageBox(Messages.getString("AdvancedTab.CHOOSEENTRY")); //$NON-NLS-1$
return;
}
table.remove(index);
}
private String getLauncherName() {
return atlVMs.getItem(atlVMs.getSelectionIndex());
}
/**
* Display a message box with the text in parameter.
*
* @param textToDisplay
* the message
*/
public static void messageBox(String textToDisplay) {
MessageBox msgBox = new MessageBox(new Shell(), SWT.APPLICATION_MODAL | SWT.OK);
msgBox.setText(Messages.getString("AdvancedTab.ERROR")); //$NON-NLS-1$
msgBox.setMessage(textToDisplay);
msgBox.open();
}
}
| true | true | public void createControl(Composite parent) {
container = new Composite(parent, SWT.NULL);
groupSuperimpose = new Group(container, SWT.NULL);
buttonSuperimpose = new Button(groupSuperimpose, SWT.CENTER);
tableSuperimpose = new Table(groupSuperimpose, SWT.FULL_SELECTION | SWT.BORDER);
buttonRemoveSuperimpose = new Button(groupSuperimpose, SWT.CENTER);
groupOthersInformation = new Group(container, SWT.NULL);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.makeColumnsEqualWidth = true;
GridData gd3 = new GridData(GridData.FILL_HORIZONTAL);
groupOthersInformation.setLayoutData(gd3);
container.setLayout(layout);
groupSuperimpose.setLayoutData(new GridData(GridData.FILL_BOTH));
/*****************************************************************************************************
* GroupSuperimpose
****************************************************************************************************/
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 4;
groupLayout.makeColumnsEqualWidth = true;
groupSuperimpose.setLayout(groupLayout);
groupSuperimpose.setText(Messages.getString("AdvancedTab.SUPERIMPOSE")); //$NON-NLS-1$
buttonSuperimpose.setText(Messages.getString("AdvancedTab.ADD")); //$NON-NLS-1$
buttonSuperimpose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
addPath(AdvancedTab.SUPERIMPOSE, tableSuperimpose);
updateLaunchConfigurationDialog();
}
});
buttonRemoveSuperimpose.setText(Messages.getString("AdvancedTab.REMOVE")); //$NON-NLS-1$
buttonRemoveSuperimpose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
removePath(tableSuperimpose);
updateLaunchConfigurationDialog();
}
});
TableLayout tableLayout = new TableLayout();
tableSuperimpose.setLayout(tableLayout);
tableLayout.addColumnData(new ColumnWeightData(100));
tableSuperimpose.setLinesVisible(true);
tableSuperimpose.setHeaderVisible(true);
// ModelChoiceTab.TABLELIBNAME
TableColumn superimposeName = new TableColumn(tableSuperimpose, SWT.LEFT);
superimposeName.setText(Messages.getString("AdvancedTab.SUPERIMPOSE")); //$NON-NLS-1$
buttonSuperimpose.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
buttonRemoveSuperimpose.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_BEGINNING));
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 3;
gd.verticalSpan = 3;
tableSuperimpose.setLayoutData(gd);
/** ***************************************** */
/*****************************************************************************************************
* Components of group3
****************************************************************************************************/
groupOthersInformation.setText(Messages.getString("MainAtlTab.OTHERSPARAMETERS")); //$NON-NLS-1$
Composite groupATLVMs = new Composite(groupOthersInformation, SWT.SHADOW_NONE);
Label atlVMLabel = new Label(groupATLVMs, SWT.NULL);
atlVMLabel.setText(Messages.getString("AdvancedTab.ATLVM")); //$NON-NLS-1$
atlVMLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
atlVMs = new Combo(groupATLVMs, SWT.NULL | SWT.READ_ONLY);
atlVMs.setItems(CoreService.getLaunchersNames());
atlVMs.select(0);
atlVMs.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
atlVMs.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
clearCheckButtons();
buildCheckButtons();
updateLaunchConfigurationDialog();
}
});
groupATLVMs.setLayout(new GridLayout(2, false));
buildCheckButtons();
groupLayout = new GridLayout();
groupLayout.numColumns = 1;
groupLayout.makeColumnsEqualWidth = true;
groupOthersInformation.setLayout(groupLayout);
container.layout();
container.pack();
setControl(container);
}
| public void createControl(Composite parent) {
container = new Composite(parent, SWT.NULL);
groupSuperimpose = new Group(container, SWT.NULL);
buttonSuperimpose = new Button(groupSuperimpose, SWT.CENTER);
tableSuperimpose = new Table(groupSuperimpose, SWT.FULL_SELECTION | SWT.BORDER);
buttonRemoveSuperimpose = new Button(groupSuperimpose, SWT.CENTER);
groupOthersInformation = new Group(container, SWT.NULL);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.makeColumnsEqualWidth = true;
GridData gd3 = new GridData(GridData.FILL_HORIZONTAL);
groupOthersInformation.setLayoutData(gd3);
container.setLayout(layout);
groupSuperimpose.setLayoutData(new GridData(GridData.FILL_BOTH));
/*****************************************************************************************************
* GroupSuperimpose
****************************************************************************************************/
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 4;
groupLayout.makeColumnsEqualWidth = true;
groupSuperimpose.setLayout(groupLayout);
groupSuperimpose.setText(Messages.getString("AdvancedTab.SUPERIMPOSE")); //$NON-NLS-1$
buttonSuperimpose.setText(Messages.getString("AdvancedTab.ADD")); //$NON-NLS-1$
buttonSuperimpose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
addPath(AdvancedTab.SUPERIMPOSE, tableSuperimpose);
updateLaunchConfigurationDialog();
}
});
buttonRemoveSuperimpose.setText(Messages.getString("AdvancedTab.REMOVE")); //$NON-NLS-1$
buttonRemoveSuperimpose.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
removePath(tableSuperimpose);
updateLaunchConfigurationDialog();
}
});
TableLayout tableLayout = new TableLayout();
tableSuperimpose.setLayout(tableLayout);
tableLayout.addColumnData(new ColumnWeightData(100));
tableSuperimpose.setLinesVisible(true);
tableSuperimpose.setHeaderVisible(true);
// ModelChoiceTab.TABLELIBNAME
TableColumn superimposeName = new TableColumn(tableSuperimpose, SWT.LEFT);
superimposeName.setText(Messages.getString("AdvancedTab.SUPERIMPOSE")); //$NON-NLS-1$
buttonSuperimpose.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
buttonRemoveSuperimpose.setLayoutData(new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_BEGINNING));
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 3;
gd.verticalSpan = 3;
tableSuperimpose.setLayoutData(gd);
/** ***************************************** */
/*****************************************************************************************************
* Components of group3
****************************************************************************************************/
groupOthersInformation.setText(Messages.getString("MainAtlTab.OTHERSPARAMETERS")); //$NON-NLS-1$
Composite groupATLVMs = new Composite(groupOthersInformation, SWT.SHADOW_NONE);
Label atlVMLabel = new Label(groupATLVMs, SWT.NULL);
atlVMLabel.setText(Messages.getString("AdvancedTab.ATLVM")); //$NON-NLS-1$
atlVMLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
atlVMs = new Combo(groupATLVMs, SWT.NULL | SWT.READ_ONLY);
atlVMs.setItems(CoreService.getLaunchersNames());
atlVMs.select(0);
atlVMs.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
atlVMs.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
clearCheckButtons();
buildCheckButtons();
container.layout();
updateLaunchConfigurationDialog();
}
});
groupATLVMs.setLayout(new GridLayout(2, false));
buildCheckButtons();
groupLayout = new GridLayout();
groupLayout.numColumns = 1;
groupLayout.makeColumnsEqualWidth = true;
groupOthersInformation.setLayout(groupLayout);
container.layout();
container.pack();
setControl(container);
}
|
diff --git a/src/main/java/com/gitblit/LogoServlet.java b/src/main/java/com/gitblit/LogoServlet.java
index 166bf40f..c8820ed3 100644
--- a/src/main/java/com/gitblit/LogoServlet.java
+++ b/src/main/java/com/gitblit/LogoServlet.java
@@ -1,93 +1,95 @@
/*
* Copyright 2013 gitblit.com.
*
* 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.gitblit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Handles requests for logo.png
*
* @author James Moger
*
*/
public class LogoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final long lastModified = System.currentTimeMillis();
public LogoServlet() {
super();
}
@Override
protected long getLastModified(HttpServletRequest req) {
File file = GitBlit.getFileOrFolder(Keys.web.headerLogo, "${baseFolder}/logo.png");
if (file.exists()) {
return Math.max(lastModified, file.lastModified());
} else {
return lastModified;
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream is = null;
try {
String contentType = null;
File file = GitBlit.getFileOrFolder(Keys.web.headerLogo, "${baseFolder}/logo.png");
if (file.exists()) {
// custom logo
ServletContext context = request.getSession().getServletContext();
contentType = context.getMimeType(file.getName());
response.setContentLength((int) file.length());
response.setDateHeader("Last-Modified", Math.max(lastModified, file.lastModified()));
is = new FileInputStream(file);
} else {
// default logo
response.setDateHeader("Last-Modified", lastModified);
is = getClass().getResourceAsStream("/logo.png");
}
if (contentType == null) {
contentType = "image/png";
}
response.setContentType(contentType);
OutputStream os = response.getOutputStream();
byte[] buf = new byte[4096];
int bytesRead = is.read(buf);
while (bytesRead != -1) {
os.write(buf, 0, bytesRead);
bytesRead = is.read(buf);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
- is.close();
+ if(is != null) {
+ is.close();
+ }
}
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream is = null;
try {
String contentType = null;
File file = GitBlit.getFileOrFolder(Keys.web.headerLogo, "${baseFolder}/logo.png");
if (file.exists()) {
// custom logo
ServletContext context = request.getSession().getServletContext();
contentType = context.getMimeType(file.getName());
response.setContentLength((int) file.length());
response.setDateHeader("Last-Modified", Math.max(lastModified, file.lastModified()));
is = new FileInputStream(file);
} else {
// default logo
response.setDateHeader("Last-Modified", lastModified);
is = getClass().getResourceAsStream("/logo.png");
}
if (contentType == null) {
contentType = "image/png";
}
response.setContentType(contentType);
OutputStream os = response.getOutputStream();
byte[] buf = new byte[4096];
int bytesRead = is.read(buf);
while (bytesRead != -1) {
os.write(buf, 0, bytesRead);
bytesRead = is.read(buf);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream is = null;
try {
String contentType = null;
File file = GitBlit.getFileOrFolder(Keys.web.headerLogo, "${baseFolder}/logo.png");
if (file.exists()) {
// custom logo
ServletContext context = request.getSession().getServletContext();
contentType = context.getMimeType(file.getName());
response.setContentLength((int) file.length());
response.setDateHeader("Last-Modified", Math.max(lastModified, file.lastModified()));
is = new FileInputStream(file);
} else {
// default logo
response.setDateHeader("Last-Modified", lastModified);
is = getClass().getResourceAsStream("/logo.png");
}
if (contentType == null) {
contentType = "image/png";
}
response.setContentType(contentType);
OutputStream os = response.getOutputStream();
byte[] buf = new byte[4096];
int bytesRead = is.read(buf);
while (bytesRead != -1) {
os.write(buf, 0, bytesRead);
bytesRead = is.read(buf);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(is != null) {
is.close();
}
}
}
|
diff --git a/src/java/org/wings/tree/SDefaultTreeCellRenderer.java b/src/java/org/wings/tree/SDefaultTreeCellRenderer.java
index 89be5d05..f291ebf8 100644
--- a/src/java/org/wings/tree/SDefaultTreeCellRenderer.java
+++ b/src/java/org/wings/tree/SDefaultTreeCellRenderer.java
@@ -1,218 +1,218 @@
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings.tree;
import org.wings.SComponent;
import org.wings.SConstants;
import org.wings.SIcon;
import org.wings.SLabel;
import org.wings.STree;
import org.wings.util.SStringBuilder;
import org.wings.resource.ResourceManager;
/**
* @author <a href="mailto:[email protected]">Holger Engels</a>
* @author <a href="mailto:[email protected]">Armin Haaf</a>
*/
public class SDefaultTreeCellRenderer
extends SLabel
implements STreeCellRenderer
{
private SStringBuilder nameBuffer = new SStringBuilder();
// Icons
/**
* Icon used to show non-leaf nodes that aren't expanded.
*/
transient protected SIcon closedIcon;
/**
* Icon used to show leaf nodes.
*/
transient protected SIcon leafIcon;
/**
* Icon used to show non-leaf nodes that are expanded.
*/
transient protected SIcon openIcon;
/**
* Create a SDefaultTreeCellRenderer with default properties.
*/
public SDefaultTreeCellRenderer() {
setHorizontalAlignment(SConstants.LEFT);
setLeafIcon(getDefaultLeafIcon());
setClosedIcon(getDefaultClosedIcon());
setOpenIcon(getDefaultOpenIcon());
}
/**
* Returns the default icon, for the current laf, that is used to
* represent non-leaf nodes that are expanded.
*/
public SIcon getDefaultOpenIcon() {
return (SIcon) ResourceManager.getObject("TreeCG.openIcon", SIcon.class);
}
/**
* Returns the default icon, for the current laf, that is used to
* represent non-leaf nodes that are not expanded.
*/
public SIcon getDefaultClosedIcon() {
return (SIcon) ResourceManager.getObject("TreeCG.closedIcon", SIcon.class);
}
/**
* Returns the default icon, for the current laf, that is used to
* represent leaf nodes.
*/
public SIcon getDefaultLeafIcon() {
return (SIcon) ResourceManager.getObject("TreeCG.leafIcon", SIcon.class);
}
/**
* Sets the icon used to represent non-leaf nodes that are expanded.
*/
public void setOpenIcon(SIcon newIcon) {
openIcon = newIcon;
}
/**
* Returns the icon used to represent non-leaf nodes that are expanded.
*/
public SIcon getOpenIcon() {
return openIcon;
}
/**
* Sets the icon used to represent non-leaf nodes that are not expanded.
*/
public void setClosedIcon(SIcon newIcon) {
closedIcon = newIcon;
}
/**
* Returns the icon used to represent non-leaf nodes that are not
* expanded.
*/
public SIcon getClosedIcon() {
return closedIcon;
}
/**
* Sets the icon used to represent leaf nodes.
*/
public void setLeafIcon(SIcon newIcon) {
leafIcon = newIcon;
}
/**
* Returns the icon used to represent leaf nodes.
*/
public SIcon getLeafIcon() {
return leafIcon;
}
/**
* Style to use for the foreground for selected nodes.
*/
protected String selectionStyle = null;
/**
* Style to use for the foreground for non-selected nodes.
*/
protected String nonSelectionStyle = null;
public SComponent getTreeCellRendererComponent(STree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
setNameRaw(name(tree, row));
if (value == null || value.toString() == null ||
value.toString().length() == 0) {
- setText(" ");
+ setText(null);
} else {
setText(value.toString());
setToolTipText(value.toString());
}
if (!tree.isEnabled()) {
setEnabled(false);
if (leaf) {
setDisabledIcon(getLeafIcon());
} else if (expanded) {
setDisabledIcon(getOpenIcon());
} else {
setDisabledIcon(getClosedIcon());
}
} else {
setEnabled(true);
if (leaf) {
setIcon(getLeafIcon());
} else if (expanded) {
setIcon(getOpenIcon());
} else {
setIcon(getClosedIcon());
}
}
if (getStyle() == null)
setStyle(tree.getStyle());
if (getDynamicStyles() == null)
setDynamicStyles(tree.getDynamicStyles());
return this;
}
protected String name(SComponent component, int row) {
nameBuffer.setLength(0);
nameBuffer.append(component.getName()).append("_").append(row);
return nameBuffer.toString();
}
/**
* Sets the style the cell is drawn with when the cell is selected.
*/
public void setSelectionStyle(String newStyle) {
selectionStyle = newStyle;
}
/**
* Returns the style the cell is drawn with when the cell is selected.
*/
public String getSelectionStyle() {
return selectionStyle;
}
/**
* Sets the style the cell is drawn with when the cell isn't selected.
*/
public void setNonSelectionStyle(String newStyle) {
nonSelectionStyle = newStyle;
}
/**
* Returns the style the cell is drawn with when the cell isn't selected.
*/
public String getNonSelectionStyle() {
return nonSelectionStyle;
}
}
| true | true | public SComponent getTreeCellRendererComponent(STree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
setNameRaw(name(tree, row));
if (value == null || value.toString() == null ||
value.toString().length() == 0) {
setText(" ");
} else {
setText(value.toString());
setToolTipText(value.toString());
}
if (!tree.isEnabled()) {
setEnabled(false);
if (leaf) {
setDisabledIcon(getLeafIcon());
} else if (expanded) {
setDisabledIcon(getOpenIcon());
} else {
setDisabledIcon(getClosedIcon());
}
} else {
setEnabled(true);
if (leaf) {
setIcon(getLeafIcon());
} else if (expanded) {
setIcon(getOpenIcon());
} else {
setIcon(getClosedIcon());
}
}
if (getStyle() == null)
setStyle(tree.getStyle());
if (getDynamicStyles() == null)
setDynamicStyles(tree.getDynamicStyles());
return this;
}
| public SComponent getTreeCellRendererComponent(STree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
setNameRaw(name(tree, row));
if (value == null || value.toString() == null ||
value.toString().length() == 0) {
setText(null);
} else {
setText(value.toString());
setToolTipText(value.toString());
}
if (!tree.isEnabled()) {
setEnabled(false);
if (leaf) {
setDisabledIcon(getLeafIcon());
} else if (expanded) {
setDisabledIcon(getOpenIcon());
} else {
setDisabledIcon(getClosedIcon());
}
} else {
setEnabled(true);
if (leaf) {
setIcon(getLeafIcon());
} else if (expanded) {
setIcon(getOpenIcon());
} else {
setIcon(getClosedIcon());
}
}
if (getStyle() == null)
setStyle(tree.getStyle());
if (getDynamicStyles() == null)
setDynamicStyles(tree.getDynamicStyles());
return this;
}
|
diff --git a/src/main/java/com/github/croesch/micro_debug/argument/AError.java b/src/main/java/com/github/croesch/micro_debug/argument/AError.java
index 17ee411..08b7bd6 100644
--- a/src/main/java/com/github/croesch/micro_debug/argument/AError.java
+++ b/src/main/java/com/github/croesch/micro_debug/argument/AError.java
@@ -1,84 +1,84 @@
/*
* Copyright (C) 2011-2012 Christian Roesch
*
* This file is part of micro-debug.
*
* micro-debug 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.
*
* micro-debug 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 micro-debug. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.croesch.micro_debug.argument;
import java.util.logging.Logger;
import com.github.croesch.micro_debug.commons.Printer;
import com.github.croesch.micro_debug.i18n.Text;
/**
* Represents an argument to represent an invalid argument.
*
* @author croesch
* @since Date: Feb 28, 2012
*/
public abstract class AError extends AArgument {
/**
* Prints the given array of arguments as an error. Returns whether the application can continue.
*
* @since Date: Jan 14, 2012
* @param params the arguments to be printed as an error
* @param errorText the {@link Text} that is used to print each argument
* @param errorArgument the type of error that the arguments are
* @return <code>true</code>, if the application can start,<br>
* <code>false</code> otherwise
*/
final boolean printError(final String[] params, final Text errorText, final AArgument errorArgument) {
if (params == null || params.length == 0) {
// if there are no arguments then calling this method might be a mistake
Logger.getLogger(getClass().getName()).warning("No parameters passed to execution of '" + errorArgument.name()
+ "'");
return true;
}
// flag, because we still might have a corrupt array
boolean argumentFound = false;
for (final String param : params) {
if (param != null) {
// we have the argument, so print it
Printer.printErrorln(errorText.text(param));
argumentFound = true;
}
}
if (argumentFound) {
- Help.getInstance().execute();
+ AArgument.of("-h").execute();
}
return !argumentFound;
}
@Override
public final boolean execute(final String ... params) {
return printError(params, getErrorText(), this);
}
@Override
protected final String name() {
return "ERROR";
}
/**
* Returns the {@link Text} to visualise the problem of the invalid argument.
*
* @since Date: Feb 28, 2012
* @return the {@link Text} that describes why the argument is invalid.
*/
protected abstract Text getErrorText();
}
| true | true | final boolean printError(final String[] params, final Text errorText, final AArgument errorArgument) {
if (params == null || params.length == 0) {
// if there are no arguments then calling this method might be a mistake
Logger.getLogger(getClass().getName()).warning("No parameters passed to execution of '" + errorArgument.name()
+ "'");
return true;
}
// flag, because we still might have a corrupt array
boolean argumentFound = false;
for (final String param : params) {
if (param != null) {
// we have the argument, so print it
Printer.printErrorln(errorText.text(param));
argumentFound = true;
}
}
if (argumentFound) {
Help.getInstance().execute();
}
return !argumentFound;
}
| final boolean printError(final String[] params, final Text errorText, final AArgument errorArgument) {
if (params == null || params.length == 0) {
// if there are no arguments then calling this method might be a mistake
Logger.getLogger(getClass().getName()).warning("No parameters passed to execution of '" + errorArgument.name()
+ "'");
return true;
}
// flag, because we still might have a corrupt array
boolean argumentFound = false;
for (final String param : params) {
if (param != null) {
// we have the argument, so print it
Printer.printErrorln(errorText.text(param));
argumentFound = true;
}
}
if (argumentFound) {
AArgument.of("-h").execute();
}
return !argumentFound;
}
|
diff --git a/core/src/main/java/hudson/model/RunMap.java b/core/src/main/java/hudson/model/RunMap.java
index faeb2b08b..19b816911 100644
--- a/core/src/main/java/hudson/model/RunMap.java
+++ b/core/src/main/java/hudson/model/RunMap.java
@@ -1,186 +1,190 @@
package hudson.model;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* {@link Map} from build number to {@link Run}.
*
* <p>
* This class is multi-thread safe by using copy-on-write technique,
* and it also updates the bi-directional links within {@link Run}
* accordingly.
*
* @author Kohsuke Kawaguchi
*/
public final class RunMap<R extends Run<?,R>> extends AbstractMap<Integer,R> implements SortedMap<Integer,R> {
// copy-on-write map
private transient volatile SortedMap<Integer,R> builds =
new TreeMap<Integer,R>(COMPARATOR);
/**
* Read-only view of this map.
*/
private final SortedMap<Integer,R> view = Collections.unmodifiableSortedMap(this);
public Set<Entry<Integer,R>> entrySet() {
// since the map is copy-on-write, make sure no one modifies it
return Collections.unmodifiableSet(builds.entrySet());
}
public synchronized R put(R value) {
return put(value.getNumber(),value);
}
public synchronized R put(Integer key, R value) {
// copy-on-write update
TreeMap<Integer,R> m = new TreeMap<Integer,R>(builds);
R r = update(m, key, value);
this.builds = m;
return r;
}
public synchronized void putAll(Map<? extends Integer,? extends R> rhs) {
// copy-on-write update
TreeMap<Integer,R> m = new TreeMap<Integer,R>(builds);
for (Map.Entry<? extends Integer,? extends R> e : rhs.entrySet())
update(m, e.getKey(), e.getValue());
this.builds = m;
}
private R update(TreeMap<Integer, R> m, Integer key, R value) {
// things are bit tricky because this map is order so that the newest one comes first,
// yet 'nextBuild' refers to the newer build.
R first = m.isEmpty() ? null : m.get(m.firstKey());
R r = m.put(key, value);
SortedMap<Integer,R> head = m.headMap(key);
if(!head.isEmpty()) {
R prev = m.get(head.lastKey());
value.previousBuild = prev.previousBuild;
value.nextBuild = prev;
if(value.previousBuild!=null)
value.previousBuild.nextBuild = value;
prev.previousBuild=value;
} else {
value.previousBuild = first;
value.nextBuild = null;
if(first!=null)
first.nextBuild = value;
}
return r;
}
public synchronized boolean remove(R run) {
if(run.nextBuild!=null)
run.nextBuild.previousBuild = run.previousBuild;
if(run.previousBuild!=null)
run.previousBuild.nextBuild = run.nextBuild;
// copy-on-write update
TreeMap<Integer,R> m = new TreeMap<Integer,R>(builds);
R r = m.remove(run.getNumber());
this.builds = m;
return r!=null;
}
public synchronized void reset(TreeMap<Integer,R> builds) {
this.builds = new TreeMap<Integer,R>(COMPARATOR);
putAll(builds);
}
/**
* Gets the read-only view of this map.
*/
public SortedMap<Integer,R> getView() {
return view;
}
//
// SortedMap delegation
//
public Comparator<? super Integer> comparator() {
return builds.comparator();
}
public SortedMap<Integer, R> subMap(Integer fromKey, Integer toKey) {
return builds.subMap(fromKey, toKey);
}
public SortedMap<Integer, R> headMap(Integer toKey) {
return builds.headMap(toKey);
}
public SortedMap<Integer, R> tailMap(Integer fromKey) {
return builds.tailMap(fromKey);
}
public Integer firstKey() {
return builds.firstKey();
}
public Integer lastKey() {
return builds.lastKey();
}
public static final Comparator<Comparable> COMPARATOR = new Comparator<Comparable>() {
public int compare(Comparable o1, Comparable o2) {
return -o1.compareTo(o2);
}
};
/**
* {@link Run} factory.
*/
public interface Constructor<R extends Run<?,R>> {
R create(File dir) throws IOException;
}
/**
* Fills in {@link RunMap} by loading build records from the file system.
*
* @param job
* Job that owns this map.
* @param cons
* Used to create new instance of {@link Run}.
*/
public synchronized void load(Job job, Constructor<R> cons) {
TreeMap<Integer,R> builds = new TreeMap<Integer,R>(RunMap.COMPARATOR);
File buildDir = job.getBuildDir();
buildDir.mkdirs();
String[] buildDirs = buildDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
- return new File(dir,name).isDirectory();
+ // HUDSON-1461 sometimes create bogus data directories with impossible dates, such as year 0.
+ // Date object doesn't roundtrip year 0 (year is -2,-1,+1,+2,... and there's no zero),
+ // so we eventually fail to load this data.
+ // so don't even bother trying.k
+ return !name.startsWith("0000") && new File(dir,name).isDirectory();
}
});
for( String build : buildDirs ) {
File d = new File(buildDir,build);
if(new File(d,"build.xml").exists()) {
// if the build result file isn't in the directory, ignore it.
try {
R b = cons.create(d);
builds.put( b.getNumber(), b );
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationError e) {
e.printStackTrace();
}
}
}
reset(builds);
}
}
| true | true | public synchronized void load(Job job, Constructor<R> cons) {
TreeMap<Integer,R> builds = new TreeMap<Integer,R>(RunMap.COMPARATOR);
File buildDir = job.getBuildDir();
buildDir.mkdirs();
String[] buildDirs = buildDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return new File(dir,name).isDirectory();
}
});
for( String build : buildDirs ) {
File d = new File(buildDir,build);
if(new File(d,"build.xml").exists()) {
// if the build result file isn't in the directory, ignore it.
try {
R b = cons.create(d);
builds.put( b.getNumber(), b );
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationError e) {
e.printStackTrace();
}
}
}
reset(builds);
}
| public synchronized void load(Job job, Constructor<R> cons) {
TreeMap<Integer,R> builds = new TreeMap<Integer,R>(RunMap.COMPARATOR);
File buildDir = job.getBuildDir();
buildDir.mkdirs();
String[] buildDirs = buildDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// HUDSON-1461 sometimes create bogus data directories with impossible dates, such as year 0.
// Date object doesn't roundtrip year 0 (year is -2,-1,+1,+2,... and there's no zero),
// so we eventually fail to load this data.
// so don't even bother trying.k
return !name.startsWith("0000") && new File(dir,name).isDirectory();
}
});
for( String build : buildDirs ) {
File d = new File(buildDir,build);
if(new File(d,"build.xml").exists()) {
// if the build result file isn't in the directory, ignore it.
try {
R b = cons.create(d);
builds.put( b.getNumber(), b );
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationError e) {
e.printStackTrace();
}
}
}
reset(builds);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.