answer
stringlengths 17
10.2M
|
|---|
package com.biermacht.brews.xml;
import android.util.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.biermacht.brews.ingredient.Fermentable;
import com.biermacht.brews.recipe.*;
import java.util.*;
import com.biermacht.brews.ingredient.*;
import com.biermacht.brews.utils.*;
import com.biermacht.brews.utils.Stack;
public class RecipeXmlReader extends DefaultHandler {
// Hold the current elements
boolean currentElement = false;
String currentValue = null;
// Lists to store all the things
ArrayList<Recipe> list = new ArrayList<Recipe>();
ArrayList<Ingredient> fermList = new ArrayList<Ingredient>();
ArrayList<Ingredient> hopList = new ArrayList<Ingredient>();
ArrayList<Ingredient> yeastList = new ArrayList<Ingredient>();
ArrayList<Ingredient> miscList = new ArrayList<Ingredient>();
ArrayList<BeerStyle> beerStyleList = new ArrayList<BeerStyle>();
ArrayList<MashProfile> mashProfileList = new ArrayList<MashProfile>();
ArrayList<MashStep> mashStepList = new ArrayList<MashStep>();
// Objects for each type of thing
Recipe r = new Recipe("");
Fermentable f = new Fermentable("");
Hop h = new Hop("");
Yeast y = new Yeast("");
Misc misc = new Misc("");
BeerStyle style = new BeerStyle("");
MashProfile profile = new MashProfile(r);
MashStep mashStep = new MashStep(r);
// How we know what thing we're looking at
Stack thingTypeStack = new Stack();
/**
* The return methods that will return lists of all of the elements
* that have been parsed in the current file.
*/
public ArrayList<Recipe> getRecipes() {
return list;
}
public ArrayList<Ingredient> getFermentables(){
return fermList;
}
public ArrayList<Ingredient> getHops() {
return hopList;
}
public ArrayList<Ingredient> getYeasts() {
return yeastList;
}
public ArrayList<Ingredient> getMiscs() {
return miscList;
}
public ArrayList<BeerStyle> getBeerStyles()
{
return beerStyleList;
}
public ArrayList<MashProfile> getMashProfiles()
{
return mashProfileList;
}
public ArrayList<MashStep> getMashSteps()
{
return mashStepList;
}
/**
* This gets called whenever we encounter a new start element. In this function
* we create the new object to be populated and set the type of what we are looking at
* so we can properly parse the following tags
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
// We encounter a new recipe
if (qName.equalsIgnoreCase("RECIPES"))
{
thingTypeStack.push(qName);
}
// We encounter a new recipe
if (qName.equalsIgnoreCase("RECIPE"))
{
thingTypeStack.push(qName);
r = new Recipe("");
}
// We encounter a new fermentables list
if (qName.equalsIgnoreCase("FERMENTABLES"))
{
thingTypeStack.push(qName);
}
// We encounter a new hops list
if (qName.equalsIgnoreCase("HOPS"))
{
thingTypeStack.push(qName);
}
// We encounter a new hop
if (qName.equalsIgnoreCase("HOP"))
{
thingTypeStack.push(qName);
h = new Hop("");
}
// We encounter a new fermentable
if (qName.equalsIgnoreCase("FERMENTABLE"))
{
thingTypeStack.push(qName);
f = new Fermentable("");
}
// We encounter a new yeast list
if (qName.equalsIgnoreCase("YEASTS"))
{
thingTypeStack.push(qName);
}
// We encounter a new yeast
if (qName.equalsIgnoreCase("YEAST"))
{
thingTypeStack.push(qName);
y = new Yeast("");
}
// Encounter new misc
if (qName.equalsIgnoreCase("MISC"))
{
thingTypeStack.push(qName);
misc = new Misc("");
}
// Encounter new miscs list
if (qName.equalsIgnoreCase("MISCS"))
{
thingTypeStack.push(qName);
}
if (qName.equalsIgnoreCase("WATERS"))
{
thingTypeStack.push(qName);
}
if (qName.equalsIgnoreCase("WATER"))
{
thingTypeStack.push(qName);
}
// Encounter new style
if (qName.equalsIgnoreCase("STYLE"))
{
thingTypeStack.push(qName);
style = new BeerStyle("");
}
// Encounter new style list
if (qName.equalsIgnoreCase("STYLES"))
{
thingTypeStack.push(qName);
}
// Encounter new mash profile list
if (qName.equalsIgnoreCase("MASHS"))
{
thingTypeStack.push(qName);
}
// Encounter new mash profile
if (qName.equalsIgnoreCase("MASH"))
{
thingTypeStack.push(qName);
profile = new MashProfile(r);
}
// Encounter new mash step
if (qName.equalsIgnoreCase("MASH_STEP"))
{
thingTypeStack.push(qName);
mashStep = new MashStep(r);
}
// Encounter new mash step list
if (qName.equalsIgnoreCase("MASH_STEPS"))
{
thingTypeStack.push(qName);
}
if (qName.equalsIgnoreCase("EQUIPMENT"))
{
thingTypeStack.push(qName);
}
if (qName.equalsIgnoreCase("EQUIPMENTS"))
{
thingTypeStack.push(qName);
}
}
/**
* This gets called when we run into an end element. The value of the element is stored in
* the variable 'currentValue' and is assigned appropriately based on thingType.
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
Log.d("RecipeXMLReader", "Reading values: " + qName + ": " + currentValue);
if (qName.equalsIgnoreCase("RECIPE"))
// We've finished a new recipe
{
list.add(r);
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("HOPS"))
// We have finished a list of hops.
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("FERMENTABLES"))
// We have finished a list of fermentables
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("YEASTS"))
// We have finished a list of yeasts
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("MISCS"))
// We have finished a list of miscs
{
thingTypeStack.pop();
return;
}
if (qName.equalsIgnoreCase("WATERS"))
{
// TODO
thingTypeStack.pop();
return;
}
if (qName.equalsIgnoreCase("WATER"))
{
// TODO
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("STYLES"))
// We have finished a list of styles
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("MASH_STEPS"))
// Finished a list of mash steps
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("MASHS"))
// Finished a list of MASHES
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("FERMENTABLE"))
// Finished a fermentable. Add it to recipe and fermentables list.
{
thingTypeStack.pop();
fermList.add(f);
// BeerXML doesn't specify a time field for fermentables...
// We need to hack it up in here...
if(r.getType().equals(Recipe.EXTRACT))
{
if(f.getFermentableType().equals(Fermentable.TYPE_GRAIN))
{
f.setTime(20);
}
else if (f.getFermentableType().equals(Fermentable.TYPE_EXTRACT))
{
f.setTime(r.getBoilTime());
}
}
r.addIngredient(f);
return;
}
else if (qName.equalsIgnoreCase("HOP"))
// Finished a hop. Add to recipe and list
{
thingTypeStack.pop();
r.addIngredient(h);
hopList.add(h);
Log.d("RecipeHandler", "Added hop: " + h.getName());
return;
}
else if (qName.equalsIgnoreCase("YEAST"))
// Finished a yeast. Add to recipe and list
{
thingTypeStack.pop();
r.addIngredient(y);
yeastList.add(y);
return;
}
else if (qName.equalsIgnoreCase("MISC"))
// Finished a misc. Add to recipe and list
{
thingTypeStack.pop();
r.addIngredient(misc);
miscList.add(misc);
return;
}
else if (qName.equalsIgnoreCase("STYLE"))
// Finished a style. Add to recipe and list
{
thingTypeStack.pop();
beerStyleList.add(style);
r.setStyle(style);
return;
}
else if (qName.equalsIgnoreCase("MASH_STEP"))
// Finisehd a mash step, add to list and profile
{
thingTypeStack.pop();
mashStepList.add(mashStep);
profile.addMashStep(mashStep);
return;
}
else if (qName.equalsIgnoreCase("MASH"))
// Finished a mash profile. Add to recipe and list
{
thingTypeStack.pop();
r.setMashProfile(profile);
mashProfileList.add(profile);
return;
}
else if (qName.equalsIgnoreCase("EQUIPMENT"))
{
thingTypeStack.pop();
return;
}
else if (qName.equalsIgnoreCase("EQUIPMENTS"))
{
thingTypeStack.pop();
return;
}
if (thingTypeStack.read().equalsIgnoreCase("RECIPE"))
{
if (qName.equalsIgnoreCase("NAME"))
{
r.setRecipeName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
r.setVersion(Integer.parseInt(currentValue));
}
else if (qName.equalsIgnoreCase("TYPE"))
{
String type = "NULL";
if (currentValue.equalsIgnoreCase(Recipe.EXTRACT))
type = Recipe.EXTRACT;
if (currentValue.contains("Extract"))
type = Recipe.EXTRACT;
if (currentValue.equalsIgnoreCase(Recipe.ALL_GRAIN))
type = Recipe.ALL_GRAIN;
if (currentValue.equalsIgnoreCase(Recipe.PARTIAL_MASH))
type = Recipe.PARTIAL_MASH;
r.setType(type);
}
else if (qName.equalsIgnoreCase("NOTES"))
{
r.setNotes(currentValue);
}
else if (qName.equalsIgnoreCase("BREWER"))
{
r.setBrewer(currentValue);
}
else if (qName.equalsIgnoreCase("ASST_BREWER"))
{
// TODO
}
else if (qName.equalsIgnoreCase("BATCH_SIZE"))
{
double s = Float.parseFloat(currentValue);
r.setBeerXmlStandardBatchSize(s);
}
else if (qName.equalsIgnoreCase("BOIL_SIZE"))
{
double s = Float.parseFloat(currentValue);
r.setBeerXmlStandardBoilSize(s);
}
else if (qName.equalsIgnoreCase("BOIL_TIME"))
{
r.setBoilTime((int)Float.parseFloat(currentValue));
}
else if (qName.equalsIgnoreCase("EFFICIENCY"))
{
r.setEfficiency(Float.parseFloat(currentValue));
}
else if (qName.equalsIgnoreCase("FERMENTATION_STAGES"))
{
r.setFermentationStages(Integer.parseInt(currentValue));
}
else if (qName.equalsIgnoreCase("PRIMARY_AGE"))
{
r.setFermentationAge(Recipe.STAGE_PRIMARY, (int) Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("PRIMARY_TEMP"))
{
r.setBeerXmlStandardFermentationTemp(Recipe.STAGE_PRIMARY, Float.parseFloat(currentValue));
}
else if (qName.equalsIgnoreCase("SECONDARY_AGE"))
{
r.setFermentationAge(Recipe.STAGE_SECONDARY, (int) Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("SECONDARY_TEMP"))
{
r.setBeerXmlStandardFermentationTemp(Recipe.STAGE_SECONDARY, Float.parseFloat(currentValue));
}
else if (qName.equalsIgnoreCase("TERTIARY_AGE"))
{
r.setFermentationAge(Recipe.STAGE_TERTIARY, (int) Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("TERTIARY_TEMP"))
{
r.setBeerXmlStandardFermentationTemp(Recipe.STAGE_TERTIARY, Float.parseFloat(currentValue));
}
else if (qName.equalsIgnoreCase("DISPLAY_OG"))
{
if (Units.getUnitsFromDisplayAmount(currentValue).equals(Units.PLATO))
r.setMeasuredOG(Units.platoToGravity(Units.getAmountFromDisplayAmount(currentValue)));
else
r.setMeasuredOG(Units.getAmountFromDisplayAmount(currentValue));
}
else if (qName.equalsIgnoreCase("DISPLAY_FG"))
{
if (Units.getUnitsFromDisplayAmount(currentValue).equals(Units.PLATO))
r.setMeasuredFG(Units.platoToGravity(Units.getAmountFromDisplayAmount(currentValue)));
else
r.setMeasuredFG(Units.getAmountFromDisplayAmount(currentValue));
}
else if (qName.equalsIgnoreCase("CARBONATION"))
{
r.setCarbonation(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("FORCED_CARBONATION"))
{
r.setIsForceCarbonated(currentValue.equalsIgnoreCase("TRUE"));
}
else if (qName.equalsIgnoreCase("CARBONATION_TEMP"))
{
r.setBeerXmlStandardCarbonationTemp(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("CALORIES"))
{
// TODO
}
}
if (thingTypeStack.read().equalsIgnoreCase("FERMENTABLE"))
// We are looking at a fermentable
// Do all of the fermentable things below
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
f.setName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
// TODO: Set version!
}
else if (qName.equalsIgnoreCase("TYPE"))
{
String type = "NULL";
if (currentValue.equalsIgnoreCase(Fermentable.TYPE_ADJUNCT))
type = Fermentable.TYPE_ADJUNCT;
if (currentValue.equalsIgnoreCase(Fermentable.TYPE_EXTRACT))
type = Fermentable.TYPE_EXTRACT;
if (currentValue.contains("Extract"))
type = Fermentable.TYPE_EXTRACT;
if (currentValue.equalsIgnoreCase(Fermentable.TYPE_GRAIN))
type = Fermentable.TYPE_GRAIN;
if (currentValue.equalsIgnoreCase(Fermentable.TYPE_SUGAR))
type = Fermentable.TYPE_SUGAR;
f.setFermentableType(type);
}
else if (qName.equalsIgnoreCase("AMOUNT"))
{
double amt = Double.parseDouble(currentValue);
f.setBeerXmlStandardAmount(amt);
}
else if (qName.equalsIgnoreCase("YIELD"))
{
double yield = Double.parseDouble(currentValue);
f.setYield(yield);
}
else if (qName.equalsIgnoreCase("COLOR"))
{
double color = Double.parseDouble(currentValue);
f.setLovibondColor(color);
}
else if (qName.equalsIgnoreCase("ADD_AFTER_BOIL"))
{
boolean aab = (currentValue.equalsIgnoreCase("FALSE")) ? false : true;
f.setAddAfterBoil(aab);
}
else if (qName.equalsIgnoreCase("ORIGIN"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("SUPPLIER"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("NOTES"))
{
f.setShortDescription(currentValue);
}
else if (qName.equalsIgnoreCase("COARSE_FINE_DIFF"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("MOISTURE"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("DIASTATIC_POWER"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("PROTEIN"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("MAX_IN_BATCH"))
{
if (currentElement != false)
{
double maxInBatch = Double.parseDouble(currentValue);
f.setMaxInBatch(maxInBatch);
}
}
else if (qName.equalsIgnoreCase("RECOMMEND_MASH"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("IBU_GAL_PER_LB"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("DISPLAY_AMOUNT"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("INVENTORY"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("POTENTIAL"))
{
// TODO: FUCK THIS SHIT
}
else if (qName.equalsIgnoreCase("DISPLAY_COLOR"))
{
// TODO: Add support for this field
}
}
else if (thingTypeStack.read().equalsIgnoreCase("HOP"))
// We are looking at a hop
// Set all the hop things here
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
h.setName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
// TODO: Set version!
}
else if (qName.equalsIgnoreCase("ORIGIN"))
{
h.setOrigin(currentValue);
}
else if (qName.equalsIgnoreCase("ALPHA"))
{
h.setAlphaAcidContent(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("AMOUNT"))
{
double amt = Double.parseDouble(currentValue);
h.setBeerXmlStandardAmount(amt);
}
else if (qName.equalsIgnoreCase("USE"))
{
String use = "";
if (currentValue.equalsIgnoreCase(Hop.USE_AROMA))
use = Hop.USE_AROMA;
if (currentValue.equalsIgnoreCase(Hop.USE_BOIL));
use = Hop.USE_BOIL;
if (currentValue.equalsIgnoreCase(Hop.USE_DRY_HOP))
use = Hop.USE_DRY_HOP;
if (currentValue.equalsIgnoreCase(Hop.USE_MASH))
use = Hop.USE_MASH;
if (currentValue.equalsIgnoreCase(Hop.USE_FIRST_WORT))
use = Hop.USE_FIRST_WORT;
h.setUse(use);
}
else if (qName.equalsIgnoreCase("TIME"))
{
h.setBeerXmlStandardTime((int) Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("NOTES"))
{
h.setDescription(currentValue);
}
else if (qName.equalsIgnoreCase("TYPE"))
{
String type = "";
if (currentValue.equalsIgnoreCase(Hop.TYPE_AROMA))
type = Hop.TYPE_AROMA;
if (currentValue.equalsIgnoreCase(Hop.TYPE_BITTERING))
type = Hop.TYPE_BITTERING;
if (currentValue.equalsIgnoreCase(Hop.TYPE_BOTH))
type = Hop.TYPE_BOTH;
h.setHopType(type);
}
else if (qName.equalsIgnoreCase("FORM"))
{
String form = "";
if (currentValue.equalsIgnoreCase(Hop.FORM_PELLET))
form = Hop.FORM_PELLET;
if (currentValue.equalsIgnoreCase(Hop.FORM_WHOLE))
form = Hop.FORM_WHOLE;
if (currentValue.equalsIgnoreCase(Hop.FORM_PLUG))
form = Hop.FORM_PLUG;
h.setForm(form);
}
}
else if (thingTypeStack.read().equalsIgnoreCase("YEAST"))
// We are looking at a yeast
// Set the yeast fiels here
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
y.setName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
int version = Integer.parseInt(currentValue);
y.setVersion(version);
}
else if (qName.equalsIgnoreCase("TYPE"))
{
String type = "Invalid Type";
if (currentValue.equalsIgnoreCase(Yeast.TYPE_ALE))
type = Yeast.TYPE_ALE;
if (currentValue.equalsIgnoreCase(Yeast.TYPE_LAGER))
type = Yeast.TYPE_LAGER;
if (currentValue.equalsIgnoreCase(Yeast.TYPE_WHEAT))
type = Yeast.TYPE_WHEAT;
if (currentValue.equalsIgnoreCase(Yeast.TYPE_WINE))
type = Yeast.TYPE_WINE;
if (currentValue.equalsIgnoreCase(Yeast.TYPE_CHAMPAGNE))
type = Yeast.TYPE_CHAMPAGNE;
y.setType(type);
}
else if (qName.equalsIgnoreCase("FORM"))
{
String form = "Invalid Form";
if (currentValue.equalsIgnoreCase(Yeast.FORM_CULTURE))
form = Yeast.FORM_CULTURE;
if (currentValue.equalsIgnoreCase(Yeast.FORM_DRY))
form = Yeast.FORM_DRY;
if (currentValue.equalsIgnoreCase(Yeast.FORM_LIQUID))
form = Yeast.FORM_LIQUID;
y.setForm(form);
}
else if (qName.equalsIgnoreCase("AMOUNT"))
{
double amt = Double.parseDouble(currentValue);
y.setBeerXmlStandardAmount(amt);
}
else if (qName.equalsIgnoreCase("AMOUNT_IS_WEIGHT"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("LABORATORY"))
{
y.setLaboratory(currentValue);
}
else if (qName.equalsIgnoreCase("PRODUCT_ID"))
{
y.setProductId(currentValue);
}
else if (qName.equalsIgnoreCase("MIN_TEMPERATURE"))
{
double minTemp = Double.parseDouble(currentValue);
y.setMinTemp(minTemp);
}
else if (qName.equalsIgnoreCase("MAX_TEMPERATURE"))
{
double maxTemp = Double.parseDouble(currentValue);
y.setMaxTemp(maxTemp);
}
else if (qName.equalsIgnoreCase("FLOCCULATION"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("ATTENUATION"))
{
double attenuation = Double.parseDouble(currentValue);
y.setAttenuation(attenuation);
}
else if (qName.equalsIgnoreCase("NOTES"))
{
y.setNotes(currentValue);
}
else if (qName.equalsIgnoreCase("BEST_FOR"))
{
y.setBestFor(currentValue);
}
else if (qName.equalsIgnoreCase("MAX_REUSE"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("TIMES_CULTURED"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("ADD_TO_SECONDARY"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("DISPLAY_AMOUNT"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("DISP_MIN_TEMP"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("DISP_MAX_TEMP"))
{
// TODO: Add support for this field
}
else if (qName.equalsIgnoreCase("INVENTORY"))
{
// TODO: FUCK THIS SHIT
}
else if (qName.equalsIgnoreCase("CULTURE_DATE"))
{
// TODO: Add support for this field
}
}
else if (thingTypeStack.read().equalsIgnoreCase("MISC"))
// We are looking at a misc
// Do all of the misc things below
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
misc.setName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
misc.setVersion(Integer.parseInt(currentValue));
}
else if (qName.equalsIgnoreCase("TYPE"))
{
String type = Misc.TYPE_OTHER;
if (currentValue.equalsIgnoreCase(Misc.TYPE_SPICE))
type = Misc.TYPE_SPICE;
if (currentValue.equalsIgnoreCase(Misc.TYPE_FINING))
type = Misc.TYPE_FINING;
if (currentValue.equalsIgnoreCase(Misc.TYPE_FLAVOR))
type = Misc.TYPE_FLAVOR;
if (currentValue.equalsIgnoreCase(Misc.TYPE_HERB))
type = Misc.TYPE_HERB;
if (currentValue.equalsIgnoreCase(Misc.TYPE_WATER_AGENT))
type = Misc.TYPE_WATER_AGENT;
if (currentValue.equalsIgnoreCase(Misc.TYPE_OTHER))
type = Misc.TYPE_OTHER;
misc.setMiscType(type);
}
else if (qName.equalsIgnoreCase("AMOUNT"))
{
double amt = Double.parseDouble(currentValue);
misc.setBeerXmlStandardAmount(amt);
}
else if (qName.equalsIgnoreCase("DISPLAY_AMOUNT"))
{
String dunit = Units.getUnitsFromDisplayAmount(currentValue);
//double amt = Units.getAmountFromDisplayAmount(currentValue);
misc.setDisplayUnits(dunit);
//misc.setDisplayAmount(amt);
}
else if (qName.equalsIgnoreCase("DISPLAY_TIME"))
{
double time = Units.getAmountFromDisplayAmount(currentValue);
misc.setTime((int)time);
}
else if (qName.equalsIgnoreCase("USE"))
{
String type = "NO_TYPE";
if (currentValue.equalsIgnoreCase(Misc.USE_BOIL))
type = Misc.USE_BOIL;
if (currentValue.equalsIgnoreCase(Misc.USE_BOTTLING))
type = Misc.USE_BOTTLING;
if (currentValue.equalsIgnoreCase(Misc.USE_MASH))
type = Misc.USE_MASH;
if (currentValue.equalsIgnoreCase(Misc.USE_PRIMARY))
type = Misc.USE_PRIMARY;
if (currentValue.equalsIgnoreCase(Misc.USE_SECONDARY))
type = Misc.USE_SECONDARY;
misc.setUse(type);
}
else if (qName.equalsIgnoreCase("NOTES"))
{
misc.setShortDescription(currentValue);
}
else if (qName.equalsIgnoreCase("AMOUNT_IS_WEIGHT"))
{
if (currentValue.equalsIgnoreCase("TRUE"))
misc.setAmountIsWeight(true);
else
misc.setAmountIsWeight(false);
}
else if (qName.equalsIgnoreCase("USE_FOR"))
{
misc.setUseFor(currentValue);
}
}
else if (thingTypeStack.read().equalsIgnoreCase("STYLE"))
// We are looking at a style
// Do all of the style things below
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
style.setName(currentValue);
}
else if (qName.equalsIgnoreCase("CATEGORY"))
{
style.setCategory(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
style.setVersion(Integer.parseInt(currentValue));
}
else if (qName.equalsIgnoreCase("CATEGORY_NUMBER"))
{
style.setCategoryNumber(currentValue);
}
else if (qName.equalsIgnoreCase("STYLE_LETTER"))
{
style.setStyleLetter(currentValue);
}
else if (qName.equalsIgnoreCase("STYLE_GUIDE"))
{
style.setStyleGuide(currentValue);
}
else if (qName.equalsIgnoreCase("TYPE"))
{
String type = "NULL";
if (currentValue.equalsIgnoreCase(BeerStyle.TYPE_ALE))
type = BeerStyle.TYPE_ALE;
if (currentValue.equalsIgnoreCase(BeerStyle.TYPE_CIDER))
type = BeerStyle.TYPE_CIDER;
if (currentValue.equalsIgnoreCase(BeerStyle.TYPE_LAGER))
type = BeerStyle.TYPE_LAGER;
if (currentValue.equalsIgnoreCase(BeerStyle.TYPE_MEAD))
type = BeerStyle.TYPE_MEAD;
if (currentValue.equalsIgnoreCase(BeerStyle.TYPE_MIXED))
type = BeerStyle.TYPE_MIXED;
if (currentValue.equalsIgnoreCase(BeerStyle.TYPE_WHEAT))
type = BeerStyle.TYPE_WHEAT;
style.setType(type);
}
else if (qName.equalsIgnoreCase("OG_MIN"))
{
style.setMinOg(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("OG_MAX"))
{
style.setMaxOg(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("FG_MIN"))
{
style.setMinFg(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("FG_MAX"))
{
style.setMaxFg(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("IBU_MIN"))
{
style.setMinIbu(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("IBU_MAX"))
{
style.setMaxIbu(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("COLOR_MIN"))
{
style.setMinColor(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("COLOR_MAX"))
{
style.setMaxColor(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("ABV_MIN"))
{
style.setMinAbv(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("ABV_MAX"))
{
style.setMaxAbv(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("NOTES"))
{
style.setNotes(currentValue);
}
else if (qName.equalsIgnoreCase("PROFILE"))
{
style.setProfile(currentValue);
}
else if (qName.equalsIgnoreCase("INGREDIENTS"))
{
style.setIngredients(currentValue);
}
else if (qName.equalsIgnoreCase("EXAMPLES"))
{
style.setExamples(currentValue);
}
}
else if (thingTypeStack.read().equalsIgnoreCase("MASH"))
// We are looking at a mash profile
// Do all of the profile things below
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
profile.setName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
profile.setVersion(Integer.parseInt(currentValue));
}
else if (qName.equalsIgnoreCase("GRAIN_TEMP"))
{
profile.setBeerXmlStandardGrainTemp(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("NOTES"))
{
profile.setNotes(currentValue);
}
else if (qName.equalsIgnoreCase("TUN_TEMP"))
{
profile.setBeerXmlStandardTunTemp(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("SPARGE_TEMP"))
{
profile.setBeerXmlStandardSpargeTemp(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("PH"))
{
profile.setpH(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("TUN_WEIGHT"))
{
profile.setBeerXmlStandardTunWeight(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("TUN_SPECIFIC_HEAT"))
{
profile.setBeerXmlStandardTunSpecHeat(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("EQUIP_ADJUST"))
{
profile.setEquipmentAdjust(currentValue.equalsIgnoreCase("TRUE") ? true : false);
}
}
else if (thingTypeStack.read().equalsIgnoreCase("MASH_STEP"))
// We are looking at a mash step
// Do all of the mash step things below
// woo.
{
if (qName.equalsIgnoreCase("NAME"))
{
mashStep.setName(currentValue);
}
else if (qName.equalsIgnoreCase("VERSION"))
{
mashStep.setVersion(Integer.parseInt(currentValue));
}
else if (qName.equalsIgnoreCase("TYPE"))
{
if (currentValue.equalsIgnoreCase(MashStep.DECOCTION))
mashStep.setType(MashStep.DECOCTION);
else if (currentValue.equalsIgnoreCase(MashStep.INFUSION))
mashStep.setType(MashStep.INFUSION);
else if (currentValue.equalsIgnoreCase(MashStep.TEMPERATURE))
mashStep.setType(MashStep.TEMPERATURE);
}
else if (qName.equalsIgnoreCase("INFUSE_AMOUNT"))
{
mashStep.setBeerXmlStandardInfuseAmount(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("INFUSE_TEMP"))
{
String unit = Units.getUnitsFromDisplayAmount(currentValue);
double temp = Units.getAmountFromDisplayAmount(currentValue);
if (unit.equals(Units.FAHRENHEIT))
mashStep.setBeerXmlStandardInfuseTemp(Units.fahrenheitToCelsius(temp));
else
mashStep.setBeerXmlStandardInfuseTemp(temp);
}
else if (qName.equalsIgnoreCase("DECOCTION_AMT"))
{
String unit = Units.getUnitsFromDisplayAmount(currentValue);
double amt = Units.getAmountFromDisplayAmount(currentValue);
mashStep.setBeerXmlDecoctAmount(Units.toLiters(amt, unit));
}
else if (qName.equalsIgnoreCase("STEP_TIME"))
{
mashStep.setStepTime(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("STEP_TEMP"))
{
mashStep.setBeerXmlStandardStepTemp(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("RAMP_TIME"))
{
mashStep.setRampTime(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("END_TEMP"))
{
mashStep.setBeerXmlStandardEndTemp(Double.parseDouble(currentValue));
}
else if (qName.equalsIgnoreCase("DESCRIPTION"))
{
mashStep.setDescription(currentValue);
}
else if (qName.equalsIgnoreCase("WATER_GRAIN_RATIO"))
{
String unit = Units.getUnitsFromDisplayAmount(currentValue);
double amt = Units.getAmountFromDisplayAmount(currentValue);
if (unit.equals(Units.QUARTS_PER_POUND))
amt = Units.QPLBtoLPKG(amt);
mashStep.setBeerXmlStandardWaterToGrainRatio(amt);
}
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
|
package com.edinarobotics.utils.gamepad;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
/**
* Represents a gamepad with two joysticks and several buttons.
* Makes interacting with a gamepad easier.
* Returns results through a GamepadResult.
*/
public class Gamepad extends Joystick{
public static final int LEFT_X_AXIS = 1;
public static final int LEFT_Y_AXIS = 2;
public static final int RIGHT_X_AXIS = 3;
public static final int RIGHT_Y_AXIS = 4;
public static final int DPAD_X = 5;
public static final int DPAD_Y = 6;
public static final int LEFT_BUMPER = 5;
public static final int LEFT_TRIGGER = 7;
public static final int RIGHT_BUMPER = 6;
public static final int RIGHT_TRIGGER = 8;
public static final int BUTTON_1 = 1;
public static final int BUTTON_2 = 2;
public static final int BUTTON_3 = 3;
public static final int BUTTON_4 = 4;
public static final int BUTTON_9 = 9;
public static final int BUTTON_10 = 10;
public static final int DPAD_UP = 100;
public static final int DPAD_DOWN = 101;
public static final int DPAD_LEFT = 102;
public static final int DPAD_RIGHT = 103;
public final JoystickButton LEFT_BUMPER_BUTTON;
public final JoystickButton LEFT_TRIGGER_BUTTON;
public final JoystickButton RIGHT_BUMPER_BUTTON;
public final JoystickButton RIGHT_TRIGGER_BUTTON;
public final JoystickButton BUTTON_1_BUTTON;
public final JoystickButton BUTTON_2_BUTTON;
public final JoystickButton BUTTON_3_BUTTON;
public final JoystickButton BUTTON_4_BUTTON;
public final JoystickButton BUTTON_9_BUTTON;
public final JoystickButton BUTTON_10_BUTTON;
public final JoystickButton LEFT_JOYSTICK_BUTTON_BUTTON;
public final JoystickButton RIGHT_JOYSTICK_BUTTON_BUTTON;
public static final int LEFT_JOYSTICK_BUTTON = 11;
public static final int RIGHT_JOYSTICK_BUTTON = 12;
private static final double DPAD_THRESHOLD = 0.9;
public Gamepad(int port){
super(port);
LEFT_BUMPER_BUTTON = new JoystickButton(this, LEFT_BUMPER);
LEFT_TRIGGER_BUTTON = new JoystickButton(this, LEFT_TRIGGER);
RIGHT_BUMPER_BUTTON = new JoystickButton(this, RIGHT_BUMPER);
RIGHT_TRIGGER_BUTTON = new JoystickButton(this, RIGHT_TRIGGER);
BUTTON_1_BUTTON = new JoystickButton(this, BUTTON_1);
BUTTON_2_BUTTON = new JoystickButton(this, BUTTON_2);
BUTTON_3_BUTTON = new JoystickButton(this, BUTTON_3);
BUTTON_4_BUTTON = new JoystickButton(this, BUTTON_4);
BUTTON_9_BUTTON = new JoystickButton(this, BUTTON_9);
BUTTON_10_BUTTON = new JoystickButton(this, BUTTON_10);
LEFT_JOYSTICK_BUTTON_BUTTON = new JoystickButton(this, LEFT_JOYSTICK_BUTTON);
RIGHT_JOYSTICK_BUTTON_BUTTON = new JoystickButton(this, RIGHT_JOYSTICK_BUTTON);
}
public double getLeftX(){
return this.getRawAxis(LEFT_X_AXIS);
}
public double getLeftY(){
return this.getRawAxis(LEFT_Y_AXIS);
}
public double getRightX(){
return this.getRawAxis(RIGHT_X_AXIS);
}
public double getRightY(){
return this.getRawAxis(RIGHT_Y_AXIS);
}
public int getDPadX()
{
return dPadToInt(this.getRawAxis(DPAD_X));
}
public int getDPadY()
{
return dPadToInt(this.getRawAxis(DPAD_Y));
}
private int dPadToInt(double value){
if(value >= DPAD_THRESHOLD){
return 1;
}
else if(value <= -DPAD_THRESHOLD){
return -1;
}
return 0;
}
public GamepadResult getJoysticks(){
return new GamepadResult(getLeftX(),getLeftY(),getRightX(),getRightY());
}
public boolean getRawButton(int button){
if(button == DPAD_UP){
return getDPadY() == 1;
}
if(button == DPAD_DOWN){
return getDPadY() == -1;
}
if(button == DPAD_RIGHT){
return getDPadX() == 1;
}
if(button == DPAD_LEFT){
return getDPadX() == -1;
}
return super.getRawButton(button);
}
}
|
package com.iskrembilen.quasseldroid;
import java.util.ArrayList;
import java.util.Date;
import android.content.Context;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
public class IrcMessage implements Comparable<IrcMessage>{
public enum Type {
Plain (0x00001),
Notice (0x00002),
Action (0x00004),
Nick (0x00008),
Mode (0x00010),
Join (0x00020),
Part (0x00040),
Quit (0x00080),
Kick (0x00100),
Kill (0x00200),
Server (0x00400),
Info (0x00800),
Error (0x01000),
DayChange (0x02000),
Topic (0x04000),
NetsplitJoin (0x08000),
NetsplitQuit (0x10000),
Invite (0x20000);
int value;
static String[] filterList = {Type.Join.name(),Type.Part.name(),Type.Quit.name(),Type.Nick.name(),Type.Mode.name(),Type.Topic.name(),Type.DayChange.name()};
Type(int value){
this.value = value;
}
public int getValue(){
return value;
}
public static Type getForValue(int value) {
for (Type type: Type.values()) {
if (type.value == value)
return type;
}
return Plain;
}
public static String[] getFilterList(){
return filterList;
}
}
public enum Flag {
None (0x00),
Self (0x01),
Highlight (0x02),
Redirected (0x04),
ServerMsg (0x08),
Backlog (0x80);
int value;
Flag (int value){
this.value = value;
}
public int getValue(){
return value;
}
};
public Date timestamp; //TODO: timezones, Java bleh as usual
public int messageId;
public BufferInfo bufferInfo;
public Spannable content;
public String sender;
public Type type;
public byte flags;
private ArrayList<String> urls = new ArrayList<String>();
@Override
public int compareTo(IrcMessage other) {
return ((Integer)messageId).compareTo((Integer)other.messageId);
}
@Override
public String toString() {
return sender +": " + content;
}
public String getTime(){
return String.format("%02d:%02d:%02d", timestamp.getHours(), timestamp.getMinutes(), timestamp.getSeconds());
}
public String getNick(){
return sender.split("!")[0];
}
public void setFlag(Flag flag) {
this.flags |= flag.value;
}
public boolean isHighlighted() {
if (((flags & Flag.Highlight.value) != 0) && ((flags & Flag.Self.value) == 0)) {
return true;
}
return false;
}
public boolean isSelf() {
return ((flags & Flag.Self.value) != 0);
}
public void addURL(Context context, String url) {
urls.add(url);
int start = content.toString().indexOf(url);
content.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.ircmessage_url_color)), start, start+url.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
content.setSpan(new UnderlineSpan(), start, start+url.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
public ArrayList<String> getURLs() {
return urls;
}
public boolean hasURLs() {
return !urls.isEmpty();
}
}
|
package com.force.deploy.tools;
import com.force.deploy.tools.utils.DeployResult;
import com.force.deploy.tools.utils.Project;
import com.force.deploy.tools.utils.Serializer;
import com.sforce.soap.metadata.AsyncResult;
import com.sforce.soap.metadata.DeleteResult;
import com.sforce.soap.metadata.DescribeMetadataObject;
import com.sforce.soap.metadata.DescribeMetadataResult;
import com.sforce.soap.metadata.FileProperties;
import com.sforce.soap.metadata.ListMetadataQuery;
import com.sforce.soap.metadata.Metadata;
import com.sforce.soap.metadata.MetadataConnection;
import com.sforce.soap.metadata.PackageTypeMembers;
import com.sforce.soap.metadata.ReadResult;
import com.sforce.soap.metadata.RetrieveMessage;
import com.sforce.soap.metadata.RetrieveRequest;
import com.sforce.soap.metadata.RetrieveResult;
import com.sforce.soap.metadata.RetrieveStatus;
import com.sforce.soap.metadata.SaveResult;
import com.sforce.soap.partner.LoginResult;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.awt.Desktop;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author Daniel
*/
public class MainUIController implements Initializable {
@FXML
private ListView<String> projects;
@FXML
private TreeView<String> metaSource;
@FXML
private TreeView<String> metaTarget;
@FXML
private ComboBox<String> target;
@FXML
private Label source;
@FXML
private TableView<DeployResult> results;
@FXML
private MenuButton loadMeta;
private static final Logger log = Logger.getLogger(MainUIController.class.getName());
public static ObservableList<String> projectItems = FXCollections.observableArrayList();
public static Project selectedProject;
public static ObservableList<DeployResult> deployResults = FXCollections.observableArrayList();
private PartnerConnection part;
private MetadataConnection meta;
@Override
public void initialize(URL url, ResourceBundle rb) {
initProjects();
initMetaSource();
initMetaTarget();
initResults();
}
@FXML
private void btnCreateAction(ActionEvent event) {
deployResults.clear();
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
MetadataConnection sourceMetaConn = getMetaConnection(saved.get(source.getText()));
MetadataConnection targetMetaConn = getMetaConnection(saved.get(target.getSelectionModel().getSelectedItem()));
for (TreeItem<String> parent : metaTarget.getRoot().getChildren()) {
String parentValue = parent.getValue();
if (parentValue.startsWith("Apex")) {
processApex(parentValue, parent.getChildren(), sourceMetaConn, targetMetaConn);
} else {
processNormal(parentValue, parent.getChildren(), sourceMetaConn, targetMetaConn);
}
}
}
@FXML
private void btnDeleteAction(ActionEvent event) {
try {
deployResults.clear();
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
MetadataConnection targetMetaConn = getMetaConnection(saved.get(target.getSelectionModel().getSelectedItem()));
for (TreeItem<String> parent : metaTarget.getRoot().getChildren()) {
Set<String> children = new TreeSet<>();
for (TreeItem<String> child : parent.getChildren()) {
children.add(child.getValue());
}
DeleteResult[] saveResult = targetMetaConn.deleteMetadata(parent.getValue(), children.toArray(new String[]{}));
List<DeployResult> resultsList = new ArrayList<>();
for (DeleteResult sr : saveResult) {
resultsList.add(new DeployResult(sr));
}
deployResults.addAll(resultsList);
}
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
@FXML
private void btnAddAction(ActionEvent event) {
try {
selectedProject = null;
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Credentials.fxml"));
Scene scene = new Scene(root);
final Stage dialog = new Stage();
dialog.setTitle("Force.com Project");
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initStyle(StageStyle.UTILITY);
dialog.setScene(scene);
dialog.showAndWait();
} catch (IOException ex) {
log.log(Level.INFO, null, ex);
}
}
private void initResults() {
results.setEditable(true);
TableColumn<DeployResult, String> c1 = new TableColumn<>("Metadata Component");
c1.setCellValueFactory(new PropertyValueFactory<>("component"));
c1.setMinWidth(200);
TableColumn<DeployResult, String> c2 = new TableColumn<>("Status Code");
c2.setCellValueFactory(new PropertyValueFactory<>("statusCode"));
c2.setMinWidth(300);
TableColumn<DeployResult, String> c3 = new TableColumn<>("Message");
c3.setCellValueFactory(new PropertyValueFactory<>("message"));
c3.setMinWidth(700);
TableColumn<DeployResult, String> c4 = new TableColumn<>("Success");
c4.setCellValueFactory(new PropertyValueFactory<>("success"));
c4.setMinWidth(73);
results.getColumns().addAll(c1, c2, c3, c4);
results.setItems(deployResults);
}
private void initLoadMeta() {
loadMeta.getItems().clear();
prepareLoad();
Set<String> thingsToLoad = new TreeSet<>();
DescribeMetadataResult desc;
try {
desc = meta.describeMetadata(30.0);
for (DescribeMetadataObject obj : desc.getMetadataObjects()) {
thingsToLoad.add(obj.getXmlName());
String[] children = obj.getChildXmlNames();
if (children != null && children.length > 0) {
for (String child : Arrays.asList(children)) {
if (child != null) {
thingsToLoad.add(child);
}
}
}
}
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
List<MenuItem> btnLoadItems = new ArrayList<>();
final Map<String, String> subFolderItems = new TreeMap<>();
for (String f : "Dashboard,Document,Report".split(",")) {
subFolderItems.put(f, f + "Folder");
}
subFolderItems.put("EmailTemplate", "EmailFolder");
for (String folder : thingsToLoad) {
MenuItem item = new MenuItem(folder);
item.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
HashMap<String, TreeSet<String>> props = new HashMap<>();
String localFolder = folder;
if (subFolderItems.containsKey(folder)) {
localFolder = subFolderItems.get(folder);
}
ListMetadataQuery query = new ListMetadataQuery();
query.setType(localFolder);
FileProperties[] fp = meta.listMetadata(new ListMetadataQuery[]{query}, 29.0);
props.putAll(buildComponents(fp));
TreeItem<String> rootItem = new TreeItem<>(localFolder);
List<TreeItem<String>> toAdd = new ArrayList<>();
for (String type : props.keySet()) {
if (subFolderItems.containsKey(folder)) {
for (String component : props.get(type)) {
ListMetadataQuery q = new ListMetadataQuery();
q.setFolder(component);
q.setType(folder);
fp = meta.listMetadata(new ListMetadataQuery[]{q}, 29.0);
if (fp.length > 0) {
TreeItem<String> item = new TreeItem<>(component);
List<TreeItem<String>> subItems = new ArrayList<>();
for (String subComponent : buildSubComponents(fp).get(component)) {
TreeItem<String> treeSubItem = new TreeItem<>(subComponent);
subItems.add(treeSubItem);
}
item.getChildren().addAll(subItems);
toAdd.add(item);
}
}
} else {
for (String component : props.get(type)) {
toAdd.add(new TreeItem<>(component));
}
}
}
metaSource.getRoot().getChildren().clear();
if (!toAdd.isEmpty()) {
rootItem.setExpanded(true);
rootItem.getChildren().addAll(toAdd);
metaSource.getRoot().getChildren().add(rootItem);
}
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
});
btnLoadItems.add(item);
}
loadMeta.getItems().addAll(btnLoadItems);
}
private void initMetaTarget() {
metaTarget.setRoot(new TreeItem<>("Target Metadata"));
metaTarget.setShowRoot(false);
metaTarget.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) {
TreeItem<String> item = metaTarget.getSelectionModel().getSelectedItem();
if (item.isLeaf()) {
TreeItem<String> parent = item.getParent();
parent.getChildren().remove(item);
if (parent.getChildren().isEmpty()) {
metaTarget.getRoot().getChildren().remove(parent);
}
}
}
}
});
}
private void initMetaSource() {
metaSource.setRoot(new TreeItem<>("Source Metadata"));
metaSource.setShowRoot(false);
metaSource.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) {
TreeItem<String> item = metaSource.getSelectionModel().getSelectedItem();
String itemVal = item.getValue();
if (item.isLeaf()) {
TreeItem<String> parent = item.getParent();
String parentVal = parent.getValue();
TreeItem<String> targetRoot = metaTarget.getRoot();
boolean parentFound = false;
for (TreeItem<String> targetRootChild : targetRoot.getChildren()) {
if (targetRootChild.getValue().equals(parentVal)) {
parentFound = true;
boolean itemFound = false;
for (TreeItem<String> targetChildCell : targetRootChild.getChildren()) {
if (targetChildCell.getValue().equals(itemVal)) {
itemFound = true;
break;
}
}
if (!itemFound) {
targetRootChild.getChildren().add(new TreeItem<>(itemVal));
}
break;
}
}
if (!parentFound) {
TreeItem<String> targetParent = new TreeItem<>(parentVal);
targetParent.setExpanded(true);
targetParent.getChildren().add(new TreeItem<>(itemVal));
targetRoot.getChildren().add(targetParent);
}
}
}
}
});
}
private void initProjects() {
projects.setItems(projectItems);
target.setItems(projectItems);
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
if (saved != null) {
projectItems.addAll(saved.keySet());
}
projects.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
try {
String name = projects.getSelectionModel().getSelectedItem();
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
selectedProject = saved.get(name);
source.setText(name);
if (event.getButton().equals(MouseButton.PRIMARY)) {
if (event.getClickCount() == 1) {
initLoadMeta();
}
if (event.getClickCount() == 2) {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Credentials.fxml"));
Scene scene = new Scene(root);
final Stage dialog = new Stage();
dialog.setTitle("Force.com Project");
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initStyle(StageStyle.UTILITY);
dialog.setScene(scene);
dialog.showAndWait();
}
}
} catch (IOException ex) {
log.log(Level.INFO, null, ex);
}
}
});
ContextMenu contextMenu = new ContextMenu();
MenuItem openWebLink = new MenuItem("Open Web Link");
openWebLink.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
Project project = selectedProject;
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig partConfig = new ConnectorConfig();
partConfig.setAuthEndpoint(endPoint);
partConfig.setServiceEndpoint(endPoint);
partConfig.setManualLogin(true);
part = new PartnerConnection(partConfig);
LoginResult result = part.login(project.username, project.password + project.securityToken);
String loginLink = result.getServerUrl();
loginLink = loginLink.substring(0, loginLink.indexOf("/", 8)) + "/secur/frontdoor.jsp?sid=" + result.getSessionId();
Desktop.getDesktop().browse(new URI(loginLink));
} catch (ConnectionException | IOException | URISyntaxException ex) {
log.log(Level.INFO, null, ex);
}
}
});
MenuItem copyWebLink = new MenuItem("Copy Web Link");
copyWebLink.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
Project project = selectedProject;
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig partConfig = new ConnectorConfig();
partConfig.setAuthEndpoint(endPoint);
partConfig.setServiceEndpoint(endPoint);
partConfig.setManualLogin(true);
part = new PartnerConnection(partConfig);
LoginResult result = part.login(project.username, project.password + project.securityToken);
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
String loginLink = result.getServerUrl();
loginLink = loginLink.substring(0, loginLink.indexOf("/", 8)) + "/secur/frontdoor.jsp?sid=" + result.getSessionId();
content.putString(loginLink);
clipboard.setContent(content);
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
});
MenuItem delete = new MenuItem("Delete");
delete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
projectItems.remove(selectedProject.name);
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
if (saved != null) {
saved.remove(selectedProject.name);
}
Serializer.serialize(saved, Project.PROJECT_REPOSITORY);
}
});
contextMenu.getItems().addAll(openWebLink, copyWebLink, delete);
projects.setContextMenu(contextMenu);
}
private void prepareLoad() {
try {
Project project = selectedProject;
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(endPoint);
config.setServiceEndpoint(endPoint);
config.setManualLogin(true);
part = new PartnerConnection(config);
LoginResult result = part.login(project.username, project.password + project.securityToken);
config.setServiceEndpoint(result.getServerUrl());
config.setSessionId(result.getSessionId());
part = com.sforce.soap.partner.Connector.newConnection(config);
config.setServiceEndpoint(result.getMetadataServerUrl());
config.setSessionId(result.getSessionId());
meta = com.sforce.soap.metadata.Connector.newConnection(config);
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
private String getEndpoint(String environment, String instance) {
if (null != environment) {
switch (environment) {
case "Production/Developer Edition":
return "https://login.salesforce.com/services/Soap/u/29.0";
case "Sandbox":
return "https://test.salesforce.com/services/Soap/u/29.0";
case "Pre-release":
return "";
case "Other (Specify)":
return instance;
}
}
return "";
}
public static HashMap<String, TreeSet<String>> buildComponents(FileProperties[] props) {
HashMap<String, TreeSet<String>> ret = new HashMap<>();
for (FileProperties prop : props) {
String type = prop.getType();
if (!ret.containsKey(type)) {
ret.put(type, new TreeSet<>());
}
ret.get(type).add(prop.getFullName());
}
return ret;
}
public static HashMap<String, TreeSet<String>> buildSubComponents(FileProperties[] props) {
HashMap<String, TreeSet<String>> ret = new HashMap<>();
for (FileProperties prop : props) {
String[] parts = prop.getFullName().split("/");
String type = parts[0];
String value = parts[1];
if (!ret.containsKey(type)) {
ret.put(type, new TreeSet<>());
}
ret.get(type).add(value);
}
return ret;
}
private MetadataConnection getMetaConnection(Project project) {
try {
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(endPoint);
config.setServiceEndpoint(endPoint);
config.setManualLogin(true);
PartnerConnection pc = new PartnerConnection(config);
LoginResult result = pc.login(project.username, project.password + project.securityToken);
config.setServiceEndpoint(result.getMetadataServerUrl());
config.setSessionId(result.getSessionId());
return com.sforce.soap.metadata.Connector.newConnection(config);
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
return null;
}
private void processNormal(String parentValue, List<TreeItem<String>> parentChildren, MetadataConnection sourceMetaConn, MetadataConnection targetMetaConn) {
try {
String prefix = "";
ListMetadataQuery query = new ListMetadataQuery();
query.setType(parentValue);
FileProperties[] props = sourceMetaConn.listMetadata(new ListMetadataQuery[]{query}, 29.0);
prefix = props[0].getNamespacePrefix();
if (!"".equals(prefix)) {
prefix += "__";
}
List<String> children = new ArrayList<>();
for (TreeItem<String> child : parentChildren) {
String v = child.getValue();
if (!"".equals(prefix) && v.contains(".")) {
String[] parts = v.split("\\.");
if (parts[0].endsWith("__c")) {
parts[0] = prefix + parts[0];
}
if (parts[1].endsWith("__c")) {
parts[1] = prefix + parts[1];
}
v = parts[0] + "." + parts[1];
}
children.add(v);
}
ReadResult readResult = sourceMetaConn.readMetadata(parentValue, children.toArray(new String[]{}));
List<Metadata> metadata = new ArrayList<>();
List<DeployResult> resultsList = new ArrayList<>();
int i = 0;
for (Metadata m : readResult.getRecords()) {
if (m != null) {
m.setFullName(m.getFullName().replace(prefix, ""));
metadata.add(m);
} else {
log.log(Level.WARNING, "Metadata not read! ({0} not created!)", children.get(i));
resultsList.add(new DeployResult(children.get(i), "Metadata not read!"));
}
i++;
}
if (!metadata.isEmpty()) {
SaveResult[] saveResult = targetMetaConn.createMetadata(metadata.toArray(new Metadata[]{}));
for (SaveResult sr : saveResult) {
resultsList.add(new DeployResult(sr));
}
}
deployResults.addAll(resultsList);
} catch (ConnectionException ex) {
log.log(Level.SEVERE, null, ex);
}
}
private void processApex(String parentValue, List<TreeItem<String>> parentChildren, MetadataConnection sourceMetaConn, MetadataConnection targetMetaConn) {
try {
// one second in milliseconds
final long ONE_SECOND = 1000;
// maximum number of attempts to retrieve the results
final int MAX_NUM_POLL_REQUESTS = 50;
// manifest file that controls which components get retrieved
final String MANIFEST_FILE = "package.xml";
final double API_VERSION = 30.0;
String prefix = "";
ListMetadataQuery query = new ListMetadataQuery();
query.setType(parentValue);
FileProperties[] props = sourceMetaConn.listMetadata(new ListMetadataQuery[]{query}, 29.0);
prefix = props[0].getNamespacePrefix();
if (!"".equals(prefix)) {
prefix += "__";
}
List<String> children = new ArrayList<>();
for (TreeItem<String> child : parentChildren) {
String v = child.getValue();
/*if (!"".equals(prefix) && v.contains(".")) {
String[] parts = v.split("\\.");
if (parts[0].endsWith("__c")) {
parts[0] = prefix + parts[0];
}
if (parts[1].endsWith("__c")) {
parts[1] = prefix + parts[1];
}
v = parts[0] + "." + parts[1];
}*/
children.add(v);
}
PackageTypeMembers ptm = new PackageTypeMembers();
ptm.setName(parentValue);
ptm.setMembers(children.toArray(new String[]{}));
com.sforce.soap.metadata.Package p = new com.sforce.soap.metadata.Package();
p.setTypes(new PackageTypeMembers[]{ptm});
p.setVersion(API_VERSION + "");
RetrieveRequest request = new RetrieveRequest();
request.setUnpackaged(p);
// Start the retrieve operation
AsyncResult asyncResult = sourceMetaConn.retrieve(request);
log.info("asyncResult " + asyncResult.toString());
String asyncResultId = asyncResult.getId();
// Wait for the retrieve to complete
int poll = 0;
long waitTimeMilliSecs = ONE_SECOND;
RetrieveResult result = null;
do {
Thread.sleep(waitTimeMilliSecs);
// Double the wait time for the next iteration
waitTimeMilliSecs *= 2;
if (poll++ > MAX_NUM_POLL_REQUESTS) {
throw new Exception("Request timed out. If this is a large set "
+ "of metadata components, check that the time allowed "
+ "by MAX_NUM_POLL_REQUESTS is sufficient.");
}
result = sourceMetaConn.checkRetrieveStatus(
asyncResultId);
System.out.println("Retrieve Status: " + result.getStatus());
} while (!result.isDone());
if (result.getStatus() == RetrieveStatus.Failed) {
throw new Exception(result.getErrorStatusCode() + " msg: "
+ result.getErrorMessage());
} else if (result.getStatus() == RetrieveStatus.Succeeded) {
// Print out any warning messages
StringBuilder buf = new StringBuilder();
if (result.getMessages() != null) {
for (RetrieveMessage rm : result.getMessages()) {
buf.append(rm.getFileName() + " - " + rm.getProblem());
}
}
if (buf.length() > 0) {
System.out.println("Retrieve warnings:\n" + buf);
}
// Write the zip to the file system
System.out.println("Writing results to zip file");
ByteArrayInputStream bais = new ByteArrayInputStream(result.getZipFile());
File resultsFile = new File("./tmp/retrieveResults.zip");
FileOutputStream os = new FileOutputStream(resultsFile);
try {
ReadableByteChannel src = Channels.newChannel(bais);
FileChannel dest = os.getChannel();
copy(src, dest);
System.out.println("Results written to " + resultsFile.getAbsolutePath());
} finally {
os.close();
}
}
} catch (Exception ex) {
log.log(Level.SEVERE, null, ex);
}
}
/**
* Helper method to copy from a readable channel to a writable channel,
* using an in-memory buffer.
*/
private void copy(ReadableByteChannel src, WritableByteChannel dest)
throws IOException {
// Use an in-memory byte buffer
ByteBuffer buffer = ByteBuffer.allocate(8092);
while (src.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
dest.write(buffer);
}
buffer.clear();
}
}
}
|
package com.force.deploy.tools;
import com.force.deploy.tools.utils.DeployResult;
import com.force.deploy.tools.utils.Project;
import com.force.deploy.tools.utils.Serializer;
import com.sforce.soap.metadata.AsyncResult;
import com.sforce.soap.metadata.DeleteResult;
import com.sforce.soap.metadata.DescribeMetadataObject;
import com.sforce.soap.metadata.DescribeMetadataResult;
import com.sforce.soap.metadata.FileProperties;
import com.sforce.soap.metadata.ListMetadataQuery;
import com.sforce.soap.metadata.Metadata;
import com.sforce.soap.metadata.MetadataConnection;
import com.sforce.soap.metadata.PackageTypeMembers;
import com.sforce.soap.metadata.ReadResult;
import com.sforce.soap.metadata.RetrieveMessage;
import com.sforce.soap.metadata.RetrieveRequest;
import com.sforce.soap.metadata.RetrieveResult;
import com.sforce.soap.metadata.RetrieveStatus;
import com.sforce.soap.metadata.SaveResult;
import com.sforce.soap.partner.LoginResult;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.awt.Desktop;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author Daniel
*/
public class MainUIController implements Initializable {
@FXML
private ListView<String> projects;
@FXML
private TreeView<String> metaSource;
@FXML
private TreeView<String> metaTarget;
@FXML
private ComboBox<String> target;
@FXML
private Label source;
@FXML
private TableView<DeployResult> results;
@FXML
private MenuButton loadMeta;
private static final Logger log = Logger.getLogger(MainUIController.class.getName());
public static ObservableList<String> projectItems = FXCollections.observableArrayList();
public static Project selectedProject;
public static ObservableList<DeployResult> deployResults = FXCollections.observableArrayList();
private PartnerConnection part;
private MetadataConnection meta;
@Override
public void initialize(URL url, ResourceBundle rb) {
initProjects();
initMetaSource();
initMetaTarget();
initResults();
}
@FXML
private void btnCreateAction(ActionEvent event) {
deployResults.clear();
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
MetadataConnection sourceMetaConn = getMetaConnection(saved.get(source.getText()));
MetadataConnection targetMetaConn = getMetaConnection(saved.get(target.getSelectionModel().getSelectedItem()));
for (TreeItem<String> parent : metaTarget.getRoot().getChildren()) {
String parentValue = parent.getValue();
if (parentValue.startsWith("Apex")) {
processApex(parentValue, parent.getChildren(), sourceMetaConn, targetMetaConn);
} else {
processNormal(parentValue, parent.getChildren(), sourceMetaConn, targetMetaConn);
}
}
}
@FXML
private void btnDeleteAction(ActionEvent event) {
try {
deployResults.clear();
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
MetadataConnection targetMetaConn = getMetaConnection(saved.get(target.getSelectionModel().getSelectedItem()));
for (TreeItem<String> parent : metaTarget.getRoot().getChildren()) {
Set<String> children = new TreeSet<>();
for (TreeItem<String> child : parent.getChildren()) {
children.add(child.getValue());
}
DeleteResult[] saveResult = targetMetaConn.deleteMetadata(parent.getValue(), children.toArray(new String[]{}));
List<DeployResult> resultsList = new ArrayList<>();
for (DeleteResult sr : saveResult) {
resultsList.add(new DeployResult(sr));
}
deployResults.addAll(resultsList);
}
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
@FXML
private void btnAddAction(ActionEvent event) {
try {
selectedProject = null;
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Credentials.fxml"));
Scene scene = new Scene(root);
final Stage dialog = new Stage();
dialog.setTitle("Force.com Project");
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initStyle(StageStyle.UTILITY);
dialog.setScene(scene);
dialog.showAndWait();
} catch (IOException ex) {
log.log(Level.INFO, null, ex);
}
}
private void initResults() {
results.setEditable(true);
TableColumn<DeployResult, String> c1 = new TableColumn<>("Metadata Component");
c1.setCellValueFactory(new PropertyValueFactory<>("component"));
c1.setMinWidth(200);
TableColumn<DeployResult, String> c2 = new TableColumn<>("Status Code");
c2.setCellValueFactory(new PropertyValueFactory<>("statusCode"));
c2.setMinWidth(300);
TableColumn<DeployResult, String> c3 = new TableColumn<>("Message");
c3.setCellValueFactory(new PropertyValueFactory<>("message"));
c3.setMinWidth(700);
TableColumn<DeployResult, String> c4 = new TableColumn<>("Success");
c4.setCellValueFactory(new PropertyValueFactory<>("success"));
c4.setMinWidth(73);
results.getColumns().addAll(c1, c2, c3, c4);
results.setItems(deployResults);
}
private void initLoadMeta() {
loadMeta.getItems().clear();
prepareLoad();
Set<String> thingsToLoad = new TreeSet<>();
DescribeMetadataResult desc;
try {
desc = meta.describeMetadata(30.0);
for (DescribeMetadataObject obj : desc.getMetadataObjects()) {
thingsToLoad.add(obj.getXmlName());
String[] children = obj.getChildXmlNames();
if (children != null && children.length > 0) {
for (String child : Arrays.asList(children)) {
if (child != null) {
thingsToLoad.add(child);
}
}
}
}
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
List<MenuItem> btnLoadItems = new ArrayList<>();
final Map<String, String> subFolderItems = new TreeMap<>();
for (String f : "Dashboard,Document,Report".split(",")) {
subFolderItems.put(f, f + "Folder");
}
subFolderItems.put("EmailTemplate", "EmailFolder");
for (String folder : thingsToLoad) {
MenuItem item = new MenuItem(folder);
item.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
HashMap<String, TreeSet<String>> props = new HashMap<>();
String localFolder = folder;
if (subFolderItems.containsKey(folder)) {
localFolder = subFolderItems.get(folder);
}
ListMetadataQuery query = new ListMetadataQuery();
query.setType(localFolder);
FileProperties[] fp = meta.listMetadata(new ListMetadataQuery[]{query}, 29.0);
props.putAll(buildComponents(fp));
TreeItem<String> rootItem = new TreeItem<>(localFolder);
List<TreeItem<String>> toAdd = new ArrayList<>();
for (String type : props.keySet()) {
if (subFolderItems.containsKey(folder)) {
for (String component : props.get(type)) {
ListMetadataQuery q = new ListMetadataQuery();
q.setFolder(component);
q.setType(folder);
fp = meta.listMetadata(new ListMetadataQuery[]{q}, 29.0);
if (fp.length > 0) {
TreeItem<String> item = new TreeItem<>(component);
List<TreeItem<String>> subItems = new ArrayList<>();
for (String subComponent : buildSubComponents(fp).get(component)) {
TreeItem<String> treeSubItem = new TreeItem<>(subComponent);
subItems.add(treeSubItem);
}
item.getChildren().addAll(subItems);
toAdd.add(item);
}
}
} else {
for (String component : props.get(type)) {
toAdd.add(new TreeItem<>(component));
}
}
}
metaSource.getRoot().getChildren().clear();
if (!toAdd.isEmpty()) {
rootItem.setExpanded(true);
rootItem.getChildren().addAll(toAdd);
metaSource.getRoot().getChildren().add(rootItem);
}
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
});
btnLoadItems.add(item);
}
loadMeta.getItems().addAll(btnLoadItems);
}
private void initMetaTarget() {
metaTarget.setRoot(new TreeItem<>("Target Metadata"));
metaTarget.setShowRoot(false);
metaTarget.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) {
TreeItem<String> item = metaTarget.getSelectionModel().getSelectedItem();
if (item.isLeaf()) {
TreeItem<String> parent = item.getParent();
parent.getChildren().remove(item);
if (parent.getChildren().isEmpty()) {
metaTarget.getRoot().getChildren().remove(parent);
}
}
}
}
});
}
private void initMetaSource() {
metaSource.setRoot(new TreeItem<>("Source Metadata"));
metaSource.setShowRoot(false);
metaSource.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) {
TreeItem<String> item = metaSource.getSelectionModel().getSelectedItem();
String itemVal = item.getValue();
if (item.isLeaf()) {
TreeItem<String> parent = item.getParent();
String parentVal = parent.getValue();
TreeItem<String> targetRoot = metaTarget.getRoot();
boolean parentFound = false;
for (TreeItem<String> targetRootChild : targetRoot.getChildren()) {
if (targetRootChild.getValue().equals(parentVal)) {
parentFound = true;
boolean itemFound = false;
for (TreeItem<String> targetChildCell : targetRootChild.getChildren()) {
if (targetChildCell.getValue().equals(itemVal)) {
itemFound = true;
break;
}
}
if (!itemFound) {
targetRootChild.getChildren().add(new TreeItem<>(itemVal));
}
break;
}
}
if (!parentFound) {
TreeItem<String> targetParent = new TreeItem<>(parentVal);
targetParent.setExpanded(true);
targetParent.getChildren().add(new TreeItem<>(itemVal));
targetRoot.getChildren().add(targetParent);
}
}
}
}
});
}
private void initProjects() {
projects.setItems(projectItems);
target.setItems(projectItems);
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
if (saved != null) {
projectItems.addAll(saved.keySet());
}
projects.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
try {
String name = projects.getSelectionModel().getSelectedItem();
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
selectedProject = saved.get(name);
source.setText(name);
if (event.getButton().equals(MouseButton.PRIMARY)) {
if (event.getClickCount() == 1) {
initLoadMeta();
}
if (event.getClickCount() == 2) {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Credentials.fxml"));
Scene scene = new Scene(root);
final Stage dialog = new Stage();
dialog.setTitle("Force.com Project");
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initStyle(StageStyle.UTILITY);
dialog.setScene(scene);
dialog.showAndWait();
}
}
} catch (IOException ex) {
log.log(Level.INFO, null, ex);
}
}
});
ContextMenu contextMenu = new ContextMenu();
MenuItem openWebLink = new MenuItem("Open Web Link");
openWebLink.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
Project project = selectedProject;
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig partConfig = new ConnectorConfig();
partConfig.setAuthEndpoint(endPoint);
partConfig.setServiceEndpoint(endPoint);
partConfig.setManualLogin(true);
part = new PartnerConnection(partConfig);
LoginResult result = part.login(project.username, project.password + project.securityToken);
String loginLink = result.getServerUrl();
loginLink = loginLink.substring(0, loginLink.indexOf("/", 8)) + "/secur/frontdoor.jsp?sid=" + result.getSessionId();
Desktop.getDesktop().browse(new URI(loginLink));
} catch (ConnectionException | IOException | URISyntaxException ex) {
log.log(Level.INFO, null, ex);
}
}
});
MenuItem copyWebLink = new MenuItem("Copy Web Link");
copyWebLink.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
Project project = selectedProject;
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig partConfig = new ConnectorConfig();
partConfig.setAuthEndpoint(endPoint);
partConfig.setServiceEndpoint(endPoint);
partConfig.setManualLogin(true);
part = new PartnerConnection(partConfig);
LoginResult result = part.login(project.username, project.password + project.securityToken);
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
String loginLink = result.getServerUrl();
loginLink = loginLink.substring(0, loginLink.indexOf("/", 8)) + "/secur/frontdoor.jsp?sid=" + result.getSessionId();
content.putString(loginLink);
clipboard.setContent(content);
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
});
MenuItem delete = new MenuItem("Delete");
delete.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
projectItems.remove(selectedProject.name);
HashMap<String, Project> saved = (HashMap<String, Project>) Serializer.deserialize(Project.PROJECT_REPOSITORY);
if (saved != null) {
saved.remove(selectedProject.name);
}
Serializer.serialize(saved, Project.PROJECT_REPOSITORY);
}
});
contextMenu.getItems().addAll(openWebLink, copyWebLink, delete);
projects.setContextMenu(contextMenu);
}
private void prepareLoad() {
try {
Project project = selectedProject;
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(endPoint);
config.setServiceEndpoint(endPoint);
config.setManualLogin(true);
part = new PartnerConnection(config);
LoginResult result = part.login(project.username, project.password + project.securityToken);
config.setServiceEndpoint(result.getServerUrl());
config.setSessionId(result.getSessionId());
part = new PartnerConnection(config);
config.setServiceEndpoint(result.getMetadataServerUrl());
config.setSessionId(result.getSessionId());
meta = new MetadataConnection(config);
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
}
private String getEndpoint(String environment, String instance) {
if (null != environment) {
switch (environment) {
case "Production/Developer Edition":
return "https://login.salesforce.com/services/Soap/u/29.0";
case "Sandbox":
return "https://test.salesforce.com/services/Soap/u/29.0";
case "Pre-release":
return "";
case "Other (Specify)":
return instance;
}
}
return "";
}
public static HashMap<String, TreeSet<String>> buildComponents(FileProperties[] props) {
HashMap<String, TreeSet<String>> ret = new HashMap<>();
for (FileProperties prop : props) {
String type = prop.getType();
if (!ret.containsKey(type)) {
ret.put(type, new TreeSet<>());
}
ret.get(type).add(prop.getFullName());
}
return ret;
}
public static HashMap<String, TreeSet<String>> buildSubComponents(FileProperties[] props) {
HashMap<String, TreeSet<String>> ret = new HashMap<>();
for (FileProperties prop : props) {
String[] parts = prop.getFullName().split("/");
String type = parts[0];
String value = parts[1];
if (!ret.containsKey(type)) {
ret.put(type, new TreeSet<>());
}
ret.get(type).add(value);
}
return ret;
}
private MetadataConnection getMetaConnection(Project project) {
try {
String endPoint = getEndpoint(project.environment, project.instance);
ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(endPoint);
config.setServiceEndpoint(endPoint);
config.setManualLogin(true);
PartnerConnection pc = new PartnerConnection(config);
LoginResult result = pc.login(project.username, project.password + project.securityToken);
config.setServiceEndpoint(result.getMetadataServerUrl());
config.setSessionId(result.getSessionId());
return new MetadataConnection(config);
} catch (ConnectionException ex) {
log.log(Level.INFO, null, ex);
}
return null;
}
private void processNormal(String parentValue, List<TreeItem<String>> parentChildren, MetadataConnection sourceMetaConn, MetadataConnection targetMetaConn) {
try {
String prefix = "";
ListMetadataQuery query = new ListMetadataQuery();
query.setType(parentValue);
FileProperties[] props = sourceMetaConn.listMetadata(new ListMetadataQuery[]{query}, 29.0);
prefix = props[0].getNamespacePrefix();
if (!"".equals(prefix)) {
prefix += "__";
}
List<String> children = new ArrayList<>();
for (TreeItem<String> child : parentChildren) {
String v = child.getValue();
if (!"".equals(prefix) && v.contains(".")) {
String[] parts = v.split("\\.");
if (parts[0].endsWith("__c")) {
parts[0] = prefix + parts[0];
}
if (parts[1].endsWith("__c")) {
parts[1] = prefix + parts[1];
}
v = parts[0] + "." + parts[1];
}
children.add(v);
}
ReadResult readResult = sourceMetaConn.readMetadata(parentValue, children.toArray(new String[]{}));
List<Metadata> metadata = new ArrayList<>();
List<DeployResult> resultsList = new ArrayList<>();
int i = 0;
for (Metadata m : readResult.getRecords()) {
if (m != null) {
m.setFullName(m.getFullName().replace(prefix, ""));
metadata.add(m);
} else {
log.log(Level.WARNING, "Metadata not read! ({0} not created!)", children.get(i));
resultsList.add(new DeployResult(children.get(i), "Metadata not read!"));
}
i++;
}
if (!metadata.isEmpty()) {
SaveResult[] saveResult = targetMetaConn.createMetadata(metadata.toArray(new Metadata[]{}));
for (SaveResult sr : saveResult) {
resultsList.add(new DeployResult(sr));
}
}
deployResults.addAll(resultsList);
} catch (ConnectionException ex) {
log.log(Level.SEVERE, null, ex);
}
}
private void processApex(String parentValue, List<TreeItem<String>> parentChildren, MetadataConnection sourceMetaConn, MetadataConnection targetMetaConn) {
try {
// one second in milliseconds
final long ONE_SECOND = 1000;
// maximum number of attempts to retrieve the results
final int MAX_NUM_POLL_REQUESTS = 50;
final double API_VERSION = 31.0;
/*String prefix = "";
ListMetadataQuery query = new ListMetadataQuery();
query.setType(parentValue);
FileProperties[] props = sourceMetaConn.listMetadata(new ListMetadataQuery[]{query}, 29.0);
prefix = props[0].getNamespacePrefix();
if (!"".equals(prefix)) {
prefix += "__";
}*/
List<String> children = new ArrayList<>();
for (TreeItem<String> child : parentChildren) {
String v = child.getValue();
/*if (!"".equals(prefix) && v.contains(".")) {
String[] parts = v.split("\\.");
if (parts[0].endsWith("__c")) {
parts[0] = prefix + parts[0];
}
if (parts[1].endsWith("__c")) {
parts[1] = prefix + parts[1];
}
v = parts[0] + "." + parts[1];
}*/
children.add(v);
}
PackageTypeMembers ptm = new PackageTypeMembers();
ptm.setName(parentValue);
ptm.setMembers(children.toArray(new String[]{}));
com.sforce.soap.metadata.Package p = new com.sforce.soap.metadata.Package();
p.setTypes(new PackageTypeMembers[]{ptm});
p.setVersion(API_VERSION + "");
RetrieveRequest request = new RetrieveRequest();
request.setUnpackaged(p);
// Start the retrieve operation
AsyncResult asyncResult = sourceMetaConn.retrieve(request);
log.info("asyncResult " + asyncResult.toString());
String asyncResultId = asyncResult.getId();
// Wait for the retrieve to complete
int poll = 0;
long waitTimeMilliSecs = ONE_SECOND;
RetrieveResult result = null;
do {
Thread.sleep(waitTimeMilliSecs);
// Double the wait time for the next iteration
waitTimeMilliSecs *= 2;
if (poll++ > MAX_NUM_POLL_REQUESTS) {
throw new Exception("Request timed out. If this is a large set "
+ "of metadata components, check that the time allowed "
+ "by MAX_NUM_POLL_REQUESTS is sufficient.");
}
result = sourceMetaConn.checkRetrieveStatus(
asyncResultId);
System.out.println("Retrieve Status: " + result.getStatus());
} while (!result.isDone());
if (result.getStatus() == RetrieveStatus.Failed) {
throw new Exception(result.getErrorStatusCode() + " msg: "
+ result.getErrorMessage());
} else if (result.getStatus() == RetrieveStatus.Succeeded) {
// Print out any warning messages
StringBuilder buf = new StringBuilder();
if (result.getMessages() != null) {
for (RetrieveMessage rm : result.getMessages()) {
buf.append(rm.getFileName() + " - " + rm.getProblem());
}
}
if (buf.length() > 0) {
System.out.println("Retrieve warnings:\n" + buf);
}
// Write the zip to the file system
System.out.println("Writing results to zip file");
ByteArrayInputStream bais = new ByteArrayInputStream(result.getZipFile());
File resultsFile = new File("./tmp/retrieveResults.zip");
FileOutputStream os = new FileOutputStream(resultsFile);
try {
ReadableByteChannel src = Channels.newChannel(bais);
FileChannel dest = os.getChannel();
copy(src, dest);
System.out.println("Results written to " + resultsFile.getAbsolutePath());
} finally {
os.close();
}
}
} catch (Exception ex) {
log.log(Level.SEVERE, null, ex);
}
}
/**
* Helper method to copy from a readable channel to a writable channel,
* using an in-memory buffer.
*/
private void copy(ReadableByteChannel src, WritableByteChannel dest)
throws IOException {
// Use an in-memory byte buffer
ByteBuffer buffer = ByteBuffer.allocate(8092);
while (src.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
dest.write(buffer);
}
buffer.clear();
}
}
}
|
package com.jme.scene.model.XMLparser;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.MaterialState;
import com.jme.math.Vector3f;
import com.jme.math.Quaternion;
import com.jme.math.Vector2f;
import com.jme.renderer.ColorRGBA;
import java.io.OutputStream;
import java.io.IOException;
public class XMLWriter {
private OutputStream myStream;
final static Vector3f defaultTranslation=new Vector3f(0,0,0);
final static Quaternion defaultRotation=new Quaternion(0,0,0,1);
final static float defaultScale=1;
StringBuffer tabs=new StringBuffer();
StringBuffer currentLine=new StringBuffer();
public XMLWriter(OutputStream o){
myStream=o;
}
public void setNewStream(OutputStream o){
myStream=o;
}
public void writeScene(Node toWrite) throws IOException {
writeHeader();
increaseTabSize();
writeNode(toWrite);
decreaseTabSize();
writeClosing();
myStream.close();
}
private void writeClosing() throws IOException {
currentLine.append("</scene>");
writeLine();
}
private void writeNode(Node toWrite) throws IOException {
currentLine.append("<node ").append(getSpatialHeader(toWrite)).append(">");
writeLine();
increaseTabSize();
writeRenderStates(toWrite);
for (int i=0;i<toWrite.getQuantity();i++){
Spatial s=toWrite.getChild(i);
if (s instanceof Node)
writeNode((Node) s);
if (s instanceof TriMesh)
writeMesh((TriMesh)s);
}
decreaseTabSize();
currentLine.append("</node>");
writeLine();
}
private void writeRenderStates(Spatial s) throws IOException {
RenderState[] states=s.getRenderStateList();
if (states[RenderState.RS_MATERIAL]!=null){
writeMaterialState((MaterialState) states[RenderState.RS_MATERIAL]);
}
}
private void writeMaterialState(MaterialState state) throws IOException {
currentLine.append("<materialstate ");
currentLine.append("emissive=\"");
appendColorRGBA(state.getEmissive());
currentLine.append("\" ");
currentLine.append("ambient=\"");
appendColorRGBA(state.getAmbient());
currentLine.append("\" ");
currentLine.append("diffuse=\"");
appendColorRGBA(state.getDiffuse());
currentLine.append("\" ");
currentLine.append("specular=\"");
appendColorRGBA(state.getSpecular());
currentLine.append("\" ");
currentLine.append("alpha=\"");
currentLine.append(state.getAlpha());
currentLine.append("\" ");
currentLine.append("shiny=\"");
currentLine.append(state.getShininess());
currentLine.append("\" ");
currentLine.append("/>");
writeLine();
}
private void writeMesh(TriMesh toWrite) throws IOException {
currentLine.append("<mesh ").append(getSpatialHeader(toWrite)).append(">");
writeLine();
increaseTabSize();
writeRenderStates(toWrite);
currentLine.append("<vertex>");
writeLine();
Vector3f[] theVerts=toWrite.getVertices();
increaseTabSize();
if (theVerts!=null)
writeVec3fArray(theVerts);
writeLine();
decreaseTabSize();
currentLine.append("</vertex>");
writeLine();
currentLine.append("<normal>");
writeLine();
Vector3f[] theNorms=toWrite.getNormals();
increaseTabSize();
if (theNorms!=null)
writeVec3fArray(theNorms);
writeLine();
decreaseTabSize();
currentLine.append("</normal>");
writeLine();
currentLine.append("<color>");
writeLine();
ColorRGBA[] theColors=toWrite.getColors();
increaseTabSize();
if (theColors!=null)
writeColorRGBAArray(theColors);
writeLine();
decreaseTabSize();
currentLine.append("</color>");
writeLine();
currentLine.append("<texturecoords>");
writeLine();
Vector2f[] theTexCoords=toWrite.getTextures();
increaseTabSize();
if (theTexCoords!=null)
writeVec2fArray(theTexCoords);
writeLine();
decreaseTabSize();
currentLine.append("</texturecoords>");
writeLine();
currentLine.append("<index>");
writeLine();
int[] indexes=toWrite.getIndices();
increaseTabSize();
if (indexes!=null)
writeIntArray(indexes);
writeLine();
decreaseTabSize();
currentLine.append("</index>");
writeLine();
decreaseTabSize();
currentLine.append("</mesh>");
writeLine();
}
private void writeIntArray(int[] indexes) throws IOException {
for (int i=0;i<indexes.length;i++){
currentLine.append(indexes[i]).append(" ");
if (i%3==0) writeLine();
}
}
private void writeVec2fArray(Vector2f[] theTexCoords) throws IOException {
int counter=0;
for (int i=0;i<theTexCoords.length;i++){
if (theTexCoords[i]!=null){
writeVector2f(theTexCoords[i]);
if (++counter==3){
writeLine();
counter=0;
}
}
}
}
private void writeVector2f(Vector2f theVec) throws IOException {
currentLine.append(Float.toString(theVec.x)).append(" ").append(Float.toString(theVec.y)).append(" ");
}
private void writeColorRGBAArray(ColorRGBA[] theColors) throws IOException {
int counter=0;
for (int i=0;i<theColors.length;i++){
if (theColors[i]!=null){
appendColorRGBA(theColors[i]);
if (++counter==3){
counter=0;
writeLine();
}
}
}
}
private void appendColorRGBA(ColorRGBA theColor) throws IOException {
currentLine.append(Float.toString(theColor.r)).append(" ").append(Float.toString(theColor.g)).append(" ").append(Float.toString(theColor.b)).append(" ").append(Float.toString(theColor.a)).append(" ");
}
private void writeVec3fArray(Vector3f[] vecs) throws IOException {
int counter=0;
for (int i=0;i<vecs.length;i++){
if (vecs[i]!=null){
writeVector3f(vecs[i]);
if (++counter==3){
counter=0;
writeLine();
}
}
}
}
private void writeVector3f(Vector3f vec) throws IOException {
currentLine.append(Float.toString(vec.x)).append(" ").append(Float.toString(vec.y)).append(" ").append(Float.toString(vec.z)).append(" " );
}
private StringBuffer getSpatialHeader(Spatial toWrite){
StringBuffer header=new StringBuffer();
header.append("name=\"").append(toWrite.getName()).append("\" ");
Vector3f trans=toWrite.getLocalTranslation();
if (!trans.equals(defaultTranslation)){
header.append("translation=\"");
header.append(trans.x).append(" ").append(trans.y).append(" ").append(trans.z).append("\" ");
}
Quaternion quat=toWrite.getLocalRotation();
if (!quat.equals(defaultRotation)){
header.append("rotation=\"");
header.append(quat.x).append(" ").append(quat.y).append(" ").append(quat.z).append(" ").append(quat.w).append("\" ");
}
if (toWrite.getLocalScale()!=defaultScale){
header.append("scale = \"").append(toWrite.getLocalScale()).append("\" ");
}
return header;
}
private void writeHeader() throws IOException {
currentLine.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writeLine();
currentLine.append("<scene xmlns:xsi=\"http:
writeLine();
}
private void writeLine() throws IOException{
myStream.write(tabs.toString().getBytes());
myStream.write(currentLine.toString().getBytes());
myStream.write('\n');
myStream.flush();
currentLine.setLength(0);
}
private void increaseTabSize(){
tabs.append('\t');
}
private void decreaseTabSize(){
tabs.deleteCharAt(0);
}
}
|
package com.lukekorth.pebblelocker;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;
public class PebbleLocker extends PreferenceActivity {
private static final int REQUEST_CODE_ENABLE_ADMIN = 1;
private DevicePolicyManager mDPM;
private ComponentName mDeviceAdmin;
private CheckBoxPreference mAdmin;
private EditTextPreference mPassword;
private CheckBoxPreference mForceLock;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.main);
mAdmin = (CheckBoxPreference) findPreference("key_enable_admin");
mPassword = (EditTextPreference) findPreference("key_password");
mForceLock = (CheckBoxPreference) findPreference("key_force_lock");
mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
mDeviceAdmin = new ComponentName(this, CustomDeviceAdminReceiver.class);
mAdmin.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean) newValue) {
// Launch the activity to have the user enable our admin.
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Pebble Locker needs device admin access to lock your device on disconnect");
startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
// return false - don't update checkbox until we're really active
return false;
} else {
mDPM.removeActiveAdmin(mDeviceAdmin);
PebbleLocker.this.enableOptions(false);
return true;
}
}
});
mPassword.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
doResetPassword((String) newValue);
return true;
}
});
}
public void onResume() {
super.onResume();
if(mDPM.isAdminActive(mDeviceAdmin)) {
mAdmin.setChecked(true);
enableOptions(true);
} else {
mAdmin.setChecked(false);
enableOptions(false);
}
}
/**
* This is dangerous, so we prevent automated tests from doing it, and we
* remind the user after we do it.
*/
private void doResetPassword(String newPassword) {
if (alertIfMonkey(this, "You can't reset my password, you are a monkey!")) {
return;
}
mDPM.resetPassword(newPassword, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String message = getString(R.string.reset_password_warning, newPassword);
builder.setMessage(message);
builder.setPositiveButton("Don't Forget It!", null);
builder.show();
}
private void enableOptions(boolean isEnabled) {
mPassword.setEnabled(isEnabled);
mForceLock.setEnabled(isEnabled);
}
/**
* If the "user" is a monkey, post an alert and notify the caller. This prevents automated
* test frameworks from stumbling into annoying or dangerous operations.
*/
private static boolean alertIfMonkey(Context context, String string) {
if (ActivityManager.isUserAMonkey()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(string);
builder.setPositiveButton("Ok", null);
builder.show();
return true;
} else {
return false;
}
}
/**
* All callbacks are on the UI thread and your implementations should not engage in any
* blocking operations, including disk I/O.
*/
public static class CustomDeviceAdminReceiver extends DeviceAdminReceiver {
@Override
public void onEnabled(Context context, Intent intent) {
// intentionally left blank
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
// intentionally left blank
return null;
}
@Override
public void onDisabled(Context context, Intent intent) {
// intentionally left blank
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
// intentionally left blank
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
Toast.makeText(context, "Password change failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
// intentionally left blank
}
@Override
public void onPasswordExpiring(Context context, Intent intent) {
// intentionally left blank
}
}
}
|
package com.ecyrd.jspwiki.xmlrpc;
import java.io.*;
import org.apache.log4j.Category;
import com.ecyrd.jspwiki.*;
import java.util.*;
import org.apache.xmlrpc.XmlRpcException;
/**
* Provides handlers for all RPC routines.
*
* @author Janne Jalkanen
* @since 1.6.6
*/
// We could use WikiEngine directly, but because of introspection it would
// show just too many methods to be safe.
public class RPCHandler
extends AbstractRPCHandler
{
Category log = Category.getInstance( RPCHandler.class );
public void initialize( WikiEngine engine )
{
super.initialize( engine );
}
/**
* Converts Java string into RPC string.
*/
private String toRPCString( String src )
{
return TextUtil.urlEncodeUTF8( src );
}
/**
* Converts RPC string (UTF-8, url encoded) into Java string.
*/
private String fromRPCString( String src )
{
return TextUtil.urlDecodeUTF8( src );
}
/**
* Transforms a Java string into UTF-8.
*/
private byte[] toRPCBase64( String src )
{
try
{
return src.getBytes("UTF-8");
}
catch( UnsupportedEncodingException e )
{
// You shouldn't be running JSPWiki on a platform that does not
// use UTF-8. We revert to platform default, so that the other
// end might have a chance of getting something.
log.fatal("Platform does not support UTF-8, reverting to platform default");
return src.getBytes();
}
}
public String getApplicationName()
{
return toRPCString(m_engine.getApplicationName());
}
public Vector getAllPages()
{
Collection pages = m_engine.getRecentChanges();
Vector result = new Vector();
int count = 0;
for( Iterator i = pages.iterator(); i.hasNext(); )
{
result.add( toRPCString(((WikiPage)i.next()).getName()) );
}
return result;
}
/**
* Encodes a single wiki page info into a Hashtable.
*/
protected Hashtable encodeWikiPage( WikiPage page )
{
Hashtable ht = new Hashtable();
ht.put( "name", toRPCString(page.getName()) );
Date d = page.getLastModified();
// Here we reset the DST and TIMEZONE offsets of the
// calendar. Unfortunately, I haven't thought of a better
// way to ensure that we're getting the proper date
// from the XML-RPC thingy, except to manually adjust the date.
Calendar cal = Calendar.getInstance();
cal.setTime( d );
cal.add( Calendar.MILLISECOND,
- (cal.get( Calendar.ZONE_OFFSET ) +
(cal.getTimeZone().inDaylightTime( d ) ? cal.get( Calendar.DST_OFFSET ) : 0 )) );
ht.put( "lastModified", cal.getTime() );
ht.put( "version", new Integer(page.getVersion()) );
if( page.getAuthor() != null )
{
ht.put( "author", toRPCString(page.getAuthor()) );
}
return ht;
}
public Vector getRecentChanges( Date since )
{
Collection pages = m_engine.getRecentChanges();
Vector result = new Vector();
Calendar cal = Calendar.getInstance();
cal.setTime( since );
// Convert UTC to our time.
cal.add( Calendar.MILLISECOND,
(cal.get( Calendar.ZONE_OFFSET ) +
(cal.getTimeZone().inDaylightTime(since) ? cal.get( Calendar.DST_OFFSET ) : 0 ) ) );
since = cal.getTime();
for( Iterator i = pages.iterator(); i.hasNext(); )
{
WikiPage page = (WikiPage)i.next();
if( page.getLastModified().after( since ) )
{
result.add( encodeWikiPage( page ) );
}
}
return result;
}
/**
* Simple helper method, turns the incoming page name into
* normal Java string, then checks page condition.
*
* @param pagename Page Name as an RPC string (URL-encoded UTF-8)
* @return Real page name, as Java string.
* @throws XmlRpcException, if there is something wrong with the page.
*/
private String parsePageCheckCondition( String pagename )
throws XmlRpcException
{
pagename = fromRPCString( pagename );
if( !m_engine.pageExists(pagename) )
{
throw new XmlRpcException( ERR_NOPAGE, "No such page '"+pagename+"' found, o master." );
}
return pagename;
}
public Hashtable getPageInfo( String pagename )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
return encodeWikiPage( m_engine.getPage(pagename) );
}
public Hashtable getPageInfoVersion( String pagename, int version )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
return encodeWikiPage( m_engine.getPage( pagename, version ) );
}
public byte[] getPage( String pagename )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
String text = m_engine.getPureText( pagename, -1 );
return toRPCBase64( text );
}
public byte[] getPageVersion( String pagename, int version )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
return toRPCBase64( m_engine.getPureText( pagename, version ) );
}
public byte[] getPageHTML( String pagename )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
return toRPCBase64( m_engine.getHTML( pagename ) );
}
public byte[] getPageHTMLVersion( String pagename, int version )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
return toRPCBase64( m_engine.getHTML( pagename, version ) );
}
public Vector listLinks( String pagename )
throws XmlRpcException
{
pagename = parsePageCheckCondition( pagename );
String pagedata = m_engine.getPureText( pagename, -1 );
LinkCollector localCollector = new LinkCollector();
LinkCollector extCollector = new LinkCollector();
m_engine.textToHTML( new WikiContext(m_engine,pagename),
pagedata,
localCollector,
extCollector );
Vector result = new Vector();
// Add local links.
for( Iterator i = localCollector.getLinks().iterator(); i.hasNext(); )
{
String link = (String) i.next();
Hashtable ht = new Hashtable();
ht.put( "page", toRPCString( link ) );
ht.put( "type", LINK_LOCAL );
ht.put( "href", m_engine.getBaseURL()+"Wiki.jsp?page="+m_engine.encodeName(link) );
result.add( ht );
}
// External links don't need to be changed into XML-RPC strings,
// simply because URLs are by definition ASCII.
for( Iterator i = extCollector.getLinks().iterator(); i.hasNext(); )
{
String link = (String) i.next();
Hashtable ht = new Hashtable();
ht.put( "page", link );
ht.put( "type", LINK_EXTERNAL );
ht.put( "href", link );
result.add( ht );
}
return result;
}
}
|
package com.opencms.file.genericSql;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.security.*;
import java.io.*;
import source.org.apache.java.io.*;
import source.org.apache.java.util.*;
import com.opencms.core.*;
import com.opencms.file.*;
import com.opencms.file.utils.*;
import com.opencms.util.*;
public class CmsDbAccess implements I_CmsConstants, I_CmsQuerys, I_CmsLogChannels {
/**
* The maximum amount of tables.
*/
private static int C_MAX_TABLES = 12;
/**
* Table-key for max-id
*/
private static int C_TABLE_SYSTEMPROPERTIES = 0;
/**
* Table-key for max-id
*/
private static int C_TABLE_GROUPS = 1;
/**
* Table-key for max-id
*/
private static int C_TABLE_GROUPUSERS = 2;
/**
* Table-key for max-id
*/
private static int C_TABLE_USERS = 3;
/**
* Table-key for max-id
*/
private static int C_TABLE_PROJECTS = 4;
/**
* Table-key for max-id
*/
private static int C_TABLE_RESOURCES = 5;
/**
* Table-key for max-id
*/
private static int C_TABLE_FILES = 6;
/**
* Table-key for max-id
*/
private static int C_TABLE_PROPERTYDEF = 7;
/**
* Table-key for max-id
*/
private static int C_TABLE_PROPERTIES = 8;
/**
* Table-key for max-id
*/
private static int C_TABLE_TASK = 9;
/**
* Table-key for max-id
*/
private static int C_TABLE_TASKTYPE = 10;
/**
* Table-key for max-id
*/
private static int C_TABLE_TASKPAR = 11;
/**
* Table-key for max-id
*/
private static int C_TABLE_TASKLOG = 12;
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_DRIVER = "driver";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_URL = "url";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_USER = "user";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_PASSWORD = "password";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_MAX_CONN = "maxConn";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_DIGEST = "digest";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_GUARD = "guard";
/**
* The prepared-statement-pool.
*/
private CmsDbPool m_pool = null;
/**
* The connection guard.
*/
private CmsConnectionGuard m_guard = null;
/**
* A array containing all max-ids for the tables.
*/
private int[] m_maxIds;
/**
* A digest to encrypt the passwords.
*/
private MessageDigest m_digest = null;
/**
* Storage for all exportpoints
*/
private Hashtable m_exportpointStorage=null;
/**
* Instanciates the access-module and sets up all required modules and connections.
* @param config The OpenCms configuration.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsDbAccess(Configurations config)
throws CmsException {
String rbName = null;
String driver = null;
String url = null;
String user = null;
String password = null;
String digest = null;
String exportpoint = null;
String exportpath = null;
int sleepTime;
boolean fillDefaults = true;
int maxConn;
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] init the dbaccess-module.");
}
// read the name of the rb from the properties
rbName = (String)config.getString(C_CONFIGURATION_RESOURCEBROKER);
// read the exportpoints
m_exportpointStorage = new Hashtable();
int i = 0;
while ((exportpoint = config.getString(C_EXPORTPOINT + Integer.toString(i))) != null){
exportpath = config.getString(C_EXPORTPOINT_PATH + Integer.toString(i));
if (exportpath != null){
m_exportpointStorage.put(exportpoint, exportpath);
}
i++;
}
// read all needed parameters from the configuration
driver = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_DRIVER);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read driver from configurations: " + driver);
}
url = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_URL);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read url from configurations: " + url);
}
user = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_USER);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read user from configurations: " + user);
}
password = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_PASSWORD, "");
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read password from configurations: " + password);
}
maxConn = config.getInteger(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_MAX_CONN);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read maxConn from configurations: " + maxConn);
}
digest = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_DIGEST, "MD5");
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read digest from configurations: " + digest);
}
sleepTime = config.getInteger(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_GUARD, 120);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read guard-sleeptime from configurations: " + sleepTime);
}
// create the digest
try {
m_digest = MessageDigest.getInstance(digest);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] digest created, using: " + m_digest.toString() );
}
} catch (NoSuchAlgorithmException e){
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] error creating digest - using clear paswords: " + e.getMessage());
}
}
// create the pool
m_pool = new CmsDbPool(driver, url, user, password, maxConn);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] pool created");
}
// now init the statements
initStatements();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] all statements initialized in the pool");
}
// now init the max-ids for key generation
initMaxIdValues();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] max-ids initialized");
}
// have we to fill the default resource like root and guest?
try {
CmsProject project = readProject(C_PROJECT_ONLINE_ID);
if( project.getName().equals( C_PROJECT_ONLINE ) ) {
// online-project exists - no need of filling defaults
fillDefaults = false;
}
} catch(Exception exc) {
// ignore the exception - fill defaults stays at true.
}
if(fillDefaults) {
// YES!
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] fill default resources");
}
fillDefaults();
}
// start the connection-guard
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] start connection guard");
}
m_guard = new CmsConnectionGuard(m_pool, sleepTime);
m_guard.start();
}
// methods working with users and groups
/**
* Add a new group to the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* @param name The name of the new group.
* @param description The description for the new group.
* @int flags The flags for the new group.
* @param name The name of the parent group (or null).
*
* @return Group
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public CmsGroup createGroup(String name, String description, int flags,String parent)
throws CmsException {
int parentId=C_UNKNOWN_ID;
CmsGroup group=null;
PreparedStatement statement=null;
try{
// get the id of the parent group if nescessary
if ((parent != null) && (!"".equals(parent))) {
parentId=readGroup(parent).getId();
}
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_CREATEGROUP_KEY);
// write new group to the database
statement.setInt(1,nextId(C_TABLE_GROUPS));
statement.setInt(2,parentId);
statement.setString(3,name);
statement.setString(4,checkNull(description));
statement.setInt(5,flags);
statement.executeUpdate();
// create the user group by reading it from the database.
// this is nescessary to get the group id which is generated in the
// database.
group=readGroup(name);
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_CREATEGROUP_KEY,statement);
}
}
return group;
}
/**
* Returns a group object.<P/>
* @param groupname The name of the group that is to be read.
* @return Group.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(String groupname)
throws CmsException {
CmsGroup group=null;
ResultSet res = null;
PreparedStatement statement=null;
try{
// read the group from the database
statement=m_pool.getPreparedStatement(C_GROUPS_READGROUP_KEY);
statement.setString(1,groupname);
res = statement.executeQuery();
// create new Cms group object
if(res.next()) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
res.close();
} else {
throw new CmsException("[" + this.getClass().getName() + "] "+groupname,CmsException.C_NO_GROUP);
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_READGROUP_KEY,statement);
}
}
return group;
}
/**
* Returns a group object.<P/>
* @param groupname The id of the group that is to be read.
* @return Group.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(int id)
throws CmsException {
CmsGroup group=null;
ResultSet res = null;
PreparedStatement statement=null;
try{
// read the group from the database
statement=m_pool.getPreparedStatement(C_GROUPS_READGROUP2_KEY);
statement.setInt(1,id);
res = statement.executeQuery();
// create new Cms group object
if(res.next()) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
res.close();
} else {
throw new CmsException("[" + this.getClass().getName() + "] "+id,CmsException.C_NO_GROUP);
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_READGROUP2_KEY,statement);
}
}
return group;
}
/**
* Writes an already existing group in the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* @param group The group that should be written to the Cms.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void writeGroup(CmsGroup group)
throws CmsException {
PreparedStatement statement = null;
try {
if (group != null){
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_WRITEGROUP_KEY);
statement.setString(1,group.getDescription());
statement.setInt(2,group.getFlags());
statement.setInt(3,group.getParentId());
statement.setInt(4,group.getId());
statement.executeUpdate();
} else {
throw new CmsException("[" + this.getClass().getName() + "] ",CmsException.C_NO_GROUP);
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_WRITEGROUP_KEY,statement);
}
}
}
/**
* Delete a group from the Cms.<BR/>
* Only groups that contain no subgroups can be deleted.
*
* Only the admin can do this.<P/>
*
* @param delgroup The name of the group that is to be deleted.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void deleteGroup(String delgroup)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_DELETEGROUP_KEY);
statement.setString(1,delgroup);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_DELETEGROUP_KEY,statement);
}
}
}
/**
* Returns all groups<P/>
*
* @return users A Vector of all existing groups.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getGroups()
throws CmsException {
Vector groups = new Vector();
CmsGroup group=null;
ResultSet res = null;
PreparedStatement statement = null;
try {
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_GETGROUPS_KEY);
res = statement.executeQuery();
// create new Cms group objects
while ( res.next() ) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
groups.addElement(group);
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETGROUPS_KEY,statement);
}
}
return groups;
}
/**
* Returns all child groups of a groups<P/>
*
*
* @param groupname The name of the group.
* @return users A Vector of all child groups or null.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getChild(String groupname)
throws CmsException {
Vector childs = new Vector();
CmsGroup group;
CmsGroup parent;
ResultSet res = null;
PreparedStatement statement = null;
try {
// get parent group
parent=readGroup(groupname);
// parent group exists, so get all childs
if (parent != null) {
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_GETCHILD_KEY);
statement.setInt(1,parent.getId());
res = statement.executeQuery();
// create new Cms group objects
while ( res.next() ) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
childs.addElement(group);
}
res.close();
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETCHILD_KEY,statement);
}
}
//check if the child vector has no elements, set it to null.
if (childs.size() == 0) {
childs=null;
}
return childs;
}
/**
* Returns the parent group of a groups<P/>
*
*
* @param groupname The name of the group.
* @return The parent group of the actual group or null;
* @exception CmsException Throws CmsException if operation was not succesful.
*/
/*public CmsGroup getParent(String groupname)
throws CmsException {
CmsGroup parent = null;
// read the actual user group to get access to the parent group id.
CmsGroup group= readGroup(groupname);
ResultSet res = null;
PreparedStatement statement = null;
try{
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_GETPARENT_KEY);
statement.setInt(1,group.getParentId());
res = statement.executeQuery();
// create new Cms group object
if(res.next()) {
parent=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETPARENT_KEY,statement);
}
}
return parent;
}*/
/**
* Returns a list of groups of a user.<P/>
*
* @param name The name of the user.
* @return Vector of groups
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(String name)
throws CmsException {
CmsGroup group;
Vector groups=new Vector();
PreparedStatement statement = null;
ResultSet res = null;
try {
// get all all groups of the user
statement = m_pool.getPreparedStatement(C_GROUPS_GETGROUPSOFUSER_KEY);
statement.setString(1,name);
res = statement.executeQuery();
while ( res.next() ) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
groups.addElement(group);
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETGROUPSOFUSER_KEY, statement);
}
}
return groups;
}
/**
* Returns a list of users of a group.<P/>
*
* @param name The name of the group.
* @param type the type of the users to read.
* @return Vector of users
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector getUsersOfGroup(String name, int type)
throws CmsException {
CmsGroup group;
Vector users = new Vector();
PreparedStatement statement = null;
ResultSet res = null;
try {
statement = m_pool.getPreparedStatement(C_GROUPS_GETUSERSOFGROUP_KEY);
statement.setString(1,name);
statement.setInt(2,type);
res = statement.executeQuery();
while( res.next() ) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
CmsUser user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_RECOVERY_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
users.addElement(user);
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETUSERSOFGROUP_KEY, statement);
}
}
return users;
}
/**
* Adds a user to a group.<BR/>
*
* Only the admin can do this.<P/>
*
* @param userid The id of the user that is to be added to the group.
* @param groupid The id of the group.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void addUserToGroup(int userid, int groupid)
throws CmsException {
PreparedStatement statement = null;
// check if user is already in group
if (!userInGroup(userid,groupid)) {
// if not, add this user to the group
try {
// create statement
statement = m_pool.getPreparedStatement(C_GROUPS_ADDUSERTOGROUP_KEY);
// write the new assingment to the database
statement.setInt(1,groupid);
statement.setInt(2,userid);
// flag field is not used yet
statement.setInt(3,C_UNKNOWN_INT);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_ADDUSERTOGROUP_KEY, statement);
}
}
}
}
/**
* Checks if a user is member of a group.<P/>
*
* @param nameid The id of the user to check.
* @param groupid The id of the group to check.
* @return True or False
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public boolean userInGroup(int userid, int groupid)
throws CmsException {
boolean userInGroup=false;
PreparedStatement statement = null;
ResultSet res = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_GROUPS_USERINGROUP_KEY);
statement.setInt(1,groupid);
statement.setInt(2,userid);
res = statement.executeQuery();
if (res.next()){
userInGroup=true;
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_USERINGROUP_KEY, statement);
}
}
return userInGroup;
}
/**
* Removes a user from a group.
*
* Only the admin can do this.<P/>
*
* @param userid The id of the user that is to be added to the group.
* @param groupid The id of the group.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void removeUserFromGroup(int userid, int groupid)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_GROUPS_REMOVEUSERFROMGROUP_KEY);
statement.setInt(1,groupid);
statement.setInt(2,userid);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_REMOVEUSERFROMGROUP_KEY, statement);
}
}
}
/**
* Adds a user to the database.
*
* @param name username
* @param password user-password
* @param description user-description
* @param firstname user-firstname
* @param lastname user-lastname
* @param email user-email
* @param lastlogin user-lastlogin
* @param lastused user-lastused
* @param flags user-flags
* @param additionalInfos user-additional-infos
* @param defaultGroup user-defaultGroup
* @param address user-defauladdress
* @param section user-section
* @param type user-type
*
* @return the created user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser addUser(String name, String password, String description,
String firstname, String lastname, String email,
long lastlogin, long lastused, int flags, Hashtable additionalInfos,
CmsGroup defaultGroup, String address, String section, int type)
throws CmsException {
int id = nextId(C_TABLE_USERS);
byte[] value=null;
PreparedStatement statement = null;
try {
// serialize the hashtable
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(additionalInfos);
oout.close();
value=bout.toByteArray();
// write data to database
statement = m_pool.getPreparedStatement(C_USERS_ADD_KEY);
statement.setInt(1,id);
statement.setString(2,name);
// crypt the password with MD5
statement.setString(3, digest(password));
statement.setString(4, digest(""));
statement.setString(5,checkNull(description));
statement.setString(6,checkNull(firstname));
statement.setString(7,checkNull(lastname));
statement.setString(8,checkNull(email));
statement.setTimestamp(9, new Timestamp(lastlogin));
statement.setTimestamp(10, new Timestamp(lastused));
statement.setInt(11,flags);
statement.setBytes(12,value);
statement.setInt(13,defaultGroup.getId());
statement.setString(14,checkNull(address));
statement.setString(15,checkNull(section));
statement.setInt(16,type);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("[CmsAccessUserInfoMySql/addUserInformation(id,object)]:"+CmsException. C_SERIALIZATION, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_ADD_KEY, statement);
}
}
return readUser(id);
}
/**
* Reads a user from the cms.
*
* @param name the name of the user.
* @param type the type of the user.
* @return the read user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser readUser(String name, int type)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
CmsUser user = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_READ_KEY);
statement.setString(1,name);
statement.setInt(2,type);
res = statement.executeQuery();
// create new Cms user object
if(res.next()) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_RECOVERY_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER);
}
res.close();
return user;
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_READ_KEY, statement);
}
}
}
/**
* Reads a user from the cms, only if the password is correct.
*
* @param name the name of the user.
* @param password the password of the user.
* @param type the type of the user.
* @return the read user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser readUser(String name, String password, int type)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
CmsUser user = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_READPW_KEY);
statement.setString(1,name);
statement.setString(2,digest(password));
statement.setInt(3,type);
res = statement.executeQuery();
// create new Cms user object
if(res.next()) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_RECOVERY_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER);
}
res.close();
return user;
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_READPW_KEY, statement);
}
}
}
/**
* Reads a user from the cms, only if the password is correct.
*
* @param id the id of the user.
* @param type the type of the user.
* @return the read user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser readUser(int id)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
CmsUser user = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_READID_KEY);
statement.setInt(1,id);
res = statement.executeQuery();
// create new Cms user object
if(res.next()) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_RECOVERY_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"]"+id,CmsException.C_NO_USER);
}
res.close();
return user;
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_READID_KEY, statement);
}
}
}
/**
* Writes a user to the database.
*
* @param user the user to write
* @exception thorws CmsException if something goes wrong.
*/
public void writeUser(CmsUser user)
throws CmsException {
byte[] value=null;
PreparedStatement statement = null;
try {
// serialize the hashtable
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(user.getAdditionalInfo());
oout.close();
value=bout.toByteArray();
// write data to database
statement = m_pool.getPreparedStatement(C_USERS_WRITE_KEY);
statement.setString(1,checkNull(user.getDescription()));
statement.setString(2,checkNull(user.getFirstname()));
statement.setString(3,checkNull(user.getLastname()));
statement.setString(4,checkNull(user.getEmail()));
statement.setTimestamp(5, new Timestamp(user.getLastlogin()));
statement.setTimestamp(6, new Timestamp(user.getLastUsed()));
statement.setInt(7,user.getFlags());
statement.setBytes(8,value);
statement.setString(9,checkNull(user.getAddress()));
statement.setString(10,checkNull(user.getSection()));
statement.setInt(11,user.getType());
statement.setInt(12,user.getId());
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("[CmsAccessUserInfoMySql/addUserInformation(id,object)]:"+CmsException. C_SERIALIZATION, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_WRITE_KEY, statement);
}
}
}
/**
* Deletes a user from the database.
*
* @param user the user to delete
* @exception thorws CmsException if something goes wrong.
*/
public void deleteUser(String name)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_DELETE_KEY);
statement.setString(1,name);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_DELETE_KEY, statement);
}
}
}
/**
* Deletes a user from the database.
*
* @param userId The Id of the user to delete
* @exception thorws CmsException if something goes wrong.
*/
public void deleteUser(int id)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_DELETEBYID_KEY);
statement.setInt(1,id);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_DELETEBYID_KEY, statement);
}
}
}
/**
* Gets all users of a type.
*
* @param type The type of the user.
* @exception thorws CmsException if something goes wrong.
*/
public Vector getUsers(int type)
throws CmsException {
Vector users = new Vector();
PreparedStatement statement = null;
ResultSet res = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_GETUSERS_KEY);
statement.setInt(1,type);
res = statement.executeQuery();
// create new Cms user objects
while( res.next() ) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
CmsUser user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_RECOVERY_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
users.addElement(user);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_GETUSERS_KEY, statement);
}
}
return users;
}
/**
* Sets a new password for a user.
*
* @param user the user to set the password for.
* @param password the password to set
* @exception thorws CmsException if something goes wrong.
*/
public void setPassword(String user, String password)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_SETPW_KEY);
statement.setString(1,digest(password));
statement.setString(2,user);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_SETPW_KEY, statement);
}
}
}
/**
* Sets the password, only if the user knows the recovery-password.
*
* @param user the user to set the password for.
* @param recoveryPassword the recoveryPassword the user has to know to set the password.
* @param password the password to set
* @exception thorws CmsException if something goes wrong.
*/
public void recoverPassword(String user, String recoveryPassword, String password )
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_RECOVERPW_KEY);
statement.setString(1,digest(password));
statement.setString(2,user);
statement.setString(3,digest(recoveryPassword));
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_RECOVERPW_KEY, statement);
}
}
}
/**
* Sets a new password for a user.
*
* @param user the user to set the password for.
* @param password the recoveryPassword to set
* @exception thorws CmsException if something goes wrong.
*/
public void setRecoveryPassword(String user, String password)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_SETRECPW_KEY);
statement.setString(1,digest(password));
statement.setString(2,user);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_SETRECPW_KEY, statement);
}
}
}
// methods working with projects
/**
* Creates a project.
*
* @param owner The owner of this project.
* @param group The group for this project.
* @param managergroup The managergroup for this project.
* @param task The task.
* @param name The name of the project to create.
* @param description The description for the new project.
* @param flags The flags for the project (e.g. archive).
* @param type the type for the project (e.g. normal).
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject createProject(CmsUser owner, CmsGroup group, CmsGroup managergroup,
CmsTask task, String name, String description,
int flags, int type)
throws CmsException {
if ((description==null) || (description.length()<1)) {
description=" ";
}
Timestamp createTime = new Timestamp(new java.util.Date().getTime());
PreparedStatement statement = null;
int id = nextId(C_TABLE_PROJECTS);
try {
// write data to database
statement = m_pool.getPreparedStatement(C_PROJECTS_CREATE_KEY);
statement.setInt(1,id);
statement.setInt(2,owner.getId());
statement.setInt(3,group.getId());
statement.setInt(4,managergroup.getId());
statement.setInt(5,task.getId());
statement.setString(6,name);
statement.setString(7,description);
statement.setInt(8,flags);
statement.setTimestamp(9,createTime);
statement.setNull(10,Types.TIMESTAMP);
statement.setInt(11,C_UNKNOWN_ID);
statement.setInt(12,type);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_CREATE_KEY, statement);
}
}
return readProject(id);
}
/**
* Reads a project.
*
* @param id The id of the project.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(int id)
throws CmsException {
PreparedStatement statement = null;
CmsProject project = null;
try {
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_KEY);
statement.setInt(1,id);
ResultSet res = statement.executeQuery();
if(res.next()) {
project = new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE));
} else {
// project not found!
throw new CmsException("[" + this.getClass().getName() + "] " + id,
CmsException.C_NOT_FOUND);
}
res.close();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_KEY, statement);
}
}
return project;
}
/**
* Reads a project by task-id.
*
* @param task The task to read the project for.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(CmsTask task)
throws CmsException {
PreparedStatement statement = null;
CmsProject project = null;
try {
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYTASK_KEY);
statement.setInt(1,task.getId());
ResultSet res = statement.executeQuery();
if(res.next()) {
project = new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE));
} else {
// project not found!
throw new CmsException("[" + this.getClass().getName() + "] " + task,
CmsException.C_NOT_FOUND);
}
res.close();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYTASK_KEY, statement);
}
}
return project;
}
/**
* Returns all projects, which are owned by a user.
*
* @param user The requesting user.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjectsByUser(CmsUser user)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYUSER_KEY);
statement.setInt(1,user.getId());
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYUSER_KEY, statement);
}
}
return(projects);
}
/**
* Returns all projects, which are accessible by a group.
*
* @param group The requesting group.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjectsByGroup(CmsGroup group)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYGROUP_KEY);
statement.setInt(1,group.getId());
statement.setInt(2,group.getId());
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYGROUP_KEY, statement);
}
}
return(projects);
}
/**
* Returns all projects, which are manageable by a group.
*
* @param group The requesting group.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjectsByManagerGroup(CmsGroup group)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYMANAGER_KEY);
statement.setInt(1,group.getId());
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYMANAGER_KEY, statement);
}
}
return(projects);
}
/**
* Returns all projects, with the overgiven state.
*
* @param state The state of the projects to read.
*
* @return a Vector of projects.
*/
public Vector getAllProjects(int state)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYFLAG_KEY);
statement.setInt(1,state);
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYFLAG_KEY, statement);
}
}
return(projects);
}
/**
* Deletes a project from the cms.
* Therefore it deletes all files, resources and properties.
*
* @param project the project to delete.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deleteProject(CmsProject project)
throws CmsException {
// delete the properties
deleteProjectProperties(project);
// delete the files and resources
deleteProjectResources(project);
// finally delete the project
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_DELETE_KEY);
statement.setInt(1,project.getId());
statement.executeUpdate();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_DELETE_KEY, statement);
}
}
}
/**
* Deletes a project from the cms.
* Therefore it deletes all files, resources and properties.
*
* @param project the project to delete.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void writeProject(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_WRITE_KEY);
statement.setInt(1,project.getOwnerId());
statement.setInt(2,project.getGroupId());
statement.setInt(3,project.getManagerGroupId());
statement.setInt(4,project.getFlags());
statement.setTimestamp(5,new Timestamp(project.getPublishingDate()));
statement.setInt(6,project.getPublishedBy());
statement.setInt(7,project.getId());
statement.executeUpdate();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_WRITE_KEY, statement);
}
}
}
// methods working with systemproperties
/**
* Deletes a serializable object from the systempropertys.
*
* @param name The name of the property.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deleteSystemProperty(String name)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_DELETE_KEY);
statement.setString(1,name);
statement.executeUpdate();
}catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_DELETE_KEY, statement);
}
}
}
/**
* Creates a serializable object in the systempropertys.
*
* @param name The name of the property.
* @param object The property-object.
*
* @return object The property-object.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Serializable addSystemProperty(String name, Serializable object)
throws CmsException {
byte[] value;
PreparedStatement statement=null;
try {
// serialize the object
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(object);
oout.close();
value=bout.toByteArray();
// create the object
statement=m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_WRITE_KEY);
statement.setInt(1,nextId(C_TABLE_SYSTEMPROPERTIES));
statement.setString(2,name);
statement.setBytes(3,value);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (IOException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_WRITE_KEY, statement);
}
}
return readSystemProperty(name);
}
/**
* Reads a serializable object from the systempropertys.
*
* @param name The name of the property.
*
* @return object The property-object.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Serializable readSystemProperty(String name)
throws CmsException {
Serializable property=null;
byte[] value;
ResultSet res = null;
PreparedStatement statement = null;
// create get the property data from the database
try {
statement=m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_READ_KEY);
statement.setString(1,name);
res = statement.executeQuery();
if(res.next()) {
value = res.getBytes(C_SYSTEMPROPERTY_VALUE);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
property=(Serializable)oin.readObject();
}
res.close();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}
catch (ClassNotFoundException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_READ_KEY, statement);
}
}
return property;
}
/**
* Writes a serializable object to the systemproperties.
*
* @param name The name of the property.
* @param object The property-object.
*
* @return object The property-object.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Serializable writeSystemProperty(String name, Serializable object)
throws CmsException {
byte[] value=null;
PreparedStatement statement = null;
try {
// serialize the object
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(object);
oout.close();
value=bout.toByteArray();
statement=m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_UPDATE_KEY);
statement.setBytes(1,value);
statement.setString(2,name);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_UPDATE_KEY, statement);
}
}
return readSystemProperty(name);
}
// methods working with propertydef
/**
* Reads a propertydefinition for the given resource type.
*
* @param name The name of the propertydefinition to read.
* @param type The resource type for which the propertydefinition is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(String name, CmsResourceType type)
throws CmsException {
return( readPropertydefinition(name, type.getResourceType() ) );
}
/**
* Reads a propertydefinition for the given resource type.
*
* @param name The name of the propertydefinition to read.
* @param type The resource type for which the propertydefinition is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(String name, int type)
throws CmsException {
CmsPropertydefinition propDef=null;
ResultSet res;
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_READ_KEY);
statement.setString(1,name);
statement.setInt(2,type);
res = statement.executeQuery();
// if resultset exists - return it
if(res.next()) {
propDef = new CmsPropertydefinition( res.getInt(C_PROPERTYDEF_ID),
res.getString(C_PROPERTYDEF_NAME),
res.getInt(C_PROPERTYDEF_RESOURCE_TYPE),
res.getInt(C_PROPERTYDEF_TYPE) );
res.close();
} else {
res.close();
// not found!
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NOT_FOUND);
}
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_READ_KEY, statement);
}
}
return propDef;
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsResourceType resourcetype)
throws CmsException {
return(readAllPropertydefinitions(resourcetype.getResourceType()));
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(int resourcetype)
throws CmsException {
Vector metadefs = new Vector();
ResultSet result = null;
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_READALL_A_KEY);
statement.setInt(1,resourcetype);
result = statement.executeQuery();
while(result.next()) {
metadefs.addElement( new CmsPropertydefinition( result.getInt(C_PROPERTYDEF_ID),
result.getString(C_PROPERTYDEF_NAME),
result.getInt(C_PROPERTYDEF_RESOURCE_TYPE),
result.getInt(C_PROPERTYDEF_TYPE) ) );
}
result.close();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_READALL_A_KEY, statement);
}
}
return(metadefs);
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
* @param type The type of the propertydefinition (normal|mandatory|optional).
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsResourceType resourcetype, int type)
throws CmsException {
return(readAllPropertydefinitions(resourcetype.getResourceType(), type));
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
* @param type The type of the propertydefinition (normal|mandatory|optional).
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(int resourcetype, int type)
throws CmsException {
Vector metadefs = new Vector();
PreparedStatement statement = null;
ResultSet result = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_READALL_B_KEY);
statement.setInt(1,resourcetype);
statement.setInt(2,type);
result = statement.executeQuery();
while(result.next()) {
metadefs.addElement( new CmsPropertydefinition( result.getInt(C_PROPERTYDEF_ID),
result.getString(C_PROPERTYDEF_NAME),
result.getInt(C_PROPERTYDEF_RESOURCE_TYPE),
result.getInt(C_PROPERTYDEF_TYPE) ) );
}
result.close();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_READALL_B_KEY, statement);
}
}
return(metadefs);
}
/**
* Creates the propertydefinitions for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param name The name of the propertydefinitions to overwrite.
* @param resourcetype The resource-type for the propertydefinitions.
* @param type The type of the propertydefinitions (normal|mandatory|optional)
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition createPropertydefinition(String name,
CmsResourceType resourcetype, int type)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_CREATE_KEY);
statement.setInt(1,nextId(C_TABLE_PROPERTYDEF));
statement.setString(2,name);
statement.setInt(3,resourcetype.getResourceType());
statement.setInt(4,type);
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_CREATE_KEY, statement);
}
}
return(readPropertydefinition(name, resourcetype));
}
/**
* Delete the propertydefinitions for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param metadef The propertydefinitions to be deleted.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deletePropertydefinition(CmsPropertydefinition metadef)
throws CmsException {
PreparedStatement statement = null;
try {
if(countProperties(metadef) != 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(),
CmsException.C_MANDATORY_PROPERTY);
}
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_DELETE_KEY);
statement.setInt(1, metadef.getId() );
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_DELETE_KEY, statement);
}
}
}
/**
* Updates the propertydefinition for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param metadef The propertydef to be deleted.
*
* @return The propertydefinition, that was written.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition writePropertydefinition(CmsPropertydefinition metadef)
throws CmsException {
PreparedStatement statement = null;
CmsPropertydefinition returnValue = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_UPDATE_KEY);
statement.setInt(1, metadef.getPropertydefType() );
statement.setInt(2, metadef.getId() );
statement.executeUpdate();
returnValue = readPropertydefinition(metadef.getName(), metadef.getType());
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_UPDATE_KEY, statement);
}
}
return returnValue;
}
// methods working with properties
/**
* Returns the amount of properties for a propertydefinition.
*
* @param metadef The propertydefinition to test.
*
* @return the amount of properties for a propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
private int countProperties(CmsPropertydefinition metadef)
throws CmsException {
ResultSet result = null;
PreparedStatement statement = null;
int returnValue;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_READALL_COUNT_KEY);
statement.setInt(1, metadef.getId());
result = statement.executeQuery();
if( result.next() ) {
returnValue = result.getInt(1) ;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(),
CmsException.C_UNKNOWN_EXCEPTION);
}
result.close();
} catch(SQLException exc) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_READALL_COUNT_KEY, statement);
}
}
return returnValue;
}
/**
* Returns a property of a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @return property The property as string or null if the property not exists.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public String readProperty(String meta, int resourceId, int resourceType)
throws CmsException {
ResultSet result;
PreparedStatement statement = null;
String returnValue = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_READ_KEY);
statement.setInt(1, resourceId);
statement.setString(2, meta);
statement.setInt(3, resourceType);
result = statement.executeQuery();
// if resultset exists - return it
if(result.next()) {
returnValue = result.getString(C_PROPERTY_VALUE);
}
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_READ_KEY, statement);
}
}
return returnValue;
}
/**
* Writes a property for a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param value The value for the property to be set.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeProperty(String meta, String value, int resourceId,
int resourceType)
throws CmsException {
CmsPropertydefinition propdef = readPropertydefinition(meta, resourceType);
if( propdef == null) {
// there is no propertydefinition for with the overgiven name for the resource
throw new CmsException("[" + this.getClass().getName() + "] " + meta,
CmsException.C_NOT_FOUND);
} else {
// write the property into the db
PreparedStatement statement = null;
boolean newprop=true;
try {
if( readProperty(propdef.getName(), resourceId, resourceType) != null) {
// property exists already - use update.
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_UPDATE_KEY);
statement.setString(1, checkNull(value) );
statement.setInt(2, resourceId);
statement.setInt(3, propdef.getId());
statement.executeUpdate();
newprop=false;
} else {
// property dosen't exist - use create.
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_CREATE_KEY);
statement.setInt(1, nextId(C_TABLE_PROPERTIES));
statement.setInt(2, propdef.getId());
statement.setInt(3, resourceId);
statement.setString(4, value);
statement.executeUpdate();
newprop=true;
}
} catch(SQLException exc) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
if (newprop) {
m_pool.putPreparedStatement(C_PROPERTIES_CREATE_KEY, statement);
} else {
m_pool.putPreparedStatement(C_PROPERTIES_UPDATE_KEY, statement);
}
}
}
}
}
/**
* Writes a couple of Properties for a file or folder.
*
* @param propertyinfos A Hashtable with propertydefinition- property-pairs as strings.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeProperties(Hashtable propertyinfos, int resourceId, int resourceType)
throws CmsException {
// get all metadefs
Enumeration keys = propertyinfos.keys();
// one metainfo-name:
String key;
while(keys.hasMoreElements()) {
key = (String) keys.nextElement();
writeProperty(key, (String) propertyinfos.get(key), resourceId, resourceType);
}
}
/**
* Returns a list of all properties of a file or folder.
*
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @return Vector of properties as Strings.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Hashtable readAllProperties(int resourceId, int resourceType)
throws CmsException {
Hashtable returnValue = new Hashtable();
ResultSet result = null;
PreparedStatement statement = null;
try {
// create project
statement = m_pool.getPreparedStatement(C_PROPERTIES_READALL_KEY);
statement.setInt(1, resourceId);
statement.setInt(2, resourceType);
result = statement.executeQuery();
while(result.next()) {
returnValue.put(result.getString(C_PROPERTYDEF_NAME),
result.getString(C_PROPERTY_VALUE));
}
result.close();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_READALL_KEY, statement);
}
}
return(returnValue);
}
/**
* Deletes all properties for a file or folder.
*
* @param resourceId The id of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteAllProperties(int resourceId)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_DELETEALL_KEY);
statement.setInt(1, resourceId);
statement.executeQuery();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_DELETEALL_KEY, statement);
}
}
}
/**
* Deletes a property for a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteProperty(String meta, int resourceId, int resourceType)
throws CmsException {
CmsPropertydefinition propdef = readPropertydefinition(meta, resourceType);
if( propdef == null) {
// there is no propdefinition with the overgiven name for the resource
throw new CmsException("[" + this.getClass().getName() + "] " + meta,
CmsException.C_NOT_FOUND);
} else {
// delete the metainfo in the db
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_DELETE_KEY);
statement.setInt(1, propdef.getId());
statement.setInt(2, resourceId);
statement.executeUpdate();
} catch(SQLException exc) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_DELETE_KEY, statement);
}
}
}
}
/**
* Deletes all properties for a project.
*
* @param project The project to delete.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteProjectProperties(CmsProject project)
throws CmsException {
// get all resources of the project
Vector resources = readResources(project);
for( int i = 0; i < resources.size(); i++) {
// delete the properties for each resource in project
deleteAllProperties( ((CmsResource) resources.elementAt(i)).getResourceId());
}
}
// methods working with resources
/**
* Copies a resource from the online project to a new, specified project.<br>
*
* @param project The project to be published.
* @param onlineProject The online project of the OpenCms.
* @param resource The resource to be copied to the offline project.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyResourceToProject(CmsProject project,
CmsProject onlineProject,
CmsResource resource)
throws CmsException {
// get the parent resource in the offline project
int id=C_UNKNOWN_ID;
try {
CmsResource parent=readResource(project,resource.getParent());
id=parent.getResourceId();
} catch (CmsException e) {
}
resource.setState(C_STATE_UNCHANGED);
resource.setParentId(id);
createResource(project,onlineProject,resource);
}
/**
* Publishes a specified project to the online project. <br>
*
* @param project The project to be published.
* @param onlineProject The online project of the OpenCms.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void publishProject(CmsUser user, int projectId, CmsProject onlineProject)
throws CmsException {
CmsAccessFilesystem discAccess = new CmsAccessFilesystem(m_exportpointStorage);
CmsFolder currentFolder = null;
CmsFile currentFile = null;
Vector offlineFolders;
Vector offlineFiles;
Vector deletedFolders = new Vector();
// folderIdIndex: offlinefolderId | onlinefolderId
Hashtable folderIdIndex = new Hashtable();
// read all folders in offlineProject
offlineFolders = readFolders(projectId);
for(int i = 0; i < offlineFolders.size(); i++) {
currentFolder = ((CmsFolder)offlineFolders.elementAt(i));
// C_STATE_DELETE
if (currentFolder.getState() == C_STATE_DELETED){
deletedFolders.addElement(currentFolder);
// C_STATE_NEW
}else if (currentFolder.getState() == C_STATE_NEW){
// export to filesystem if necessary
String exportKey = checkExport(currentFolder.getAbsolutePath());
if (exportKey != null){
discAccess.createFolder(currentFolder.getAbsolutePath(), exportKey);
}
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFolder.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId);
}
// create the new folder and insert its id in the folderindex
CmsFolder newFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(),
currentFolder.getAbsolutePath());
newFolder.setState(C_STATE_UNCHANGED);
writeFolder(onlineProject, newFolder, false);
folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(newFolder.getResourceId()));
// copy properties
try {
Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType());
writeProperties(props, newFolder.getResourceId(), newFolder.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + newFolder.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_CHANGED
}else if (currentFolder.getState() == C_STATE_CHANGED){
// export to filesystem if necessary
String exportKey = checkExport(currentFolder.getAbsolutePath());
if (exportKey != null){
discAccess.createFolder(currentFolder.getAbsolutePath(), exportKey);
}
CmsFolder onlineFolder = null;
try{
onlineFolder = readFolder(onlineProject.getId(), currentFolder.getAbsolutePath());
} catch(CmsException exc) {
// if folder does not exist create it
if (exc.getType() == CmsException.C_NOT_FOUND){
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFolder.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId);
}
// create the new folder
onlineFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(),
currentFolder.getAbsolutePath());
onlineFolder.setState(C_STATE_UNCHANGED);
writeFolder(onlineProject, onlineFolder, false);
}else {
throw exc;
}
}// end of catch
PreparedStatement statement = null;
try {
// update the onlineFolder with data from offlineFolder
statement = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_KEY);
statement.setInt(1,currentFolder.getType());
statement.setInt(2,currentFolder.getFlags());
statement.setInt(3,currentFolder.getOwnerId());
statement.setInt(4,currentFolder.getGroupId());
statement.setInt(5,onlineFolder.getProjectId());
statement.setInt(6,currentFolder.getAccessFlags());
statement.setInt(7,C_STATE_UNCHANGED);
statement.setInt(8,currentFolder.isLockedBy());
statement.setInt(9,currentFolder.getLauncherType());
statement.setString(10,currentFolder.getLauncherClassname());
statement.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statement.setInt(12,currentFolder.getResourceLastModifiedBy());
statement.setInt(13,0);
statement.setInt(14,currentFolder.getFileId());
statement.setInt(15,onlineFolder.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_KEY, statement);
}
}
folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(onlineFolder.getResourceId()));
// copy properties
try {
deleteAllProperties(onlineFolder.getResourceId());
Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType());
writeProperties(props, onlineFolder.getResourceId(), currentFolder.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + onlineFolder.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_UNCHANGED
}else if(currentFolder.getState() == C_STATE_UNCHANGED){
CmsFolder onlineFolder = null;
try{
onlineFolder = readFolder(onlineProject.getId(), currentFolder.getAbsolutePath());
} catch(CmsException exc){
if ( exc.getType() == CmsException.C_NOT_FOUND){
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFolder.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId);
}
// create the new folder
onlineFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(),
currentFolder.getAbsolutePath());
onlineFolder.setState(C_STATE_UNCHANGED);
writeFolder(onlineProject, onlineFolder, false);
// copy properties
try {
Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType());
writeProperties(props, onlineFolder.getResourceId(), onlineFolder.getType());
} catch(CmsException exc2) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + onlineFolder.toString() + " Message= " + exc.getMessage());
}
}
}else {
throw exc;
}
}// end of catch
folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(onlineFolder.getResourceId()));
}// end of else if
}// end of for(...
// now read all FILES in offlineProject
offlineFiles = readFiles(projectId);
for (int i = 0; i < offlineFiles.size(); i++){
currentFile = ((CmsFile)offlineFiles.elementAt(i));
if (currentFile.getName().startsWith(C_TEMP_PREFIX)) {
removeFile(projectId,currentFile.getAbsolutePath());
// C_STATE_DELETE
}else if (currentFile.getState() == C_STATE_DELETED){
// delete in filesystem if necessary
String exportKey = checkExport(currentFile.getAbsolutePath());
if (exportKey != null){
try {
discAccess.removeResource(currentFile.getAbsolutePath(), exportKey);
} catch (Exception ex) {
}
}
CmsFile currentOnlineFile = readFile(onlineProject.getId(),onlineProject.getId(),currentFile.getAbsolutePath());
try {
deleteAllProperties(currentOnlineFile.getResourceId());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + currentOnlineFile.toString() + " Message= " + exc.getMessage());
}
}
try {
deleteResource(currentOnlineFile.getResourceId());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting resource for " + currentOnlineFile.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_CHANGED
}else if ( currentFile.getState() == C_STATE_CHANGED){
// export to filesystem if necessary
String exportKey = checkExport(currentFile.getAbsolutePath());
if (exportKey != null){
discAccess.writeFile(currentFile.getAbsolutePath(), exportKey, readFileContent(currentFile.getFileId()));
}
CmsFile onlineFile = null;
try{
onlineFile = readFileHeader(onlineProject.getId(), currentFile.getAbsolutePath());
} catch(CmsException exc){
if ( exc.getType() == CmsException.C_NOT_FOUND){
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFile.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFile.getParentId()), parentId);
}
// create a new File
currentFile.setState(C_STATE_UNCHANGED);
onlineFile = createFile(onlineProject, onlineProject, currentFile, user.getId(), parentId.intValue(),
currentFile.getAbsolutePath(), false);
}
}// end of catch
PreparedStatement statement = null;
try {
// update the onlineFile with data from offlineFile
statement = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_FILE_KEY);
statement.setInt(1,currentFile.getType());
statement.setInt(2,currentFile.getFlags());
statement.setInt(3,currentFile.getOwnerId());
statement.setInt(4,currentFile.getGroupId());
statement.setInt(5,onlineFile.getProjectId());
statement.setInt(6,currentFile.getAccessFlags());
statement.setInt(7,C_STATE_UNCHANGED);
statement.setInt(8,currentFile.isLockedBy());
statement.setInt(9,currentFile.getLauncherType());
statement.setString(10,currentFile.getLauncherClassname());
statement.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statement.setInt(12,currentFile.getResourceLastModifiedBy());
statement.setInt(13,currentFile.getLength());
statement.setInt(14,currentFile.getFileId());
statement.setInt(15,onlineFile.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_FILE_KEY, statement);
}
}
// copy properties
try {
deleteAllProperties(onlineFile.getResourceId());
Hashtable props = readAllProperties(currentFile.getResourceId(), currentFile.getType());
writeProperties(props, onlineFile.getResourceId(), currentFile.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + onlineFile.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_NEW
}else if (currentFile.getState() == C_STATE_NEW){
// export to filesystem if necessary
String exportKey = checkExport(currentFile.getAbsolutePath());
if (exportKey != null){
discAccess.writeFile(currentFile.getAbsolutePath(), exportKey, readFileContent(currentFile.getFileId()));
}
// get parentId for onlineFile either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFile.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFile.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFile.getParentId()), parentId);
}
// create the new file
CmsFile newFile = createFile(onlineProject, onlineProject, currentFile, user.getId(),
parentId.intValue(),currentFile.getAbsolutePath(), false);
newFile.setState(C_STATE_UNCHANGED);
writeFile(onlineProject, onlineProject,newFile,false);
// copy properties
try {
Hashtable props = readAllProperties(currentFile.getResourceId(), currentFile.getType());
writeProperties(props, newFile.getResourceId(), newFile.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + newFile.toString() + " Message= " + exc.getMessage());
}
}
}
}// end of for(...
// now delete the "deleted" folders
for(int i = deletedFolders.size()-1; i > -1; i
currentFolder = ((CmsFolder)deletedFolders.elementAt(i));
String exportKey = checkExport(currentFolder.getAbsolutePath());
if (exportKey != null){
discAccess.removeResource(currentFolder.getAbsolutePath(), exportKey);
}
try {
deleteAllProperties(currentFolder.getResourceId());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + currentFolder.toString() + " Message= " + exc.getMessage());
}
}
removeFolderForPublish(onlineProject, currentFolder.getAbsolutePath());
}// end of for
//clearFilesTable();
}
/**
* Private helper method for publihing into the filesystem.
* test if resource must be written to the filesystem
*
* @param filename Name of a resource in the OpenCms system.
* @return key in m_exportpointStorage Hashtable or null.
*/
private String checkExport(String filename){
String key = null;
String exportpoint = null;
Enumeration e = m_exportpointStorage.keys();
while (e.hasMoreElements()) {
exportpoint = (String)e.nextElement();
if (filename.startsWith(exportpoint)){
return exportpoint;
}
}
return key;
}
/**
* Private helper method to read the fileContent for publishProject(export).
*
* @param fileId the fileId.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
private byte[] readFileContent(int fileId)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
byte[] returnValue = null;
try {
// read fileContent from database
statement = m_pool.getPreparedStatement(C_FILE_READ_KEY);
statement.setInt(1,fileId);
res = statement.executeQuery();
if (res.next()) {
returnValue = res.getBytes(C_FILE_CONTENT);
} else {
throw new CmsException("["+this.getClass().getName()+"]"+fileId,CmsException.C_NOT_FOUND);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_FILE_READ_KEY, statement);
}
}
return returnValue;
}
/**
* Private helper method to delete a resource.
*
* @param id the id of the resource to delete.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
private void deleteResource(int id)
throws CmsException {
PreparedStatement statement = null;
try {
// read resource data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETEBYID_KEY);
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETEBYID_KEY, statement);
}
}
}
/**
* Reads a resource from the Cms.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return The resource read.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
private CmsResource readResource(CmsProject project, String filename)
throws CmsException {
CmsResource file = null;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read resource data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READ_KEY);
statement.setString(1,filename);
statement.setInt(2,project.getId());
res = statement.executeQuery();
// create new resource
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectId=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
int resSize= res.getInt(C_RESOURCES_SIZE);
file=new CmsResource(resId,parentId,fileId,resName,resType,resFlags,
userId,groupId,projectId,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
resSize);
res.close();
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readResource "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_KEY, statement);
}
}
return file;
}
/**
* Reads all resource from the Cms, that are in one project.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
*
* @return A Vecor of resources.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readResources(CmsProject project)
throws CmsException {
Vector resources = new Vector();
CmsResource file;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read resource data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READBYPROJECT_KEY);
statement.setInt(1,project.getId());
res = statement.executeQuery();
// create new resource
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectId=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
int resSize= res.getInt(C_RESOURCES_SIZE);
file=new CmsResource(resId,parentId,fileId,resName,resType,resFlags,
userId,groupId,projectId,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
resSize);
resources.addElement(file);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception ex) {
throw new CmsException("["+this.getClass().getName()+"]", ex);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READBYPROJECT_KEY, statement);
}
}
return resources;
}
/**
* Reads all folders from the Cms, that are in one project.<BR/>
*
* @param project The project in which the folders are.
*
* @return A Vecor of folders.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readFolders(int projectId)
throws CmsException {
Vector folders = new Vector();
CmsFolder folder;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read folder data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READFOLDERSBYPROJECT_KEY);
statement.setInt(1,projectId);
res = statement.executeQuery();
// create new folder
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,created,
modified,modifiedBy);
folders.addElement(folder);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception ex) {
throw new CmsException("["+this.getClass().getName()+"]", ex);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READFOLDERSBYPROJECT_KEY, statement);
}
}
return folders;
}
/**
* Reads all files from the Cms, that are in one project.<BR/>
*
* @param project The project in which the files are.
*
* @return A Vecor of files.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readFiles(int projectId)
throws CmsException {
Vector files = new Vector();
CmsFile file;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read file data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READFILESBYPROJECT_KEY);
statement.setInt(1,projectId);
res = statement.executeQuery();
// create new file
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
files.addElement(file);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception ex) {
throw new CmsException("["+this.getClass().getName()+"]", ex);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READFILESBYPROJECT_KEY, statement);
}
}
return files;
}
/**
* Creates a new resource from an given CmsResource object.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param resource The resource to be written to the Cms.
*
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void createResource(CmsProject project,
CmsProject onlineProject,
CmsResource resource)
throws CmsException {
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
int id=nextId(C_TABLE_RESOURCES);
// write new resource to the database
statement.setInt(1,id);
statement.setInt(2,resource.getParentId());
statement.setString(3,resource.getAbsolutePath());
statement.setInt(4,resource.getType());
statement.setInt(5,resource.getFlags());
statement.setInt(6,resource.getOwnerId());
statement.setInt(7,resource.getGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,resource.getFileId());
statement.setInt(10,resource.getAccessFlags());
statement.setInt(11,resource.getState());
statement.setInt(12,resource.isLockedBy());
statement.setInt(13,resource.getLauncherType());
statement.setString(14,resource.getLauncherClassname());
statement.setTimestamp(15,new Timestamp(resource.getDateCreated()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,resource.getLength());
statement.setInt(18,resource.getResourceLastModifiedBy());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
}
// return readResource(project,resource.getAbsolutePath());
}
/**
* Deletes a specified project
*
* @param project The project to be deleted.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteProjectResources(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
try {
// delete all project-resources.
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETE_PROJECT_KEY);
statement.setInt(1,project.getId());
statement.executeQuery();
// delete all project-files.
//clearFilesTable();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETE_PROJECT_KEY, statement);
}
}
}
/**
* Reads a file from the Cms.<BR/>
*
* @param projectId The Id of the project in which the resource will be used.
* @param onlineProjectId The online projectId of the OpenCms.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFile(int projectId,
int onlineProjectId,
String filename)
throws CmsException {
CmsFile file = null;
PreparedStatement statement = null;
ResultSet res = null;
try {
// if the actual project is the online project read file header and content
// from the online project
if (projectId == onlineProjectId) {
statement = m_pool.getPreparedStatement(C_FILE_READ_ONLINE_KEY);
statement.setString(1, filename);
statement.setInt(2,onlineProjectId);
res = statement.executeQuery();
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
int resSize= res.getInt(C_RESOURCES_SIZE);
byte[] content=res.getBytes(C_RESOURCES_FILE_CONTENT);
/*InputStream inStream = res.getBinaryStream(C_RESOURCES_FILE_CONTENT);
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer= new byte[128];
while (true) {
int bytesRead = inStream.read(buffer);
if (bytesRead ==-1) break;
outStream.write(buffer,0,bytesRead);
}
byte[] content=outStream.toByteArray();*/
file=new CmsFile(resId,parentId,fileId,filename,resType,resFlags,userId,
groupId,onlineProjectId,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
content,resSize);
res.close();
} else {
throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND);
}
} else {
// reading a file from an offline project must be done in two steps:
// first read the file header from the offline project, then get either
// the file content of the offline project (if it is already existing)
// or form the online project.
// get the file header
file=readFileHeader(projectId, filename);
// check if the file is marked as deleted
if (file.getState() == C_STATE_DELETED) {
throw new CmsException("["+this.getClass().getName()+"] "+CmsException.C_NOT_FOUND);
}
// read the file content
statement = m_pool.getPreparedStatement(C_FILE_READ_KEY);
statement.setInt(1,file.getFileId());
res = statement.executeQuery();
if (res.next()) {
file.setContents(res.getBytes(C_FILE_CONTENT));
} else {
throw new CmsException("["+this.getClass().getName()+"]"+filename,CmsException.C_NOT_FOUND);
}
res.close();
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if (projectId == onlineProjectId) {
if( statement != null) {
m_pool.putPreparedStatement(C_FILE_READ_ONLINE_KEY, statement);
}
}else{
if( statement != null) {
m_pool.putPreparedStatement(C_FILE_READ_KEY, statement);
}
}
}
return file;
}
/**
* Reads all file headers of a file in the OpenCms.<BR>
* The reading excludes the filecontent.
*
* @param filename The name of the file to be read.
*
* @return Vector of file headers read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readAllFileHeaders(String filename)
throws CmsException {
CmsFile file=null;
ResultSet res =null;
Vector allHeaders = new Vector();
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_RESOURCES_READ_ALL_KEY);
// read file header data from database
statement.setString(1, filename);
res = statement.executeQuery();
// create new file headers
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
allHeaders.addElement(file);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readAllFileHeaders "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_ALL_KEY, statement);
}
}
return allHeaders;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param projectId The Id of the project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int projectId, String filename)
throws CmsException {
CmsFile file=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_READ_KEY);
// read file data from database
statement.setString(1, filename);
statement.setInt(2, projectId);
res = statement.executeQuery();
// create new file
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
res.close();
// check if this resource is marked as deleted
if (file.getState() == C_STATE_DELETED) {
throw new CmsException("["+this.getClass().getName()+"] "+file.getAbsolutePath(),CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (CmsException ex) {
throw ex;
} catch( Exception exc ) {
throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_KEY, statement);
}
}
return file;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param resourceId The Id of the resource.
*
* @return file The read file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int resourceId)
throws CmsException {
CmsFile file=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_READBYID_KEY);
// read file data from database
statement.setInt(1, resourceId);
res = statement.executeQuery();
// create new file
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
res.close();
// check if this resource is marked as deleted
if (file.getState() == C_STATE_DELETED) {
throw new CmsException("["+this.getClass().getName()+"] "+file.getAbsolutePath(),CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+resourceId,CmsException.C_NOT_FOUND);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (CmsException ex) {
throw ex;
} catch( Exception exc ) {
throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READBYID_KEY, statement);
}
}
return file;
}
/**
* Creates a new file with the given content and resourcetype.
*
* @param user The user who wants to create the file.
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param filename The complete name of the new file (including pathinformation).
* @param flags The flags of this resource.
* @param parentId The parentId of the resource.
* @param contents The contents of the new file.
* @param resourceType The resourceType of the new file.
*
* @return file The created file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile createFile(CmsUser user,
CmsProject project,
CmsProject onlineProject,
String filename, int flags,int parentId,
byte[] contents, CmsResourceType resourceType)
throws CmsException {
// it is not allowed, that there is no content in the file
// TODO: check if this can be done in another way:
if(contents.length == 0) {
contents = " ".getBytes();
}
int state= C_STATE_NEW;
// Test if the file is already there and marked as deleted.
// If so, delete it
try {
readFileHeader(project.getId(),filename);
} catch (CmsException e) {
// if the file is maked as deleted remove it!
if (e.getType()==CmsException.C_RESOURCE_DELETED) {
removeFile(project.getId(),filename);
state=C_STATE_CHANGED;
}
}
int resourceId = nextId(C_TABLE_RESOURCES);
int fileId = nextId(C_TABLE_FILES);
PreparedStatement statement = null;
PreparedStatement statementFileWrite = null;
try {
statement = m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
// write new resource to the database
statement.setInt(1,resourceId);
statement.setInt(2,parentId);
statement.setString(3, filename);
statement.setInt(4,resourceType.getResourceType());
statement.setInt(5,flags);
statement.setInt(6,user.getId());
statement.setInt(7,user.getDefaultGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,fileId);
statement.setInt(10,C_ACCESS_DEFAULT_FLAGS);
statement.setInt(11,state);
statement.setInt(12,C_UNKNOWN_ID);
statement.setInt(13,resourceType.getLauncherType());
statement.setString(14,resourceType.getLauncherClass());
statement.setTimestamp(15,new Timestamp(System.currentTimeMillis()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,contents.length);
statement.setInt(18,user.getId());
statement.executeUpdate();
statementFileWrite = m_pool.getPreparedStatement(C_FILES_WRITE_KEY);
statementFileWrite.setInt(1,fileId);
statementFileWrite.setBytes(2,contents);
statementFileWrite.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
if( statementFileWrite != null) {
m_pool.putPreparedStatement(C_FILES_WRITE_KEY, statementFileWrite);
}
}
return readFile(project.getId(),onlineProject.getId(),filename);
}
/**
* Creates a new file from an given CmsFile object and a new filename.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The file to be written to the Cms.
* @param user The Id of the user who changed the resourse.
* @param parentId The parentId of the resource.
* @param filename The complete new name of the file (including pathinformation).
*
* @return file The created file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile createFile(CmsProject project,
CmsProject onlineProject,
CmsFile file,
int userId,
int parentId, String filename, boolean copy)
throws CmsException {
int state=0;
if (project.equals(onlineProject)) {
state= file.getState();
} else {
state=C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it
try {
readFileHeader(project.getId(),filename);
} catch (CmsException e) {
// if the file is maked as deleted remove it!
if (e.getType()==CmsException.C_RESOURCE_DELETED) {
removeFile(project.getId(),filename);
state=C_STATE_CHANGED;
}
}
int newFileId = file.getFileId();
int resourceId = nextId(C_TABLE_RESOURCES);
if (copy){
PreparedStatement statementFileWrite = null;
try {
newFileId = nextId(C_TABLE_FILES);
statementFileWrite = m_pool.getPreparedStatement(C_FILES_WRITE_KEY);
statementFileWrite.setInt(1, newFileId);
statementFileWrite.setBytes(2, file.getContents());
statementFileWrite.executeUpdate();
} catch (SQLException se) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsAccessFileMySql] " + se.getMessage());
se.printStackTrace();
}
}finally {
if( statementFileWrite != null) {
m_pool.putPreparedStatement(C_FILES_WRITE_KEY, statementFileWrite);
}
}
}
PreparedStatement statementResourceWrite = null;
try {
statementResourceWrite = m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
statementResourceWrite.setInt(1,resourceId);
statementResourceWrite.setInt(2,parentId);
statementResourceWrite.setString(3, filename);
statementResourceWrite.setInt(4,file.getType());
statementResourceWrite.setInt(5,file.getFlags());
statementResourceWrite.setInt(6,file.getOwnerId());
statementResourceWrite.setInt(7,file.getGroupId());
statementResourceWrite.setInt(8,project.getId());
statementResourceWrite.setInt(9,newFileId);
statementResourceWrite.setInt(10,file.getAccessFlags());
statementResourceWrite.setInt(11,state);
statementResourceWrite.setInt(12,file.isLockedBy());
statementResourceWrite.setInt(13,file.getLauncherType());
statementResourceWrite.setString(14,file.getLauncherClassname());
statementResourceWrite.setTimestamp(15,new Timestamp(file.getDateCreated()));
statementResourceWrite.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statementResourceWrite.setInt(17,file.getLength());
statementResourceWrite.setInt(18,userId);
statementResourceWrite.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statementResourceWrite != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statementResourceWrite);
}
}
return readFile(project.getId(),onlineProject.getId(),filename);
}
/**
* Deletes a file in the database.
* This method is used to physically remove a file form the database.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void removeFile(int projectId, String filename)
throws CmsException{
PreparedStatement statement = null;
try {
// delete the file header
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETE_KEY);
statement.setString(1, filename);
statement.setInt(2,projectId);
statement.executeUpdate();
// delete the file content
// clearFilesTable();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETE_KEY, statement);
}
}
}
/**
* Renames the file to the new name.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param userId The user id
* @param oldfileID The id of the resource which will be renamed.
* @param newname The new name of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void renameFile(CmsProject project,
CmsProject onlineProject,
int userId,
int oldfileID,
String newname)
throws CmsException {
PreparedStatement statement = null;
try{
statement = m_pool.getPreparedStatement(C_RESOURCES_RENAMERESOURCE_KEY);
statement.setString(1,newname);
statement.setInt(2,userId);
statement.setInt(3,oldfileID);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_RENAMERESOURCE_KEY, statement);
}
}
}
/**
* Deletes a folder in the database.
* This method is used to physically remove a folder form the database.
* It is internally used by the publish project method.
*
* @param project The project in which the resource will be used.
* @param foldername The complete path of the folder.
* @exception CmsException Throws CmsException if operation was not succesful
*/
private void removeFolderForPublish(CmsProject project, String foldername)
throws CmsException{
PreparedStatement statement = null;
try {
// delete the folder
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETE_KEY);
statement.setString(1, foldername);
statement.setInt(2,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETE_KEY, statement);
}
}
}
/**
* Reads a folder from the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param foldername The name of the folder to be read.
*
* @return The read folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder readFolder(int projectId, String foldername)
throws CmsException {
CmsFolder folder=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_READ_KEY);
statement.setString(1, foldername);
statement.setInt(2,projectId);
res = statement.executeQuery();
// create new resource
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,created,
modified,modifiedBy);
}else {
throw new CmsException("["+this.getClass().getName()+"] "+foldername,CmsException.C_NOT_FOUND);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readFolder "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_KEY, statement);
}
}
return folder;
}
/**
* Writes the fileheader to the Cms.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFileHeader(CmsProject project,
CmsProject onlineProject,
CmsFile file,boolean changed)
throws CmsException {
ResultSet res;
ResultSet tmpres;
byte[] content;
PreparedStatement statementFileRead = null;
PreparedStatement statementResourceUpdate = null;
try {
// check if the file content for this file is already existing in the
// offline project. If not, load it from the online project and add it
// to the offline project.
if ((file.getState() == C_STATE_UNCHANGED) && (changed == true) ) {
// read file content form the online project
statementFileRead = m_pool.getPreparedStatement(C_FILE_READ_KEY);
statementFileRead.setInt(1,file.getFileId());
res = statementFileRead.executeQuery();
if (res.next()) {
content=res.getBytes(C_FILE_CONTENT);
} else {
throw new CmsException("["+this.getClass().getName()+"]"+file.getAbsolutePath(),CmsException.C_NOT_FOUND);
}
res.close();
// add the file content to the offline project.
PreparedStatement statementFileWrite = null;
try {
file.setFileId(nextId(C_TABLE_FILES));
statementFileWrite = m_pool.getPreparedStatement(C_FILES_WRITE_KEY);
statementFileWrite.setInt(1,file.getFileId());
statementFileWrite.setBytes(2,content);
statementFileWrite.executeUpdate();
} catch (SQLException se) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsAccessFileMySql] " + se.getMessage());
se.printStackTrace();
}
}finally {
if( statementFileWrite != null) {
m_pool.putPreparedStatement(C_FILES_WRITE_KEY, statementFileWrite);
}
}
}
// update resource in the database
statementResourceUpdate = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_KEY);
statementResourceUpdate.setInt(1,file.getType());
statementResourceUpdate.setInt(2,file.getFlags());
statementResourceUpdate.setInt(3,file.getOwnerId());
statementResourceUpdate.setInt(4,file.getGroupId());
statementResourceUpdate.setInt(5,file.getProjectId());
statementResourceUpdate.setInt(6,file.getAccessFlags());
//STATE
int state=file.getState();
if ((state == C_STATE_NEW) || (state == C_STATE_CHANGED)) {
statementResourceUpdate.setInt(7,state);
} else {
if (changed==true) {
statementResourceUpdate.setInt(7,C_STATE_CHANGED);
} else {
statementResourceUpdate.setInt(7,file.getState());
}
}
statementResourceUpdate.setInt(8,file.isLockedBy());
statementResourceUpdate.setInt(9,file.getLauncherType());
statementResourceUpdate.setString(10,file.getLauncherClassname());
statementResourceUpdate.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statementResourceUpdate.setInt(12,file.getResourceLastModifiedBy());
statementResourceUpdate.setInt(13,file.getLength());
statementResourceUpdate.setInt(14,file.getFileId());
statementResourceUpdate.setInt(15,file.getResourceId());
statementResourceUpdate.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statementFileRead != null) {
m_pool.putPreparedStatement(C_FILE_READ_KEY, statementFileRead);
}
if( statementResourceUpdate != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_KEY, statementResourceUpdate);
}
}
}
/**
* Writes a file to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFile(CmsProject project,
CmsProject onlineProject,
CmsFile file,boolean changed)
throws CmsException {
PreparedStatement statement = null;
try {
// update the file header in the RESOURCE database.
writeFileHeader(project,onlineProject,file,changed);
// update the file content in the FILES database.
statement = m_pool.getPreparedStatement(C_FILES_UPDATE_KEY);
statement.setBytes(1,file.getContents());
statement.setInt(2,file.getFileId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_FILES_UPDATE_KEY, statement);
}
}
}
/**
* Writes a folder to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param folder The folder to be written.
* @param changed Flag indicating if the file state must be set to changed.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFolder(CmsProject project, CmsFolder folder, boolean changed)
throws CmsException {
PreparedStatement statement = null;
try {
// update resource in the database
statement = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_KEY);
statement.setInt(1,folder.getType());
statement.setInt(2,folder.getFlags());
statement.setInt(3,folder.getOwnerId());
statement.setInt(4,folder.getGroupId());
statement.setInt(5,folder.getProjectId());
statement.setInt(6,folder.getAccessFlags());
int state=folder.getState();
if ((state == C_STATE_NEW) || (state == C_STATE_CHANGED)) {
statement.setInt(7,state);
} else {
if (changed==true) {
statement.setInt(7,C_STATE_CHANGED);
} else {
statement.setInt(7,folder.getState());
}
}
statement.setInt(8,folder.isLockedBy());
statement.setInt(9,folder.getLauncherType());
statement.setString(10,folder.getLauncherClassname());
statement.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statement.setInt(12,folder.getResourceLastModifiedBy());
statement.setInt(13,0);
statement.setInt(14,C_UNKNOWN_ID);
statement.setInt(15,folder.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_KEY, statement);
}
}
}
/**
* Creates a new folder
*
* @param user The user who wants to create the folder.
* @param project The project in which the resource will be used.
* @param parentId The parentId of the folder.
* @param fileId The fileId of the folder.
* @param foldername The complete path to the folder in which the new folder will
* be created.
* @param flags The flags of this resource.
*
* @return The created folder.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder createFolder(CmsUser user, CmsProject project, int parentId,
int fileId, String foldername, int flags)
throws CmsException {
int resourceId = nextId(C_TABLE_RESOURCES);
PreparedStatement statement = null;
try {
// write new resource to the database
statement=m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
statement.setInt(1,resourceId);
statement.setInt(2,parentId);
statement.setString(3, foldername);
statement.setInt(4,C_TYPE_FOLDER);
statement.setInt(5,flags);
statement.setInt(6,user.getId());
statement.setInt(7,user.getDefaultGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,fileId);
statement.setInt(10,C_ACCESS_DEFAULT_FLAGS);
statement.setInt(11,C_STATE_NEW);
statement.setInt(12,C_UNKNOWN_ID);
statement.setInt(13,C_UNKNOWN_LAUNCHER_ID);
statement.setString(14,C_UNKNOWN_LAUNCHER);
statement.setTimestamp(15,new Timestamp(System.currentTimeMillis()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,0);
statement.setInt(18,user.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
}
return readFolder(project.getId(),foldername);
}
/**
* Creates a new folder from an existing folder object.
*
* @param user The user who wants to create the folder.
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param folder The folder to be written to the Cms.
* @param parentId The parentId of the resource.
*
* @param foldername The complete path of the new name of this folder.
*
* @return The created folder.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder createFolder(CmsUser user,
CmsProject project,
CmsProject onlineProject,
CmsFolder folder,
int parentId,
String foldername)
throws CmsException{
CmsFolder oldFolder = null;
int state=0;
if (project.equals(onlineProject)) {
state= folder.getState();
} else {
state=C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it
try {
oldFolder = readFolder(project.getId(),foldername);
if (oldFolder.getState() == C_STATE_DELETED){
removeFolder(oldFolder);
state = C_STATE_CHANGED;
}
} catch (CmsException e) {}
int resourceId = nextId(C_TABLE_RESOURCES);
int fileId = nextId(C_TABLE_FILES);
PreparedStatement statement = null;
try {
// write new resource to the database
statement = m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
statement.setInt(1,resourceId);
statement.setInt(2,parentId);
statement.setString(3, foldername);
statement.setInt(4,folder.getType());
statement.setInt(5,folder.getFlags());
statement.setInt(6,folder.getOwnerId());
statement.setInt(7,folder.getGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,fileId);
statement.setInt(10,folder.getAccessFlags());
statement.setInt(11,C_STATE_NEW);
statement.setInt(12,folder.isLockedBy());
statement.setInt(13,folder.getLauncherType());
statement.setString(14,folder.getLauncherClassname());
statement.setTimestamp(15,new Timestamp(folder.getDateCreated()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,0);
statement.setInt(18,user.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
}
//return readFolder(project,folder.getAbsolutePath());
return readFolder(project.getId(),foldername);
}
/**
* Deletes a folder in the database.
* This method is used to physically remove a folder form the database.
*
* @param folder The folder.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void removeFolder(CmsFolder folder)
throws CmsException{
// the current implementation only deletes empty folders
// check if the folder has any files in it
Vector files= getFilesInFolder(folder);
files=getUndeletedResources(files);
if (files.size()==0) {
// check if the folder has any folders in it
Vector folders= getSubFolders(folder);
folders=getUndeletedResources(folders);
if (folders.size()==0) {
//this folder is empty, delete it
PreparedStatement statement = null;
try {
// delete the folder
statement = m_pool.getPreparedStatement(C_RESOURCES_ID_DELETE_KEY);
statement.setInt(1,folder.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_ID_DELETE_KEY, statement);
}
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+folder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+folder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
}
/**
* Deletes the folder.
*
* Only empty folders can be deleted yet.
*
* @param project The project in which the resource will be used.
* @param orgFolder The folder that will be deleted.
* @param force If force is set to true, all sub-resources will be deleted.
* If force is set to false, the folder will be deleted only if it is empty.
* This parameter is not used yet as only empty folders can be deleted!
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFolder(CmsProject project, CmsFolder orgFolder, boolean force)
throws CmsException {
// the current implementation only deletes empty folders
// check if the folder has any files in it
Vector files= getFilesInFolder(orgFolder);
files=getUndeletedResources(files);
if (files.size()==0) {
// check if the folder has any folders in it
Vector folders= getSubFolders(orgFolder);
folders=getUndeletedResources(folders);
if (folders.size()==0) {
//this folder is empty, delete it
PreparedStatement statement = null;
try {
// mark the folder as deleted
statement=m_pool.getPreparedStatement(C_RESOURCES_REMOVE_KEY);
statement.setInt(1,C_STATE_DELETED);
statement.setInt(2,C_UNKNOWN_ID);
statement.setString(3, orgFolder.getAbsolutePath());
statement.setInt(4,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_REMOVE_KEY, statement);
}
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+orgFolder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+orgFolder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
}
/**
* Copies the file.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param userId The id of the user who wants to copy the file.
* @param source The complete path of the sourcefile.
* @param parentId The parentId of the resource.
* @param destination The complete path of the destinationfile.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyFile(CmsProject project,
CmsProject onlineProject,
int userId,
String source,
int parentId,
String destination)
throws CmsException {
CmsFile file;
// read sourcefile
file=readFile(project.getId(),onlineProject.getId(),source);
// create destination file
createFile(project,onlineProject,file,userId,parentId,destination, true);
}
/**
* Deletes the file.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFile(CmsProject project, String filename)
throws CmsException {
PreparedStatement statement = null;
try {
statement =m_pool.getPreparedStatement(C_RESOURCES_REMOVE_KEY);
// mark the file as deleted
statement.setInt(1,C_STATE_DELETED);
statement.setInt(2,C_UNKNOWN_ID);
statement.setString(3, filename);
statement.setInt(4,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_REMOVE_KEY, statement);
}
}
}
/**
* Undeletes the file.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void undeleteFile(CmsProject project, String filename)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_RESOURCES_REMOVE_KEY);
// mark the file as deleted
statement.setInt(1,C_STATE_CHANGED);
statement.setInt(2,C_UNKNOWN_ID);
statement.setString(3, filename);
statement.setInt(4,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_REMOVE_KEY, statement);
}
}
}
/**
* Returns a Vector with all subfolders.<BR/>
*
* @param parentFolder The folder to be searched.
*
* @return Vector with all subfolders for the given folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getSubFolders(CmsFolder parentFolder)
throws CmsException {
Vector folders=new Vector();
CmsFolder folder=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
// get all subfolders
statement = m_pool.getPreparedStatement(C_RESOURCES_GET_SUBFOLDER_KEY);
statement.setInt(1,parentFolder.getResourceId());
res = statement.executeQuery();
// create new folder objects
while ( res.next() ) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,created,
modified,modifiedBy);
folders.addElement(folder);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("getSubFolders "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_GET_SUBFOLDER_KEY, statement);
}
}
return SortEntrys(folders);
}
/**
* Returns a Vector with all file headers of a folder.<BR/>
*
* @param parentFolder The folder to be searched.
*
* @return subfiles A Vector with all file headers of the folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesInFolder(CmsFolder parentFolder)
throws CmsException {
Vector files=new Vector();
CmsResource file=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
// get all files in folder
statement = m_pool.getPreparedStatement(C_RESOURCES_GET_FILESINFOLDER_KEY);
statement.setInt(1,parentFolder.getResourceId());
res = statement.executeQuery();
// create new file objects
while ( res.next() ) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
files.addElement(file);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("getFilesInFolder "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_GET_FILESINFOLDER_KEY, statement);
}
}
return SortEntrys(files);
}
/**
* Sorts a vector of files or folders alphabetically.
* This method uses an insertion sort algorithem.
*
* @param unsortedList Array of strings containing the list of files or folders.
* @return Array of sorted strings.
*/
private Vector SortEntrys(Vector list) {
int in,out;
int nElem = list.size();
CmsResource[] unsortedList = new CmsResource[list.size()];
for (int i=0;i<list.size();i++) {
unsortedList[i]=(CmsResource)list.elementAt(i);
}
for(out=1; out < nElem; out++) {
CmsResource temp= unsortedList[out];
in = out;
while (in >0 && unsortedList[in-1].getAbsolutePath().compareTo(temp.getAbsolutePath()) >= 0){
unsortedList[in]=unsortedList[in-1];
--in;
}
unsortedList[in]=temp;
}
Vector sortedList=new Vector();
for (int i=0;i<list.size();i++) {
sortedList.addElement(unsortedList[i]);
}
return sortedList;
}
/**
* Gets all resources that are marked as undeleted.
* @param resources Vector of resources
* @return Returns all resources that are markes as deleted
*/
private Vector getUndeletedResources(Vector resources) {
Vector undeletedResources=new Vector();
for (int i=0;i<resources.size();i++) {
CmsResource res=(CmsResource)resources.elementAt(i);
if (res.getState() != C_STATE_DELETED) {
undeletedResources.addElement(res);
}
}
return undeletedResources;
}
/**
* Deletes all files in CMS_FILES without fileHeader in CMS_RESOURCES
*
*
*/
private void clearFilesTable()
throws CmsException{
PreparedStatement statementSearch = null;
PreparedStatement statementDestroy = null;
ResultSet res = null;
try{
statementSearch = m_pool.getPreparedStatement(C_RESOURCES_GET_LOST_ID_KEY);
res = statementSearch.executeQuery();
// delete the lost fileId's
statementDestroy = m_pool.getPreparedStatement(C_FILE_DELETE_KEY);
while (res.next() ){
statementDestroy.setInt(1,res.getInt(C_FILE_ID));
statementDestroy.executeUpdate();
statementDestroy.clearParameters();
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statementSearch != null) {
m_pool.putPreparedStatement(C_RESOURCES_GET_LOST_ID_KEY, statementSearch);
}
if( statementDestroy != null) {
m_pool.putPreparedStatement(C_FILE_DELETE_KEY, statementDestroy);
}
}
}
/**
* Unlocks all resources in this project.
*
* @param project The project to be unlocked.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void unlockProject(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_RESOURCES_UNLOCK_KEY);
statement.setInt(1,project.getId());
statement.executeUpdate();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UNLOCK_KEY, statement);
}
}
}
/**
* Counts the locked resources in this project.
*
* @param project The project to be unlocked.
* @return the amount of locked resources in this project.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public int countLockedResources(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
int retValue;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_RESOURCES_COUNTLOCKED_KEY);
statement.setInt(1,project.getId());
res = statement.executeQuery();
if(res.next()) {
retValue = res.getInt(1);
} else {
res.close();
retValue=0;
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_COUNTLOCKED_KEY, statement);
}
}
return retValue;
}
/**
* Private method to init all statements in the pool.
*/
private void initStatements()
throws CmsException {
// init statements for resources and files
m_pool.initPreparedStatement(C_RESOURCES_MAXID_KEY,C_RESOURCES_MAXID);
m_pool.initPreparedStatement(C_RESOURCES_REMOVE_KEY,C_RESOURCES_REMOVE);
m_pool.initPreparedStatement(C_FILES_MAXID_KEY,C_FILES_MAXID);
m_pool.initPreparedStatement(C_FILES_UPDATE_KEY,C_FILES_UPDATE);
m_pool.initPreparedStatement(C_RESOURCES_READ_KEY,C_RESOURCES_READ);
m_pool.initPreparedStatement(C_RESOURCES_READBYID_KEY,C_RESOURCES_READBYID);
m_pool.initPreparedStatement(C_RESOURCES_WRITE_KEY,C_RESOURCES_WRITE);
m_pool.initPreparedStatement(C_RESOURCES_GET_SUBFOLDER_KEY,C_RESOURCES_GET_SUBFOLDER);
m_pool.initPreparedStatement(C_RESOURCES_DELETE_KEY,C_RESOURCES_DELETE);
m_pool.initPreparedStatement(C_RESOURCES_ID_DELETE_KEY,C_RESOURCES_ID_DELETE);
m_pool.initPreparedStatement(C_RESOURCES_GET_FILESINFOLDER_KEY,C_RESOURCES_GET_FILESINFOLDER);
m_pool.initPreparedStatement(C_RESOURCES_PUBLISH_PROJECT_READFILE_KEY,C_RESOURCES_PUBLISH_PROJECT_READFILE);
m_pool.initPreparedStatement(C_RESOURCES_PUBLISH_PROJECT_READFOLDER_KEY,C_RESOURCES_PUBLISH_PROJECT_READFOLDER);
m_pool.initPreparedStatement(C_RESOURCES_UPDATE_KEY,C_RESOURCES_UPDATE);
m_pool.initPreparedStatement(C_RESOURCES_UPDATE_FILE_KEY,C_RESOURCES_UPDATE_FILE);
m_pool.initPreparedStatement(C_RESOURCES_GET_LOST_ID_KEY,C_RESOURCES_GET_LOST_ID);
m_pool.initPreparedStatement(C_FILE_DELETE_KEY,C_FILE_DELETE);
m_pool.initPreparedStatement(C_RESOURCES_DELETE_PROJECT_KEY,C_RESOURCES_DELETE_PROJECT);
m_pool.initPreparedStatement(C_FILE_READ_ONLINE_KEY,C_FILE_READ_ONLINE);
m_pool.initPreparedStatement(C_FILE_READ_KEY,C_FILE_READ);
m_pool.initPreparedStatement(C_FILES_WRITE_KEY,C_FILES_WRITE);
m_pool.initPreparedStatement(C_RESOURCES_UNLOCK_KEY,C_RESOURCES_UNLOCK);
m_pool.initPreparedStatement(C_RESOURCES_COUNTLOCKED_KEY,C_RESOURCES_COUNTLOCKED);
m_pool.initPreparedStatement(C_RESOURCES_READBYPROJECT_KEY,C_RESOURCES_READBYPROJECT);
m_pool.initPreparedStatement(C_RESOURCES_READFOLDERSBYPROJECT_KEY,C_RESOURCES_READFOLDERSBYPROJECT);
m_pool.initPreparedStatement(C_RESOURCES_READFILESBYPROJECT_KEY,C_RESOURCES_READFILESBYPROJECT);
m_pool.initPreparedStatement(C_RESOURCES_PUBLISH_MARKED_KEY,C_RESOURCES_PUBLISH_MARKED);
m_pool.initPreparedStatement(C_RESOURCES_DELETEBYID_KEY,C_RESOURCES_DELETEBYID);
m_pool.initPreparedStatement(C_RESOURCES_RENAMERESOURCE_KEY,C_RESOURCES_RENAMERESOURCE);
m_pool.initPreparedStatement(C_RESOURCES_READ_ALL_KEY,C_RESOURCES_READ_ALL);
// init statements for groups
m_pool.initPreparedStatement(C_GROUPS_MAXID_KEY,C_GROUPS_MAXID);
m_pool.initPreparedStatement(C_GROUPS_READGROUP_KEY,C_GROUPS_READGROUP);
m_pool.initPreparedStatement(C_GROUPS_READGROUP2_KEY,C_GROUPS_READGROUP2);
m_pool.initPreparedStatement(C_GROUPS_CREATEGROUP_KEY,C_GROUPS_CREATEGROUP);
m_pool.initPreparedStatement(C_GROUPS_WRITEGROUP_KEY,C_GROUPS_WRITEGROUP);
m_pool.initPreparedStatement(C_GROUPS_DELETEGROUP_KEY,C_GROUPS_DELETEGROUP);
m_pool.initPreparedStatement(C_GROUPS_GETGROUPS_KEY,C_GROUPS_GETGROUPS);
m_pool.initPreparedStatement(C_GROUPS_GETCHILD_KEY,C_GROUPS_GETCHILD);
m_pool.initPreparedStatement(C_GROUPS_GETPARENT_KEY,C_GROUPS_GETPARENT);
m_pool.initPreparedStatement(C_GROUPS_GETGROUPSOFUSER_KEY,C_GROUPS_GETGROUPSOFUSER);
m_pool.initPreparedStatement(C_GROUPS_ADDUSERTOGROUP_KEY,C_GROUPS_ADDUSERTOGROUP);
m_pool.initPreparedStatement(C_GROUPS_USERINGROUP_KEY,C_GROUPS_USERINGROUP);
m_pool.initPreparedStatement(C_GROUPS_GETUSERSOFGROUP_KEY,C_GROUPS_GETUSERSOFGROUP);
m_pool.initPreparedStatement(C_GROUPS_REMOVEUSERFROMGROUP_KEY,C_GROUPS_REMOVEUSERFROMGROUP);
// init statements for users
m_pool.initPreparedStatement(C_USERS_MAXID_KEY,C_USERS_MAXID);
m_pool.initPreparedStatement(C_USERS_ADD_KEY,C_USERS_ADD);
m_pool.initPreparedStatement(C_USERS_READ_KEY,C_USERS_READ);
m_pool.initPreparedStatement(C_USERS_READID_KEY,C_USERS_READID);
m_pool.initPreparedStatement(C_USERS_READPW_KEY,C_USERS_READPW);
m_pool.initPreparedStatement(C_USERS_WRITE_KEY,C_USERS_WRITE);
m_pool.initPreparedStatement(C_USERS_DELETE_KEY,C_USERS_DELETE);
m_pool.initPreparedStatement(C_USERS_GETUSERS_KEY,C_USERS_GETUSERS);
m_pool.initPreparedStatement(C_USERS_SETPW_KEY,C_USERS_SETPW);
m_pool.initPreparedStatement(C_USERS_SETRECPW_KEY,C_USERS_SETRECPW);
m_pool.initPreparedStatement(C_USERS_RECOVERPW_KEY,C_USERS_RECOVERPW);
m_pool.initPreparedStatement(C_USERS_DELETEBYID_KEY,C_USERS_DELETEBYID);
// init statements for projects
m_pool.initPreparedStatement(C_PROJECTS_MAXID_KEY, C_PROJECTS_MAXID);
m_pool.initPreparedStatement(C_PROJECTS_CREATE_KEY, C_PROJECTS_CREATE);
m_pool.initPreparedStatement(C_PROJECTS_READ_KEY, C_PROJECTS_READ);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYTASK_KEY, C_PROJECTS_READ_BYTASK);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYUSER_KEY, C_PROJECTS_READ_BYUSER);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYGROUP_KEY, C_PROJECTS_READ_BYGROUP);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYFLAG_KEY, C_PROJECTS_READ_BYFLAG);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYMANAGER_KEY, C_PROJECTS_READ_BYMANAGER);
m_pool.initPreparedStatement(C_PROJECTS_DELETE_KEY, C_PROJECTS_DELETE);
m_pool.initPreparedStatement(C_PROJECTS_WRITE_KEY, C_PROJECTS_WRITE);
// init statements for systemproperties
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_MAXID_KEY, C_SYSTEMPROPERTIES_MAXID);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_READ_KEY,C_SYSTEMPROPERTIES_READ);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_WRITE_KEY,C_SYSTEMPROPERTIES_WRITE);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_UPDATE_KEY,C_SYSTEMPROPERTIES_UPDATE);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_DELETE_KEY,C_SYSTEMPROPERTIES_DELETE);
// init statements for propertydef
m_pool.initPreparedStatement(C_PROPERTYDEF_MAXID_KEY,C_PROPERTYDEF_MAXID);
m_pool.initPreparedStatement(C_PROPERTYDEF_READ_KEY,C_PROPERTYDEF_READ);
m_pool.initPreparedStatement(C_PROPERTYDEF_READALL_A_KEY,C_PROPERTYDEF_READALL_A);
m_pool.initPreparedStatement(C_PROPERTYDEF_READALL_B_KEY,C_PROPERTYDEF_READALL_B);
m_pool.initPreparedStatement(C_PROPERTYDEF_CREATE_KEY,C_PROPERTYDEF_CREATE);
m_pool.initPreparedStatement(C_PROPERTYDEF_DELETE_KEY,C_PROPERTYDEF_DELETE);
m_pool.initPreparedStatement(C_PROPERTYDEF_UPDATE_KEY,C_PROPERTYDEF_UPDATE);
// init statements for properties
m_pool.initPreparedStatement(C_PROPERTIES_MAXID_KEY,C_PROPERTIES_MAXID);
m_pool.initPreparedStatement(C_PROPERTIES_READALL_COUNT_KEY,C_PROPERTIES_READALL_COUNT);
m_pool.initPreparedStatement(C_PROPERTIES_READ_KEY,C_PROPERTIES_READ);
m_pool.initPreparedStatement(C_PROPERTIES_UPDATE_KEY,C_PROPERTIES_UPDATE);
m_pool.initPreparedStatement(C_PROPERTIES_CREATE_KEY,C_PROPERTIES_CREATE);
m_pool.initPreparedStatement(C_PROPERTIES_READALL_KEY,C_PROPERTIES_READALL);
m_pool.initPreparedStatement(C_PROPERTIES_DELETEALL_KEY,C_PROPERTIES_DELETEALL);
m_pool.initPreparedStatement(C_PROPERTIES_DELETE_KEY,C_PROPERTIES_DELETE);
// init statements for tasks
m_pool.initPreparedStatement(C_TASK_TYPE_COPY_KEY,C_TASK_TYPE_COPY);
m_pool.initPreparedStatement(C_TASK_UPDATE_KEY,C_TASK_UPDATE);
m_pool.initPreparedStatement(C_TASK_READ_KEY,C_TASK_READ);
m_pool.initPreparedStatement(C_TASK_END_KEY,C_TASK_END);
m_pool.initPreparedStatement(C_TASK_FIND_AGENT_KEY,C_TASK_FIND_AGENT);
m_pool.initPreparedStatement(C_TASK_FORWARD_KEY,C_TASK_FORWARD);
m_pool.initPreparedStatement(C_TASK_GET_TASKTYPE_KEY,C_TASK_GET_TASKTYPE);
// init statements for taskpars
m_pool.initPreparedStatement(C_TASKPAR_TEST_KEY,C_TASKPAR_TEST);
m_pool.initPreparedStatement(C_TASKPAR_UPDATE_KEY,C_TASKPAR_UPDATE);
m_pool.initPreparedStatement(C_TASKPAR_INSERT_KEY,C_TASKPAR_INSERT);
m_pool.initPreparedStatement(C_TASKPAR_GET_KEY,C_TASKPAR_GET);
// init statements for tasklogs
m_pool.initPreparedStatement(C_TASKLOG_WRITE_KEY,C_TASKLOG_WRITE);
m_pool.initPreparedStatement(C_TASKLOG_READ_KEY,C_TASKLOG_READ);
m_pool.initPreparedStatement(C_TASKLOG_READ_LOGS_KEY,C_TASKLOG_READ_LOGS);
m_pool.initPreparedStatement(C_TASKLOG_READ_PPROJECTLOGS_KEY,C_TASKLOG_READ_PPROJECTLOGS);
// init statements for id
m_pool.initPreparedStatement(C_SYSTEMID_INIT_KEY,C_SYSTEMID_INIT);
m_pool.initPreparedStatement(C_SYSTEMID_LOCK_KEY,C_SYSTEMID_LOCK);
m_pool.initPreparedStatement(C_SYSTEMID_READ_KEY,C_SYSTEMID_READ);
m_pool.initPreparedStatement(C_SYSTEMID_WRITE_KEY,C_SYSTEMID_WRITE);
m_pool.initPreparedStatement(C_SYSTEMID_UNLOCK_KEY,C_SYSTEMID_UNLOCK);
}
/**
* Private method to init all default-resources
*/
private void fillDefaults()
throws CmsException {
// insert the first Id
initId();
// the resourceType "folder" is needed always - so adding it
Hashtable resourceTypes = new Hashtable(1);
resourceTypes.put(C_TYPE_FOLDER_NAME, new CmsResourceType(C_TYPE_FOLDER, 0,
C_TYPE_FOLDER_NAME, ""));
// sets the last used index of resource types.
resourceTypes.put(C_TYPE_LAST_INDEX, new Integer(C_TYPE_FOLDER));
// add the resource-types to the database
addSystemProperty( C_SYSTEMPROPERTY_RESOURCE_TYPE, resourceTypes );
// set the mimetypes
addSystemProperty(C_SYSTEMPROPERTY_MIMETYPES,initMimetypes());
// set the groups
CmsGroup guests = createGroup(C_GROUP_GUEST, "the guest-group", C_FLAG_ENABLED, null);
CmsGroup administrators = createGroup(C_GROUP_ADMIN, "the admin-group", C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER, null);
CmsGroup projectleader = createGroup(C_GROUP_PROJECTLEADER, "the projectmanager-group",C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER|C_FLAG_GROUP_PROJECTCOWORKER|C_FLAG_GROUP_ROLE,null);
CmsGroup users = createGroup(C_GROUP_USERS, "the users-group to access the workplace", C_FLAG_ENABLED|C_FLAG_GROUP_ROLE|C_FLAG_GROUP_PROJECTCOWORKER, C_GROUP_GUEST);
// add the users
CmsUser guest = addUser(C_USER_GUEST, "", "the guest-user", " ", " ", " ", 0, 0, C_FLAG_ENABLED, new Hashtable(), guests, " ", " ", C_USER_TYPE_SYSTEMUSER);
CmsUser admin = addUser(C_USER_ADMIN, "admin", "the admin-user", " ", " ", " ", 0, 0, C_FLAG_ENABLED, new Hashtable(), administrators, " ", " ", C_USER_TYPE_SYSTEMUSER);
addUserToGroup(guest.getId(), guests.getId());
addUserToGroup(admin.getId(), administrators.getId());
CmsTask task=createTask(0,0,1, // standart project type,
admin.getId(),
admin.getId(),
administrators.getId(),
C_PROJECT_ONLINE,
new java.sql.Timestamp(new java.util.Date().getTime()),
new java.sql.Timestamp(new java.util.Date().getTime()),
C_TASK_PRIORITY_NORMAL);
CmsProject online = createProject(admin, guests, projectleader, task, C_PROJECT_ONLINE, "the online-project", C_FLAG_ENABLED, C_PROJECT_TYPE_NORMAL);
// create the root-folder
CmsFolder rootFolder = createFolder(admin, online, C_UNKNOWN_ID, C_UNKNOWN_ID, C_ROOT, 0);
rootFolder.setGroupId(users.getId());
writeFolder(online, rootFolder, false);
}
/**
* Private method to init the max-id values.
*
* @exception throws CmsException if something goes wrong.
*/
private void initMaxIdValues()
throws CmsException {
m_maxIds = new int[C_MAX_TABLES];
m_maxIds[C_TABLE_GROUPS] = initMaxId(C_GROUPS_MAXID_KEY);
m_maxIds[C_TABLE_PROJECTS] = initMaxId(C_PROJECTS_MAXID_KEY);
m_maxIds[C_TABLE_USERS] = initMaxId(C_USERS_MAXID_KEY);
m_maxIds[C_TABLE_SYSTEMPROPERTIES] = initMaxId(C_SYSTEMPROPERTIES_MAXID_KEY);
m_maxIds[C_TABLE_PROPERTYDEF] = initMaxId(C_PROPERTYDEF_MAXID_KEY);
m_maxIds[C_TABLE_PROPERTIES] = initMaxId(C_PROPERTIES_MAXID_KEY);
m_maxIds[C_TABLE_RESOURCES] = initMaxId(C_RESOURCES_MAXID_KEY);
m_maxIds[C_TABLE_FILES] = initMaxId(C_FILES_MAXID_KEY);
}
/**
* Private method to init the max-id of the projects-table.
*
* @param key the key for the prepared statement to use.
* @return the max-id
* @exception throws CmsException if something goes wrong.
*/
private int initMaxId(Integer key)
throws CmsException {
int id;
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(key);
ResultSet res = statement.executeQuery();
if (res.next()){
id = res.getInt(1);
}else {
// no values in Database
id = 0;
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(key, statement);
}
}
return id;
}
/**
* Private method to init the id-Table of the Database.
*
* @exception throws CmsException if something goes wrong.
*/
private void initId()
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_SYSTEMID_INIT_KEY);
for (int i = 0; i < C_MAX_TABLES; i++){
statement.setInt(1,i);
statement.executeUpdate();
statement.clearParameters();
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMID_INIT_KEY, statement);
}
}
}
/**
* Private method to get the next id for a table.
* This method is synchronized, to generate unique id's.
*
* @param key A key for the table to get the max-id from.
* @return next-id The next possible id for this table.
*/
private synchronized int nextId(int key)
throws CmsException {
int newId = C_UNKNOWN_INT;
PreparedStatement firstStatement = null;
PreparedStatement statement = null;
ResultSet res = null;
try {
firstStatement = m_pool.getPreparedStatement(C_SYSTEMID_LOCK_KEY);
firstStatement.executeUpdate();
statement = m_pool.getNextPreparedStatement(firstStatement, C_SYSTEMID_READ_KEY);
statement.setInt(1,key);
res = statement.executeQuery();
if (res.next()){
newId = res.getInt(C_SYSTEMID_ID);
res.close();
}else{
res.close();
throw new CmsException("[" + this.getClass().getName() + "] "+" cant read Id! ",CmsException.C_NO_GROUP);
}
statement = m_pool.getNextPreparedStatement(firstStatement, C_SYSTEMID_WRITE_KEY);
statement.setInt(1,newId+1);
statement.setInt(2,key);
statement.executeUpdate();
statement = m_pool.getNextPreparedStatement(firstStatement, C_SYSTEMID_UNLOCK_KEY);
statement.executeUpdate();
m_pool.putPreparedStatement(C_SYSTEMID_LOCK_KEY, firstStatement);
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
return( newId );
}
/**
* Private method to encrypt the passwords.
*
* @param value The value to encrypt.
* @return The encrypted value.
*/
private String digest(String value) {
// is there a valid digest?
if( m_digest != null ) {
return new String(m_digest.digest(value.getBytes()));
} else {
// no digest - use clear passwords
return value;
}
}
/**
* Inits all mimetypes.
* The mimetype-data should be stored in the database. But now this data
* is putted directly here.
*
* @return Returns a hashtable with all mimetypes.
*/
private Hashtable initMimetypes() {
Hashtable mt=new Hashtable();
mt.put( "ez", "application/andrew-inset" );
mt.put( "hqx", "application/mac-binhex40" );
mt.put( "cpt", "application/mac-compactpro" );
mt.put( "doc", "application/msword" );
mt.put( "bin", "application/octet-stream" );
mt.put( "dms", "application/octet-stream" );
mt.put( "lha", "application/octet-stream" );
mt.put( "lzh", "application/octet-stream" );
mt.put( "exe", "application/octet-stream" );
mt.put( "class", "application/octet-stream" );
mt.put( "oda", "application/oda" );
mt.put( "pdf", "application/pdf" );
mt.put( "ai", "application/postscript" );
mt.put( "eps", "application/postscript" );
mt.put( "ps", "application/postscript" );
mt.put( "rtf", "application/rtf" );
mt.put( "smi", "application/smil" );
mt.put( "smil", "application/smil" );
mt.put( "mif", "application/vnd.mif" );
mt.put( "xls", "application/vnd.ms-excel" );
mt.put( "ppt", "application/vnd.ms-powerpoint" );
mt.put( "bcpio", "application/x-bcpio" );
mt.put( "vcd", "application/x-cdlink" );
mt.put( "pgn", "application/x-chess-pgn" );
mt.put( "cpio", "application/x-cpio" );
mt.put( "csh", "application/x-csh" );
mt.put( "dcr", "application/x-director" );
mt.put( "dir", "application/x-director" );
mt.put( "dxr", "application/x-director" );
mt.put( "dvi", "application/x-dvi" );
mt.put( "spl", "application/x-futuresplash" );
mt.put( "gtar", "application/x-gtar" );
mt.put( "hdf", "application/x-hdf" );
mt.put( "js", "application/x-javascript" );
mt.put( "skp", "application/x-koan" );
mt.put( "skd", "application/x-koan" );
mt.put( "skt", "application/x-koan" );
mt.put( "skm", "application/x-koan" );
mt.put( "latex", "application/x-latex" );
mt.put( "nc", "application/x-netcdf" );
mt.put( "cdf", "application/x-netcdf" );
mt.put( "sh", "application/x-sh" );
mt.put( "shar", "application/x-shar" );
mt.put( "swf", "application/x-shockwave-flash" );
mt.put( "sit", "application/x-stuffit" );
mt.put( "sv4cpio", "application/x-sv4cpio" );
mt.put( "sv4crc", "application/x-sv4crc" );
mt.put( "tar", "application/x-tar" );
mt.put( "tcl", "application/x-tcl" );
mt.put( "tex", "application/x-tex" );
mt.put( "texinfo", "application/x-texinfo" );
mt.put( "texi", "application/x-texinfo" );
mt.put( "t", "application/x-troff" );
mt.put( "tr", "application/x-troff" );
mt.put( "roff", "application/x-troff" );
mt.put( "man", "application/x-troff-man" );
mt.put( "me", "application/x-troff-me" );
mt.put( "ms", "application/x-troff-ms" );
mt.put( "ustar", "application/x-ustar" );
mt.put( "src", "application/x-wais-source" );
mt.put( "zip", "application/zip" );
mt.put( "au", "audio/basic" );
mt.put( "snd", "audio/basic" );
mt.put( "mid", "audio/midi" );
mt.put( "midi", "audio/midi" );
mt.put( "kar", "audio/midi" );
mt.put( "mpga", "audio/mpeg" );
mt.put( "mp2", "audio/mpeg" );
mt.put( "mp3", "audio/mpeg" );
mt.put( "aif", "audio/x-aiff" );
mt.put( "aiff", "audio/x-aiff" );
mt.put( "aifc", "audio/x-aiff" );
mt.put( "ram", "audio/x-pn-realaudio" );
mt.put( "rm", "audio/x-pn-realaudio" );
mt.put( "rpm", "audio/x-pn-realaudio-plugin" );
mt.put( "ra", "audio/x-realaudio" );
mt.put( "wav", "audio/x-wav" );
mt.put( "pdb", "chemical/x-pdb" );
mt.put( "xyz", "chemical/x-pdb" );
mt.put( "bmp", "image/bmp" );
mt.put( "wbmp", "image/vnd.wap.wbmp" );
mt.put( "gif", "image/gif" );
mt.put( "ief", "image/ief" );
mt.put( "jpeg", "image/jpeg" );
mt.put( "jpg", "image/jpeg" );
mt.put( "jpe", "image/jpeg" );
mt.put( "png", "image/png" );
mt.put( "tiff", "image/tiff" );
mt.put( "tif", "image/tiff" );
mt.put( "ras", "image/x-cmu-raster" );
mt.put( "pnm", "image/x-portable-anymap" );
mt.put( "pbm", "image/x-portable-bitmap" );
mt.put( "pgm", "image/x-portable-graymap" );
mt.put( "ppm", "image/x-portable-pixmap" );
mt.put( "rgb", "image/x-rgb" );
mt.put( "xbm", "image/x-xbitmap" );
mt.put( "xpm", "image/x-xpixmap" );
mt.put( "xwd", "image/x-xwindowdump" );
mt.put( "igs", "model/iges" );
mt.put( "iges", "model/iges" );
mt.put( "msh", "model/mesh" );
mt.put( "mesh", "model/mesh" );
mt.put( "silo", "model/mesh" );
mt.put( "wrl", "model/vrml" );
mt.put( "vrml", "model/vrml" );
mt.put( "css", "text/css" );
mt.put( "html", "text/html" );
mt.put( "htm", "text/html" );
mt.put( "asc", "text/plain" );
mt.put( "txt", "text/plain" );
mt.put( "rtx", "text/richtext" );
mt.put( "rtf", "text/rtf" );
mt.put( "sgml", "text/sgml" );
mt.put( "sgm", "text/sgml" );
mt.put( "tsv", "text/tab-separated-values" );
mt.put( "etx", "text/x-setext" );
mt.put( "xml", "text/xml" );
mt.put( "wml", "text/vnd.wap.wml" );
mt.put( "mpeg", "video/mpeg" );
mt.put( "mpg", "video/mpeg" );
mt.put( "mpe", "video/mpeg" );
mt.put( "qt", "video/quicktime" );
mt.put( "mov", "video/quicktime" );
mt.put( "avi", "video/x-msvideo" );
mt.put( "movie", "video/x-sgi-movie" );
mt.put( "ice", "x-conference/x-cooltalk" );
return mt;
}
/**
* Destroys this access-module
* @exception throws CmsException if something goes wrong.
*/
public void destroy()
throws CmsException {
// stop the connection-guard
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] stop connection guard");
}
m_guard.destroy();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] destroy the db-pool.");
}
m_pool.destroy();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] destroy complete.");
}
}
/**
* Creates a new task.
* rootId Id of the root task project
* parentId Id of the parent task
* tasktype Type of the task
* ownerId Id of the owner
* agentId Id of the agent
* roleId Id of the role
* taskname Name of the Task
* wakeuptime Time when the task will be wake up
* timeout Time when the task times out
* priority priority of the task
*
* @return The Taskobject of the generated Task
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask createTask(int rootId, int parentId, int tasktype,
int ownerId, int agentId,int roleId, String taskname,
java.sql.Timestamp wakeuptime, java.sql.Timestamp timeout,
int priority)
throws CmsException {
int newId = C_UNKNOWN_ID;
CmsTask task = null;
PreparedStatement statement = null;
try {
newId = nextId(C_TABLE_TASK);
statement = m_pool.getPreparedStatement(C_TASK_TYPE_COPY_KEY);
// create task by copying from tasktype table
statement.setInt(1,newId);
statement.setInt(2,tasktype);
statement.executeUpdate();
task = this.readTask(newId);
task.setRoot(rootId);
task.setParent(parentId);
task.setName(taskname);
task.setTaskType(tasktype);
task.setRole(roleId);
if(agentId==C_UNKNOWN_ID){
agentId = findAgent(roleId);
}
task.setAgentUser(agentId);
task.setOriginalUser(agentId);
task.setWakeupTime(wakeuptime);
task.setTimeOut(timeout);
task.setPriority(priority);
task.setPercentage(0);
task.setState(C_TASK_STATE_STARTED);
task.setInitiatorUser(ownerId);
task.setStartTime(new java.sql.Timestamp(System.currentTimeMillis()));
task.setMilestone(0);
task = this.writeTask(task);
} catch( SQLException exc ) {
System.err.println(exc.getMessage());
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_TYPE_COPY_KEY, statement);
}
}
return task;
}
/**
* Reads a task from the Cms.
*
* @param id The id of the task to read.
*
* @return a task object or null if the task is not found.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask readTask(int id)
throws CmsException {
ResultSet res;
CmsTask task = null;
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_TASK_READ_KEY);
statement.setInt(1,id);
res = statement.executeQuery();
if(res.next()) {
id = res.getInt(C_TASK_ID);
String name = res.getString(C_TASK_NAME);
int autofinish = res.getInt(C_TASK_AUTOFINISH);
java.sql.Timestamp starttime = SqlHelper.getTimestamp(res,C_TASK_STARTTIME);
java.sql.Timestamp timeout = SqlHelper.getTimestamp(res,C_TASK_TIMEOUT);
java.sql.Timestamp endtime = SqlHelper.getTimestamp(res,C_TASK_ENDTIME);
java.sql.Timestamp wakeuptime = SqlHelper.getTimestamp(res,C_TASK_WAKEUPTIME);
int escalationtype = res.getInt(C_TASK_ESCALATIONTYPE);
int initiatoruser = res.getInt(C_TASK_INITIATORUSER);
int originaluser = res.getInt(C_TASK_ORIGINALUSER);
int agentuser = res.getInt(C_TASK_AGENTUSER);
int role = res.getInt(C_TASK_ROLE);
int root = res.getInt(C_TASK_ROOT);
int parent = res.getInt(C_TASK_PARENT);
int milestone = res.getInt(C_TASK_MILESTONE);
int percentage = res.getInt(C_TASK_PERCENTAGE);
String permission = res.getString(C_TASK_PERMISSION);
int priority = res.getInt(C_TASK_PRIORITY);
int state = res.getInt(C_TASK_STATE);
int tasktype = res.getInt(C_TASK_TASKTYPE);
String htmllink = res.getString(C_TASK_HTMLLINK);
res.close();
task = new CmsTask(id, name, state, tasktype, root, parent,
initiatoruser, role, agentuser, originaluser,
starttime, wakeuptime, timeout, endtime,
percentage, permission, priority, escalationtype,
htmllink, milestone, autofinish);
}
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} catch( Exception exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_READ_KEY, statement);
}
}
return task;
}
/**
* Updates a task.
*
* @param task The task that will be written.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTask writeTask(CmsTask task)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_TASK_UPDATE_KEY);
statement.setString(1,task.getName());
statement.setInt(2,task.getState());
statement.setInt(3,task.getTaskType());
statement.setInt(4,task.getRoot());
statement.setInt(5,task.getParent());
statement.setInt(6,task.getInitiatorUser());
statement.setInt(7,task.getRole());
statement.setInt(8,task.getAgentUser());
statement.setInt(9,task.getOriginalUser());
statement.setTimestamp(10,task.getStartTime());
statement.setTimestamp(11,task.getWakeupTime());
statement.setTimestamp(12,task.getTimeOut());
statement.setTimestamp(13,task.getEndTime());
statement.setInt(14,task.getPercentage());
statement.setString(15,task.getPermission());
statement.setInt(16,task.getPriority());
statement.setInt(17,task.getEscalationType());
statement.setString(18,task.getHtmlLink());
statement.setInt(19,task.getMilestone());
statement.setInt(20,task.getAutoFinish());
statement.setInt(21,task.getId());
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_UPDATE_KEY, statement);
}
}
return(readTask(task.getId()));
}
/**
* Ends a task from the Cms.
*
* @param taskid Id of the task to end.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void endTask(int taskId)
throws CmsException {
PreparedStatement statement = null;
try{
statement = m_pool.getPreparedStatement(C_TASK_END_KEY);
statement.setInt(1, 100);
statement.setTimestamp(2,new java.sql.Timestamp(System.currentTimeMillis()));
statement.setInt(3,taskId);
statement.executeQuery();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_END_KEY, statement);
}
}
}
/**
* Forwards a task to another user.
*
* @param taskId The id of the task that will be fowarded.
* @param newRoleId The new Group the task belongs to
* @param newUserId User who gets the task.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void forwardTask(int taskId, int newRoleId, int newUserId)
throws CmsException {
PreparedStatement statement = null;
try{
statement = m_pool.getPreparedStatement(C_TASK_FORWARD_KEY);
statement.setInt(1,newRoleId);
statement.setInt(2,newUserId);
statement.setInt(3,taskId);
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_FORWARD_KEY, statement);
}
}
}
/**
* Reads all tasks of a user in a project.
* @param project The Project in which the tasks are defined.
* @param agent The task agent
* @param owner The task owner .
* @param group The group who has to process the task.
* @tasktype C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy Chooses, how to order the tasks.
* @param sort Sort Ascending or Descending (ASC or DESC)
*
* @return A vector with the tasks
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readTasks(CmsProject project, CmsUser agent, CmsUser owner,
CmsGroup role, int tasktype,
String orderBy, String sort)
throws CmsException {
boolean first = true;
Vector tasks = new Vector(); // vector for the return result
CmsTask task = null; // tmp task for adding to vector
ResultSet recset = null;
// create the sql string depending on parameters
// handle the project for the SQL String
String sqlstr = "SELECT * FROM " + C_TABLENAME_TASK+" WHERE ";
if(project!=null){
sqlstr = sqlstr + C_TASK_ROOT + "=" + project.getTaskId();
first = false;
}
else
{
sqlstr = sqlstr + C_TASK_ROOT + "<>0 AND " + C_TASK_PARENT + "<>0";
first = false;
}
// handle the agent for the SQL String
if(agent!=null){
if(!first){
sqlstr = sqlstr + " AND ";
}
sqlstr = sqlstr + C_TASK_AGENTUSER + "=" + agent.getId();
first = false;
}
// handle the owner for the SQL String
if(owner!=null){
if(!first){
sqlstr = sqlstr + " AND ";
}
sqlstr = sqlstr + this.C_TASK_INITIATORUSER + "=" + owner.getId();
first = false;
}
// handle the role for the SQL String
if(role!=null){
if(!first){
sqlstr = sqlstr+" AND ";
}
sqlstr = sqlstr + C_TASK_ROLE + "=" + role.getId();
first = false;
}
sqlstr = sqlstr + getTaskTypeConditon(first, tasktype);
// handel the order and sort parameter for the SQL String
if(orderBy!=null) {
if(!orderBy.equals("")) {
sqlstr = sqlstr + " ORDER BY " + orderBy;
if(orderBy!=null) {
if(!orderBy.equals("")) {
sqlstr = sqlstr + " " + sort;
}
}
}
}
Statement statement = null;
try {
statement = m_pool.getStatement();
recset = statement.executeQuery(sqlstr);
// if resultset exists - return vector of tasks
while(recset.next()) {
task = new CmsTask(recset.getInt(C_TASK_ID),
recset.getString(C_TASK_NAME),
recset.getInt(C_TASK_STATE),
recset.getInt(C_TASK_TASKTYPE),
recset.getInt(C_TASK_ROOT),
recset.getInt(C_TASK_PARENT),
recset.getInt(C_TASK_INITIATORUSER),
recset.getInt(C_TASK_ROLE),
recset.getInt(C_TASK_AGENTUSER),
recset.getInt(C_TASK_ORIGINALUSER),
SqlHelper.getTimestamp(recset,C_TASK_STARTTIME),
SqlHelper.getTimestamp(recset,C_TASK_WAKEUPTIME),
SqlHelper.getTimestamp(recset,C_TASK_TIMEOUT),
SqlHelper.getTimestamp(recset,C_TASK_ENDTIME),
recset.getInt(C_TASK_PERCENTAGE),
recset.getString(C_TASK_PERMISSION),
recset.getInt(C_TASK_PRIORITY),
recset.getInt(C_TASK_ESCALATIONTYPE),
recset.getString(C_TASK_HTMLLINK),
recset.getInt(C_TASK_MILESTONE),
recset.getInt(C_TASK_AUTOFINISH));
tasks.addElement(task);
}
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} catch( Exception exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
if( statement != null) {
m_pool.putStatement(statement);
}
}
return tasks;
}
/**
* Finds an agent for a given role (group).
* @param roleId The Id for the role (group).
*
* @return A vector with the tasks
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
protected int findAgent(int roleid)
throws CmsException {
int result = C_UNKNOWN_ID;
PreparedStatement statement = null;
ResultSet res = null;
try {
statement = m_pool.getPreparedStatement(C_TASK_FIND_AGENT_KEY);
statement.setInt(1,roleid);
res = statement.executeQuery();
if(res.next()) {
result = res.getInt(C_DATABASE_PREFIX+"USERS.USER_ID");
} else {
System.out.println("No User for role "+ roleid + " found");
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} catch( Exception exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_FIND_AGENT_KEY, statement);
}
}
return result;
}
/**
* Writes new log for a task.
*
* @param taskid The id of the task.
* @param user User who added the Log.
* @param starttime Time when the log is created.
* @param comment Description for the log.
* @param type Type of the log. 0 = Sytem log, 1 = User Log
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void writeTaskLog(int taskId, int userid,
java.sql.Timestamp starttime, String comment, int type)
throws CmsException {
int newId = C_UNKNOWN_ID;
PreparedStatement statement = null;
try{
newId = nextId(C_TABLE_TASKLOG);
statement = m_pool.getPreparedStatement(C_TASKLOG_WRITE_KEY);
statement.setInt(1, newId);
statement.setInt(2, taskId);
if(userid!=C_UNKNOWN_ID){
statement.setInt(3, userid);
}
else {
// no user is specified so set to system user
// is only valid for system task log
statement.setInt(3, 1);
}
statement.setTimestamp(4, starttime);
statement.setString(5, comment);
statement.setInt(6, type);
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKLOG_WRITE_KEY, statement);
}
}
}
public void writeSystemTaskLog(int taskid, String comment)
throws CmsException {
this.writeTaskLog(taskid, C_UNKNOWN_ID,
new java.sql.Timestamp(System.currentTimeMillis()),
comment, C_TASKLOG_USER);
}
/**
* Reads a log for a task.
*
* @param id The id for the tasklog .
* @return A new TaskLog object
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsTaskLog readTaskLog(int id)
throws CmsException {
ResultSet res;
CmsTaskLog tasklog = null;
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_TASKLOG_READ_KEY);
statement.setInt(1, id);
res = statement.executeQuery();
if(res.next()) {
String comment = res.getString(C_LOG_COMMENT);
String externalusername;
id = res.getInt(C_LOG_ID);
java.sql.Timestamp starttime = SqlHelper.getTimestamp(res,C_LOG_STARTTIME);
int task = res.getInt(C_LOG_TASK);
int user = res.getInt(C_LOG_USER);
int type = res.getInt(C_LOG_TYPE);
tasklog = new CmsTaskLog(id, comment, task, user, starttime, type);
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} catch( Exception exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKLOG_READ_KEY, statement);
}
}
return tasklog;
}
/**
* Reads log entries for a task.
*
* @param taskid The id of the task for the tasklog to read .
* @return A Vector of new TaskLog objects
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readTaskLogs(int taskId)
throws CmsException {
ResultSet res;
CmsTaskLog tasklog = null;
Vector logs = new Vector();
PreparedStatement statement = null;
String comment = null;
String externalusername = null;
java.sql.Timestamp starttime = null;
int id = C_UNKNOWN_ID;
int task = C_UNKNOWN_ID;
int user = C_UNKNOWN_ID;
int type = C_UNKNOWN_ID;
try {
statement = m_pool.getPreparedStatement(C_TASKLOG_READ_LOGS_KEY);
statement.setInt(1, taskId);
res = statement.executeQuery();
while(res.next()) {
comment = res.getString(C_LOG_COMMENT);
externalusername = res.getString(C_LOG_EXUSERNAME);
id = res.getInt(C_LOG_ID);
starttime = SqlHelper.getTimestamp(res,C_LOG_STARTTIME);
task = res.getInt(C_LOG_TASK);
user = res.getInt(C_LOG_USER);
type = res.getInt(C_LOG_TYPE);
tasklog = new CmsTaskLog(id, comment, task, user, starttime, type);
logs.addElement(tasklog);
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} catch( Exception exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKLOG_READ_LOGS_KEY, statement);
}
}
return logs;
}
/**
* Reads log entries for a project.
*
* @param project The projec for tasklog to read.
* @return A Vector of new TaskLog objects
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readProjectLogs(int projectid)
throws CmsException {
ResultSet res;
CmsTaskLog tasklog = null;
Vector logs = new Vector();
PreparedStatement statement = null;
String comment = null;
String externalusername = null;
java.sql.Timestamp starttime = null;
int id = C_UNKNOWN_ID;
int task = C_UNKNOWN_ID;
int user = C_UNKNOWN_ID;
int type = C_UNKNOWN_ID;
try {
statement = m_pool.getPreparedStatement(C_TASKLOG_READ_PPROJECTLOGS_KEY);
statement.setInt(1, projectid);
res = statement.executeQuery();
while(res.next()) {
comment = res.getString(C_LOG_COMMENT);
externalusername = res.getString(C_LOG_EXUSERNAME);
id = res.getInt(C_LOG_ID);
starttime = SqlHelper.getTimestamp(res,C_LOG_STARTTIME);
task = res.getInt(C_LOG_TASK);
user = res.getInt(C_LOG_USER);
type = res.getInt(C_LOG_TYPE);
tasklog = new CmsTaskLog(id, comment, task, user, starttime, type);
logs.addElement(tasklog);
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} catch( Exception exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKLOG_READ_PPROJECTLOGS_KEY, statement);
}
}
return logs;
}
/**
* Set a Parameter for a task.
*
* @param task The task.
* @param parname Name of the parameter.
* @param parvalue Value if the parameter.
*
* @return The id of the inserted parameter or 0 if the parameter exists for this task.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public int setTaskPar(int taskId, String parname, String parvalue)
throws CmsException {
ResultSet res;
int result = 0;
PreparedStatement statement = null;
try {
// test if the parameter already exists for this task
statement = m_pool.getPreparedStatement(C_TASKPAR_TEST_KEY);
statement.setInt(1, taskId);
statement.setString(2, parname);
res = statement.executeQuery();
if(res.next()) {
//Parameter exisits, so make an update
updateTaskPar(res.getInt(C_PAR_ID), parname, parvalue);
}
else {
//Parameter is not exisiting, so make an insert
result = insertTaskPar(taskId, parname, parvalue);
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKPAR_TEST_KEY, statement);
}
}
return result;
}
private void updateTaskPar(int parid, String parname, String parvalue)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_TASKPAR_UPDATE_KEY);
statement.setString(1, parvalue);
statement.setInt(2, parid);
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKPAR_UPDATE_KEY, statement);
}
}
}
private int insertTaskPar(int taskId, String parname, String parvalue)
throws CmsException {
PreparedStatement statement = null;
int newId = C_UNKNOWN_ID;
try {
newId = nextId(C_TABLE_TASKPAR);
statement = m_pool.getPreparedStatement(C_TASKPAR_INSERT_KEY);
statement.setInt(1, newId);
statement.setInt(2, taskId);
statement.setString(3, parname);
statement.setString(4, parvalue);
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKPAR_INSERT_KEY, statement);
}
}
return newId;
}
/**
* Get a parameter value for a task.
*
* @param task The task.
* @param parname Name of the parameter.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public String getTaskPar(int taskId, String parname)
throws CmsException {
String result = null;
ResultSet res = null;
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_TASKPAR_GET_KEY);
statement.setInt(1, taskId);
statement.setString(2, parname);
res = statement.executeQuery();
if(res.next()) {
result = res.getString(C_PAR_VALUE);
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASKPAR_GET_KEY, statement);
}
}
return result;
}
/**
* Get the template task id fo a given taskname.
*
* @param taskName Name of the TAsk
*
* @return id from the task template
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public int getTaskType(String taskName)
throws CmsException {
int result = 1;
PreparedStatement statement = null;
ResultSet res = null;
try {
statement = m_pool.getPreparedStatement(C_TASK_GET_TASKTYPE_KEY);
statement.setString(1, taskName);
res = statement.executeQuery();
if (res.next()) {
result = res.getInt("id");
}
res.close();
} catch( SQLException exc ) {
throw new CmsException(exc.getMessage(), CmsException.C_SQL_ERROR, exc);
} finally {
if(statement != null) {
m_pool.putPreparedStatement(C_TASK_GET_TASKTYPE_KEY, statement);
}
}
return result;
}
private String getTaskTypeConditon(boolean first, int tasktype) {
String result = "";
// handle the tasktype for the SQL String
if(!first){
result = result+" AND ";
}
switch(tasktype)
{
case C_TASKS_ALL: {
result = result + C_TASK_ROOT + "<>0";
break;
}
case C_TASKS_OPEN: {
result = result + C_TASK_STATE + "=" + C_TASK_STATE_STARTED;
break;
}
case C_TASKS_ACTIVE: {
result = result + C_TASK_STATE + "=" + C_TASK_STATE_STARTED;
break;
}
case C_TASKS_DONE: {
result = result + C_TASK_STATE + "=" + C_TASK_STATE_ENDED;
break;
}
case C_TASKS_NEW: {
result = result + C_TASK_PERCENTAGE + "=0 AND " + C_TASK_STATE + "=" + C_TASK_STATE_STARTED;
break;
}
default:{}
}
return result;
}
/**
* Checks, if the String was null or is empty. If this is so it returns " ".
*
* This is for oracle-issues, because in oracle an empty string is the same as null.
* @param value the String to check.
* @return the value, or " " if needed.
*/
private String checkNull(String value) {
String ret = " ";
if( (value != null) && (value.length() != 0) ) {
ret = value;
}
return ret;
}
}
|
package com.opencms.template;
import com.opencms.core.*;
import com.opencms.template.cache.CmsTimeout;
import com.opencms.file.*;
import java.util.*;
public class CmsCacheDirectives implements I_CmsLogChannels {
/** Bitfield for storing external cache properties */
public int m_cd;
// everthing to get the cache key
// indicates if the username is part of the cache key
private boolean m_user = false;
// indicates if the groupname is part of the cache key
private boolean m_group = false;
//the groupnames for which the element is cacheable
private Vector m_cacheGroups;
//indicates if the uri is part of the cache key
private boolean m_uri = false;
//the parameters for which the element is cacheable
private Vector m_cacheParameter = null;
// if one of these parameters occures the element is dynamic
private Vector m_dynamicParameter = null;
// indicates if this element should removed from cache after publish even if the template is unchanged.
private boolean renewAfterEveryPublish = false;
// the timeout object
private CmsTimeout m_timeout;
boolean m_timecheck = false;
// indicates if the user has set the value or if it has to be generated
boolean m_userSetProxyPrivate = false;
boolean m_userSetProxyPublic = false;
boolean m_userSetExport = false;
/** Flag for internal cacheable */
public static final int C_CACHE_INTERNAL = 1;
/** Flag for cacheable in private proxies */
public static final int C_CACHE_PROXY_PRIVATE = 2;
/** Flag for cacheable in public proxies */
public static final int C_CACHE_PROXY_PUBLIC = 4;
/** Flag for exportable */
public static final int C_CACHE_EXPORT = 8;
/** Flag for streamable */
public static final int C_CACHE_STREAM = 16;
/**
* Constructor for initializing all caching properties with the same boolean
* value.
* @param b Boolean value that should be set for all caching properties
*/
public CmsCacheDirectives(boolean b) {
if(b) {
m_cd = C_CACHE_INTERNAL | C_CACHE_PROXY_PRIVATE | C_CACHE_PROXY_PUBLIC | C_CACHE_EXPORT | C_CACHE_STREAM;
} else {
m_cd = 0;
}
m_userSetExport = true;
m_userSetProxyPrivate = true;
m_userSetProxyPublic = true;
}
/**
* Constructor for initializing all caching properties given boolean
* values.
* @param internal Initial value for "internal cacheable" property.
* @param proxyPriv Initial value for "proxy private cacheable" property.
* @param proxyPub Initial value for "internal cacheable" property.
* @param export Initial value for "exportable" property.
* @param stream Initial value for "streamable" property.
*/
public CmsCacheDirectives(boolean internal, boolean proxyPriv, boolean proxyPub, boolean export, boolean stream) {
m_cd = 0;
m_cd |= internal?C_CACHE_INTERNAL:0;
m_cd |= proxyPriv?C_CACHE_PROXY_PRIVATE:0;
m_cd |= proxyPub?C_CACHE_PROXY_PUBLIC:0;
m_cd |= export?C_CACHE_EXPORT:0;
m_cd |= stream?C_CACHE_STREAM:0;
m_userSetExport = true;
m_userSetProxyPrivate = true;
m_userSetProxyPublic = true;
}
/**
* Constructor
* @param internal Initial value for "internal cacheable" property.
* @param stream Initial value for "streamable" property.
*/
public CmsCacheDirectives(boolean internal, boolean stream) {
m_cd = 0;
m_cd |= internal?C_CACHE_INTERNAL:0;
m_cd |= stream?C_CACHE_STREAM:0;
}
/**
* Method for setting all caching properties given boolean
* values.
* @param internal Initial value for "internal cacheable" property.
* @param proxyPriv Initial value for "proxy private cacheable" property.
* @param proxyPub Initial value for "internal cacheable" property.
* @param export Initial value for "exportable" property.
* @param stream Initial value for "streamable" property.
*/
private void setExternalCaching(boolean internal, boolean proxyPriv, boolean proxyPub, boolean export, boolean stream) {
m_cd = 0;
m_cd |= internal?C_CACHE_INTERNAL:0;
m_cd |= proxyPriv?C_CACHE_PROXY_PRIVATE:0;
m_cd |= proxyPub?C_CACHE_PROXY_PUBLIC:0;
m_cd |= export?C_CACHE_EXPORT:0;
m_cd |= stream?C_CACHE_STREAM:0;
}
/**
* Merge the current CmsCacheDirective object with another cache directive.
* Resulting properties will be build by a conjunction (logical AND) of
* the two source properties.
* @param cd CmsCacheDirectives to be merged.
*/
public void merge(CmsCacheDirectives cd) {
m_cd &= cd.m_cd;
}
/**
* enables or disables the proxy public cache for this element.
*/
public void setProxyPublicCacheable(boolean proxPublic){
m_userSetProxyPublic = true;
setExternalCaching(isInternalCacheable(), isProxyPrivateCacheable(),
proxPublic, isExportable(), isStreamable());
}
/**
* enables or disables the proxy private cache for this element.
*/
public void setProxyPrivateCacheable(boolean proxPrivate){
m_userSetProxyPrivate = true;
setExternalCaching(isInternalCacheable(), proxPrivate,
isProxyPublicCacheable(), isExportable(), isStreamable());
}
/**
* enables or disables the export for this element.
*/
public void setExport(boolean export){
m_userSetExport = true;
setExternalCaching(isInternalCacheable(), isProxyPrivateCacheable(),
isProxyPublicCacheable(), export, isStreamable());
}
/**
* Get the state of the "internal cacheable" property.
* @return <code>true</code> if internal caching is possible, <code>false</code> otherwise.
*/
public boolean isInternalCacheable() {
return (m_cd & C_CACHE_INTERNAL) == C_CACHE_INTERNAL;
}
/**
* Get the state of the "proxy private cacheable" property.
* @return <code>true</code> if proxy private caching is possible, <code>false</code> otherwise.
*/
public boolean isProxyPrivateCacheable() {
return (m_cd & C_CACHE_PROXY_PRIVATE) == C_CACHE_PROXY_PRIVATE;
}
/**
* Get the state of the "proxy public cacheable" property.
* @return <code>true</code> if proxy public caching is possible, <code>false</code> otherwise.
*/
public boolean isProxyPublicCacheable() {
return (m_cd & C_CACHE_PROXY_PUBLIC) == C_CACHE_PROXY_PUBLIC;
}
/**
* Get the state of the "exporting ability" property.
* @return <code>true</code> if exporting is possible, <code>false</code> otherwise.
*/
public boolean isExportable() {
return (m_cd & C_CACHE_EXPORT) == C_CACHE_EXPORT;
}
/**
* Get the state of the "streaming ability" property.
* @return <code>true</code> if streaming is possible, <code>false</code> otherwise.
*/
public boolean isStreamable() {
return (m_cd & C_CACHE_STREAM) == C_CACHE_STREAM;
}
/**
* Get the timeout object(used if the element should be reloaded every x minutes.
* @return timeout object.
*/
public CmsTimeout getTimeout() {
return m_timeout;
}
public boolean isTimeCritical(){
return m_timecheck;
}
/**
* set the timeout object(used if the element should be reloaded every x minutes.
*/
public void setTimeout(CmsTimeout timeout) {
m_timecheck = true;
m_timeout = timeout;
}
/**
* sets the renewAfterEveryPublish value to true. This means that this element
* is removed from cache every time a project is published even if its template or class
* was not changed in the project.
*/
public void renewAfterEveryPublish(){
renewAfterEveryPublish = true;
}
/**
* returns true if this element has to be deleted from cache every time a project
* is published. This is when the uri is part of the cacheKey or if the user says so.
*/
public boolean shouldRenew(){
return renewAfterEveryPublish || m_uri;
}
/**
* calculates the cacheKey for the element.
* @return The cache key or null if it is not cacheable
*/
public String getCacheKey(CmsObject cms, Hashtable parameters) {
if ( ! this.isInternalCacheable()){
return null;
}
if (parameters == null){
parameters = new Hashtable();
}
// first test the parameters which say it is dynamic
if((m_dynamicParameter != null) && (!m_dynamicParameter.isEmpty())){
for (int i=0; i < m_dynamicParameter.size(); i++){
String testparameter = (String)m_dynamicParameter.elementAt(i);
if(parameters.containsKey(testparameter)){
return null;
}
}
}
CmsRequestContext reqContext = cms.getRequestContext();
String groupKey = "";
if(m_group){
groupKey = reqContext.currentGroup().getName();
if((m_cacheGroups != null) && (!m_cacheGroups.isEmpty())){
if(!m_cacheGroups.contains(groupKey)){
return null;
}
}
}
// ok, a cachekey exists. lets put it together
String key = "key_";
if(m_uri){
key += reqContext.getUri();
}
if(m_user){
key += reqContext.currentUser().getName();
}
key += groupKey;
if((m_cacheParameter != null) && ( !m_cacheParameter.isEmpty())){
for (int i=0; i < m_cacheParameter.size(); i++){
String para = (String)m_cacheParameter.elementAt(i);
if (parameters.containsKey(para)){
key += (String)parameters.get(para);
}
}
}
if(key.equals("")){
return null;
}
return key;
}
/**
* defines if the group is part of the cacheKey
* @param groupCache if true the group will be part of the cache key.
*/
public void setCacheGroups(boolean groupCache){
m_group = groupCache;
}
/**
* if this Vector is set the groups are part of the cache key and the element
* will be cacheable only if the current group is in the Vector. If not it is dynamic.
* @param groupNames A Vector with the names of the groups for which the element is cacheable.
*/
public void setCacheGroups(Vector groupNames){
m_group = true;
m_cacheGroups = groupNames;
}
/**
* includes the user in the cache key.
* @param userCache if true the user will be part of the cachekey.
*/
public void setCacheUser(boolean userCache){
m_user = userCache;
//autoSetExternalCache();
}
/**
* includes the uri in the cache key.
* @param uriCache if true the uri will be part of the cachekey.
*/
public void setCacheUri(boolean uriCache){
m_uri = uriCache;
//autoSetExternalCache();
}
/**
* if this Vector is set the values of each of the parameters in the Vector
* will appear in the cachekey.
* @param parameterNames the parameter that should take part in the cachkey generation.
*/
public void setCacheParameters(Vector parameterNames){
m_cacheParameter = parameterNames;
//autoSetExternalCache();
}
/**
* If one of this parameters apear in the request the element is dynamic! (no cachkey).
* @param parameterNames the names of the parameter that make a element dynamic
*/
public void setNoCacheParameters(Vector parameterNames){
m_dynamicParameter = parameterNames;
}
/* private void autoSetExternalCache(){
if (m_changeCd){
boolean proxPriv = m_uri && (m_cacheParameter == null || m_cacheParameter.isEmpty())
&& isInternalCacheable();
boolean proxPubl = proxPriv && m_user;
// ToDo: check the internal flag for export
boolean export = proxPubl; // && !flag(extenal);
setExternalCaching(isInternalCacheable(), proxPriv, proxPubl, export, isStreamable());
}
}
*/
}
|
package com.opencms.file.genericSql;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import java.security.*;
import java.io.*;
import source.org.apache.java.io.*;
import source.org.apache.java.util.*;
import com.opencms.core.*;
import com.opencms.file.*;
import com.opencms.file.utils.*;
import com.opencms.util.*;
public class CmsDbAccess implements I_CmsConstants, I_CmsQuerys, I_CmsLogChannels {
/**
* The maximum amount of tables.
*/
private static int C_MAX_TABLES = 9;
/**
* Table-key for max-id
*/
private static int C_TABLE_SYSTEMPROPERTIES = 0;
/**
* Table-key for max-id
*/
private static int C_TABLE_GROUPS = 1;
/**
* Table-key for max-id
*/
private static int C_TABLE_GROUPUSERS = 2;
/**
* Table-key for max-id
*/
private static int C_TABLE_USERS = 3;
/**
* Table-key for max-id
*/
private static int C_TABLE_PROJECTS = 4;
/**
* Table-key for max-id
*/
private static int C_TABLE_RESOURCES = 5;
/**
* Table-key for max-id
*/
private static int C_TABLE_FILES = 6;
/**
* Table-key for max-id
*/
private static int C_TABLE_PROPERTYDEF = 7;
/**
* Table-key for max-id
*/
private static int C_TABLE_PROPERTIES = 8;
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_DRIVER = "driver";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_URL = "url";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_USER = "user";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_PASSWORD = "password";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_MAX_CONN = "maxConn";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_FILLDEFAULTS = "filldefaults";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_DIGEST = "digest";
/**
* Constant to get property from configurations.
*/
private static final String C_CONFIGURATIONS_GUARD = "guard";
/**
* The prepared-statement-pool.
*/
private CmsPreparedStatementPool m_pool = null;
/**
* The connection guard.
*/
private CmsConnectionGuard m_guard = null;
/**
* A array containing all max-ids for the tables.
*/
private int[] m_maxIds;
/**
* A digest to encrypt the passwords.
*/
private MessageDigest m_digest = null;
/**
* Storage for all exportpoints
*/
private Hashtable m_exportpointStorage=null;
/**
* Instanciates the access-module and sets up all required modules and connections.
* @param config The OpenCms configuration.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsDbAccess(Configurations config)
throws CmsException {
String rbName = null;
String driver = null;
String url = null;
String user = null;
String password = null;
String digest = null;
String exportpoint = null;
String exportpath = null;
int sleepTime;
boolean fillDefaults;
int maxConn;
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] init the dbaccess-module.");
}
// read the name of the rb from the properties
rbName = (String)config.getString(C_CONFIGURATION_RESOURCEBROKER);
// read the exportpoints
m_exportpointStorage = new Hashtable();
int i = 0;
while ((exportpoint = config.getString(C_EXPORTPOINT + Integer.toString(i))) != null){
exportpath = config.getString(C_EXPORTPOINT_PATH + Integer.toString(i));
if (exportpath != null){
m_exportpointStorage.put(exportpoint, exportpath);
}
i++;
}
// read all needed parameters from the configuration
driver = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_DRIVER);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read driver from configurations: " + driver);
}
url = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_URL);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read url from configurations: " + url);
}
user = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_USER);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read user from configurations: " + user);
}
password = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_PASSWORD, "");
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read password from configurations: " + password);
}
maxConn = config.getInteger(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_MAX_CONN);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read maxConn from configurations: " + maxConn);
}
fillDefaults = config.getBoolean(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_FILLDEFAULTS, false);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read fillDefaults from configurations: " + fillDefaults);
}
digest = config.getString(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_DIGEST, "MD5");
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read digest from configurations: " + digest);
}
sleepTime = config.getInteger(C_CONFIGURATION_RESOURCEBROKER + "." + rbName + "." + C_CONFIGURATIONS_GUARD, 120);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] read guard-sleeptime from configurations: " + sleepTime);
}
// create the digest
try {
m_digest = MessageDigest.getInstance(digest);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] digest created, using: " + m_digest.toString() );
}
} catch (NoSuchAlgorithmException e){
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] error creating digest - using clear paswords: " + e.getMessage());
}
}
// create the pool
m_pool = new CmsPreparedStatementPool(driver, url, user, password, maxConn);
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] pool created");
}
// now init the statements
initStatements();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] all statements initialized in the pool");
}
// now init the max-ids for key generation
initMaxIdValues();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] max-ids initialized");
}
// have we to fill the default resource like root and guest?
if(fillDefaults) {
// YES!
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] fill default resources");
}
fillDefaults();
}
// start the connection-guard
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] start connection guard");
}
m_guard = new CmsConnectionGuard(m_pool, sleepTime);
m_guard.start();
}
// methods working with users and groups
/**
* Add a new group to the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* @param name The name of the new group.
* @param description The description for the new group.
* @int flags The flags for the new group.
* @param name The name of the parent group (or null).
*
* @return Group
*
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public CmsGroup createGroup(String name, String description, int flags,String parent)
throws CmsException {
int parentId=C_UNKNOWN_ID;
CmsGroup group=null;
PreparedStatement statement=null;
try{
// get the id of the parent group if nescessary
if ((parent != null) && (!"".equals(parent))) {
parentId=readGroup(parent).getId();
}
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_CREATEGROUP_KEY);
// write new group to the database
statement.setInt(1,nextId(C_TABLE_GROUPS));
statement.setInt(2,parentId);
statement.setString(3,name);
statement.setString(4,description);
statement.setInt(5,flags);
statement.executeUpdate();
// create the user group by reading it from the database.
// this is nescessary to get the group id which is generated in the
// database.
group=readGroup(name);
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_CREATEGROUP_KEY,statement);
}
}
return group;
}
/**
* Returns a group object.<P/>
* @param groupname The name of the group that is to be read.
* @return Group.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(String groupname)
throws CmsException {
CmsGroup group=null;
ResultSet res = null;
PreparedStatement statement=null;
try{
// read the group from the database
statement=m_pool.getPreparedStatement(C_GROUPS_READGROUP_KEY);
statement.setString(1,groupname);
res = statement.executeQuery();
// create new Cms group object
if(res.next()) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
res.close();
} else {
throw new CmsException("[" + this.getClass().getName() + "] "+groupname,CmsException.C_NO_GROUP);
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_READGROUP_KEY,statement);
}
}
return group;
}
/**
* Returns a group object.<P/>
* @param groupname The id of the group that is to be read.
* @return Group.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(int id)
throws CmsException {
CmsGroup group=null;
ResultSet res = null;
PreparedStatement statement=null;
try{
// read the group from the database
statement=m_pool.getPreparedStatement(C_GROUPS_READGROUP2_KEY);
statement.setInt(1,id);
res = statement.executeQuery();
// create new Cms group object
if(res.next()) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
res.close();
} else {
throw new CmsException("[" + this.getClass().getName() + "] "+id,CmsException.C_NO_GROUP);
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_READGROUP2_KEY,statement);
}
}
return group;
}
/**
* Writes an already existing group in the Cms.<BR/>
*
* Only the admin can do this.<P/>
*
* @param group The group that should be written to the Cms.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void writeGroup(CmsGroup group)
throws CmsException {
PreparedStatement statement = null;
try {
if (group != null){
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_WRITEGROUP_KEY);
statement.setString(1,group.getDescription());
statement.setInt(2,group.getFlags());
statement.setInt(3,group.getParentId());
statement.setInt(4,group.getId());
statement.executeUpdate();
} else {
throw new CmsException("[" + this.getClass().getName() + "] ",CmsException.C_NO_GROUP);
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_WRITEGROUP_KEY,statement);
}
}
}
/**
* Delete a group from the Cms.<BR/>
* Only groups that contain no subgroups can be deleted.
*
* Only the admin can do this.<P/>
*
* @param delgroup The name of the group that is to be deleted.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void deleteGroup(String delgroup)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_DELETEGROUP_KEY);
statement.setString(1,delgroup);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_DELETEGROUP_KEY,statement);
}
}
}
/**
* Returns all groups<P/>
*
* @return users A Vector of all existing groups.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getGroups()
throws CmsException {
Vector groups = new Vector();
CmsGroup group=null;
ResultSet res = null;
PreparedStatement statement = null;
try {
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_GETGROUPS_KEY);
res = statement.executeQuery();
// create new Cms group objects
while ( res.next() ) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
groups.addElement(group);
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETGROUPS_KEY,statement);
}
}
return groups;
}
/**
* Returns all child groups of a groups<P/>
*
*
* @param groupname The name of the group.
* @return users A Vector of all child groups or null.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getChild(String groupname)
throws CmsException {
Vector childs = new Vector();
CmsGroup group;
CmsGroup parent;
ResultSet res = null;
PreparedStatement statement = null;
try {
// get parent group
parent=readGroup(groupname);
// parent group exists, so get all childs
if (parent != null) {
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_GETCHILD_KEY);
statement.setInt(1,parent.getId());
res = statement.executeQuery();
// create new Cms group objects
while ( res.next() ) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
childs.addElement(group);
}
res.close();
}
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETCHILD_KEY,statement);
}
}
//check if the child vector has no elements, set it to null.
if (childs.size() == 0) {
childs=null;
}
return childs;
}
/**
* Returns the parent group of a groups<P/>
*
*
* @param groupname The name of the group.
* @return The parent group of the actual group or null;
* @exception CmsException Throws CmsException if operation was not succesful.
*/
/*public CmsGroup getParent(String groupname)
throws CmsException {
CmsGroup parent = null;
// read the actual user group to get access to the parent group id.
CmsGroup group= readGroup(groupname);
ResultSet res = null;
PreparedStatement statement = null;
try{
// create statement
statement=m_pool.getPreparedStatement(C_GROUPS_GETPARENT_KEY);
statement.setInt(1,group.getParentId());
res = statement.executeQuery();
// create new Cms group object
if(res.next()) {
parent=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETPARENT_KEY,statement);
}
}
return parent;
}*/
/**
* Returns a list of groups of a user.<P/>
*
* @param name The name of the user.
* @return Vector of groups
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(String name)
throws CmsException {
CmsGroup group;
Vector groups=new Vector();
PreparedStatement statement = null;
ResultSet res = null;
try {
// get all all groups of the user
statement = m_pool.getPreparedStatement(C_GROUPS_GETGROUPSOFUSER_KEY);
statement.setString(1,name);
res = statement.executeQuery();
while ( res.next() ) {
group=new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS));
groups.addElement(group);
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETGROUPSOFUSER_KEY, statement);
}
}
return groups;
}
/**
* Returns a list of users of a group.<P/>
*
* @param name The name of the group.
* @param type the type of the users to read.
* @return Vector of users
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector getUsersOfGroup(String name, int type)
throws CmsException {
CmsGroup group;
Vector users = new Vector();
PreparedStatement statement = null;
ResultSet res = null;
try {
statement = m_pool.getPreparedStatement(C_GROUPS_GETUSERSOFGROUP_KEY);
statement.setString(1,name);
statement.setInt(2,type);
res = statement.executeQuery();
while( res.next() ) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
CmsUser user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
users.addElement(user);
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] " + e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_GETUSERSOFGROUP_KEY, statement);
}
}
return users;
}
/**
* Adds a user to a group.<BR/>
*
* Only the admin can do this.<P/>
*
* @param userid The id of the user that is to be added to the group.
* @param groupid The id of the group.
* @exception CmsException Throws CmsException if operation was not succesfull.
*/
public void addUserToGroup(int userid, int groupid)
throws CmsException {
PreparedStatement statement = null;
// check if user is already in group
if (!userInGroup(userid,groupid)) {
// if not, add this user to the group
try {
// create statement
statement = m_pool.getPreparedStatement(C_GROUPS_ADDUSERTOGROUP_KEY);
// write the new assingment to the database
statement.setInt(1,groupid);
statement.setInt(2,userid);
// flag field is not used yet
statement.setInt(3,C_UNKNOWN_INT);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_ADDUSERTOGROUP_KEY, statement);
}
}
}
}
/**
* Checks if a user is member of a group.<P/>
*
* @param nameid The id of the user to check.
* @param groupid The id of the group to check.
* @return True or False
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public boolean userInGroup(int userid, int groupid)
throws CmsException {
boolean userInGroup=false;
PreparedStatement statement = null;
ResultSet res = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_GROUPS_USERINGROUP_KEY);
statement.setInt(1,groupid);
statement.setInt(2,userid);
res = statement.executeQuery();
if (res.next()){
userInGroup=true;
}
res.close();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_USERINGROUP_KEY, statement);
}
}
return userInGroup;
}
/**
* Removes a user from a group.
*
* Only the admin can do this.<P/>
*
* @param userid The id of the user that is to be added to the group.
* @param groupid The id of the group.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void removeUserFromGroup(int userid, int groupid)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_GROUPS_REMOVEUSERFROMGROUP_KEY);
statement.setInt(1,groupid);
statement.setInt(2,userid);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("[" + this.getClass().getName() + "] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_GROUPS_REMOVEUSERFROMGROUP_KEY, statement);
}
}
}
/**
* Adds a user to the database.
*
* @param name username
* @param password user-password
* @param description user-description
* @param firstname user-firstname
* @param lastname user-lastname
* @param email user-email
* @param lastlogin user-lastlogin
* @param lastused user-lastused
* @param flags user-flags
* @param additionalInfos user-additional-infos
* @param defaultGroup user-defaultGroup
* @param address user-defauladdress
* @param section user-section
* @param type user-type
*
* @return the created user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser addUser(String name, String password, String description,
String firstname, String lastname, String email,
long lastlogin, long lastused, int flags, Hashtable additionalInfos,
CmsGroup defaultGroup, String address, String section, int type)
throws CmsException {
int id = nextId(C_TABLE_USERS);
byte[] value=null;
PreparedStatement statement = null;
try {
// serialize the hashtable
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(additionalInfos);
oout.close();
value=bout.toByteArray();
// write data to database
statement = m_pool.getPreparedStatement(C_USERS_ADD_KEY);
statement.setInt(1,id);
statement.setString(2,name);
// crypt the password with MD5
statement.setString(3, digest(password));
statement.setString(4,description);
statement.setString(5,firstname);
statement.setString(6,lastname);
statement.setString(7,email);
statement.setTimestamp(8, new Timestamp(lastlogin));
statement.setTimestamp(9, new Timestamp(lastused));
statement.setInt(10,flags);
statement.setBytes(11,value);
statement.setInt(12,defaultGroup.getId());
statement.setString(13,address);
statement.setString(14,section);
statement.setInt(15,type);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("[CmsAccessUserInfoMySql/addUserInformation(id,object)]:"+CmsException. C_SERIALIZATION, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_ADD_KEY, statement);
}
}
return readUser(id);
}
/**
* Reads a user from the cms.
*
* @param name the name of the user.
* @param type the type of the user.
* @return the read user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser readUser(String name, int type)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
CmsUser user = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_READ_KEY);
statement.setString(1,name);
statement.setInt(2,type);
res = statement.executeQuery();
// create new Cms user object
if(res.next()) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER);
}
res.close();
return user;
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_READ_KEY, statement);
}
}
}
/**
* Reads a user from the cms, only if the password is correct.
*
* @param name the name of the user.
* @param password the password of the user.
* @param type the type of the user.
* @return the read user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser readUser(String name, String password, int type)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
CmsUser user = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_READPW_KEY);
statement.setString(1,name);
statement.setString(2,digest(password));
statement.setInt(3,type);
res = statement.executeQuery();
// create new Cms user object
if(res.next()) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER);
}
res.close();
return user;
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_READPW_KEY, statement);
}
}
}
/**
* Reads a user from the cms, only if the password is correct.
*
* @param id the id of the user.
* @param type the type of the user.
* @return the read user.
* @exception thorws CmsException if something goes wrong.
*/
public CmsUser readUser(int id)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
CmsUser user = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_READID_KEY);
statement.setInt(1,id);
res = statement.executeQuery();
// create new Cms user object
if(res.next()) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"]"+id,CmsException.C_NO_USER);
}
res.close();
return user;
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_READID_KEY, statement);
}
}
}
/**
* Writes a user to the database.
*
* @param user the user to write
* @exception thorws CmsException if something goes wrong.
*/
public void writeUser(CmsUser user)
throws CmsException {
byte[] value=null;
PreparedStatement statement = null;
try {
// serialize the hashtable
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(user.getAdditionalInfo());
oout.close();
value=bout.toByteArray();
// write data to database
statement = m_pool.getPreparedStatement(C_USERS_WRITE_KEY);
statement.setString(1,user.getDescription());
statement.setString(2,user.getFirstname());
statement.setString(3,user.getLastname());
statement.setString(4,user.getEmail());
statement.setTimestamp(5, new Timestamp(user.getLastlogin()));
statement.setTimestamp(6, new Timestamp(user.getLastUsed()));
statement.setInt(7,user.getFlags());
statement.setBytes(8,value);
statement.setString(9,user.getAddress());
statement.setString(10,user.getSection());
statement.setInt(11,user.getType());
statement.setInt(12,user.getId());
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("[CmsAccessUserInfoMySql/addUserInformation(id,object)]:"+CmsException. C_SERIALIZATION, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_WRITE_KEY, statement);
}
}
}
/**
* Deletes a user from the database.
*
* @param user the user to delete
* @exception thorws CmsException if something goes wrong.
*/
public void deleteUser(String name)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_DELETE_KEY);
statement.setString(1,name);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_DELETE_KEY, statement);
}
}
}
/**
* Deletes a user from the database.
*
* @param userId The Id of the user to delete
* @exception thorws CmsException if something goes wrong.
*/
public void deleteUser(int id)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_DELETEBYID_KEY);
statement.setInt(1,id);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_DELETEBYID_KEY, statement);
}
}
}
/**
* Gets all users of a type.
*
* @param type The type of the user.
* @exception thorws CmsException if something goes wrong.
*/
public Vector getUsers(int type)
throws CmsException {
Vector users = new Vector();
PreparedStatement statement = null;
ResultSet res = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_GETUSERS_KEY);
statement.setInt(1,type);
res = statement.executeQuery();
// create new Cms user objects
while( res.next() ) {
// read the additional infos.
byte[] value = res.getBytes(C_USERS_USER_INFO);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
Hashtable info=(Hashtable)oin.readObject();
CmsUser user = new CmsUser(res.getInt(C_USERS_USER_ID),
res.getString(C_USERS_USER_NAME),
res.getString(C_USERS_USER_PASSWORD),
res.getString(C_USERS_USER_DESCRIPTION),
res.getString(C_USERS_USER_FIRSTNAME),
res.getString(C_USERS_USER_LASTNAME),
res.getString(C_USERS_USER_EMAIL),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTLOGIN).getTime(),
SqlHelper.getTimestamp(res,C_USERS_USER_LASTUSED).getTime(),
res.getInt(C_USERS_USER_FLAGS),
info,
new CmsGroup(res.getInt(C_GROUPS_GROUP_ID),
res.getInt(C_GROUPS_PARENT_GROUP_ID),
res.getString(C_GROUPS_GROUP_NAME),
res.getString(C_GROUPS_GROUP_DESCRIPTION),
res.getInt(C_GROUPS_GROUP_FLAGS)),
res.getString(C_USERS_USER_ADDRESS),
res.getString(C_USERS_USER_SECTION),
res.getInt(C_USERS_USER_TYPE));
users.addElement(user);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_GETUSERS_KEY, statement);
}
}
return users;
}
/**
* Sets a new password for a user.
*
* @param user the user to set the password for.
* @param password the password to set
* @exception thorws CmsException if something goes wrong.
*/
public void setPassword(String user, String password)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_USERS_SETPW_KEY);
statement.setString(1,digest(password));
statement.setString(2,user);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_USERS_SETPW_KEY, statement);
}
}
}
// methods working with projects
/**
* Creates a project.
*
* @param owner The owner of this project.
* @param group The group for this project.
* @param managergroup The managergroup for this project.
* @param task The task.
* @param name The name of the project to create.
* @param description The description for the new project.
* @param flags The flags for the project (e.g. archive).
* @param type the type for the project (e.g. normal).
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject createProject(CmsUser owner, CmsGroup group, CmsGroup managergroup,
CmsTask task, String name, String description,
int flags, int type)
throws CmsException {
if ((description==null) || (description.length()<1)) {
description=" ";
}
Timestamp createTime = new Timestamp(new java.util.Date().getTime());
PreparedStatement statement = null;
int id = nextId(C_TABLE_PROJECTS);
try {
// write data to database
statement = m_pool.getPreparedStatement(C_PROJECTS_CREATE_KEY);
statement.setInt(1,id);
statement.setInt(2,owner.getId());
statement.setInt(3,group.getId());
statement.setInt(4,managergroup.getId());
statement.setInt(5,task.getId());
statement.setString(6,name);
statement.setString(7,description);
statement.setInt(8,flags);
statement.setTimestamp(9,createTime);
statement.setNull(10,Types.TIMESTAMP);
statement.setInt(11,C_UNKNOWN_ID);
statement.setInt(12,type);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_CREATE_KEY, statement);
}
}
return readProject(id);
}
/**
* Reads a project.
*
* @param id The id of the project.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(int id)
throws CmsException {
PreparedStatement statement = null;
CmsProject project = null;
try {
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_KEY);
statement.setInt(1,id);
ResultSet res = statement.executeQuery();
if(res.next()) {
project = new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE));
} else {
// project not found!
throw new CmsException("[" + this.getClass().getName() + "] " + id,
CmsException.C_NOT_FOUND);
}
res.close();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_KEY, statement);
}
}
return project;
}
/**
* Reads a project by task-id.
*
* @param task The task to read the project for.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(CmsTask task)
throws CmsException {
PreparedStatement statement = null;
CmsProject project = null;
try {
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYTASK_KEY);
statement.setInt(1,task.getId());
ResultSet res = statement.executeQuery();
if(res.next()) {
project = new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE));
} else {
// project not found!
throw new CmsException("[" + this.getClass().getName() + "] " + task,
CmsException.C_NOT_FOUND);
}
res.close();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception e) {
throw new CmsException("["+this.getClass().getName()+"]", e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYTASK_KEY, statement);
}
}
return project;
}
/**
* Returns all projects, which are owned by a user.
*
* @param user The requesting user.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjectsByUser(CmsUser user)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYUSER_KEY);
statement.setInt(1,user.getId());
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYUSER_KEY, statement);
}
}
return(projects);
}
/**
* Returns all projects, which are accessible by a group.
*
* @param group The requesting group.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjectsByGroup(CmsGroup group)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYGROUP_KEY);
statement.setInt(1,group.getId());
statement.setInt(2,group.getId());
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYGROUP_KEY, statement);
}
}
return(projects);
}
/**
* Returns all projects, which are manageable by a group.
*
* @param group The requesting group.
*
* @return a Vector of projects.
*/
public Vector getAllAccessibleProjectsByManagerGroup(CmsGroup group)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYMANAGER_KEY);
statement.setInt(1,group.getId());
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYMANAGER_KEY, statement);
}
}
return(projects);
}
/**
* Returns all projects, with the overgiven state.
*
* @param state The state of the projects to read.
*
* @return a Vector of projects.
*/
public Vector getAllProjects(int state)
throws CmsException {
Vector projects = new Vector();
ResultSet res;
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_READ_BYFLAG_KEY);
statement.setInt(1,state);
res = statement.executeQuery();
while(res.next()) {
projects.addElement( new CmsProject(res.getInt(C_PROJECTS_PROJECT_ID),
res.getString(C_PROJECTS_PROJECT_NAME),
res.getString(C_PROJECTS_PROJECT_DESCRIPTION),
res.getInt(C_PROJECTS_TASK_ID),
res.getInt(C_PROJECTS_USER_ID),
res.getInt(C_PROJECTS_GROUP_ID),
res.getInt(C_PROJECTS_MANAGERGROUP_ID),
res.getInt(C_PROJECTS_PROJECT_FLAGS),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_CREATEDATE),
SqlHelper.getTimestamp(res,C_PROJECTS_PROJECT_PUBLISHDATE),
res.getInt(C_PROJECTS_PROJECT_PUBLISHED_BY),
res.getInt(C_PROJECTS_PROJECT_TYPE) ) );
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_READ_BYFLAG_KEY, statement);
}
}
return(projects);
}
/**
* Deletes a project from the cms.
* Therefore it deletes all files, resources and properties.
*
* @param project the project to delete.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deleteProject(CmsProject project)
throws CmsException {
// delete the properties
deleteProjectProperties(project);
// delete the files and resources
deleteProjectResources(project);
// finally delete the project
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_DELETE_KEY);
statement.setInt(1,project.getId());
statement.executeUpdate();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_DELETE_KEY, statement);
}
}
}
/**
* Deletes a project from the cms.
* Therefore it deletes all files, resources and properties.
*
* @param project the project to delete.
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void writeProject(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_PROJECTS_WRITE_KEY);
statement.setInt(1,project.getOwnerId());
statement.setInt(2,project.getGroupId());
statement.setInt(3,project.getManagerGroupId());
statement.setInt(4,project.getFlags());
statement.setTimestamp(5,new Timestamp(project.getPublishingDate()));
statement.setInt(6,project.getPublishedBy());
statement.setInt(7,project.getId());
statement.executeUpdate();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROJECTS_WRITE_KEY, statement);
}
}
}
// methods working with systemproperties
/**
* Deletes a serializable object from the systempropertys.
*
* @param name The name of the property.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deleteSystemProperty(String name)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_DELETE_KEY);
statement.setString(1,name);
statement.executeUpdate();
}catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_DELETE_KEY, statement);
}
}
}
/**
* Creates a serializable object in the systempropertys.
*
* @param name The name of the property.
* @param object The property-object.
*
* @return object The property-object.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Serializable addSystemProperty(String name, Serializable object)
throws CmsException {
byte[] value;
PreparedStatement statement=null;
try {
// serialize the object
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(object);
oout.close();
value=bout.toByteArray();
// create the object
statement=m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_WRITE_KEY);
statement.setInt(1,nextId(C_TABLE_SYSTEMPROPERTIES));
statement.setString(2,name);
statement.setBytes(3,value);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (IOException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_WRITE_KEY, statement);
}
}
return readSystemProperty(name);
}
/**
* Reads a serializable object from the systempropertys.
*
* @param name The name of the property.
*
* @return object The property-object.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Serializable readSystemProperty(String name)
throws CmsException {
Serializable property=null;
byte[] value;
ResultSet res = null;
PreparedStatement statement = null;
// create get the property data from the database
try {
statement=m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_READ_KEY);
statement.setString(1,name);
res = statement.executeQuery();
if(res.next()) {
value = res.getBytes(C_SYSTEMPROPERTY_VALUE);
// now deserialize the object
ByteArrayInputStream bin= new ByteArrayInputStream(value);
ObjectInputStream oin = new ObjectInputStream(bin);
property=(Serializable)oin.readObject();
}
res.close();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}
catch (ClassNotFoundException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_READ_KEY, statement);
}
}
return property;
}
/**
* Writes a serializable object to the systemproperties.
*
* @param name The name of the property.
* @param object The property-object.
*
* @return object The property-object.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Serializable writeSystemProperty(String name, Serializable object)
throws CmsException {
byte[] value=null;
PreparedStatement statement = null;
try {
// serialize the object
ByteArrayOutputStream bout= new ByteArrayOutputStream();
ObjectOutputStream oout=new ObjectOutputStream(bout);
oout.writeObject(object);
oout.close();
value=bout.toByteArray();
statement=m_pool.getPreparedStatement(C_SYSTEMPROPERTIES_UPDATE_KEY);
statement.setBytes(1,value);
statement.setString(2,name);
statement.executeUpdate();
}
catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}
catch (IOException e){
throw new CmsException("["+this.getClass().getName()+"]"+CmsException. C_SERIALIZATION, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_SYSTEMPROPERTIES_UPDATE_KEY, statement);
}
}
return readSystemProperty(name);
}
// methods working with propertydef
/**
* Reads a propertydefinition for the given resource type.
*
* @param name The name of the propertydefinition to read.
* @param type The resource type for which the propertydefinition is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(String name, CmsResourceType type)
throws CmsException {
return( readPropertydefinition(name, type.getResourceType() ) );
}
/**
* Reads a propertydefinition for the given resource type.
*
* @param name The name of the propertydefinition to read.
* @param type The resource type for which the propertydefinition is valid.
*
* @return propertydefinition The propertydefinition that corresponds to the overgiven
* arguments - or null if there is no valid propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition readPropertydefinition(String name, int type)
throws CmsException {
CmsPropertydefinition propDef=null;
ResultSet res;
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_READ_KEY);
statement.setString(1,name);
statement.setInt(2,type);
res = statement.executeQuery();
// if resultset exists - return it
if(res.next()) {
propDef = new CmsPropertydefinition( res.getInt(C_PROPERTYDEF_ID),
res.getString(C_PROPERTYDEF_NAME),
res.getInt(C_PROPERTYDEF_RESOURCE_TYPE),
res.getInt(C_PROPERTYDEF_TYPE) );
res.close();
} else {
res.close();
// not found!
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_NOT_FOUND);
}
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_READ_KEY, statement);
}
}
return propDef;
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsResourceType resourcetype)
throws CmsException {
return(readAllPropertydefinitions(resourcetype.getResourceType()));
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(int resourcetype)
throws CmsException {
Vector metadefs = new Vector();
ResultSet result = null;
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_READALL_A_KEY);
statement.setInt(1,resourcetype);
result = statement.executeQuery();
while(result.next()) {
metadefs.addElement( new CmsPropertydefinition( result.getInt(C_PROPERTYDEF_ID),
result.getString(C_PROPERTYDEF_NAME),
result.getInt(C_PROPERTYDEF_RESOURCE_TYPE),
result.getInt(C_PROPERTYDEF_TYPE) ) );
}
result.close();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_READALL_A_KEY, statement);
}
}
return(metadefs);
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
* @param type The type of the propertydefinition (normal|mandatory|optional).
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsResourceType resourcetype, int type)
throws CmsException {
return(readAllPropertydefinitions(resourcetype.getResourceType(), type));
}
/**
* Reads all propertydefinitions for the given resource type.
*
* @param resourcetype The resource type to read the propertydefinitions for.
* @param type The type of the propertydefinition (normal|mandatory|optional).
*
* @return propertydefinitions A Vector with propertydefefinitions for the resource type.
* The Vector is maybe empty.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(int resourcetype, int type)
throws CmsException {
Vector metadefs = new Vector();
PreparedStatement statement = null;
ResultSet result = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_READALL_B_KEY);
statement.setInt(1,resourcetype);
statement.setInt(2,type);
result = statement.executeQuery();
while(result.next()) {
metadefs.addElement( new CmsPropertydefinition( result.getInt(C_PROPERTYDEF_ID),
result.getString(C_PROPERTYDEF_NAME),
result.getInt(C_PROPERTYDEF_RESOURCE_TYPE),
result.getInt(C_PROPERTYDEF_TYPE) ) );
}
result.close();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_READALL_B_KEY, statement);
}
}
return(metadefs);
}
/**
* Creates the propertydefinitions for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param name The name of the propertydefinitions to overwrite.
* @param resourcetype The resource-type for the propertydefinitions.
* @param type The type of the propertydefinitions (normal|mandatory|optional)
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition createPropertydefinition(String name,
CmsResourceType resourcetype, int type)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_CREATE_KEY);
statement.setInt(1,nextId(C_TABLE_PROPERTYDEF));
statement.setString(2,name);
statement.setInt(3,resourcetype.getResourceType());
statement.setInt(4,type);
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_CREATE_KEY, statement);
}
}
return(readPropertydefinition(name, resourcetype));
}
/**
* Delete the propertydefinitions for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param metadef The propertydefinitions to be deleted.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void deletePropertydefinition(CmsPropertydefinition metadef)
throws CmsException {
PreparedStatement statement = null;
try {
if(countProperties(metadef) != 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(),
CmsException.C_MANDATORY_PROPERTY);
}
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_DELETE_KEY);
statement.setInt(1, metadef.getId() );
statement.executeUpdate();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_DELETE_KEY, statement);
}
}
}
/**
* Updates the propertydefinition for the resource type.<BR/>
*
* Only the admin can do this.
*
* @param metadef The propertydef to be deleted.
*
* @return The propertydefinition, that was written.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsPropertydefinition writePropertydefinition(CmsPropertydefinition metadef)
throws CmsException {
PreparedStatement statement = null;
CmsPropertydefinition returnValue = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTYDEF_UPDATE_KEY);
statement.setInt(1, metadef.getPropertydefType() );
statement.setInt(2, metadef.getId() );
statement.executeUpdate();
returnValue = readPropertydefinition(metadef.getName(), metadef.getType());
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTYDEF_UPDATE_KEY, statement);
}
}
return returnValue;
}
// methods working with properties
/**
* Returns the amount of properties for a propertydefinition.
*
* @param metadef The propertydefinition to test.
*
* @return the amount of properties for a propertydefinition.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
private int countProperties(CmsPropertydefinition metadef)
throws CmsException {
ResultSet result = null;
PreparedStatement statement = null;
int returnValue;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_READALL_COUNT_KEY);
statement.setInt(1, metadef.getId());
result = statement.executeQuery();
if( result.next() ) {
returnValue = result.getInt(1) ;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + metadef.getName(),
CmsException.C_UNKNOWN_EXCEPTION);
}
result.close();
} catch(SQLException exc) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_READALL_COUNT_KEY, statement);
}
}
return returnValue;
}
/**
* Returns a property of a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @return property The property as string or null if the property not exists.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public String readProperty(String meta, int resourceId, int resourceType)
throws CmsException {
ResultSet result;
PreparedStatement statement = null;
String returnValue = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_READ_KEY);
statement.setInt(1, resourceId);
statement.setString(2, meta);
statement.setInt(3, resourceType);
result = statement.executeQuery();
// if resultset exists - return it
if(result.next()) {
returnValue = result.getString(C_PROPERTY_VALUE);
}
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_READ_KEY, statement);
}
}
return returnValue;
}
/**
* Writes a property for a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param value The value for the property to be set.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeProperty(String meta, String value, int resourceId,
int resourceType)
throws CmsException {
CmsPropertydefinition propdef = readPropertydefinition(meta, resourceType);
if( propdef == null) {
// there is no propertydefinition for with the overgiven name for the resource
throw new CmsException("[" + this.getClass().getName() + "] " + meta,
CmsException.C_NOT_FOUND);
} else {
// write the property into the db
PreparedStatement statement = null;
boolean newprop=true;
try {
if( readProperty(propdef.getName(), resourceId, resourceType) != null) {
// property exists already - use update.
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_UPDATE_KEY);
statement.setString(1, value);
statement.setInt(2, resourceId);
statement.setInt(3, propdef.getId());
statement.executeUpdate();
newprop=false;
} else {
// property dosen't exist - use create.
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_CREATE_KEY);
statement.setInt(1, nextId(C_TABLE_PROPERTIES));
statement.setInt(2, propdef.getId());
statement.setInt(3, resourceId);
statement.setString(4, value);
statement.executeUpdate();
newprop=true;
}
} catch(SQLException exc) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
if (newprop) {
m_pool.putPreparedStatement(C_PROPERTIES_CREATE_KEY, statement);
} else {
m_pool.putPreparedStatement(C_PROPERTIES_UPDATE_KEY, statement);
}
}
}
}
}
/**
* Writes a couple of Properties for a file or folder.
*
* @param propertyinfos A Hashtable with propertydefinition- property-pairs as strings.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void writeProperties(Hashtable propertyinfos, int resourceId, int resourceType)
throws CmsException {
// get all metadefs
Enumeration keys = propertyinfos.keys();
// one metainfo-name:
String key;
while(keys.hasMoreElements()) {
key = (String) keys.nextElement();
writeProperty(key, (String) propertyinfos.get(key), resourceId, resourceType);
}
}
/**
* Returns a list of all properties of a file or folder.
*
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @return Vector of properties as Strings.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Hashtable readAllProperties(int resourceId, int resourceType)
throws CmsException {
Hashtable returnValue = new Hashtable();
ResultSet result = null;
PreparedStatement statement = null;
try {
// create project
statement = m_pool.getPreparedStatement(C_PROPERTIES_READALL_KEY);
statement.setInt(1, resourceId);
statement.setInt(2, resourceType);
result = statement.executeQuery();
while(result.next()) {
returnValue.put(result.getString(C_PROPERTYDEF_NAME),
result.getString(C_PROPERTY_VALUE));
}
result.close();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_READALL_KEY, statement);
}
}
return(returnValue);
}
/**
* Deletes all properties for a file or folder.
*
* @param resourceId The id of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteAllProperties(int resourceId)
throws CmsException {
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_DELETEALL_KEY);
statement.setInt(1, resourceId);
statement.executeQuery();
} catch( SQLException exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_DELETEALL_KEY, statement);
}
}
}
/**
* Deletes a property for a file or folder.
*
* @param meta The property-name of which the property has to be read.
* @param resourceId The id of the resource.
* @param resourceType The Type of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteProperty(String meta, int resourceId, int resourceType)
throws CmsException {
CmsPropertydefinition propdef = readPropertydefinition(meta, resourceType);
if( propdef == null) {
// there is no propdefinition with the overgiven name for the resource
throw new CmsException("[" + this.getClass().getName() + "] " + meta,
CmsException.C_NOT_FOUND);
} else {
// delete the metainfo in the db
PreparedStatement statement = null;
try {
// create statement
statement = m_pool.getPreparedStatement(C_PROPERTIES_DELETE_KEY);
statement.setInt(1, propdef.getId());
statement.setInt(2, resourceId);
statement.executeUpdate();
} catch(SQLException exc) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_PROPERTIES_DELETE_KEY, statement);
}
}
}
}
/**
* Deletes all properties for a project.
*
* @param project The project to delete.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void deleteProjectProperties(CmsProject project)
throws CmsException {
// get all resources of the project
Vector resources = readResources(project);
for( int i = 0; i < resources.size(); i++) {
// delete the properties for each resource in project
deleteAllProperties( ((CmsResource) resources.elementAt(i)).getResourceId());
}
}
// methods working with resources
/**
* Copies a resource from the online project to a new, specified project.<br>
*
* @param project The project to be published.
* @param onlineProject The online project of the OpenCms.
* @param resource The resource to be copied to the offline project.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyResourceToProject(CmsProject project,
CmsProject onlineProject,
CmsResource resource)
throws CmsException {
// get the parent resource in the offline project
int id=C_UNKNOWN_ID;
try {
CmsResource parent=readResource(project,resource.getParent());
id=parent.getResourceId();
} catch (CmsException e) {
}
resource.setState(C_STATE_UNCHANGED);
resource.setParentId(id);
createResource(project,onlineProject,resource);
}
/**
* Publishes a specified project to the online project. <br>
*
* @param project The project to be published.
* @param onlineProject The online project of the OpenCms.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void publishProject(CmsUser user, int projectId, CmsProject onlineProject)
throws CmsException {
CmsAccessFilesystem discAccess = new CmsAccessFilesystem(m_exportpointStorage);
CmsFolder currentFolder = null;
CmsFile currentFile = null;
Vector offlineFolders;
Vector offlineFiles;
Vector deletedFolders = new Vector();
// folderIdIndex: offlinefolderId | onlinefolderId
Hashtable folderIdIndex = new Hashtable();
// read all folders in offlineProject
offlineFolders = readFolders(projectId);
for(int i = 0; i < offlineFolders.size(); i++) {
currentFolder = ((CmsFolder)offlineFolders.elementAt(i));
// C_STATE_DELETE
if (currentFolder.getState() == C_STATE_DELETED){
deletedFolders.addElement(currentFolder);
// C_STATE_NEW
}else if (currentFolder.getState() == C_STATE_NEW){
// export to filesystem if necessary
String exportKey = checkExport(currentFolder.getAbsolutePath());
if (exportKey != null){
discAccess.createFolder(currentFolder.getAbsolutePath(), exportKey);
}
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFolder.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId);
}
// create the new folder and insert its id in the folderindex
CmsFolder newFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(),
currentFolder.getAbsolutePath());
newFolder.setState(C_STATE_UNCHANGED);
writeFolder(onlineProject, newFolder, false);
folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(newFolder.getResourceId()));
// copy properties
try {
Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType());
writeProperties(props, newFolder.getResourceId(), newFolder.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + newFolder.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_CHANGED
}else if (currentFolder.getState() == C_STATE_CHANGED){
// export to filesystem if necessary
String exportKey = checkExport(currentFolder.getAbsolutePath());
if (exportKey != null){
discAccess.createFolder(currentFolder.getAbsolutePath(), exportKey);
}
CmsFolder onlineFolder = null;
try{
onlineFolder = readFolder(onlineProject.getId(), currentFolder.getAbsolutePath());
} catch(CmsException exc) {
// if folder does not exist create it
if (exc.getType() == CmsException.C_NOT_FOUND){
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFolder.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId);
}
// create the new folder
onlineFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(),
currentFolder.getAbsolutePath());
onlineFolder.setState(C_STATE_UNCHANGED);
writeFolder(onlineProject, onlineFolder, false);
}else {
throw exc;
}
}// end of catch
PreparedStatement statement = null;
try {
// update the onlineFolder with data from offlineFolder
statement = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_KEY);
statement.setInt(1,currentFolder.getType());
statement.setInt(2,currentFolder.getFlags());
statement.setInt(3,currentFolder.getOwnerId());
statement.setInt(4,currentFolder.getGroupId());
statement.setInt(5,onlineFolder.getProjectId());
statement.setInt(6,currentFolder.getAccessFlags());
statement.setInt(7,C_STATE_UNCHANGED);
statement.setInt(8,currentFolder.isLockedBy());
statement.setInt(9,currentFolder.getLauncherType());
statement.setString(10,currentFolder.getLauncherClassname());
statement.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statement.setInt(12,currentFolder.getResourceLastModifiedBy());
statement.setInt(13,0);
statement.setInt(14,currentFolder.getFileId());
statement.setInt(15,onlineFolder.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_KEY, statement);
}
}
folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(onlineFolder.getResourceId()));
// copy properties
try {
deleteAllProperties(onlineFolder.getResourceId());
Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType());
writeProperties(props, onlineFolder.getResourceId(), currentFolder.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + onlineFolder.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_UNCHANGED
}else if(currentFolder.getState() == C_STATE_UNCHANGED){
CmsFolder onlineFolder = null;
try{
onlineFolder = readFolder(onlineProject.getId(), currentFolder.getAbsolutePath());
} catch(CmsException exc){
if ( exc.getType() == CmsException.C_NOT_FOUND){
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFolder.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFolder.getParentId()), parentId);
}
// create the new folder
onlineFolder = createFolder(user, onlineProject, onlineProject, currentFolder, parentId.intValue(),
currentFolder.getAbsolutePath());
onlineFolder.setState(C_STATE_UNCHANGED);
writeFolder(onlineProject, onlineFolder, false);
// copy properties
try {
Hashtable props = readAllProperties(currentFolder.getResourceId(), currentFolder.getType());
writeProperties(props, onlineFolder.getResourceId(), onlineFolder.getType());
} catch(CmsException exc2) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + onlineFolder.toString() + " Message= " + exc.getMessage());
}
}
}else {
throw exc;
}
}// end of catch
folderIdIndex.put(new Integer(currentFolder.getResourceId()), new Integer(onlineFolder.getResourceId()));
}// end of else if
}// end of for(...
// now read all FILES in offlineProject
offlineFiles = readFiles(projectId);
for (int i = 0; i < offlineFiles.size(); i++){
currentFile = ((CmsFile)offlineFiles.elementAt(i));
if (currentFile.getName().startsWith(C_TEMP_PREFIX)) {
removeFile(projectId,currentFile.getAbsolutePath());
// C_STATE_DELETE
}else if (currentFile.getState() == C_STATE_DELETED){
// delete in filesystem if necessary
String exportKey = checkExport(currentFile.getAbsolutePath());
if (exportKey != null){
try {
discAccess.removeResource(currentFile.getAbsolutePath(), exportKey);
} catch (Exception ex) {
}
}
CmsFile currentOnlineFile = readFile(onlineProject.getId(),onlineProject.getId(),currentFile.getAbsolutePath());
try {
deleteAllProperties(currentOnlineFile.getResourceId());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + currentOnlineFile.toString() + " Message= " + exc.getMessage());
}
}
try {
deleteResource(currentOnlineFile.getResourceId());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting resource for " + currentOnlineFile.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_CHANGED
}else if ( currentFile.getState() == C_STATE_CHANGED){
// export to filesystem if necessary
String exportKey = checkExport(currentFile.getAbsolutePath());
if (exportKey != null){
discAccess.writeFile(currentFile.getAbsolutePath(), exportKey, readFileContent(currentFile.getFileId()));
}
CmsFile onlineFile = null;
try{
onlineFile = readFileHeader(onlineProject.getId(), currentFile.getAbsolutePath());
} catch(CmsException exc){
if ( exc.getType() == CmsException.C_NOT_FOUND){
// get parentId for onlineFolder either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFile.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFolder.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFile.getParentId()), parentId);
}
// create a new File
currentFile.setState(C_STATE_UNCHANGED);
onlineFile = createFile(onlineProject, onlineProject, currentFile, user.getId(), parentId.intValue(),
currentFile.getAbsolutePath(), false);
}
}// end of catch
PreparedStatement statement = null;
try {
// update the onlineFile with data from offlineFile
statement = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_FILE_KEY);
statement.setInt(1,currentFile.getType());
statement.setInt(2,currentFile.getFlags());
statement.setInt(3,currentFile.getOwnerId());
statement.setInt(4,currentFile.getGroupId());
statement.setInt(5,onlineFile.getProjectId());
statement.setInt(6,currentFile.getAccessFlags());
statement.setInt(7,C_STATE_UNCHANGED);
statement.setInt(8,currentFile.isLockedBy());
statement.setInt(9,currentFile.getLauncherType());
statement.setString(10,currentFile.getLauncherClassname());
statement.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statement.setInt(12,currentFile.getResourceLastModifiedBy());
statement.setInt(13,currentFile.getLength());
statement.setInt(14,currentFile.getFileId());
statement.setInt(15,onlineFile.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_FILE_KEY, statement);
}
}
// copy properties
try {
deleteAllProperties(onlineFile.getResourceId());
Hashtable props = readAllProperties(currentFile.getResourceId(), currentFile.getType());
writeProperties(props, onlineFile.getResourceId(), currentFile.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + onlineFile.toString() + " Message= " + exc.getMessage());
}
}
// C_STATE_NEW
}else if (currentFile.getState() == C_STATE_NEW){
// export to filesystem if necessary
String exportKey = checkExport(currentFile.getAbsolutePath());
if (exportKey != null){
discAccess.writeFile(currentFile.getAbsolutePath(), exportKey, readFileContent(currentFile.getFileId()));
}
// get parentId for onlineFile either from folderIdIndex or from the database
Integer parentId = (Integer)folderIdIndex.get(new Integer(currentFile.getParentId()));
if (parentId == null){
CmsFolder currentOnlineParent = readFolder(onlineProject.getId(), currentFile.getParent());
parentId = new Integer(currentOnlineParent.getResourceId());
folderIdIndex.put(new Integer(currentFile.getParentId()), parentId);
}
// create the new file
CmsFile newFile = createFile(onlineProject, onlineProject, currentFile, user.getId(),
parentId.intValue(),currentFile.getAbsolutePath(), false);
newFile.setState(C_STATE_UNCHANGED);
writeFile(onlineProject, onlineProject,newFile,false);
// copy properties
try {
Hashtable props = readAllProperties(currentFile.getResourceId(), currentFile.getType());
writeProperties(props, newFile.getResourceId(), newFile.getType());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, copy properties for " + newFile.toString() + " Message= " + exc.getMessage());
}
}
}
}// end of for(...
// now delete the "deleted" folders
for(int i = deletedFolders.size()-1; i > -1; i
currentFolder = ((CmsFolder)deletedFolders.elementAt(i));
String exportKey = checkExport(currentFolder.getAbsolutePath());
if (exportKey != null){
discAccess.removeResource(currentFolder.getAbsolutePath(), exportKey);
}
try {
deleteAllProperties(currentFolder.getResourceId());
} catch(CmsException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[CmsDbAccess] error publishing, deleting properties for " + currentFolder.toString() + " Message= " + exc.getMessage());
}
}
removeFolderForPublish(onlineProject, currentFolder.getAbsolutePath());
}// end of for
clearFilesTable();
}
/**
* Private helper method for publihing into the filesystem.
* test if resource must be written to the filesystem
*
* @param filename Name of a resource in the OpenCms system.
* @return key in m_exportpointStorage Hashtable or null.
*/
private String checkExport(String filename){
String key = null;
String exportpoint = null;
Enumeration e = m_exportpointStorage.keys();
while (e.hasMoreElements()) {
exportpoint = (String)e.nextElement();
if (filename.startsWith(exportpoint)){
return exportpoint;
}
}
return key;
}
/**
* Private helper method to read the fileContent for publishProject(export).
*
* @param fileId the fileId.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
private byte[] readFileContent(int fileId)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
byte[] returnValue = null;
try {
// read fileContent from database
statement = m_pool.getPreparedStatement(C_FILE_READ_KEY);
statement.setInt(1,fileId);
res = statement.executeQuery();
if (res.next()) {
returnValue = res.getBytes(C_FILE_CONTENT);
} else {
throw new CmsException("["+this.getClass().getName()+"]"+fileId,CmsException.C_NOT_FOUND);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_FILE_READ_KEY, statement);
}
}
return returnValue;
}
/**
* Private helper method to delete a resource.
*
* @param id the id of the resource to delete.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
private void deleteResource(int id)
throws CmsException {
PreparedStatement statement = null;
try {
// read resource data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETEBYID_KEY);
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETEBYID_KEY, statement);
}
}
}
/**
* Reads a resource from the Cms.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return The resource read.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
private CmsResource readResource(CmsProject project, String filename)
throws CmsException {
CmsResource file = null;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read resource data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READ_KEY);
statement.setString(1,filename);
statement.setInt(2,project.getId());
res = statement.executeQuery();
// create new resource
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectId=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
int resSize= res.getInt(C_RESOURCES_SIZE);
file=new CmsResource(resId,parentId,fileId,resName,resType,resFlags,
userId,groupId,projectId,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
resSize);
res.close();
} else {
res.close();
throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readResource "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_KEY, statement);
}
}
return file;
}
/**
* Reads all resource from the Cms, that are in one project.<BR/>
* A resource is either a file header or a folder.
*
* @param project The project in which the resource will be used.
*
* @return A Vecor of resources.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readResources(CmsProject project)
throws CmsException {
Vector resources = new Vector();
CmsResource file;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read resource data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READBYPROJECT_KEY);
statement.setInt(1,project.getId());
res = statement.executeQuery();
// create new resource
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectId=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
int resSize= res.getInt(C_RESOURCES_SIZE);
file=new CmsResource(resId,parentId,fileId,resName,resType,resFlags,
userId,groupId,projectId,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
resSize);
resources.addElement(file);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception ex) {
throw new CmsException("["+this.getClass().getName()+"]", ex);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READBYPROJECT_KEY, statement);
}
}
return resources;
}
/**
* Reads all folders from the Cms, that are in one project.<BR/>
*
* @param project The project in which the folders are.
*
* @return A Vecor of folders.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readFolders(int projectId)
throws CmsException {
Vector folders = new Vector();
CmsFolder folder;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read folder data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READFOLDERSBYPROJECT_KEY);
statement.setInt(1,projectId);
res = statement.executeQuery();
// create new folder
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,created,
modified,modifiedBy);
folders.addElement(folder);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception ex) {
throw new CmsException("["+this.getClass().getName()+"]", ex);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READFOLDERSBYPROJECT_KEY, statement);
}
}
return folders;
}
/**
* Reads all files from the Cms, that are in one project.<BR/>
*
* @param project The project in which the files are.
*
* @return A Vecor of files.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readFiles(int projectId)
throws CmsException {
Vector files = new Vector();
CmsFile file;
ResultSet res = null;
PreparedStatement statement = null;
try {
// read file data from database
statement = m_pool.getPreparedStatement(C_RESOURCES_READFILESBYPROJECT_KEY);
statement.setInt(1,projectId);
res = statement.executeQuery();
// create new file
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
files.addElement(file);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"]"+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (Exception ex) {
throw new CmsException("["+this.getClass().getName()+"]", ex);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READFILESBYPROJECT_KEY, statement);
}
}
return files;
}
/**
* Creates a new resource from an given CmsResource object.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param resource The resource to be written to the Cms.
*
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void createResource(CmsProject project,
CmsProject onlineProject,
CmsResource resource)
throws CmsException {
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
int id=nextId(C_TABLE_RESOURCES);
// write new resource to the database
statement.setInt(1,id);
statement.setInt(2,resource.getParentId());
statement.setString(3,resource.getAbsolutePath());
statement.setInt(4,resource.getType());
statement.setInt(5,resource.getFlags());
statement.setInt(6,resource.getOwnerId());
statement.setInt(7,resource.getGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,resource.getFileId());
statement.setInt(10,resource.getAccessFlags());
statement.setInt(11,resource.getState());
statement.setInt(12,resource.isLockedBy());
statement.setInt(13,resource.getLauncherType());
statement.setString(14,resource.getLauncherClassname());
statement.setTimestamp(15,new Timestamp(resource.getDateCreated()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,resource.getLength());
statement.setInt(18,resource.getResourceLastModifiedBy());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
}
// return readResource(project,resource.getAbsolutePath());
}
/**
* Deletes a specified project
*
* @param project The project to be deleted.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteProjectResources(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
try {
// delete all project-resources.
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETE_PROJECT_KEY);
statement.setInt(1,project.getId());
statement.executeQuery();
// delete all project-files.
clearFilesTable();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETE_PROJECT_KEY, statement);
}
}
}
/**
* Reads a file from the Cms.<BR/>
*
* @param projectId The Id of the project in which the resource will be used.
* @param onlineProjectId The online projectId of the OpenCms.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFile(int projectId,
int onlineProjectId,
String filename)
throws CmsException {
CmsFile file = null;
PreparedStatement statement = null;
ResultSet res = null;
try {
// if the actual project is the online project read file header and content
// from the online project
if (projectId == onlineProjectId) {
statement = m_pool.getPreparedStatement(C_FILE_READ_ONLINE_KEY);
statement.setString(1, filename);
statement.setInt(2,onlineProjectId);
res = statement.executeQuery();
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
int resSize= res.getInt(C_RESOURCES_SIZE);
byte[] content=res.getBytes(C_RESOURCES_FILE_CONTENT);
file=new CmsFile(resId,parentId,fileId,filename,resType,resFlags,userId,
groupId,onlineProjectId,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
content,resSize);
res.close();
} else {
throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND);
}
} else {
// reading a file from an offline project must be done in two steps:
// first read the file header from the offline project, then get either
// the file content of the offline project (if it is already existing)
// or form the online project.
// get the file header
file=readFileHeader(projectId, filename);
// check if the file is marked as deleted
if (file.getState() == C_STATE_DELETED) {
throw new CmsException("["+this.getClass().getName()+"] "+CmsException.C_NOT_FOUND);
}
// read the file content
statement = m_pool.getPreparedStatement(C_FILE_READ_KEY);
statement.setInt(1,file.getFileId());
res = statement.executeQuery();
if (res.next()) {
file.setContents(res.getBytes(C_FILE_CONTENT));
} else {
throw new CmsException("["+this.getClass().getName()+"]"+filename,CmsException.C_NOT_FOUND);
}
res.close();
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if (projectId == onlineProjectId) {
if( statement != null) {
m_pool.putPreparedStatement(C_FILE_READ_ONLINE_KEY, statement);
}
}else{
if( statement != null) {
m_pool.putPreparedStatement(C_FILE_READ_KEY, statement);
}
}
}
return file;
}
/**
* Reads all file headers of a file in the OpenCms.<BR>
* The reading excludes the filecontent.
*
* @param filename The name of the file to be read.
*
* @return Vector of file headers read from the Cms.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public Vector readAllFileHeaders(String filename)
throws CmsException {
CmsFile file=null;
ResultSet res =null;
Vector allHeaders = new Vector();
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_RESOURCES_READ_ALL_KEY);
// read file header data from database
statement.setString(1, filename);
res = statement.executeQuery();
// create new file headers
while(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
allHeaders.addElement(file);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readAllFileHeaders "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_ALL_KEY, statement);
}
}
return allHeaders;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param projectId The Id of the project in which the resource will be used.
* @param filename The complete name of the new file (including pathinformation).
*
* @return file The read file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int projectId, String filename)
throws CmsException {
CmsFile file=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_READ_KEY);
// read file data from database
statement.setString(1, filename);
statement.setInt(2, projectId);
res = statement.executeQuery();
// create new file
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
res.close();
// check if this resource is marked as deleted
if (file.getState() == C_STATE_DELETED) {
throw new CmsException("["+this.getClass().getName()+"] "+file.getAbsolutePath(),CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+filename,CmsException.C_NOT_FOUND);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (CmsException ex) {
throw ex;
} catch( Exception exc ) {
throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_KEY, statement);
}
}
return file;
}
/**
* Reads a file header from the Cms.<BR/>
* The reading excludes the filecontent.
*
* @param resourceId The Id of the resource.
*
* @return file The read file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile readFileHeader(int resourceId)
throws CmsException {
CmsFile file=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_READBYID_KEY);
// read file data from database
statement.setInt(1, resourceId);
res = statement.executeQuery();
// create new file
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
res.close();
// check if this resource is marked as deleted
if (file.getState() == C_STATE_DELETED) {
throw new CmsException("["+this.getClass().getName()+"] "+file.getAbsolutePath(),CmsException.C_RESOURCE_DELETED);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+resourceId,CmsException.C_NOT_FOUND);
}
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch (CmsException ex) {
throw ex;
} catch( Exception exc ) {
throw new CmsException("readFile "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READBYID_KEY, statement);
}
}
return file;
}
/**
* Creates a new file with the given content and resourcetype.
*
* @param user The user who wants to create the file.
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param filename The complete name of the new file (including pathinformation).
* @param flags The flags of this resource.
* @param parentId The parentId of the resource.
* @param contents The contents of the new file.
* @param resourceType The resourceType of the new file.
*
* @return file The created file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile createFile(CmsUser user,
CmsProject project,
CmsProject onlineProject,
String filename, int flags,int parentId,
byte[] contents, CmsResourceType resourceType)
throws CmsException {
int state= C_STATE_NEW;
// Test if the file is already there and marked as deleted.
// If so, delete it
try {
readFileHeader(project.getId(),filename);
} catch (CmsException e) {
// if the file is maked as deleted remove it!
if (e.getType()==CmsException.C_RESOURCE_DELETED) {
removeFile(project.getId(),filename);
state=C_STATE_CHANGED;
}
}
int resourceId = nextId(C_TABLE_RESOURCES);
int fileId = nextId(C_TABLE_FILES);
PreparedStatement statement = null;
PreparedStatement statementFileWrite = null;
try {
statement = m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
// write new resource to the database
statement.setInt(1,resourceId);
statement.setInt(2,parentId);
statement.setString(3, filename);
statement.setInt(4,resourceType.getResourceType());
statement.setInt(5,flags);
statement.setInt(6,user.getId());
statement.setInt(7,user.getDefaultGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,fileId);
statement.setInt(10,C_ACCESS_DEFAULT_FLAGS);
statement.setInt(11,state);
statement.setInt(12,C_UNKNOWN_ID);
statement.setInt(13,resourceType.getLauncherType());
statement.setString(14,resourceType.getLauncherClass());
statement.setTimestamp(15,new Timestamp(System.currentTimeMillis()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,contents.length);
statement.setInt(18,user.getId());
statement.executeUpdate();
statementFileWrite = m_pool.getPreparedStatement(C_FILES_WRITE_KEY);
statementFileWrite.setInt(1,fileId);
statementFileWrite.setBytes(2,contents);
statementFileWrite.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
if( statementFileWrite != null) {
m_pool.putPreparedStatement(C_FILES_WRITE_KEY, statementFileWrite);
}
}
return readFile(project.getId(),onlineProject.getId(),filename);
}
/**
* Creates a new file from an given CmsFile object and a new filename.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The file to be written to the Cms.
* @param user The Id of the user who changed the resourse.
* @param parentId The parentId of the resource.
* @param filename The complete new name of the file (including pathinformation).
*
* @return file The created file.
*
* @exception CmsException Throws CmsException if operation was not succesful
*/
public CmsFile createFile(CmsProject project,
CmsProject onlineProject,
CmsFile file,
int userId,
int parentId, String filename, boolean copy)
throws CmsException {
int state=0;
if (project.equals(onlineProject)) {
state= file.getState();
} else {
state=C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it
try {
readFileHeader(project.getId(),filename);
} catch (CmsException e) {
// if the file is maked as deleted remove it!
if (e.getType()==CmsException.C_RESOURCE_DELETED) {
removeFile(project.getId(),filename);
state=C_STATE_CHANGED;
}
}
int newFileId = file.getFileId();
int resourceId = nextId(C_TABLE_RESOURCES);
if (copy){
PreparedStatement statementFileWrite = null;
try {
newFileId = nextId(C_TABLE_FILES);
statementFileWrite = m_pool.getPreparedStatement(C_FILES_WRITE_KEY);
statementFileWrite.setInt(1, newFileId);
statementFileWrite.setBytes(2, file.getContents());
statementFileWrite.executeUpdate();
} catch (SQLException se) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsAccessFileMySql] " + se.getMessage());
se.printStackTrace();
}
}finally {
if( statementFileWrite != null) {
m_pool.putPreparedStatement(C_FILES_WRITE_KEY, statementFileWrite);
}
}
}
PreparedStatement statementResourceWrite = null;
try {
statementResourceWrite = m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
statementResourceWrite.setInt(1,resourceId);
statementResourceWrite.setInt(2,parentId);
statementResourceWrite.setString(3, filename);
statementResourceWrite.setInt(4,file.getType());
statementResourceWrite.setInt(5,file.getFlags());
statementResourceWrite.setInt(6,file.getOwnerId());
statementResourceWrite.setInt(7,file.getGroupId());
statementResourceWrite.setInt(8,project.getId());
statementResourceWrite.setInt(9,newFileId);
statementResourceWrite.setInt(10,file.getAccessFlags());
statementResourceWrite.setInt(11,state);
statementResourceWrite.setInt(12,file.isLockedBy());
statementResourceWrite.setInt(13,file.getLauncherType());
statementResourceWrite.setString(14,file.getLauncherClassname());
statementResourceWrite.setTimestamp(15,new Timestamp(file.getDateCreated()));
statementResourceWrite.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statementResourceWrite.setInt(17,file.getLength());
statementResourceWrite.setInt(18,userId);
statementResourceWrite.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statementResourceWrite != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statementResourceWrite);
}
}
return readFile(project.getId(),onlineProject.getId(),filename);
}
/**
* Deletes a file in the database.
* This method is used to physically remove a file form the database.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void removeFile(int projectId, String filename)
throws CmsException{
PreparedStatement statement = null;
try {
// delete the file header
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETE_KEY);
statement.setString(1, filename);
statement.setInt(2,projectId);
statement.executeUpdate();
// delete the file content
// clearFilesTable();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETE_KEY, statement);
}
}
}
/**
* Renames the file to the new name.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param userId The user id
* @param oldfileID The id of the resource which will be renamed.
* @param newname The new name of the resource.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void renameFile(CmsProject project,
CmsProject onlineProject,
int userId,
int oldfileID,
String newname)
throws CmsException {
PreparedStatement statement = null;
try{
statement = m_pool.getPreparedStatement(C_RESOURCES_RENAMERESOURCE_KEY);
statement.setString(1,newname);
statement.setInt(2,userId);
statement.setInt(3,oldfileID);
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_RENAMERESOURCE_KEY, statement);
}
}
}
/**
* Deletes a folder in the database.
* This method is used to physically remove a folder form the database.
* It is internally used by the publish project method.
*
* @param project The project in which the resource will be used.
* @param foldername The complete path of the folder.
* @exception CmsException Throws CmsException if operation was not succesful
*/
private void removeFolderForPublish(CmsProject project, String foldername)
throws CmsException{
PreparedStatement statement = null;
try {
// delete the folder
statement = m_pool.getPreparedStatement(C_RESOURCES_DELETE_KEY);
statement.setString(1, foldername);
statement.setInt(2,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_DELETE_KEY, statement);
}
}
}
/**
* Reads a folder from the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param foldername The name of the folder to be read.
*
* @return The read folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder readFolder(int projectId, String foldername)
throws CmsException {
CmsFolder folder=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
statement=m_pool.getPreparedStatement(C_RESOURCES_READ_KEY);
statement.setString(1, foldername);
statement.setInt(2,projectId);
res = statement.executeQuery();
// create new resource
if(res.next()) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,created,
modified,modifiedBy);
}else {
throw new CmsException("["+this.getClass().getName()+"] "+foldername,CmsException.C_NOT_FOUND);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("readFolder "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_READ_KEY, statement);
}
}
return folder;
}
/**
* Writes the fileheader to the Cms.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFileHeader(CmsProject project,
CmsProject onlineProject,
CmsFile file,boolean changed)
throws CmsException {
ResultSet res;
ResultSet tmpres;
byte[] content;
PreparedStatement statementFileRead = null;
PreparedStatement statementResourceUpdate = null;
try {
// check if the file content for this file is already existing in the
// offline project. If not, load it from the online project and add it
// to the offline project.
if ((file.getState() == C_STATE_UNCHANGED) && (changed == true) ) {
// read file content form the online project
statementFileRead = m_pool.getPreparedStatement(C_FILE_READ_KEY);
statementFileRead.setInt(1,file.getFileId());
res = statementFileRead.executeQuery();
if (res.next()) {
content=res.getBytes(C_FILE_CONTENT);
} else {
throw new CmsException("["+this.getClass().getName()+"]"+file.getAbsolutePath(),CmsException.C_NOT_FOUND);
}
res.close();
// add the file content to the offline project.
PreparedStatement statementFileWrite = null;
try {
file.setFileId(nextId(C_TABLE_FILES));
statementFileWrite = m_pool.getPreparedStatement(C_FILES_WRITE_KEY);
statementFileWrite.setInt(1,file.getFileId());
statementFileWrite.setBytes(2,content);
statementFileWrite.executeUpdate();
} catch (SQLException se) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsAccessFileMySql] " + se.getMessage());
se.printStackTrace();
}
}finally {
if( statementFileWrite != null) {
m_pool.putPreparedStatement(C_FILES_WRITE_KEY, statementFileWrite);
}
}
}
// update resource in the database
statementResourceUpdate = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_KEY);
statementResourceUpdate.setInt(1,file.getType());
statementResourceUpdate.setInt(2,file.getFlags());
statementResourceUpdate.setInt(3,file.getOwnerId());
statementResourceUpdate.setInt(4,file.getGroupId());
statementResourceUpdate.setInt(5,file.getProjectId());
statementResourceUpdate.setInt(6,file.getAccessFlags());
//STATE
int state=file.getState();
if ((state == C_STATE_NEW) || (state == C_STATE_CHANGED)) {
statementResourceUpdate.setInt(7,state);
} else {
if (changed==true) {
statementResourceUpdate.setInt(7,C_STATE_CHANGED);
} else {
statementResourceUpdate.setInt(7,file.getState());
}
}
statementResourceUpdate.setInt(8,file.isLockedBy());
statementResourceUpdate.setInt(9,file.getLauncherType());
statementResourceUpdate.setString(10,file.getLauncherClassname());
statementResourceUpdate.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statementResourceUpdate.setInt(12,file.getResourceLastModifiedBy());
statementResourceUpdate.setInt(13,file.getLength());
statementResourceUpdate.setInt(14,file.getFileId());
statementResourceUpdate.setInt(15,file.getResourceId());
statementResourceUpdate.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statementFileRead != null) {
m_pool.putPreparedStatement(C_FILE_READ_KEY, statementFileRead);
}
if( statementResourceUpdate != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_KEY, statementResourceUpdate);
}
}
}
/**
* Writes a file to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param file The new file.
* @param changed Flag indicating if the file state must be set to changed.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFile(CmsProject project,
CmsProject onlineProject,
CmsFile file,boolean changed)
throws CmsException {
PreparedStatement statement = null;
try {
// update the file header in the RESOURCE database.
writeFileHeader(project,onlineProject,file,changed);
// update the file content in the FILES database.
statement = m_pool.getPreparedStatement(C_FILES_UPDATE_KEY);
statement.setBytes(1,file.getContents());
statement.setInt(2,file.getFileId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_FILES_UPDATE_KEY, statement);
}
}
}
/**
* Writes a folder to the Cms.<BR/>
*
* @param project The project in which the resource will be used.
* @param folder The folder to be written.
* @param changed Flag indicating if the file state must be set to changed.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void writeFolder(CmsProject project, CmsFolder folder, boolean changed)
throws CmsException {
PreparedStatement statement = null;
try {
// update resource in the database
statement = m_pool.getPreparedStatement(C_RESOURCES_UPDATE_KEY);
statement.setInt(1,folder.getType());
statement.setInt(2,folder.getFlags());
statement.setInt(3,folder.getOwnerId());
statement.setInt(4,folder.getGroupId());
statement.setInt(5,folder.getProjectId());
statement.setInt(6,folder.getAccessFlags());
int state=folder.getState();
if ((state == C_STATE_NEW) || (state == C_STATE_CHANGED)) {
statement.setInt(7,state);
} else {
if (changed==true) {
statement.setInt(7,C_STATE_CHANGED);
} else {
statement.setInt(7,folder.getState());
}
}
statement.setInt(8,folder.isLockedBy());
statement.setInt(9,folder.getLauncherType());
statement.setString(10,folder.getLauncherClassname());
statement.setTimestamp(11,new Timestamp(System.currentTimeMillis()));
statement.setInt(12,folder.getResourceLastModifiedBy());
statement.setInt(13,0);
statement.setInt(14,C_UNKNOWN_ID);
statement.setInt(15,folder.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UPDATE_KEY, statement);
}
}
}
/**
* Creates a new folder
*
* @param user The user who wants to create the folder.
* @param project The project in which the resource will be used.
* @param parentId The parentId of the folder.
* @param fileId The fileId of the folder.
* @param foldername The complete path to the folder in which the new folder will
* be created.
* @param flags The flags of this resource.
*
* @return The created folder.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder createFolder(CmsUser user, CmsProject project, int parentId,
int fileId, String foldername, int flags)
throws CmsException {
int resourceId = nextId(C_TABLE_RESOURCES);
PreparedStatement statement = null;
try {
// write new resource to the database
statement=m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
statement.setInt(1,resourceId);
statement.setInt(2,parentId);
statement.setString(3, foldername);
statement.setInt(4,C_TYPE_FOLDER);
statement.setInt(5,flags);
statement.setInt(6,user.getId());
statement.setInt(7,user.getDefaultGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,fileId);
statement.setInt(10,C_ACCESS_DEFAULT_FLAGS);
statement.setInt(11,C_STATE_NEW);
statement.setInt(12,C_UNKNOWN_ID);
statement.setInt(13,C_UNKNOWN_LAUNCHER_ID);
statement.setString(14,C_UNKNOWN_LAUNCHER);
statement.setTimestamp(15,new Timestamp(System.currentTimeMillis()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,0);
statement.setInt(18,user.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
}
return readFolder(project.getId(),foldername);
}
/**
* Creates a new folder from an existing folder object.
*
* @param user The user who wants to create the folder.
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param folder The folder to be written to the Cms.
* @param parentId The parentId of the resource.
*
* @param foldername The complete path of the new name of this folder.
*
* @return The created folder.
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public CmsFolder createFolder(CmsUser user,
CmsProject project,
CmsProject onlineProject,
CmsFolder folder,
int parentId,
String foldername)
throws CmsException{
CmsFolder oldFolder = null;
int state=0;
if (project.equals(onlineProject)) {
state= folder.getState();
} else {
state=C_STATE_NEW;
}
// Test if the file is already there and marked as deleted.
// If so, delete it
try {
oldFolder = readFolder(project.getId(),foldername);
if (oldFolder.getState() == C_STATE_DELETED){
removeFolder(oldFolder);
state = C_STATE_CHANGED;
}
} catch (CmsException e) {}
int resourceId = nextId(C_TABLE_RESOURCES);
int fileId = nextId(C_TABLE_FILES);
PreparedStatement statement = null;
try {
// write new resource to the database
statement = m_pool.getPreparedStatement(C_RESOURCES_WRITE_KEY);
statement.setInt(1,resourceId);
statement.setInt(2,parentId);
statement.setString(3, foldername);
statement.setInt(4,folder.getType());
statement.setInt(5,folder.getFlags());
statement.setInt(6,folder.getOwnerId());
statement.setInt(7,folder.getGroupId());
statement.setInt(8,project.getId());
statement.setInt(9,fileId);
statement.setInt(10,folder.getAccessFlags());
statement.setInt(11,C_STATE_NEW);
statement.setInt(12,folder.isLockedBy());
statement.setInt(13,folder.getLauncherType());
statement.setString(14,folder.getLauncherClassname());
statement.setTimestamp(15,new Timestamp(folder.getDateCreated()));
statement.setTimestamp(16,new Timestamp(System.currentTimeMillis()));
statement.setInt(17,0);
statement.setInt(18,user.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_WRITE_KEY, statement);
}
}
//return readFolder(project,folder.getAbsolutePath());
return readFolder(project.getId(),foldername);
}
/**
* Deletes a folder in the database.
* This method is used to physically remove a folder form the database.
*
* @param folder The folder.
* @exception CmsException Throws CmsException if operation was not succesful
*/
public void removeFolder(CmsFolder folder)
throws CmsException{
// the current implementation only deletes empty folders
// check if the folder has any files in it
Vector files= getFilesInFolder(folder);
files=getUndeletedResources(files);
if (files.size()==0) {
// check if the folder has any folders in it
Vector folders= getSubFolders(folder);
folders=getUndeletedResources(folders);
if (folders.size()==0) {
//this folder is empty, delete it
PreparedStatement statement = null;
try {
// delete the folder
statement = m_pool.getPreparedStatement(C_RESOURCES_ID_DELETE_KEY);
statement.setInt(1,folder.getResourceId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_ID_DELETE_KEY, statement);
}
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+folder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+folder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
}
/**
* Deletes the folder.
*
* Only empty folders can be deleted yet.
*
* @param project The project in which the resource will be used.
* @param orgFolder The folder that will be deleted.
* @param force If force is set to true, all sub-resources will be deleted.
* If force is set to false, the folder will be deleted only if it is empty.
* This parameter is not used yet as only empty folders can be deleted!
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFolder(CmsProject project, CmsFolder orgFolder, boolean force)
throws CmsException {
// the current implementation only deletes empty folders
// check if the folder has any files in it
Vector files= getFilesInFolder(orgFolder);
files=getUndeletedResources(files);
if (files.size()==0) {
// check if the folder has any folders in it
Vector folders= getSubFolders(orgFolder);
folders=getUndeletedResources(folders);
if (folders.size()==0) {
//this folder is empty, delete it
PreparedStatement statement = null;
try {
// mark the folder as deleted
statement=m_pool.getPreparedStatement(C_RESOURCES_REMOVE_KEY);
statement.setInt(1,C_STATE_DELETED);
statement.setInt(2,C_UNKNOWN_ID);
statement.setString(3, orgFolder.getAbsolutePath());
statement.setInt(4,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_REMOVE_KEY, statement);
}
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+orgFolder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
} else {
throw new CmsException("["+this.getClass().getName()+"] "+orgFolder.getAbsolutePath(),CmsException.C_NOT_EMPTY);
}
}
/**
* Copies the file.
*
* @param project The project in which the resource will be used.
* @param onlineProject The online project of the OpenCms.
* @param userId The id of the user who wants to copy the file.
* @param source The complete path of the sourcefile.
* @param parentId The parentId of the resource.
* @param destination The complete path of the destinationfile.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void copyFile(CmsProject project,
CmsProject onlineProject,
int userId,
String source,
int parentId,
String destination)
throws CmsException {
CmsFile file;
// read sourcefile
file=readFile(project.getId(),onlineProject.getId(),source);
// create destination file
createFile(project,onlineProject,file,userId,parentId,destination, true);
}
/**
* Deletes the file.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void deleteFile(CmsProject project, String filename)
throws CmsException {
PreparedStatement statement = null;
try {
statement =m_pool.getPreparedStatement(C_RESOURCES_REMOVE_KEY);
// mark the file as deleted
statement.setInt(1,C_STATE_DELETED);
statement.setInt(2,C_UNKNOWN_ID);
statement.setString(3, filename);
statement.setInt(4,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_REMOVE_KEY, statement);
}
}
}
/**
* Undeletes the file.
*
* @param project The project in which the resource will be used.
* @param filename The complete path of the file.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public void undeleteFile(CmsProject project, String filename)
throws CmsException {
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(C_RESOURCES_REMOVE_KEY);
// mark the file as deleted
statement.setInt(1,C_STATE_CHANGED);
statement.setInt(2,C_UNKNOWN_ID);
statement.setString(3, filename);
statement.setInt(4,project.getId());
statement.executeUpdate();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_REMOVE_KEY, statement);
}
}
}
/**
* Returns a Vector with all subfolders.<BR/>
*
* @param parentFolder The folder to be searched.
*
* @return Vector with all subfolders for the given folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getSubFolders(CmsFolder parentFolder)
throws CmsException {
Vector folders=new Vector();
CmsFolder folder=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
// get all subfolders
statement = m_pool.getPreparedStatement(C_RESOURCES_GET_SUBFOLDER_KEY);
statement.setInt(1,parentFolder.getResourceId());
res = statement.executeQuery();
// create new folder objects
while ( res.next() ) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
folder = new CmsFolder(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,created,
modified,modifiedBy);
folders.addElement(folder);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("getSubFolders "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_GET_SUBFOLDER_KEY, statement);
}
}
return SortEntrys(folders);
}
/**
* Returns a Vector with all file headers of a folder.<BR/>
*
* @param parentFolder The folder to be searched.
*
* @return subfiles A Vector with all file headers of the folder.
*
* @exception CmsException Throws CmsException if operation was not succesful.
*/
public Vector getFilesInFolder(CmsFolder parentFolder)
throws CmsException {
Vector files=new Vector();
CmsResource file=null;
ResultSet res =null;
PreparedStatement statement = null;
try {
// get all files in folder
statement = m_pool.getPreparedStatement(C_RESOURCES_GET_FILESINFOLDER_KEY);
statement.setInt(1,parentFolder.getResourceId());
res = statement.executeQuery();
// create new file objects
while ( res.next() ) {
int resId=res.getInt(C_RESOURCES_RESOURCE_ID);
int parentId=res.getInt(C_RESOURCES_PARENT_ID);
String resName=res.getString(C_RESOURCES_RESOURCE_NAME);
int resType= res.getInt(C_RESOURCES_RESOURCE_TYPE);
int resFlags=res.getInt(C_RESOURCES_RESOURCE_FLAGS);
int userId=res.getInt(C_RESOURCES_USER_ID);
int groupId= res.getInt(C_RESOURCES_GROUP_ID);
int projectID=res.getInt(C_RESOURCES_PROJECT_ID);
int fileId=res.getInt(C_RESOURCES_FILE_ID);
int accessFlags=res.getInt(C_RESOURCES_ACCESS_FLAGS);
int state= res.getInt(C_RESOURCES_STATE);
int lockedBy= res.getInt(C_RESOURCES_LOCKED_BY);
int launcherType= res.getInt(C_RESOURCES_LAUNCHER_TYPE);
String launcherClass= res.getString(C_RESOURCES_LAUNCHER_CLASSNAME);
long created=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_CREATED).getTime();
long modified=SqlHelper.getTimestamp(res,C_RESOURCES_DATE_LASTMODIFIED).getTime();
int resSize= res.getInt(C_RESOURCES_SIZE);
int modifiedBy=res.getInt(C_RESOURCES_LASTMODIFIED_BY);
file=new CmsFile(resId,parentId,fileId,resName,resType,resFlags,userId,
groupId,projectID,accessFlags,state,lockedBy,
launcherType,launcherClass,created,modified,modifiedBy,
new byte[0],resSize);
files.addElement(file);
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} catch( Exception exc ) {
throw new CmsException("getFilesInFolder "+exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc);
}finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_GET_FILESINFOLDER_KEY, statement);
}
}
return SortEntrys(files);
}
/**
* Sorts a vector of files or folders alphabetically.
* This method uses an insertion sort algorithem.
*
* @param unsortedList Array of strings containing the list of files or folders.
* @return Array of sorted strings.
*/
private Vector SortEntrys(Vector list) {
int in,out;
int nElem = list.size();
CmsResource[] unsortedList = new CmsResource[list.size()];
for (int i=0;i<list.size();i++) {
unsortedList[i]=(CmsResource)list.elementAt(i);
}
for(out=1; out < nElem; out++) {
CmsResource temp= unsortedList[out];
in = out;
while (in >0 && unsortedList[in-1].getAbsolutePath().compareTo(temp.getAbsolutePath()) >= 0){
unsortedList[in]=unsortedList[in-1];
--in;
}
unsortedList[in]=temp;
}
Vector sortedList=new Vector();
for (int i=0;i<list.size();i++) {
sortedList.addElement(unsortedList[i]);
}
return sortedList;
}
/**
* Gets all resources that are marked as undeleted.
* @param resources Vector of resources
* @return Returns all resources that are markes as deleted
*/
private Vector getUndeletedResources(Vector resources) {
Vector undeletedResources=new Vector();
for (int i=0;i<resources.size();i++) {
CmsResource res=(CmsResource)resources.elementAt(i);
if (res.getState() != C_STATE_DELETED) {
undeletedResources.addElement(res);
}
}
return undeletedResources;
}
/**
* Deletes all files in CMS_FILES without fileHeader in CMS_RESOURCES
*
*
*/
private void clearFilesTable()
throws CmsException{
PreparedStatement statementSearch = null;
PreparedStatement statementDestroy = null;
ResultSet res = null;
try{
statementSearch = m_pool.getPreparedStatement(C_RESOURCES_GET_LOST_ID_KEY);
res = statementSearch.executeQuery();
// delete the lost fileId's
statementDestroy = m_pool.getPreparedStatement(C_FILE_DELETE_KEY);
while (res.next() ){
statementDestroy.setInt(1,res.getInt(C_FILE_ID));
statementDestroy.executeUpdate();
statementDestroy.clearParameters();
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
}finally {
if( statementSearch != null) {
m_pool.putPreparedStatement(C_RESOURCES_GET_LOST_ID_KEY, statementSearch);
}
if( statementDestroy != null) {
m_pool.putPreparedStatement(C_FILE_DELETE_KEY, statementDestroy);
}
}
}
/**
* Unlocks all resources in this project.
*
* @param project The project to be unlocked.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public void unlockProject(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_RESOURCES_UNLOCK_KEY);
statement.setInt(1,project.getId());
statement.executeUpdate();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_UNLOCK_KEY, statement);
}
}
}
/**
* Counts the locked resources in this project.
*
* @param project The project to be unlocked.
* @return the amount of locked resources in this project.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public int countLockedResources(CmsProject project)
throws CmsException {
PreparedStatement statement = null;
ResultSet res = null;
int retValue;
try {
// create the statement
statement = m_pool.getPreparedStatement(C_RESOURCES_COUNTLOCKED_KEY);
statement.setInt(1,project.getId());
res = statement.executeQuery();
if(res.next()) {
retValue = res.getInt(1);
} else {
res.close();
retValue=0;
}
res.close();
} catch( Exception exc ) {
throw new CmsException("[" + this.getClass().getName() + "] " + exc.getMessage(),
CmsException.C_SQL_ERROR, exc);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(C_RESOURCES_COUNTLOCKED_KEY, statement);
}
}
return retValue;
}
/**
* Private method to init all statements in the pool.
*/
private void initStatements()
throws CmsException {
// init statements for resources and files
m_pool.initPreparedStatement(C_RESOURCES_MAXID_KEY,C_RESOURCES_MAXID);
m_pool.initPreparedStatement(C_RESOURCES_REMOVE_KEY,C_RESOURCES_REMOVE);
m_pool.initPreparedStatement(C_FILES_MAXID_KEY,C_FILES_MAXID);
m_pool.initPreparedStatement(C_FILES_UPDATE_KEY,C_FILES_UPDATE);
m_pool.initPreparedStatement(C_RESOURCES_READ_KEY,C_RESOURCES_READ);
m_pool.initPreparedStatement(C_RESOURCES_READBYID_KEY,C_RESOURCES_READBYID);
m_pool.initPreparedStatement(C_RESOURCES_WRITE_KEY,C_RESOURCES_WRITE);
m_pool.initPreparedStatement(C_RESOURCES_GET_SUBFOLDER_KEY,C_RESOURCES_GET_SUBFOLDER);
m_pool.initPreparedStatement(C_RESOURCES_DELETE_KEY,C_RESOURCES_DELETE);
m_pool.initPreparedStatement(C_RESOURCES_ID_DELETE_KEY,C_RESOURCES_ID_DELETE);
m_pool.initPreparedStatement(C_RESOURCES_GET_FILESINFOLDER_KEY,C_RESOURCES_GET_FILESINFOLDER);
m_pool.initPreparedStatement(C_RESOURCES_PUBLISH_PROJECT_READFILE_KEY,C_RESOURCES_PUBLISH_PROJECT_READFILE);
m_pool.initPreparedStatement(C_RESOURCES_PUBLISH_PROJECT_READFOLDER_KEY,C_RESOURCES_PUBLISH_PROJECT_READFOLDER);
m_pool.initPreparedStatement(C_RESOURCES_UPDATE_KEY,C_RESOURCES_UPDATE);
m_pool.initPreparedStatement(C_RESOURCES_UPDATE_FILE_KEY,C_RESOURCES_UPDATE_FILE);
m_pool.initPreparedStatement(C_RESOURCES_GET_LOST_ID_KEY,C_RESOURCES_GET_LOST_ID);
m_pool.initPreparedStatement(C_FILE_DELETE_KEY,C_FILE_DELETE);
m_pool.initPreparedStatement(C_RESOURCES_DELETE_PROJECT_KEY,C_RESOURCES_DELETE_PROJECT);
m_pool.initPreparedStatement(C_FILE_READ_ONLINE_KEY,C_FILE_READ_ONLINE);
m_pool.initPreparedStatement(C_FILE_READ_KEY,C_FILE_READ);
m_pool.initPreparedStatement(C_FILES_WRITE_KEY,C_FILES_WRITE);
m_pool.initPreparedStatement(C_RESOURCES_UNLOCK_KEY,C_RESOURCES_UNLOCK);
m_pool.initPreparedStatement(C_RESOURCES_COUNTLOCKED_KEY,C_RESOURCES_COUNTLOCKED);
m_pool.initPreparedStatement(C_RESOURCES_READBYPROJECT_KEY,C_RESOURCES_READBYPROJECT);
m_pool.initPreparedStatement(C_RESOURCES_READFOLDERSBYPROJECT_KEY,C_RESOURCES_READFOLDERSBYPROJECT);
m_pool.initPreparedStatement(C_RESOURCES_READFILESBYPROJECT_KEY,C_RESOURCES_READFILESBYPROJECT);
m_pool.initPreparedStatement(C_RESOURCES_PUBLISH_MARKED_KEY,C_RESOURCES_PUBLISH_MARKED);
m_pool.initPreparedStatement(C_RESOURCES_DELETEBYID_KEY,C_RESOURCES_DELETEBYID);
m_pool.initPreparedStatement(C_RESOURCES_RENAMERESOURCE_KEY,C_RESOURCES_RENAMERESOURCE);
m_pool.initPreparedStatement(C_RESOURCES_READ_ALL_KEY,C_RESOURCES_READ_ALL);
// init statements for groups
m_pool.initPreparedStatement(C_GROUPS_MAXID_KEY,C_GROUPS_MAXID);
m_pool.initPreparedStatement(C_GROUPS_READGROUP_KEY,C_GROUPS_READGROUP);
m_pool.initPreparedStatement(C_GROUPS_READGROUP2_KEY,C_GROUPS_READGROUP2);
m_pool.initPreparedStatement(C_GROUPS_CREATEGROUP_KEY,C_GROUPS_CREATEGROUP);
m_pool.initPreparedStatement(C_GROUPS_WRITEGROUP_KEY,C_GROUPS_WRITEGROUP);
m_pool.initPreparedStatement(C_GROUPS_DELETEGROUP_KEY,C_GROUPS_DELETEGROUP);
m_pool.initPreparedStatement(C_GROUPS_GETGROUPS_KEY,C_GROUPS_GETGROUPS);
m_pool.initPreparedStatement(C_GROUPS_GETCHILD_KEY,C_GROUPS_GETCHILD);
m_pool.initPreparedStatement(C_GROUPS_GETPARENT_KEY,C_GROUPS_GETPARENT);
m_pool.initPreparedStatement(C_GROUPS_GETGROUPSOFUSER_KEY,C_GROUPS_GETGROUPSOFUSER);
m_pool.initPreparedStatement(C_GROUPS_ADDUSERTOGROUP_KEY,C_GROUPS_ADDUSERTOGROUP);
m_pool.initPreparedStatement(C_GROUPS_USERINGROUP_KEY,C_GROUPS_USERINGROUP);
m_pool.initPreparedStatement(C_GROUPS_GETUSERSOFGROUP_KEY,C_GROUPS_GETUSERSOFGROUP);
m_pool.initPreparedStatement(C_GROUPS_REMOVEUSERFROMGROUP_KEY,C_GROUPS_REMOVEUSERFROMGROUP);
// init statements for users
m_pool.initPreparedStatement(C_USERS_MAXID_KEY,C_USERS_MAXID);
m_pool.initPreparedStatement(C_USERS_ADD_KEY,C_USERS_ADD);
m_pool.initPreparedStatement(C_USERS_READ_KEY,C_USERS_READ);
m_pool.initPreparedStatement(C_USERS_READID_KEY,C_USERS_READID);
m_pool.initPreparedStatement(C_USERS_READPW_KEY,C_USERS_READPW);
m_pool.initPreparedStatement(C_USERS_WRITE_KEY,C_USERS_WRITE);
m_pool.initPreparedStatement(C_USERS_DELETE_KEY,C_USERS_DELETE);
m_pool.initPreparedStatement(C_USERS_GETUSERS_KEY,C_USERS_GETUSERS);
m_pool.initPreparedStatement(C_USERS_SETPW_KEY,C_USERS_SETPW);
m_pool.initPreparedStatement(C_USERS_DELETEBYID_KEY,C_USERS_DELETEBYID);
// init statements for projects
m_pool.initPreparedStatement(C_PROJECTS_MAXID_KEY, C_PROJECTS_MAXID);
m_pool.initPreparedStatement(C_PROJECTS_CREATE_KEY, C_PROJECTS_CREATE);
m_pool.initPreparedStatement(C_PROJECTS_READ_KEY, C_PROJECTS_READ);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYTASK_KEY, C_PROJECTS_READ_BYTASK);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYUSER_KEY, C_PROJECTS_READ_BYUSER);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYGROUP_KEY, C_PROJECTS_READ_BYGROUP);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYFLAG_KEY, C_PROJECTS_READ_BYFLAG);
m_pool.initPreparedStatement(C_PROJECTS_READ_BYMANAGER_KEY, C_PROJECTS_READ_BYMANAGER);
m_pool.initPreparedStatement(C_PROJECTS_DELETE_KEY, C_PROJECTS_DELETE);
m_pool.initPreparedStatement(C_PROJECTS_WRITE_KEY, C_PROJECTS_WRITE);
// init statements for systemproperties
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_MAXID_KEY, C_SYSTEMPROPERTIES_MAXID);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_READ_KEY,C_SYSTEMPROPERTIES_READ);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_WRITE_KEY,C_SYSTEMPROPERTIES_WRITE);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_UPDATE_KEY,C_SYSTEMPROPERTIES_UPDATE);
m_pool.initPreparedStatement(C_SYSTEMPROPERTIES_DELETE_KEY,C_SYSTEMPROPERTIES_DELETE);
// init statements for propertydef
m_pool.initPreparedStatement(C_PROPERTYDEF_MAXID_KEY,C_PROPERTYDEF_MAXID);
m_pool.initPreparedStatement(C_PROPERTYDEF_READ_KEY,C_PROPERTYDEF_READ);
m_pool.initPreparedStatement(C_PROPERTYDEF_READALL_A_KEY,C_PROPERTYDEF_READALL_A);
m_pool.initPreparedStatement(C_PROPERTYDEF_READALL_B_KEY,C_PROPERTYDEF_READALL_B);
m_pool.initPreparedStatement(C_PROPERTYDEF_CREATE_KEY,C_PROPERTYDEF_CREATE);
m_pool.initPreparedStatement(C_PROPERTYDEF_DELETE_KEY,C_PROPERTYDEF_DELETE);
m_pool.initPreparedStatement(C_PROPERTYDEF_UPDATE_KEY,C_PROPERTYDEF_UPDATE);
// init statements for properties
m_pool.initPreparedStatement(C_PROPERTIES_MAXID_KEY,C_PROPERTIES_MAXID);
m_pool.initPreparedStatement(C_PROPERTIES_READALL_COUNT_KEY,C_PROPERTIES_READALL_COUNT);
m_pool.initPreparedStatement(C_PROPERTIES_READ_KEY,C_PROPERTIES_READ);
m_pool.initPreparedStatement(C_PROPERTIES_UPDATE_KEY,C_PROPERTIES_UPDATE);
m_pool.initPreparedStatement(C_PROPERTIES_CREATE_KEY,C_PROPERTIES_CREATE);
m_pool.initPreparedStatement(C_PROPERTIES_READALL_KEY,C_PROPERTIES_READALL);
m_pool.initPreparedStatement(C_PROPERTIES_DELETEALL_KEY,C_PROPERTIES_DELETEALL);
m_pool.initPreparedStatement(C_PROPERTIES_DELETE_KEY,C_PROPERTIES_DELETE);
}
/**
* Private method to init all default-resources
*/
private void fillDefaults()
throws CmsException {
// the resourceType "folder" is needed always - so adding it
Hashtable resourceTypes = new Hashtable(1);
resourceTypes.put(C_TYPE_FOLDER_NAME, new CmsResourceType(C_TYPE_FOLDER, 0,
C_TYPE_FOLDER_NAME, ""));
// sets the last used index of resource types.
resourceTypes.put(C_TYPE_LAST_INDEX, new Integer(C_TYPE_FOLDER));
// add the resource-types to the database
addSystemProperty( C_SYSTEMPROPERTY_RESOURCE_TYPE, resourceTypes );
// set the mimetypes
addSystemProperty(C_SYSTEMPROPERTY_MIMETYPES,initMimetypes());
// set the groups
CmsGroup guests = createGroup(C_GROUP_GUEST, "the guest-group", C_FLAG_ENABLED, null);
CmsGroup administrators = createGroup(C_GROUP_ADMIN, "the admin-group", C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER, null);
CmsGroup projectleader = createGroup(C_GROUP_PROJECTLEADER, "the projectmanager-group",C_FLAG_ENABLED|C_FLAG_GROUP_PROJECTMANAGER|C_FLAG_GROUP_PROJECTCOWORKER|C_FLAG_GROUP_ROLE,null);
createGroup(C_GROUP_USERS, "the users-group to access the workplace", C_FLAG_ENABLED|C_FLAG_GROUP_ROLE|C_FLAG_GROUP_PROJECTCOWORKER, C_GROUP_GUEST);
// add the users
CmsUser guest = addUser(C_USER_GUEST, "", "the guest-user", "", "", "", 0, 0, C_FLAG_ENABLED, new Hashtable(), guests, "", "", C_USER_TYPE_SYSTEMUSER);
CmsUser admin = addUser(C_USER_ADMIN, "admin", "the admin-user", "", "", "", 0, 0, C_FLAG_ENABLED, new Hashtable(), administrators, "", "", C_USER_TYPE_SYSTEMUSER);
addUserToGroup(guest.getId(), guests.getId());
addUserToGroup(admin.getId(), administrators.getId());
// TODO: use real task here-when available!
CmsTask task = new CmsTask();
CmsProject online = createProject(admin, guests, projectleader, task, C_PROJECT_ONLINE, "the online-project", C_FLAG_ENABLED, C_PROJECT_TYPE_NORMAL);
// create the root-folder
createFolder(admin, online, C_UNKNOWN_ID, C_UNKNOWN_ID, C_ROOT, 0);
}
/**
* Private method to init the max-id values.
*
* @exception throws CmsException if something goes wrong.
*/
private void initMaxIdValues()
throws CmsException {
m_maxIds = new int[C_MAX_TABLES];
m_maxIds[C_TABLE_GROUPS] = initMaxId(C_GROUPS_MAXID_KEY);
m_maxIds[C_TABLE_PROJECTS] = initMaxId(C_PROJECTS_MAXID_KEY);
m_maxIds[C_TABLE_USERS] = initMaxId(C_USERS_MAXID_KEY);
m_maxIds[C_TABLE_SYSTEMPROPERTIES] = initMaxId(C_SYSTEMPROPERTIES_MAXID_KEY);
m_maxIds[C_TABLE_PROPERTYDEF] = initMaxId(C_PROPERTYDEF_MAXID_KEY);
m_maxIds[C_TABLE_PROPERTIES] = initMaxId(C_PROPERTIES_MAXID_KEY);
m_maxIds[C_TABLE_RESOURCES] = initMaxId(C_RESOURCES_MAXID_KEY);
m_maxIds[C_TABLE_FILES] = initMaxId(C_FILES_MAXID_KEY);
}
/**
* Private method to init the max-id of the projects-table.
*
* @param key the key for the prepared statement to use.
* @return the max-id
* @exception throws CmsException if something goes wrong.
*/
private int initMaxId(Integer key)
throws CmsException {
int id;
PreparedStatement statement = null;
try {
statement = m_pool.getPreparedStatement(key);
ResultSet res = statement.executeQuery();
if (res.next()){
id = res.getInt(1);
}else {
// no values in Database
id = 0;
}
res.close();
} catch (SQLException e){
throw new CmsException("["+this.getClass().getName()+"] "+e.getMessage(),CmsException.C_SQL_ERROR, e);
} finally {
if( statement != null) {
m_pool.putPreparedStatement(key, statement);
}
}
return id;
}
/**
* Private method to get the next id for a table.
* This method is synchronized, to generate unique id's.
*
* @param key A key for the table to get the max-id from.
* @return next-id The next possible id for this table.
*/
private synchronized int nextId(int key) {
// increment the id-value and return it.
return( ++m_maxIds[key] );
}
/**
* Private method to encrypt the passwords.
*
* @param value The value to encrypt.
* @return The encrypted value.
*/
private String digest(String value) {
// is there a valid digest?
if( m_digest != null ) {
return new String(m_digest.digest(value.getBytes()));
} else {
// no digest - use clear passwords
return value;
}
}
/**
* Inits all mimetypes.
* The mimetype-data should be stored in the database. But now this data
* is putted directly here.
*
* @return Returns a hashtable with all mimetypes.
*/
private Hashtable initMimetypes() {
Hashtable mt=new Hashtable();
mt.put( "ez", "application/andrew-inset" );
mt.put( "hqx", "application/mac-binhex40" );
mt.put( "cpt", "application/mac-compactpro" );
mt.put( "doc", "application/msword" );
mt.put( "bin", "application/octet-stream" );
mt.put( "dms", "application/octet-stream" );
mt.put( "lha", "application/octet-stream" );
mt.put( "lzh", "application/octet-stream" );
mt.put( "exe", "application/octet-stream" );
mt.put( "class", "application/octet-stream" );
mt.put( "oda", "application/oda" );
mt.put( "pdf", "application/pdf" );
mt.put( "ai", "application/postscript" );
mt.put( "eps", "application/postscript" );
mt.put( "ps", "application/postscript" );
mt.put( "rtf", "application/rtf" );
mt.put( "smi", "application/smil" );
mt.put( "smil", "application/smil" );
mt.put( "mif", "application/vnd.mif" );
mt.put( "xls", "application/vnd.ms-excel" );
mt.put( "ppt", "application/vnd.ms-powerpoint" );
mt.put( "bcpio", "application/x-bcpio" );
mt.put( "vcd", "application/x-cdlink" );
mt.put( "pgn", "application/x-chess-pgn" );
mt.put( "cpio", "application/x-cpio" );
mt.put( "csh", "application/x-csh" );
mt.put( "dcr", "application/x-director" );
mt.put( "dir", "application/x-director" );
mt.put( "dxr", "application/x-director" );
mt.put( "dvi", "application/x-dvi" );
mt.put( "spl", "application/x-futuresplash" );
mt.put( "gtar", "application/x-gtar" );
mt.put( "hdf", "application/x-hdf" );
mt.put( "js", "application/x-javascript" );
mt.put( "skp", "application/x-koan" );
mt.put( "skd", "application/x-koan" );
mt.put( "skt", "application/x-koan" );
mt.put( "skm", "application/x-koan" );
mt.put( "latex", "application/x-latex" );
mt.put( "nc", "application/x-netcdf" );
mt.put( "cdf", "application/x-netcdf" );
mt.put( "sh", "application/x-sh" );
mt.put( "shar", "application/x-shar" );
mt.put( "swf", "application/x-shockwave-flash" );
mt.put( "sit", "application/x-stuffit" );
mt.put( "sv4cpio", "application/x-sv4cpio" );
mt.put( "sv4crc", "application/x-sv4crc" );
mt.put( "tar", "application/x-tar" );
mt.put( "tcl", "application/x-tcl" );
mt.put( "tex", "application/x-tex" );
mt.put( "texinfo", "application/x-texinfo" );
mt.put( "texi", "application/x-texinfo" );
mt.put( "t", "application/x-troff" );
mt.put( "tr", "application/x-troff" );
mt.put( "roff", "application/x-troff" );
mt.put( "man", "application/x-troff-man" );
mt.put( "me", "application/x-troff-me" );
mt.put( "ms", "application/x-troff-ms" );
mt.put( "ustar", "application/x-ustar" );
mt.put( "src", "application/x-wais-source" );
mt.put( "zip", "application/zip" );
mt.put( "au", "audio/basic" );
mt.put( "snd", "audio/basic" );
mt.put( "mid", "audio/midi" );
mt.put( "midi", "audio/midi" );
mt.put( "kar", "audio/midi" );
mt.put( "mpga", "audio/mpeg" );
mt.put( "mp2", "audio/mpeg" );
mt.put( "mp3", "audio/mpeg" );
mt.put( "aif", "audio/x-aiff" );
mt.put( "aiff", "audio/x-aiff" );
mt.put( "aifc", "audio/x-aiff" );
mt.put( "ram", "audio/x-pn-realaudio" );
mt.put( "rm", "audio/x-pn-realaudio" );
mt.put( "rpm", "audio/x-pn-realaudio-plugin" );
mt.put( "ra", "audio/x-realaudio" );
mt.put( "wav", "audio/x-wav" );
mt.put( "pdb", "chemical/x-pdb" );
mt.put( "xyz", "chemical/x-pdb" );
mt.put( "bmp", "image/bmp" );
mt.put( "wbmp", "image/vnd.wap.wbmp" );
mt.put( "gif", "image/gif" );
mt.put( "ief", "image/ief" );
mt.put( "jpeg", "image/jpeg" );
mt.put( "jpg", "image/jpeg" );
mt.put( "jpe", "image/jpeg" );
mt.put( "png", "image/png" );
mt.put( "tiff", "image/tiff" );
mt.put( "tif", "image/tiff" );
mt.put( "ras", "image/x-cmu-raster" );
mt.put( "pnm", "image/x-portable-anymap" );
mt.put( "pbm", "image/x-portable-bitmap" );
mt.put( "pgm", "image/x-portable-graymap" );
mt.put( "ppm", "image/x-portable-pixmap" );
mt.put( "rgb", "image/x-rgb" );
mt.put( "xbm", "image/x-xbitmap" );
mt.put( "xpm", "image/x-xpixmap" );
mt.put( "xwd", "image/x-xwindowdump" );
mt.put( "igs", "model/iges" );
mt.put( "iges", "model/iges" );
mt.put( "msh", "model/mesh" );
mt.put( "mesh", "model/mesh" );
mt.put( "silo", "model/mesh" );
mt.put( "wrl", "model/vrml" );
mt.put( "vrml", "model/vrml" );
mt.put( "css", "text/css" );
mt.put( "html", "text/html" );
mt.put( "htm", "text/html" );
mt.put( "asc", "text/plain" );
mt.put( "txt", "text/plain" );
mt.put( "rtx", "text/richtext" );
mt.put( "rtf", "text/rtf" );
mt.put( "sgml", "text/sgml" );
mt.put( "sgm", "text/sgml" );
mt.put( "tsv", "text/tab-separated-values" );
mt.put( "etx", "text/x-setext" );
mt.put( "xml", "text/xml" );
mt.put( "wml", "text/vnd.wap.wml" );
mt.put( "mpeg", "video/mpeg" );
mt.put( "mpg", "video/mpeg" );
mt.put( "mpe", "video/mpeg" );
mt.put( "qt", "video/quicktime" );
mt.put( "mov", "video/quicktime" );
mt.put( "avi", "video/x-msvideo" );
mt.put( "movie", "video/x-sgi-movie" );
mt.put( "ice", "x-conference/x-cooltalk" );
return mt;
}
/**
* Destroys this access-module
* @exception throws CmsException if something goes wrong.
*/
public void destroy()
throws CmsException {
Vector statements;
Hashtable allStatements = m_pool.getAllPreparedStatement();
Enumeration keys = allStatements.keys();
Vector connections = m_pool.getAllConnections();
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] closing all statements.");
}
// close all statements
while(keys.hasMoreElements()) {
Object key = keys.nextElement();
statements = (Vector) allStatements.get(key);
for(int i = 0; i < statements.size(); i++) {
try {
((PreparedStatement) statements.elementAt(i)).close();
} catch(SQLException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] error closing statement: " + exc.getMessage());
}
}
}
}
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] closing all connections.");
}
// close all connections
for(int i = 0; i < connections.size(); i++) {
try {
((Connection) connections.elementAt(i)).close();
} catch(SQLException exc) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] error closing connection: " + exc.getMessage());
}
}
}
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] destroy complete.");
}
// stop the connection-guard
if(A_OpenCms.isLogging()) {
A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsDbAccess] stop connection guard");
}
m_guard.destroy();
}
}
|
package com.patr.radix.ui.unlock;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.xutils.common.util.LogUtil;
import com.felipecsl.gifimageview.library.GifImageView;
import com.patr.radix.LockValidateActivity;
import com.patr.radix.MyApplication;
import com.patr.radix.R;
import com.patr.radix.adapter.CommunityListAdapter;
import com.patr.radix.bean.GetCommunityListResult;
import com.patr.radix.bean.GetLockListResult;
import com.patr.radix.bean.GetWeatherResult;
import com.patr.radix.bean.MDevice;
import com.patr.radix.bean.RadixLock;
import com.patr.radix.ble.BluetoothLeService;
import com.patr.radix.bll.CacheManager;
import com.patr.radix.bll.GetCommunityListParser;
import com.patr.radix.bll.GetLockListParser;
import com.patr.radix.bll.ServiceManager;
import com.patr.radix.network.RequestListener;
import com.patr.radix.ui.WeatherActivity;
import com.patr.radix.ui.view.ListSelectDialog;
import com.patr.radix.ui.view.LoadingDialog;
import com.patr.radix.ui.view.TitleBarView;
import com.patr.radix.utils.Constants;
import com.patr.radix.utils.GattAttributes;
import com.patr.radix.utils.NetUtils;
import com.patr.radix.utils.PrefUtil;
import com.patr.radix.utils.ToastUtil;
import com.patr.radix.utils.Utils;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.FileAccessor;
import com.yuntongxun.ecdemo.core.ClientUser;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecsdk.ECInitParams.LoginAuthType;
import com.yuntongxun.ecsdk.ECInitParams.LoginMode;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class UnlockFragment extends Fragment implements OnClickListener,
OnItemClickListener, SensorEventListener {
private Context context;
private TextView areaTv;
private ImageView weatherIv;
private TextView weatherTv;
private TextView tempTv;
private ImageButton detailBtn;
private ImageButton shakeBtn;
private TextView keyTv;
private Button sendKeyBtn;
private LinearLayout keysLl;
private CommunityListAdapter adapter;
private LoadingDialog loadingDialog;
SensorManager sensorManager = null;
Vibrator vibrator = null;
private Handler handler;
private static BluetoothAdapter mBluetoothAdapter;
private final List<MDevice> list = new ArrayList<MDevice>();
private BluetoothLeScanner bleScanner;
private boolean mScanning = false;
private BluetoothGattCharacteristic notifyCharacteristic;
private BluetoothGattCharacteristic writeCharacteristic;
private boolean notifyEnable = false;
private boolean handShake = false;
private String currentDevAddress;
private String currentDevName;
private boolean isUnlocking = false;
private boolean isDisconnectForUnlock = false;
private boolean isScanningForUnlock = false;
private int retryCount = 0;
private static final int REQUEST_FINE_LOCATION = 0;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_unlock, container, false);
areaTv = (TextView) view.findViewById(R.id.area_tv);
weatherIv = (ImageView) view.findViewById(R.id.weather_iv);
weatherTv = (TextView) view.findViewById(R.id.weather_tv);
tempTv = (TextView) view.findViewById(R.id.temp_tv);
detailBtn = (ImageButton) view.findViewById(R.id.weather_detail_btn);
shakeBtn = (ImageButton) view.findViewById(R.id.shake_btn);
keyTv = (TextView) view.findViewById(R.id.key_tv);
sendKeyBtn = (Button) view.findViewById(R.id.send_key_btn);
keysLl = (LinearLayout) view.findViewById(R.id.key_ll);
detailBtn.setOnClickListener(this);
shakeBtn.setOnClickListener(this);
sendKeyBtn.setOnClickListener(this);
loadingDialog = new LoadingDialog(context);
init();
loadData();
return view;
}
private void init() {
sensorManager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
vibrator = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
adapter = new CommunityListAdapter(context,
MyApplication.instance.getCommunities());
checkBleSupportAndInitialize();
handler = new Handler();
context.registerReceiver(mGattUpdateReceiver,
Utils.makeGattUpdateIntentFilter());
Intent gattServiceIntent = new Intent(context.getApplicationContext(),
BluetoothLeService.class);
context.startService(gattServiceIntent);
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
// if (!mScanning) {
// startScan();
// }, 2000);
}
/**
* BroadcastReceiver for receiving the GATT communication status
*/
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
// Status received when connected to GATT Server
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
System.out.println("
// statusTv.setText("");
LogUtil.d("");
BluetoothLeService.discoverServices();
}
// Services Discovered from GATT Server
else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
.equals(action)) {
System.out.println("
// statusTv.setText();
LogUtil.d("…");
prepareGattServices(BluetoothLeService
.getSupportedGattServices());
doUnlock();
} else if (action
.equals(BluetoothLeService.ACTION_GATT_DISCONNECTED)) {
System.out.println("
// connect break ()
// statusTv.setText("");
LogUtil.d("");
if (isDisconnectForUnlock) {
// BluetoothLeService.close();
isUnlocking = false;
loadingDialog.dismiss();
}
}
// There are four basic operations for moving data in BLE: read,
// write, notify,
// and indicate. The BLE protocol specification requires that the
// maximum data
// payload size for these operations is 20 bytes, or in the case of
// read operations,
// 22 bytes. BLE is built for low power consumption, for infrequent
// short-burst data transmissions.
// Sending lots of data is possible, but usually ends up being less
// efficient than classic Bluetooth
// when trying to achieve maximum throughput.
// googleandroidnotify
Bundle extras = intent.getExtras();
if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
// Data Received
if (extras.containsKey(Constants.EXTRA_BYTE_VALUE)) {
byte[] array = intent
.getByteArrayExtra(Constants.EXTRA_BYTE_VALUE);
LogUtil.d("" + Utils.ByteArraytoHex(array));
if (extras.containsKey(Constants.EXTRA_BYTE_UUID_VALUE)) {
// int size = encryptArray.length;
// byte[] array = new byte[size];
// for (int i = 0; i < size; i++) {
// array[i] = (byte) (encryptArray[i] ^
// Constants.ENCRYPT);
handle(array);
}
}
if (extras.containsKey(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE)) {
if (extras
.containsKey(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE_CHARACTERISTIC_UUID)) {
byte[] array = intent
.getByteArrayExtra(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE);
// updateButtonStatus(array);
}
}
}
if (action
.equals(BluetoothLeService.ACTION_GATT_DESCRIPTORWRITE_RESULT)) {
if (extras.containsKey(Constants.EXTRA_DESCRIPTOR_WRITE_RESULT)) {
int status = extras
.getInt(Constants.EXTRA_DESCRIPTOR_WRITE_RESULT);
if (status != BluetoothGatt.GATT_SUCCESS) {
Toast.makeText(context, R.string.option_fail,
Toast.LENGTH_LONG).show();
}
}
}
if (action
.equals(BluetoothLeService.ACTION_GATT_CHARACTERISTIC_ERROR)) {
if (extras
.containsKey(Constants.EXTRA_CHARACTERISTIC_ERROR_MESSAGE)) {
String errorMessage = extras
.getString(Constants.EXTRA_CHARACTERISTIC_ERROR_MESSAGE);
System.out
.println("GattDetailActivity
+ errorMessage);
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG)
.show();
}
}
// write characteristics succcess
if (action
.equals(BluetoothLeService.ACTION_GATT_CHARACTERISTIC_WRITE_SUCCESS)) {
LogUtil.d("");
// handler.post(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(5000);
// if (isUnlocking) {
// ToastUtil.showShort(context, "");
// disconnectDevice();
// } catch (Exception e) {
// e.printStackTrace();
}
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
// final int state =
// intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
// BluetoothDevice.ERROR);
// if (state == BluetoothDevice.BOND_BONDING) {}
// else if (state == BluetoothDevice.BOND_BONDED) {}
// else if (state == BluetoothDevice.BOND_NONE) {}
}
}
};
/**
* Getting the GATT Services
*
* @param gattServices
*/
private void prepareGattServices(List<BluetoothGattService> gattServices) {
prepareData(gattServices);
}
/**
* Prepare GATTServices data.
*
* @param gattServices
*/
private void prepareData(List<BluetoothGattService> gattServices) {
if (gattServices == null)
return;
for (BluetoothGattService gattService : gattServices) {
String uuid = gattService.getUuid().toString();
if (uuid.equals(GattAttributes.GENERIC_ACCESS_SERVICE)
|| uuid.equals(GattAttributes.GENERIC_ATTRIBUTE_SERVICE))
continue;
if (uuid.equals(GattAttributes.USR_SERVICE)) {
initCharacteristics(gattService.getCharacteristics());
notifyOption();
break;
}
}
}
private void handle(byte[] array) {
int size = array.length;
if (size < 6 || array[0] != (byte) 0xAA) {
// invalid msg
// if (isUnlocking) {
// retryCount++;
// if (retryCount <= 3) {
// doUnlock();
// } else {
// ToastUtil.showShort(context, "");
// disconnectDevice();
return;
}
byte cmd = array[2];
int len;
switch (cmd) {
case Constants.UNLOCK:
len = array[3];
if (size < 6 + len || array[len + 5] != (byte) 0xDD) {
// invalid msg
if (isUnlocking) {
retryCount++;
if (retryCount <= 3) {
// ToastUtil.showShort(context, "" + retryCount
doUnlock();
} else {
ToastUtil.showShort(context, "");
disconnectDevice();
}
}
} else {
byte check = array[1];
check = (byte) (check ^ cmd ^ array[3]);
for (int i = 0; i < len; i++) {
check ^= array[i + 4];
}
if (check == array[len + 4]) {
// check pass
if (array[4] == 0x00) {
ToastUtil.showShort(context, "");
disconnectDevice();
} else {
if (isUnlocking) {
retryCount++;
if (retryCount <= 3) {
// ToastUtil.showShort(context, ""
doUnlock();
} else {
ToastUtil.showShort(context, "");
disconnectDevice();
}
}
}
} else {
// check fail
if (isUnlocking) {
retryCount++;
if (retryCount <= 3) {
// ToastUtil.showShort(context, "" +
// retryCount
doUnlock();
} else {
ToastUtil.showShort(context, "");
disconnectDevice();
}
}
}
}
break;
default:
// INVALID REQUEST/RESPONSE.
break;
// case Constants.HAND_SHAKE:
// if (size < 5 || array[4] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// if ((cmd ^ array[2]) == array[3]) {
// if (array[2] == (byte) 0x00) {
// handShake = true;
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// } else {
// // checkFailed();
// break;
// case Constants.READ_CARD:
// if (size < 12 || array[11] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// for (int i = 2; i < 10; i++) {
// if (array[i] != (byte) 0x00) {
// // checkFailed();
// writeOption("90 ", "FF 00 00 00 00 00 00 00 00 ");
// return;
// byte check = cmd;
// for (int i = 2; i < 10; i++) {
// check ^= array[i];
// if (check == array[10]) {
// if (handShake) {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("90 ", "00 00 00 00 00 " +
// MyApplication.instance.getCardNum());
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("90 ", "FF 00 00 00 00 00 00 00 00 ");
// } else {
// // checkFailed();
// writeOption("90 ", "FF 00 00 00 00 00 00 00 00 ");
// break;
// case Constants.WRITE_CARD:
// if (size < 12 || array[11] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// for (int i = 2; i < 6; i++) {
// if (array[i] != (byte) 0x00) {
// // checkFailed();
// writeOption("91 ", "FF 00 00 00 00 00 00 00 00 ");
// return;
// byte check = cmd;
// for (int i = 2; i < 10; i++) {
// check ^= array[i];
// if (check == array[10]) {
// if (handShake) {
// byte[] cn = new byte[4];
// for (int i = 0; i < 4; i++) {
// cn[i] = array[i + 6];
// MyApplication.instance.setCardNum(Utils.ByteArraytoHex(cn));
// MyApplication.instance.setCsn(MyApplication.instance.getCardNum());
// // messageEt.append("" + cardNum + "\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("91 ", "00 ");
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("91 ", "FF ");
// } else {
// // checkFailed();
// writeOption("91 ", "FF ");
// break;
// case Constants.DISCONNECT:
// if (size < 12 || array[11] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// for (int i = 2; i < 10; i++) {
// if (array[i] != (byte) 0x00) {
// // checkFailed();
// writeOption("A0 ", "FF ");
// return;
// byte check = cmd;
// for (int i = 2; i < 10; i++) {
// check ^= array[i];
// if (check == array[10]) {
// if (handShake) {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("A0 ", "00 ");
// handShake = false;
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("A0 ", "FF ");
// } else {
// // checkFailed();
// writeOption("A0 ", "FF ");
// break;
// default:
// // messageEt.append("INVALID REQUEST/RESPONSE.");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// break;
}
}
private void doUnlock() {
writeOption("30 ", "06 00 00 "
+ MyApplication.instance.getUserInfo().getCardNo());
// handler.post(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(5000);
// if (isUnlocking) {
// ToastUtil.showShort(context, "");
// disconnectDevice();
// } catch (Exception e) {
// e.printStackTrace();
}
private void writeOption(String cmd, String data) {
writeOption(Utils.getCmdData("00 ", cmd, data));
}
private void writeOption(String hexStr) {
writeCharacteristic(writeCharacteristic,
Utils.getCmdDataByteArray(hexStr));
}
private void writeCharacteristic(
BluetoothGattCharacteristic characteristic, byte[] bytes) {
// Writing the hexValue to the characteristics
try {
LogUtil.d("write bytes: " + Utils.ByteArraytoHex(bytes));
BluetoothLeService.writeCharacteristicGattDb(characteristic, bytes);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void initCharacteristics(
List<BluetoothGattCharacteristic> characteristics) {
for (BluetoothGattCharacteristic c : characteristics) {
if (Utils.getPorperties(context, c).equals("Notify")) {
notifyCharacteristic = c;
continue;
}
if (Utils.getPorperties(context, c).equals("Write")) {
writeCharacteristic = c;
continue;
}
}
}
private void notifyOption() {
if (notifyEnable) {
notifyEnable = false;
stopBroadcastDataNotify(notifyCharacteristic);
// messageEt.append("STOP NOTIFY\n");
// messageEt.setSelection(messageEt.getText().length(),
// messageEt.getText().length());
} else {
notifyEnable = true;
prepareBroadcastDataNotify(notifyCharacteristic);
// messageEt.append("NOTIFY\n");
// messageEt.setSelection(messageEt.getText().length(),
// messageEt.getText().length());
}
}
/**
* Preparing Broadcast receiver to broadcast notify characteristics
*
* @param characteristic
*/
void prepareBroadcastDataNotify(BluetoothGattCharacteristic characteristic) {
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
BluetoothLeService.setCharacteristicNotification(characteristic,
true);
}
}
/**
* Stopping Broadcast receiver to broadcast notify characteristics
*
* @param characteristic
*/
void stopBroadcastDataNotify(BluetoothGattCharacteristic characteristic) {
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
BluetoothLeService.setCharacteristicNotification(characteristic,
false);
}
}
private void connectDevice(BluetoothDevice device) {
currentDevAddress = device.getAddress();
currentDevName = device.getName();
LogUtil.d("connectDevice: DevName = " + currentDevName
+ "; DevAddress = " + currentDevAddress);
if (BluetoothLeService.getConnectionState() != BluetoothLeService.STATE_DISCONNECTED) {
isDisconnectForUnlock = false;
BluetoothLeService.disconnect();
}
BluetoothLeService.connect(currentDevAddress, currentDevName, context);
}
private void disconnectDevice() {
notifyOption();
if (isUnlocking) {
isDisconnectForUnlock = true;
} else {
isDisconnectForUnlock = false;
}
BluetoothLeService.disconnect();
}
private void loadData() {
if (MyApplication.instance.getSelectedCommunity() == null) {
getCommunityList();
return;
}
if (MyApplication.instance.getSelectedLock() == null) {
getLockList();
} else {
refreshKey();
}
if (!TextUtils.isEmpty(MyApplication.instance.getUserInfo()
.getAccount())) {
String appKey = FileAccessor.getAppKey();
String token = FileAccessor.getAppToken();
String myMobile = MyApplication.instance.getUserInfo().getMobile();
String pass = "";
ClientUser clientUser = new ClientUser(myMobile);
clientUser.setAppKey(appKey);
clientUser.setAppToken(token);
clientUser.setLoginAuthType(LoginAuthType.NORMAL_AUTH);
clientUser.setPassword(pass);
CCPAppManager.setClientUser(clientUser);
SDKCoreHelper.init(context, LoginMode.FORCE_LOGIN);
}
}
private void getWeather() {
ServiceManager.getWeather(new RequestListener<GetWeatherResult>() {
@Override
public void onStart() {
loadingDialog.show("…");
}
@Override
public void onSuccess(int stateCode, GetWeatherResult result) {
if (result.getErrorCode().equals("0")) {
refreshWeather(result);
} else {
ToastUtil.showShort(context, result.getReason());
}
loadingDialog.dismiss();
}
@Override
public void onFailure(Exception error, String content) {
ToastUtil.showShort(context, "");
loadingDialog.dismiss();
}
});
}
private void refreshWeather(GetWeatherResult result) {
Field f;
try {
f = (Field) R.drawable.class.getDeclaredField("ww"
+ result.getImg());
int id = f.getInt(R.drawable.class);
weatherIv.setImageResource(id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
weatherTv.setText(result.getWeather());
tempTv.setText(result.getTemp() + "℃");
areaTv.setText(result.getCity());
}
private void getCommunityList() {
switch (NetUtils.getConnectedType(context)) {
case NONE:
getCommunityListFromCache();
break;
case WIFI:
case OTHER:
getCommunityListFromServer();
break;
default:
break;
}
}
private void getCommunityListFromCache() {
CacheManager.getCacheContent(context,
CacheManager.getCommunityListUrl(),
new RequestListener<GetCommunityListResult>() {
@Override
public void onSuccess(int stateCode,
GetCommunityListResult result) {
if (result != null) {
MyApplication.instance.setCommunities(result
.getCommunities());
adapter.notifyDataSetChanged();
ListSelectDialog.show(context, "", adapter,
UnlockFragment.this);
}
}
}, new GetCommunityListParser());
}
private void getCommunityListFromServer() {
ServiceManager
.getCommunityList(new RequestListener<GetCommunityListResult>() {
@Override
public void onSuccess(int stateCode,
GetCommunityListResult result) {
if (result != null) {
if (result.isSuccesses()) {
MyApplication.instance.setCommunities(result
.getCommunities());
saveCommunityListToDb(result.getResponse());
adapter.notifyDataSetChanged();
ListSelectDialog.show(context, "",
adapter, UnlockFragment.this);
} else {
ToastUtil.showShort(context,
result.getRetinfo());
getCommunityListFromCache();
}
} else {
getCommunityListFromCache();
}
}
@Override
public void onFailure(Exception error, String content) {
getCommunityListFromCache();
}
});
}
/**
*
*
* @param content
*/
protected void saveCommunityListToDb(String content) {
CacheManager.saveCacheContent(context,
CacheManager.getCommunityListUrl(), content,
new RequestListener<Boolean>() {
@Override
public void onSuccess(Boolean result) {
LogUtil.i("save " + CacheManager.getCommunityListUrl()
+ "=" + result);
}
});
}
private void getLockList() {
if (MyApplication.instance.getLocks().size() == 0) {
switch (NetUtils.getConnectedType(context)) {
case NONE:
getLockListFromCache();
break;
case WIFI:
case OTHER:
getLockListFromServer();
break;
default:
break;
}
} else {
MyApplication.instance.setSelectedLock(MyApplication.instance
.getLocks().get(0));
}
}
private void getLockListFromCache() {
if (MyApplication.instance.getSelectedCommunity() != null) {
CacheManager.getCacheContent(context,
CacheManager.getLockListUrl(),
new RequestListener<GetLockListResult>() {
@Override
public void onSuccess(int stateCode,
GetLockListResult result) {
if (result != null) {
MyApplication.instance.setLocks(result
.getLocks());
setSelectedKey();
refreshKey();
}
}
}, new GetLockListParser());
}
}
private void getLockListFromServer() {
ServiceManager.getLockList(new RequestListener<GetLockListResult>() {
@Override
public void onSuccess(int stateCode, GetLockListResult result) {
if (result != null) {
if (result.isSuccesses()) {
MyApplication.instance.setLocks(result.getLocks());
saveLockListToDb(result.getResponse());
setSelectedKey();
refreshKey();
} else {
ToastUtil.showShort(context, result.getRetinfo());
getLockListFromCache();
}
} else {
getLockListFromCache();
}
}
@Override
public void onFailure(Exception error, String content) {
getLockListFromCache();
}
});
}
/**
*
*
* @param content
*/
protected void saveLockListToDb(String content) {
CacheManager.saveCacheContent(context, CacheManager.getLockListUrl(),
content, new RequestListener<Boolean>() {
@Override
public void onSuccess(Boolean result) {
LogUtil.i("save " + CacheManager.getLockListUrl() + "="
+ result);
}
});
}
private void refreshKey() {
RadixLock selectedKey = MyApplication.instance.getSelectedLock();
keyTv.setText(selectedKey.getName());
keysLl.removeAllViews();
final List<RadixLock> keys = MyApplication.instance.getLocks();
int size = keys.size();
for (int i = 0; i < size; i++) {
KeyView keyView;
if (keys.get(i).equals(selectedKey)) {
keyView = new KeyView(context, keys.get(i), i, true);
} else {
keyView = new KeyView(context, keys.get(i), i, false);
}
keyView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int idx = (int) v.getTag();
if (!keys.get(idx).equals(
MyApplication.instance.getSelectedLock())) {
MyApplication.instance.setSelectedLock(keys.get(idx));
refreshKey();
}
}
});
keysLl.addView(keyView);
}
}
private void setSelectedKey() {
String selectedKey = PrefUtil.getString(context,
Constants.PREF_SELECTED_KEY);
for (RadixLock lock : MyApplication.instance.getLocks()) {
if (selectedKey.equals(lock.getId())) {
MyApplication.instance.setSelectedLock(lock);
return;
}
}
if (MyApplication.instance.getLocks().size() > 0) {
MyApplication.instance.setSelectedLock(MyApplication.instance
.getLocks().get(0));
}
}
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
}
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
getWeather();
}
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
context.unregisterReceiver(mGattUpdateReceiver);
if (loadingDialog.isShowing()) {
loadingDialog.dismiss();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.weather_detail_btn:
context.startActivity(new Intent(context, WeatherActivity.class));
break;
case R.id.send_key_btn:
context.startActivity(new Intent(context, MyKeysActivity.class));
break;
case R.id.shake_btn:
preUnlock();
break;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MyApplication.instance.setSelectedCommunity(adapter.getItem(position));
if (!adapter.isSelect(position)) {
MyApplication.instance.setSelectedLock(null);
getLockList();
}
adapter.select(position);
}
@Override
public void onSensorChanged(SensorEvent event) {
int sensorType = event.sensor.getType();
// values[0]:Xvalues[1]Yvalues[2]Z
float[] values = event.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER) {
if ((Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math
.abs(values[2]) > 17)) {
LogUtil.d("============ values[0] = " + values[0]);
LogUtil.d("============ values[1] = " + values[1]);
LogUtil.d("============ values[2] = " + values[2]);
vibrator.vibrate(500);
preUnlock();
}
}
}
private void preUnlock() {
RadixLock lock = MyApplication.instance.getSelectedLock();
LogUtil.d("preUnlock: lock = " + lock.getBleName1());
if (lock != null) {
String lockPaternStr = PrefUtil.getString(context,
Constants.PREF_LOCK_KEY, null);
if (!TextUtils.isEmpty(lockPaternStr)) {
LockValidateActivity.startForResult(this, Constants.LOCK_CHECK);
} else {
unlock();
}
} else {
ToastUtil.showShort(context, "");
}
}
private void unlock() {
RadixLock lock = MyApplication.instance.getSelectedLock();
String bleName = lock.getBleName1();
if (TextUtils.isEmpty(bleName)) {
bleName = lock.getBleName2();
}
LogUtil.d("unlock: lock = " + bleName);
if (mBluetoothAdapter == null) {
getBluetoothAdapter();
}
if (!mBluetoothAdapter.isEnabled()) {
ToastUtil.showLong(context, "");
return;
}
if (!isUnlocking) {
handler.post(new Runnable() {
@Override
public void run() {
loadingDialog.show("…");
}
});
isUnlocking = true;
retryCount = 0;
startScan();
}
// for (MDevice device : list) {
// LogUtil.d("device list: " + device.getDevice().getName());
// if (device.getDevice().getName() != null &&
// device.getDevice().getName().equalsIgnoreCase(bleName)) {
// if (!isUnlocking) {
// isUnlocking = true;
// retryCount = 0;
// connectDevice(device.getDevice());
// break;
}
private void checkBleSupportAndInitialize() {
// Use this check to determine whether BLE is supported on the device.
if (!context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show();
return;
}
// Initializes a Blue tooth adapter.
getBluetoothAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Blue tooth
Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
}
private void getBluetoothAdapter() {
final BluetoothManager bluetoothManager = (BluetoothManager) context
.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
/**
* Call back for BLE Scan This call back is called when a BLE device is
* found near by.
*/
private LeScanCallback mLeScanCallback = new LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
byte[] scanRecord) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
MDevice mDev = new MDevice(device, rssi);
if (list.contains(mDev))
return;
String name = mDev.getDevice().getName();
if (name == null) {
return;
}
RadixLock lock = MyApplication.instance.getSelectedLock();
if (name.equalsIgnoreCase(lock.getBleName1())
|| name.equalsIgnoreCase(lock.getBleName2())) {
list.add(mDev);
if (mBluetoothAdapter != null) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
connectDevice(mDev.getDevice());
}
LogUtil.d("" + mDev.getDevice().getName());
}
});
}
};
private void startScan() {
list.clear();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
scanPrevious21Version();
} else {
scanAfter21Version();
}
}
private void scanPrevious21Version() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mBluetoothAdapter != null) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
LogUtil.d("" + list.size());
if (list.size() <= 0) {
ToastUtil.showShort(context, "");
loadingDialog.dismiss();
}
mScanning = false;
}
}, 2800);
if (mBluetoothAdapter == null) {
getBluetoothAdapter();
}
if (mBluetoothAdapter != null) {
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void scanAfter21Version() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (bleScanner != null) {
bleScanner.stopScan(new ScanCallback() {
@Override
public void onScanResult(int callbackType,
ScanResult result) {
super.onScanResult(callbackType, result);
}
});
}
LogUtil.d("" + list.size());
if (list.size() <= 0) {
ToastUtil.showShort(context, "");
loadingDialog.dismiss();
}
mScanning = false;
}
}, 2800);
if (bleScanner == null) {
if (mBluetoothAdapter == null) {
getBluetoothAdapter();
}
bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
if (bleScanner != null) {
mScanning = true;
bleScanner.startScan(new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
MDevice mDev = new MDevice(result.getDevice(), result
.getRssi());
if (list.contains(mDev))
return;
String name = mDev.getDevice().getName();
if (name == null) {
return;
}
RadixLock lock = MyApplication.instance.getSelectedLock();
if (name.equalsIgnoreCase(lock.getBleName1())
|| name.equalsIgnoreCase(lock.getBleName2())) {
list.add(mDev);
if (bleScanner != null) {
bleScanner.stopScan(new ScanCallback() {
@Override
public void onScanResult(int callbackType,
ScanResult result) {
super.onScanResult(callbackType, result);
}
});
}
connectDevice(mDev.getDevice());
}
LogUtil.d("" + mDev.getDevice().getName());
}
});
}
}
// @TargetApi(Build.VERSION_CODES.M)
// private void mayRequestLocation() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// ToastUtil.showLong(context, "Android 6.0");
// REQUEST_FINE_LOCATION);
// return;
// } else {
// } else {
// @Override
// switch (requestCode) {
// case REQUEST_FINE_LOCATION:
// // If request is cancelled, the result arrays are empty.
// if (grantResults.length > 0
// if (mScanning == false) {
// startScan();
// } else {
// break;
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constants.LOCK_CHECK) {
if (resultCode == Constants.LOCK_CHECK_OK) {
unlock();
} else {
ToastUtil.showShort(context, "");
}
}
}
}
|
package com.opera.core.systems.util;
/**
* A replacement for a subset of com.sun.xml.ws.util.VersionUtil.
*
* @author Jan Vidar Krey
*/
public class VersionUtil {
/**
* Compares the versions given in string format
*
* @param a version2
* @param b version1
* @return -1, 0 or 1 based upon the comparison results -1 if version1 is
* less than version2 0 if version1 is equal to version2 1 if
* version1 is greater than version2
*/
public static int compare(String a, String b)
{
int minlen = (a.length() < b.length()) ? a.length() : b.length();
for (int i = 0; i < minlen; i++)
{
if (a.charAt(i) < b.charAt(i))
return -1;
else if (a.charAt(i) > b.charAt(i))
return 1;
}
// Check for more specific versions, assume the more specific
// version to be higher.
// So, "2.0.1" is higher than "2.0", and "2.0.0" is higher than "2.0".
if (b.length() > a.length())
return 1;
if (b.length() < a.length())
return -1;
return 0;
}
}
|
package com.prinjsystems.grengine.virtual;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.util.List;
import javax.media.j3d.Appearance;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Material;
import javax.swing.JOptionPane;
import javax.vecmath.Color3f;
import javax.vecmath.TexCoord2f;
import com.prinjsystems.grengine.Universe;
import com.prinjsystems.grengine.utils.GrengineException;
import com.sun.j3d.loaders.IncorrectFormatException;
import com.sun.j3d.loaders.ParsingErrorException;
import com.sun.j3d.utils.geometry.Sphere;
public class Thing {
private BranchGroup bg;
/**
* The new value of rotation or translation will be added to the current value.
*/
public static final int TRANSFORM_ROTATE_ADDICTIVE = 1;
/**
* The new value of rotation or translation will take place of the current value.
*/
public static final int TRANSFORM_ROTATE_DEFINITIVE = 2;
/**
* The new value of rotation or translation will be subtracted from the current value.
*/
public static final int TRANSFORM_ROTATE_SUBTRACTIVE = 3;
private int trMode;
private double tX, tY, tZ;
private double rX, rY, rZ;
private SimpleModel model;
private Universe u;
/**
* Simple constructor
*/
public Thing(Universe u) {
trMode = TRANSFORM_ROTATE_DEFINITIVE;
bg = new BranchGroup();
this.u = u;
}
/**
* Complete constructor
*/
public Thing(String modelLocation, String[] names, Universe u) {
trMode = TRANSFORM_ROTATE_DEFINITIVE;
bg = new BranchGroup();
try {
Color ambientColour = new Color(1.0f, 1.0f, 1.0f);
Color diffuseColour = new Color(1.0f, 1.0f, 1.0f);
Color specularColour = new Color(1.0f, 1.0f, 1.0f);
Color emissiveColour = new Color(0.0f, 0.0f, 0.0f);
float sh = 100.0f;
model = new SimpleModel(modelLocation, names, ambientColour, emissiveColour, diffuseColour,
specularColour, sh);
bg.addChild(model.getTransformGroup());
} catch (IncorrectFormatException | ParsingErrorException | FileNotFoundException
| MalformedURLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
System.exit(-1);
}
this.u = u;
}
/**
* Creates a standard 50% size ColorCube.
*/
public void createTestSphere() {
Appearance app = new Appearance();
Color3f ambientColour = new Color3f(1.0f, 0.0f, 0.0f);
Color3f diffuseColour = new Color3f(1.0f, 0.0f, 0.0f);
Color3f specularColour = new Color3f(1.0f, 1.0f, 1.0f);
Color3f emissiveColour = new Color3f(0.0f, 0.0f, 0.0f);
float s = 20.0f;
app.setMaterial(new Material(ambientColour, emissiveColour, diffuseColour, specularColour, s));
Sphere sphere = new Sphere(0.3f, Sphere.GENERATE_NORMALS, 120, app);
bg.addChild(sphere);
}
/**
* Changes rotation of the model contained here.
* @param x new X axis rotation.
* @param y new Y axis rotation.
* @param z new Z axis rotation.
*/
public void rotate(double x, double y, double z) {
if(trMode == TRANSFORM_ROTATE_DEFINITIVE) {
model.rotate(Math.toRadians(x), Math.toRadians(y), Math.toRadians(z));
} else if(trMode == TRANSFORM_ROTATE_ADDICTIVE) {
rX += x;
rY += y;
rZ += z;
model.rotate(Math.toRadians(rX), Math.toRadians(rY), Math.toRadians(rZ));
} else if(trMode == TRANSFORM_ROTATE_SUBTRACTIVE) {
rX -= x;
rY -= y;
rZ -= z;
model.rotate(Math.toRadians(rX), Math.toRadians(rY), Math.toRadians(rZ));
}
}
/**
* Changes position of the model contained here.
* @param x new X axis position.
* @param y new Y axis position.
* @param z new Z axis position.
*/
public void translate(double x, double y, double z) {
if(trMode == TRANSFORM_ROTATE_DEFINITIVE) {
model.translate(x * u.getDeltaTime(), y * u.getDeltaTime(), z * u.getDeltaTime());
} else if(trMode == TRANSFORM_ROTATE_ADDICTIVE) {
tX += x;
tY += y;
tZ += z;
model.translate(tX * u.getDeltaTime(), tY * u.getDeltaTime(), tZ * u.getDeltaTime());
} else if(trMode == TRANSFORM_ROTATE_SUBTRACTIVE) {
tX -= x;
tY -= y;
tZ -= z;
model.translate(tX * u.getDeltaTime(), tY * u.getDeltaTime(), tZ * u.getDeltaTime());
}
}
/**
* Changes the natural size of the model.
* @param factor Change the size of the model. Lower than zero and the model will reduce, greater than
* zero and it will enlarge.
*/
public void scale(double factor) {
model.scale(factor);
}
/**
* Changes the TransferRotation Mode, which defines if the new value of translation/rotation will
* replace the last, or will be added to then.
* @param mode Is the mode to take place of the last. Can be {@link TRANSFORM_ROTATE_ADDICTIVE},
* {@link TRANSFORM_ROTATE_DEFINITIVE} or {@link TRANSFORM_ROTATE_SUBTRACTIVE}.
*/
public void setTransformRotateMode(int mode) {
trMode = mode;
System.out.println("Changed TransformRotate Mode to " + mode);
}
public void setTexture(Universe u, String path, int id) {
model.setTexture(u, path, id);
}
public void setTextures(Universe u, String[] paths) throws GrengineException {
model.setTextures(u, paths);
}
public void setAllTextures(Universe u, String path) {
model.setAllTextures(u, path);
}
public void setTextureCoordinates(List<TexCoord2f> coordinates) {
model.setTextureCoordinates(coordinates);
}
public void setReflectionMaterial(int index, Color ambientColor, Color emissiveColor,
Color diffuseColor, Color specularColor, float shiness) {
model.setReflectionMaterial(index, ambientColor, emissiveColor, diffuseColor, specularColor, shiness);
}
public void setAllReflectionMaterials(Color ambientColor, Color emissiveColor,
Color diffuseColor, Color specularColor, float shiness) {
model.setAllReflectionMaterials(ambientColor, emissiveColor, diffuseColor, specularColor, shiness);
}
public Color getReflectionAmbientColor(int index) {
return model.getReflectionAmbientColor(index);
}
public Color getReflectionEmissiveColor(int index) {
return model.getReflectionEmissiveColor(index);
}
public Color getReflectionDiffuseColor(int index) {
return model.getReflectionDiffuseColor(index);
}
public Color getReflectionSpecularColor(int index) {
return model.getReflectionSpecularColor(index);
}
public void addFormMaterial(Color ambientColor, Color emissiveColor, Color diffuseColor,
Color specularColor, float shiness) {
model.addFormMaterial(ambientColor, emissiveColor, diffuseColor, specularColor, shiness);
}
public void mixMaterials(int materialIndex, int formMaterialIndex) {
model.mixMaterials(materialIndex, formMaterialIndex);
}
/**
* Mix all current reflection materials with the specified form material.
* @param formMaterialIndex Index of the form material to be integrated to all reflection materials.
*/
public void mixAllMaterials(int formMaterialIndex) {
model.mixAllMaterials(formMaterialIndex);
}
/**
* Compile the model in the {@link BranchGroup} and return it.
* @return The compiled {@link BranchGroup}.
*/
public BranchGroup getModel() {
// if(model != null) {
// tg.addChild(model);
// bg.addChild(tg);
bg.compile();
return bg;
}
public SimpleModel getPrimitiveModel() {
return model;
}
}
|
package com.vaadin.terminal.gwt.client.ui;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.UIObject;
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.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
public class VTree extends FlowPanel implements Paintable, VHasDropHandler {
public static final String CLASSNAME = "v-tree";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
private Set<String> selectedIds = new HashSet<String>();
private ApplicationConnection client;
private String paintableId;
private boolean selectable;
private boolean isMultiselect;
private String currentMouseOverKey;
private final HashMap<String, TreeNode> keyToNode = new HashMap<String, TreeNode>();
private final HashMap<String, String> actionMap = new HashMap<String, String>();
private boolean immediate;
private boolean isNullSelectionAllowed = true;
private boolean disabled = false;
private boolean readonly;
private boolean rendering;
private VAbstractDropHandler dropHandler;
private int dragMode;
public VTree() {
super();
setStyleName(CLASSNAME);
}
private void updateActionMap(UIDL c) {
final Iterator it = c.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation and let container manage caption
if (client.updateComponent(this, uidl, true)) {
return;
}
rendering = true;
this.client = client;
if (uidl.hasAttribute("partialUpdate")) {
handleUpdate(uidl);
rendering = false;
return;
}
paintableId = uidl.getId();
immediate = uidl.hasAttribute("immediate");
disabled = uidl.getBooleanAttribute("disabled");
readonly = uidl.getBooleanAttribute("readonly");
dragMode = uidl.hasAttribute("dragMode") ? uidl
.getIntAttribute("dragMode") : 0;
isNullSelectionAllowed = uidl.getBooleanAttribute("nullselect");
clear();
for (final Iterator i = uidl.getChildIterator(); i.hasNext();) {
final UIDL childUidl = (UIDL) i.next();
if ("actions".equals(childUidl.getTag())) {
updateActionMap(childUidl);
continue;
} else if ("-ac".equals(childUidl.getTag())) {
updateDropHandler(childUidl);
continue;
}
final TreeNode childTree = new TreeNode();
if (childTree.ie6compatnode != null) {
this.add(childTree);
}
childTree.updateFromUIDL(childUidl, client);
if (childTree.ie6compatnode == null) {
this.add(childTree);
}
}
final String selectMode = uidl.getStringAttribute("selectmode");
selectable = !"none".equals(selectMode);
isMultiselect = "multi".equals(selectMode);
selectedIds = uidl.getStringArrayVariableAsSet("selected");
rendering = false;
}
private void updateTreeRelatedDragData(VDragEvent drag) {
currentMouseOverKey = findCurrentMouseOverKey(drag.getElementOver());
if (currentMouseOverKey != null) {
VerticalDropLocation detail = getDropDetail(drag
.getCurrentGwtEvent());
Boolean overTreeNode = null;
TreeNode treeNode = keyToNode.get(currentMouseOverKey);
if (treeNode != null && !treeNode.isLeaf()
&& detail == VerticalDropLocation.MIDDLE) {
overTreeNode = true;
}
drag.getDropDetails().put("itemIdOver", currentMouseOverKey);
drag.getDropDetails().put("itemIdOverIsNode", overTreeNode);
drag.getDropDetails().put("detail", detail);
}
}
private String findCurrentMouseOverKey(Element elementOver) {
TreeNode treeNode = Util.findWidget(elementOver, TreeNode.class);
return treeNode == null ? null : treeNode.key;
}
private void updateDropHandler(UIDL childUidl) {
if (dropHandler == null) {
dropHandler = new VAbstractDropHandler() {
@Override
public void dragEnter(VDragEvent drag) {
}
@Override
protected void dragAccepted(final VDragEvent drag) {
}
@Override
public void dragOver(final VDragEvent currentDrag) {
final Object oldIdOver = currentDrag.getDropDetails().get(
"itemIdOver");
final VerticalDropLocation oldDetail = (VerticalDropLocation) currentDrag
.getDropDetails().get("detail");
updateTreeRelatedDragData(currentDrag);
final VerticalDropLocation detail = getDropDetail(currentDrag
.getCurrentGwtEvent());
boolean nodeHasChanged = (currentMouseOverKey != null && currentMouseOverKey != oldIdOver)
|| (currentMouseOverKey == null && oldIdOver != null);
boolean detailHasChanded = (detail != null && detail != oldDetail)
|| (detail == null && oldDetail != null);
if (nodeHasChanged || detailHasChanded) {
ApplicationConnection.getConsole().log(
"Change in Transferable " + currentMouseOverKey
+ " " + detail);
final String newKey = currentMouseOverKey;
TreeNode treeNode = keyToNode.get(oldIdOver);
if (treeNode != null) {
// clear old styles
treeNode.emphasis(null);
}
validate(new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newKey != null) {
keyToNode.get(newKey).emphasis(detail);
}
}
}, currentDrag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
cleanUp();
}
private void cleanUp() {
if (currentMouseOverKey != null) {
keyToNode.get(currentMouseOverKey).emphasis(null);
currentMouseOverKey = null;
}
}
@Override
public boolean drop(VDragEvent drag) {
cleanUp();
return super.drop(drag);
}
@Override
public Paintable getPaintable() {
return VTree.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
};
}
dropHandler.updateAcceptRules(childUidl);
}
public VerticalDropLocation getDropDetail(NativeEvent event) {
TreeNode treeNode = keyToNode.get(currentMouseOverKey);
if (treeNode == null) {
return null;
}
VerticalDropLocation verticalDropLocation = DDUtil
.getVerticalDropLocation(treeNode.nodeCaptionDiv, event
.getClientY(), 0.2);
return verticalDropLocation;
}
private void handleUpdate(UIDL uidl) {
final TreeNode rootNode = keyToNode.get(uidl
.getStringAttribute("rootKey"));
if (rootNode != null) {
if (!rootNode.getState()) {
// expanding node happened server side
rootNode.setState(true, false);
}
rootNode.renderChildNodes(uidl.getChildIterator());
}
}
public void setSelected(TreeNode treeNode, boolean selected) {
if (selected) {
if (!isMultiselect) {
while (selectedIds.size() > 0) {
final String id = selectedIds.iterator().next();
final TreeNode oldSelection = keyToNode.get(id);
if (oldSelection != null) {
// can be null if the node is not visible (parent
// collapsed)
oldSelection.setSelected(false);
}
selectedIds.remove(id);
}
}
treeNode.setSelected(true);
selectedIds.add(treeNode.key);
} else {
if (!isNullSelectionAllowed) {
if (!isMultiselect || selectedIds.size() == 1) {
return;
}
}
selectedIds.remove(treeNode.key);
treeNode.setSelected(false);
}
client.updateVariable(paintableId, "selected", selectedIds
.toArray(new String[selectedIds.size()]), immediate);
}
public boolean isSelected(TreeNode treeNode) {
return selectedIds.contains(treeNode.key);
}
public class TreeNode extends SimplePanel implements ActionOwner {
public static final String CLASSNAME = "v-tree-node";
public String key;
private String[] actionKeys = null;
private boolean childrenLoaded;
private Element nodeCaptionDiv;
protected Element nodeCaptionSpan;
private FlowPanel childNodeContainer;
private boolean open;
private Icon icon;
private Element ie6compatnode;
private Event mouseDownEvent;
public TreeNode() {
constructDom();
sinkEvents(Event.ONCLICK | Event.ONDBLCLICK | Event.MOUSEEVENTS
| Event.ONCONTEXTMENU);
}
protected void emphasis(VerticalDropLocation detail) {
String base = "v-tree-node-drag-";
UIObject.setStyleName(getElement(), base + "top",
VerticalDropLocation.TOP == detail);
UIObject.setStyleName(getElement(), base + "bottom",
VerticalDropLocation.BOTTOM == detail);
UIObject.setStyleName(getElement(), base + "center",
VerticalDropLocation.MIDDLE == detail);
base = "v-tree-node-caption-drag-";
UIObject.setStyleName(nodeCaptionDiv, base + "top",
VerticalDropLocation.TOP == detail);
UIObject.setStyleName(nodeCaptionDiv, base + "bottom",
VerticalDropLocation.BOTTOM == detail);
UIObject.setStyleName(nodeCaptionDiv, base + "center",
VerticalDropLocation.MIDDLE == detail);
// also add classname to "folder node" into which the drag is
// targeted
TreeNode folder = null;
/* Possible parent of this TreeNode will be stored here */
TreeNode parentFolder = getParentNode();
// TODO fix my bugs
if (isLeaf()) {
folder = parentFolder;
// note, parent folder may be null if this is root node => no
// folder target exists
} else {
if (detail == VerticalDropLocation.TOP) {
folder = parentFolder;
} else {
folder = this;
}
// ensure we remove the dragfolder classname from the previous
// folder node
setDragFolderStyleName(this, false);
setDragFolderStyleName(parentFolder, false);
}
if (folder != null) {
setDragFolderStyleName(folder, detail != null);
}
}
private TreeNode getParentNode() {
Widget parent2 = getParent().getParent();
if (parent2 instanceof TreeNode) {
return (TreeNode) parent2;
}
return null;
}
private void setDragFolderStyleName(TreeNode folder, boolean add) {
if (folder != null) {
UIObject.setStyleName(folder.getElement(),
"v-tree-node-dragfolder", add);
UIObject.setStyleName(folder.nodeCaptionDiv,
"v-tree-node-caption-dragfolder", add);
}
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (disabled) {
return;
}
final int type = DOM.eventGetType(event);
final Element target = DOM.eventGetTarget(event);
if (client.hasEventListeners(VTree.this, ITEM_CLICK_EVENT_ID)
&& target == nodeCaptionSpan
&& (type == Event.ONDBLCLICK || type == Event.ONMOUSEUP)) {
fireClick(event);
}
if (type == Event.ONCLICK) {
if (getElement() == target || ie6compatnode == target) {
// state change
toggleState();
} else if (!readonly && target == nodeCaptionSpan) {
// caption click = selection change && possible click event
toggleSelection();
}
DOM.eventCancelBubble(event, true);
} else if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
}
if (dragMode != 0 || dropHandler != null) {
if (type == Event.ONMOUSEDOWN) {
if (nodeCaptionDiv.isOrHasChild(event.getTarget())) {
if (dragMode > 0
&& event.getButton() == NativeEvent.BUTTON_LEFT) {
ApplicationConnection.getConsole().log(
"TreeNode m down");
event.preventDefault(); // prevent text selection
mouseDownEvent = event;
}
}
} else if (type == Event.ONMOUSEMOVE
|| type == Event.ONMOUSEOUT) {
if (mouseDownEvent != null) {
ApplicationConnection.getConsole().log(
"TreeNode drag start " + event.getType());
// start actual drag on slight move when mouse is down
VTransferable t = new VTransferable();
t.setDragSource(VTree.this);
t.setData("itemId", key);
VDragEvent drag = VDragAndDropManager.get().startDrag(
t, mouseDownEvent, true);
drag.createDragImage(nodeCaptionDiv, true);
event.stopPropagation();
mouseDownEvent = null;
}
} else if (type == Event.ONMOUSEUP) {
mouseDownEvent = null;
}
if (type == Event.ONMOUSEOVER) {
mouseDownEvent = null;
currentMouseOverKey = key;
event.stopPropagation();
}
}
}
private void fireClick(Event evt) {
// non-immediate iff an immediate select event is going to happen
boolean imm = !immediate
|| !selectable
|| (!isNullSelectionAllowed && isSelected() && selectedIds
.size() == 1);
MouseEventDetails details = new MouseEventDetails(evt);
client.updateVariable(paintableId, "clickedKey", key, false);
client.updateVariable(paintableId, "clickEvent",
details.toString(), imm);
}
private void toggleSelection() {
if (selectable) {
VTree.this.setSelected(this, !isSelected());
}
}
private void toggleState() {
setState(!getState(), true);
}
protected void constructDom() {
// workaround for a very weird IE6 issue #1245
if (BrowserInfo.get().isIE6()) {
ie6compatnode = DOM.createDiv();
setStyleName(ie6compatnode, CLASSNAME + "-ie6compatnode");
DOM.setInnerText(ie6compatnode, " ");
DOM.appendChild(getElement(), ie6compatnode);
DOM.sinkEvents(ie6compatnode, Event.ONCLICK);
}
nodeCaptionDiv = DOM.createDiv();
DOM.setElementProperty(nodeCaptionDiv, "className", CLASSNAME
+ "-caption");
Element wrapper = DOM.createDiv();
nodeCaptionSpan = DOM.createSpan();
DOM.appendChild(getElement(), nodeCaptionDiv);
DOM.appendChild(nodeCaptionDiv, wrapper);
DOM.appendChild(wrapper, nodeCaptionSpan);
childNodeContainer = new FlowPanel();
childNodeContainer.setStylePrimaryName(CLASSNAME + "-children");
setWidget(childNodeContainer);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
setText(uidl.getStringAttribute("caption"));
key = uidl.getStringAttribute("key");
keyToNode.put(key, this);
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
if (uidl.getTag().equals("node")) {
if (uidl.getChildCount() == 0) {
childNodeContainer.setVisible(false);
} else {
renderChildNodes(uidl.getChildIterator());
childrenLoaded = true;
}
} else {
addStyleName(CLASSNAME + "-leaf");
}
addStyleName(CLASSNAME);
if (uidl.hasAttribute("style")) {
addStyleName(CLASSNAME + "-" + uidl.getStringAttribute("style"));
Widget.setStyleName(nodeCaptionDiv, CLASSNAME + "-caption-"
+ uidl.getStringAttribute("style"), true);
childNodeContainer.addStyleName(CLASSNAME + "-children-"
+ uidl.getStringAttribute("style"));
}
if (uidl.getBooleanAttribute("expanded") && !getState()) {
setState(true, false);
}
if (uidl.getBooleanAttribute("selected")) {
setSelected(true);
// ensure that identifier is in selectedIds array (this may be a
// partial update)
selectedIds.add(key);
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.insertBefore(DOM.getFirstChild(nodeCaptionDiv), icon
.getElement(), nodeCaptionSpan);
}
icon.setUri(uidl.getStringAttribute("icon"));
} else {
if (icon != null) {
DOM.removeChild(DOM.getFirstChild(nodeCaptionDiv), icon
.getElement());
icon = null;
}
}
if (BrowserInfo.get().isIE6() && isAttached()) {
fixWidth();
}
}
public boolean isLeaf() {
return getStyleName().contains("leaf");
}
private void setState(boolean state, boolean notifyServer) {
if (open == state) {
return;
}
if (state) {
if (!childrenLoaded && notifyServer) {
client.updateVariable(paintableId, "requestChildTree",
true, false);
}
if (notifyServer) {
client.updateVariable(paintableId, "expand",
new String[] { key }, true);
}
addStyleName(CLASSNAME + "-expanded");
childNodeContainer.setVisible(true);
} else {
removeStyleName(CLASSNAME + "-expanded");
childNodeContainer.setVisible(false);
if (notifyServer) {
client.updateVariable(paintableId, "collapse",
new String[] { key }, true);
}
}
open = state;
if (!rendering) {
Util.notifyParentOfSizeChange(VTree.this, false);
}
}
private boolean getState() {
return open;
}
private void setText(String text) {
DOM.setInnerText(nodeCaptionSpan, text);
}
private void renderChildNodes(Iterator i) {
childNodeContainer.clear();
childNodeContainer.setVisible(true);
while (i.hasNext()) {
final UIDL childUidl = (UIDL) i.next();
// actions are in bit weird place, don't mix them with children,
// but current node's actions
if ("actions".equals(childUidl.getTag())) {
updateActionMap(childUidl);
continue;
}
final TreeNode childTree = new TreeNode();
if (ie6compatnode != null) {
childNodeContainer.add(childTree);
}
childTree.updateFromUIDL(childUidl, client);
if (ie6compatnode == null) {
childNodeContainer.add(childTree);
}
}
childrenLoaded = true;
}
public boolean isChildrenLoaded() {
return childrenLoaded;
}
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this, String.valueOf(key),
actionKey);
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Adds/removes Vaadin specific style name. This method ought to be
* called only from VTree.
*
* @param selected
*/
protected void setSelected(boolean selected) {
// add style name to caption dom structure only, not to subtree
setStyleName(nodeCaptionDiv, "v-tree-node-selected", selected);
}
protected boolean isSelected() {
return VTree.this.isSelected(this);
}
public void showContextMenu(Event event) {
if (!readonly && !disabled) {
if (actionKeys != null) {
int left = event.getClientX();
int top = event.getClientY();
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.cancelBubble(true);
event.preventDefault();
}
}
/*
* We need to fix the width of TreeNodes so that the float in
* ie6compatNode does not wrap (see ticket #1245)
*/
private void fixWidth() {
nodeCaptionDiv.getStyle().setProperty("styleFloat", "left");
nodeCaptionDiv.getStyle().setProperty("display", "inline");
nodeCaptionDiv.getStyle().setProperty("marginLeft", "0");
final int captionWidth = ie6compatnode.getOffsetWidth()
+ nodeCaptionDiv.getOffsetWidth();
setWidth(captionWidth + "px");
}
@Override
public void onAttach() {
super.onAttach();
if (ie6compatnode != null) {
fixWidth();
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
}
public VDropHandler getDropHandler() {
return dropHandler;
}
public TreeNode getNodeByKey(String key) {
return keyToNode.get(key);
}
}
|
package com.wywy.log4j.appender;
import org.apache.logging.log4j.core.*;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.pattern.NameAbbreviator;
import org.apache.logging.log4j.core.util.Booleans;
import org.apache.logging.log4j.status.StatusLogger;
import org.komamitsu.fluency.Fluency;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Plugin(name="Fluency", category="Core", elementType="appender", printObject=true)
public final class FluencyAppender extends AbstractAppender {
private static final StatusLogger LOG = StatusLogger.getLogger();
private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private final NameAbbreviator abbr = NameAbbreviator.getAbbreviator("1.");
private boolean usePre26Abbreviate = false;
private Method abbreviateMethod;
private Fluency fluency;
private Map<String, Object> parameters;
private Map<String, String> staticFields;
private FluencyAppender(final String name, final Map<String, Object> parameters, final Map<String, String> staticFields,
final Server[] servers, final FluencyConfig fluencyConfig, final Filter filter,
final Layout<? extends Serializable> layout, final boolean ignoreExceptions) {
super(name, filter, layout, ignoreExceptions);
this.parameters = parameters;
this.staticFields = staticFields;
try {
this.fluency = makeFluency(servers, fluencyConfig);
LOG.info("FluencyAppender initialized");
} catch (IOException e) {
LOG.error(e.getMessage());
}
try {
abbreviateMethod = NameAbbreviator.class.getMethod("abbreviate", new Class[] { String.class });
usePre26Abbreviate = true;
} catch (final NoSuchMethodException e) {
try {
abbreviateMethod = NameAbbreviator.class.getMethod("abbreviate", new Class[] { String.class, StringBuilder.class });
} catch (final NoSuchMethodException | SecurityException e1) {
LOG.error(e.getMessage(), e);
}
} catch (final SecurityException e) {
LOG.error(e.getMessage(), e);
}
}
@PluginFactory
public static FluencyAppender createAppender(@PluginAttribute("name") final String name,
@PluginAttribute("tag") final String tag,
@PluginAttribute("application") final String application,
@PluginAttribute("ignoreExceptions") final String ignore,
@PluginElement("StaticField") final StaticField[] staticFields,
@PluginElement("Server") final Server[] servers,
@PluginElement("FluencyConfig") final FluencyConfig fluencyConfig,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginElement("Filter") final Filter filter) {
final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true);
Map<String, Object> parameters = new HashMap<>();
Map<String, String> fields = new HashMap<>();
// the @Required annotation for Attributes just returns a non helpful exception, so i'll check it manually
// we need the tag for fluency itself (it's actually a part of the fluentd protocol
if (tag != null) {
parameters.put("tag", tag);
} else {
throw new IllegalArgumentException("tag is required");
}
// Deprecated
if (application != null) {
fields.put("application", application);
}
for (StaticField field: staticFields) {
if (field.getName().trim().equals("")) {
LOG.warn("Skipping empty field");
continue;
}
if (field.getValue().trim().equals("")) {
LOG.warn("Skipping field {} due to empty value", field.getName());
continue;
}
fields.put(field.getName(), field.getValue());
}
if (layout == null) {
layout = PatternLayout.createDefaultLayout();
}
return new FluencyAppender(name, parameters, fields, servers, fluencyConfig, filter,
layout, ignoreExceptions);
}
// These are the defaults, it no configuration is given:
// Single Fluentd(localhost:24224 by default)
// - TCP heartbeat (by default)
// - Asynchronous flush (by default)
// - Without ack response (by default)
// - Flush interval is 600ms (by default)
// - Initial chunk buffer size is 1MB (by default)
// - Threshold chunk buffer size to flush is 4MB (by default)
// - Max total buffer size is 16MB (by default)
// - Max retry of sending events is 8 (by default)
// - Max wait until all buffers are flushed is 60 seconds (by default)
// - Max wait until the flusher is terminated is 60 seconds (by default)
static Fluency makeFluency(Server[] servers, FluencyConfig config) throws IOException {
if (servers.length == 0 && config == null) {
return Fluency.defaultFluency();
}
if (servers.length == 0) {
return Fluency.defaultFluency(config.configure());
}
List<InetSocketAddress> addresses = new ArrayList<>(servers.length);
for (Server s : servers) {
addresses.add(s.configure());
}
if (config == null) {
return Fluency.defaultFluency(addresses);
}
return Fluency.defaultFluency(addresses, config.configure());
}
@Override
public void append(LogEvent logEvent) {
String level = logEvent.getLevel().name();
String loggerName = logEvent.getLoggerName();
String message = new String(this.getLayout().toByteArray(logEvent));
Date eventTime = new Date(logEvent.getTimeMillis());
Map<String, Object> m = new HashMap<>();
m.put("level", level);
StackTraceElement logSource = logEvent.getSource();
if (logSource == null || logSource.getFileName() == null) {
m.put("sourceFile", "<unknown>");
} else {
m.put("sourceFile", logSource.getFileName());
}
if (logSource == null || logSource.getClassName() == null) {
m.put("sourceClass", "<unknown>");
} else {
m.put("sourceClass", logEvent.getSource().getClassName());
}
if (logSource == null || logSource.getMethodName() == null) {
m.put("sourceMethod", "<unknown>");
} else {
m.put("sourceMethod", logEvent.getSource().getMethodName());
}
if (logSource == null || logSource.getLineNumber() == 0) {
m.put("sourceLine", 0);
} else {
m.put("sourceLine", logEvent.getSource().getLineNumber());
}
try {
if(usePre26Abbreviate) {
m.put("logger", abbreviatePre26(loggerName));
} else if(abbreviateMethod != null) {
m.put("logger", abbreviate(loggerName));
} else {
//just a safety net in case abbreviate() changes again in a future API
m.put("logger", loggerName);
}
} catch (final IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOG.error(e.getMessage());
}
m.put("loggerFull", loggerName);
m.put("message", message);
m.put("thread", logEvent.getThreadName());
m.putAll(this.staticFields);
// TODO: get rid of that, once the whole stack supports subsecond timestamps
// this is just a workaround due to the lack of support
m.put("@timestamp", format.format(eventTime));
if (this.fluency != null) {
try {
// the tag is required for further processing within fluentd,
// otherwise we would have no way to manipulate messages in transit
this.fluency.emit((String) parameters.get("tag"), logEvent.getTimeMillis(), m);
} catch (IOException e) {
LOG.error(e.getMessage());
}
}
}
private String abbreviatePre26(final String stringToAbbreviate) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
return (String) abbreviateMethod.invoke(abbr, stringToAbbreviate);
}
private String abbreviate(final String stringToAbbreviate) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
final StringBuilder logger = new StringBuilder();
abbreviateMethod.invoke(abbr, stringToAbbreviate, logger);
return logger.toString();
}
}
|
package com.opencms.template;
import java.util.*;
import java.io.*;
import com.opencms.launcher.*;
import com.opencms.file.*;
import com.opencms.util.*;
import com.opencms.defaults.*;
import com.opencms.core.*;
import com.opencms.template.cache.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.servlet.http.*;
public class CmsXmlTemplate extends A_CmsTemplate implements I_CmsXmlTemplate {
public static final String C_FRAME_SELECTOR = "cmsframe";
/** name of the special body element */
public final static String C_BODY_ELEMENT = "body";
/** Boolean for additional debug output control */
public final static boolean C_DEBUG = false;
/** Error string to be inserted for corrupt subtemplates for guest user requests. */
private final static String C_ERRORTEXT = "ERROR!";
/**
* Template cache for storing cacheable results of the subtemplates.
*/
protected static com.opencms.launcher.I_CmsTemplateCache m_cache = null;
/**
* For debugging purposes only.
* Counts the number of re-uses od the instance of this class.
*/
private int counter = 0;
/**
* For debugging purposes only.
* Increments the class variable <code>counter</code> and
* prints out its new value..
* <P>
* May be called from the template file using
* <code><METHOD name="counter"></code>.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return Actual value of <code>counter</code>.
*/
public Integer counter(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
counter++;
return new Integer(counter);
}
/**
* Help method to print nice classnames in error messages
* @return class name in [ClassName] format
*/
protected String getClassName() {
String name = getClass().getName();
return "[" + name.substring(name.lastIndexOf(".") + 1) + "] ";
}
/**
* Gets the content of a given template file and its subtemplates
* with the given parameters. The default section in the template file
* will be used.
* <P>
* Parameters are stored in a hashtable and can derive from
* <UL>
* <LI>Template file of the parent template</LI>
* <LI>Body file clicked by the user</LI>
* <LI>URL parameters</LI>
* </UL>
* Paramter names must be in "elementName.parameterName" format.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template
* @param parameters Hashtable with all template class parameters.
* @return Content of the template and all subtemplates.
* @exception CmsException
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters) throws CmsException {
return getContent(cms, templateFile, elementName, parameters, null);
}
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() && C_DEBUG ) {
A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] getting content of element " + ((elementName == null) ? "<root>" : elementName));
A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] template file is: " + templateFile);
A_OpenCms.log(C_OPENCMS_DEBUG, "[CmsXmlTemplate] selected template section is: " + ((templateSelector == null) ? "<default>" : templateSelector));
}
CmsXmlTemplateFile xmlTemplateDocument = getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector);
if(templateSelector == null || "".equals(templateSelector)) {
templateSelector = (String)parameters.get(C_FRAME_SELECTOR);
}
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector);
}
/**
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getFileUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
return cms.getRequestContext().getFileUri().getBytes();
}
/**
* Returns the absolute path of a resource merged with the absolute path of the file and
* the relative path in the tagcontent. This path is a intern OpenCms path (i.e. it starts
* with a "/" ).
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent The relative path of the resource incl. name of the resource.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object mergeAbsolutePath(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
return Utils.mergeAbsolutePath(doc.getAbsoluteFilename(), tagcontent).getBytes();
}
/**
* Returns the absolute path of a resource merged with the absolute path of the file and
* the relative path in the tagcontent. This method adds the servlet path at the beginning
* of the path.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent The relative path of the resource incl. name of the resource.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object mergeAbsoluteUrl(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String ocPath = new String((byte[])mergeAbsolutePath(cms,tagcontent, doc, userObject));
String servletPath = cms.getRequestContext().getRequest().getServletUrl();
return (servletPath + ocPath).getBytes();
}
/**
* Gets the QueryString for CmsFrameTemplates.
* <P>
* This method can be called using <code><METHOD name="getCmsQueryString"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getFrameQueryString(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String query = new String();
// get the parameternames of the original request and get the values from the userObject
try{
Enumeration parameters = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getParameterNames();
StringBuffer paramQuery = new StringBuffer();
while(parameters.hasMoreElements()){
String name = (String)parameters.nextElement();
String value = (String)((Hashtable)userObject).get(name);
if(value != null && !"".equals(value)){
paramQuery.append(name+"="+value+"&");
}
}
if(paramQuery.length() > 0){
// add the parameters to the query string
query = paramQuery.substring(0,paramQuery.length()-1).toString();
}
} catch (Exception exc){
exc.printStackTrace();
}
// get the name of the frame and parameters
String frame = "", param = "";
if(!tagcontent.equals("")) {
if(!tagcontent.startsWith("&")) {
if(tagcontent.indexOf(",") != -1) {
frame = tagcontent.substring(0, tagcontent.indexOf(","));
param = tagcontent.substring(tagcontent.indexOf(",") + 1);
}
else {
frame = tagcontent;
}
}
else {
param = tagcontent;
}
}
query = (query == null ? "" : query);
if(!query.equals("")) {
if(query.indexOf("cmsframe=") != -1) {
int start = query.indexOf("cmsframe=");
int end = query.indexOf("&", start);
String cmsframe = "";
if(end != -1) {
cmsframe = query.substring(start + 9, end);
}
else {
cmsframe = query.substring(start + 9);
}
if(!cmsframe.equals("plain")) {
if(!frame.equals("")) {
if(end != -1) {
query = query.substring(0, start + 9) + frame + query.substring(end);
}
else {
query = query.substring(0, start + 9) + frame;
}
}
else {
if(end != -1) {
query = query.substring(0, start) + query.substring(end + 1);
}
else {
query = query.substring(0, start);
}
}
}
}
else {
if(!tagcontent.equals("")) {
query = query + "&cmsframe=" + frame;
}
}
if(!query.equals("")) {
query = "?" + query;
}
}
else {
if(!frame.equals("")) {
query = "?cmsframe=" + frame;
}
}
if(!query.equals("")) {
query = query + param;
}
else {
query = "?" + param.substring(param.indexOf("&") + 1);
}
if (query.trim().equals("?") || query.trim().equals("&") || query.trim().equals("?&") ||
query.trim().equals("??")) {
query="";
}
return query;
}
/**
* Gets the target for a link.
* <P>
* This method can be called using <code><METHOD name="getCmsFrame"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getFrameTarget(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String target = "";
String cmsframe = (String)((Hashtable)userObject).get("cmsframe");
cmsframe = (cmsframe == null ? "" : cmsframe);
if(cmsframe.equals("plain")) {
target = "";
}else {
if(tagcontent.equals("")) {
target = "target=_top";
}else {
target = "target=" + tagcontent;
}
}
return target;
}
/**
* Gets the key that should be used to cache the results of
* <EM>this</EM> template class.
* <P>
* Since our results may depend on the used template file,
* the parameters and the requested body document, we must
* build a complex key using this three arguments.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return key that can be used for caching
*/
public Object getKey(CmsObject cms, String templateFile, Hashtable parameters, String templateSelector) {
//Vector v = new Vector();
CmsRequestContext reqContext = cms.getRequestContext();
//v.addElement(reqContext.currentProject().getName());
//v.addElement(reqContext.getUri());
//v.addElement(templateFile);
//v.addElement(parameters);
//v.addElement(templateSelector);
//return v;
String result = "" + reqContext.currentProject().getId() + ":" + reqContext.currentUser().getName() + reqContext.getUri() + templateFile;
Enumeration keys = parameters.keys();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
result = result + key + parameters.get(key);
}
result = result + templateSelector;
return result;
}
/**
* Reads in the template file and starts the XML parser for the expected
* content type.
* <P>
* Every extending class using not CmsXmlTemplateFile as content type,
* but any derived type should override this method.
*
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public CmsXmlTemplateFile getOwnTemplateFile(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException {
CmsXmlTemplateFile xmlTemplateDocument = new CmsXmlTemplateFile(cms, templateFile);
return xmlTemplateDocument;
}
/**
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getPathUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String path = cms.getRequestContext().getUri();
path = path.substring(0, path.lastIndexOf("/") + 1);
path = cms.getRequestContext().getRequest().getServletUrl() + path;
return path.getBytes();
}
/**
* Inserts the correct servlet path title into the template.
* <P>
* This method can be called using <code><METHOD name="getTitle"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getQueryString(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String query = "";
if(cms.getMode() == cms.C_MODUS_EXPORT){
Enumeration parameters = cms.getRequestContext().getRequest().getParameterNames();
if(parameters == null){
return query;
}
StringBuffer paramQuery = new StringBuffer();
while(parameters.hasMoreElements()){
String name = (String)parameters.nextElement();
String value = (String)((Hashtable)userObject).get(name);
if(value != null && !"".equals(value)){
paramQuery.append(name+"="+value+"&");
}
}
if(paramQuery.length() > 0){
query = paramQuery.substring(0,paramQuery.length()-1).toString();
}
}else{
query = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getQueryString();
}
if(query != null && !"".equals(query)) {
query = "?" + query;
}
return query;
}
/**
* Get the IP address of the current request.
* <P>
* This method can be called using <code><METHOD name="getRequestIp"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public String getRequestIp(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getRemoteAddr();
}
/**
* Inserts the correct servlet path title into the template.
* <P>
* This method can be called using <code><METHOD name="getTitle"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
* @deprecated instead of this method you should use the link tag.
*/
public Object getServletPath(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
return cms.getRequestContext().getRequest().getServletUrl() + "/";
}
/**
* Get the session id. If no session exists, a new one will be created.
* <P>
* This method can be called using <code><METHOD name="getSessionId"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public String getSessionId(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
return ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true).getId();
}
/**
* Inserts the correct stylesheet into the layout template.
* <P>
* This method can be called using <code><METHOD name="getStylesheet"></code>
* in the template file.
* <P>
* When using this method follwing parameters should be defined
* either in the page file or in the template file:
* <ul>
* <li><code>root.stylesheet-ie</code></li>
* <li><code>root.stylesheet-ns</code></li>
* </ul>
* These parameters should contain the correct OpenCms path
* for the Internet Explorer and Netscape Navigate
* specific stylesheets.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @throws CmsException In case no stylesheet was found (or there were errors accessing the CmsObject)
*/
public String getStylesheet(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String styleSheetUri = "";
try {
styleSheetUri = getStylesheet(cms, tagcontent, "frametemplate", doc, userObject);
} catch (CmsException e) {} // Happens if no frametemplate is defined, can be ignored
if ((styleSheetUri == null) || ("".equals(styleSheetUri))) {
styleSheetUri = getStylesheet(cms, tagcontent, null, doc, userObject);
} // The original behaviour is to throw an exception in case no stylesheed could be found
return styleSheetUri;
}
/**
* Internal method to do the actual lookup of the "stylesheet" tag
* on the subtemplate / element specified.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param templatename The subtemplate / element to look up the "stylesheet" tag
* in, if null the mastertemplate is used.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @throws CmsException In case no stylesheet was found (or there were errors accessing the CmsObject)
*/
private String getStylesheet(CmsObject cms, String tagcontent, String templatename, A_CmsXmlContent doc, Object userObject) throws CmsException {
CmsXmlTemplateFile tempTemplateFile = (CmsXmlTemplateFile)doc;
// If templatename==null look in the master template
CmsXmlTemplateFile templateFile = tempTemplateFile;
if (templatename != null) {
// Get the XML parsed content of the selected template file.
// This can be done by calling the getOwnTemplateFile() method of the
// mastertemplate class.
// The content is needed to determine the HTML style of the body element.
Object tempObj = CmsTemplateClassManager.getClassInstance(cms, tempTemplateFile.getSubtemplateClass(templatename));
CmsXmlTemplate frameTemplateClassObject = (CmsXmlTemplate)tempObj;
templateFile = frameTemplateClassObject.getOwnTemplateFile(cms, tempTemplateFile.getSubtemplateFilename(templatename), null, null, null);
}
// Get the styles from the parameter hashtable
String styleIE = null;
String styleNS = null;
if(templateFile.hasData("stylesheet-ie")) {
styleIE = templateFile.getDataValue("stylesheet-ie");
}
else {
if(templateFile.hasData("stylesheet")) {
styleIE = templateFile.getDataValue("stylesheet");
}
else {
styleIE = "";
}
}
if(templateFile.hasData("stylesheet-ns")) {
styleNS = templateFile.getDataValue("stylesheet-ns");
}
else {
if(templateFile.hasData("stylesheet")) {
styleNS = templateFile.getDataValue("stylesheet");
}
else {
styleNS = "";
}
}
HttpServletRequest orgReq = (HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest();
String servletPath = cms.getRequestContext().getRequest().getServletUrl();
if(!servletPath.endsWith("/")){
// Make sure servletPath always end's with a "/"
servletPath = cms.getRequestContext().getRequest().getServletUrl() + "/";
}
// Make sure we don't have a double "/" in the style sheet path
if (styleIE.startsWith("/")) styleIE = styleIE.substring(1);
if (styleNS.startsWith("/")) styleNS = styleNS.substring(1);
// Get the user's browser
String browser = orgReq.getHeader("user-agent");
if ((browser!= null) && (browser.indexOf("MSIE") > -1)) {
return ("".equals(styleIE))?"":servletPath + styleIE;
} else {
// return NS style as default value
return ("".equals(styleNS))?"":servletPath + styleNS;
}
}
/**
* Find the corresponding template class to be loaded.
* this should be defined in the template file of the parent
* template and can be overwritten in the body file.
*
* @param elementName Element name of this template in our parent template.
* @param doc CmsXmlTemplateFile object of our template file including a subtemplate.
* @param parameters Hashtable with all template class parameters.
* @return Name of the class that should generate the output for the included template file.
*/
protected String getTemplateClassName(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException {
String result = null;
if(parameters.containsKey(elementName + "._CLASS_")) {
result = (String)parameters.get(elementName + "._CLASS_");
}else {
if(doc.hasSubtemplateClass(elementName)) {
result = doc.getSubtemplateClass(elementName);
}else {
// Fallback to "body" element
if(parameters.containsKey("body._CLASS_")) {
result = (String)parameters.get("body._CLASS_");
}
}
}
if(result == null){
CmsElementDefinitionCollection elDefs = (CmsElementDefinitionCollection)parameters.get("_ELDEFS_");
if(elDefs != null){
CmsElementDefinition elDef = elDefs.get(elementName);
if(elDef != null){
result = elDef.getClassName();
}
}
}
return result;
}
/**
* Find the corresponding template file to be loaded by the template class.
* this should be defined in the template file of the parent
* template and can be overwritten in the body file.
*
* @param elementName Element name of this template in our parent template.
* @param doc CmsXmlTemplateFile object of our template file including a subtemplate.
* @param parameters Hashtable with all template class parameters.
* @return Name of the template file that should be included.
*/
protected String getTemplateFileName(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException {
String result = null;
if(parameters.containsKey(elementName + "._TEMPLATE_")) {
result = (String)parameters.get(elementName + "._TEMPLATE_");
}else {
if(doc.hasSubtemplateFilename(elementName)) {
result = doc.getSubtemplateFilename(elementName);
}else {
// Fallback to "body" element
if(parameters.containsKey("body._TEMPLATE_")) {
result = (String)parameters.get("body._TEMPLATE_");
}
}
}
if(result == null){
CmsElementDefinitionCollection elDefs = (CmsElementDefinitionCollection)parameters.get("_ELDEFS_");
if(elDefs != null){
CmsElementDefinition elDef = elDefs.get(elementName);
if(elDef != null){
result = elDef.getTemplateName();
}
}
}
return result;
}
/**
* Find the corresponding template selector to be activated.
* This may be defined in the template file of the parent
* template and can be overwritten in the body file.
*
* @param elementName Element name of this template in our parent template.
* @param doc CmsXmlTemplateFile object of our template file including a subtemplate.
* @param parameters Hashtable with all template class parameters.
* @return Name of the class that should generate the output for the included template file.
*/
protected String getTemplateSelector(String elementName, CmsXmlTemplateFile doc, Hashtable parameters) throws CmsException {
if(parameters.containsKey(elementName + "._TEMPLATESELECTOR_")) {
return (String)parameters.get(elementName + "._TEMPLATESELECTOR_");
}
else {
if(doc.hasSubtemplateSelector(elementName)) {
return doc.getSubtemplateSelector(elementName);
}
else {
CmsElementDefinitionCollection elDefs = (CmsElementDefinitionCollection)parameters.get("_ELDEFS_");
if(elDefs != null){
CmsElementDefinition elDef = elDefs.get(elementName);
if(elDef != null){
return elDef.getTemplateSelector();
}
}
return null;
}
}
}
/**
* Inserts the correct document title into the template.
* <P>
* This method can be called using <code><METHOD name="getTitle"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getTitle(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String requestedUri = cms.getRequestContext().getUri();
String title = cms.readProperty(requestedUri, C_PROPERTY_TITLE);
if(title == null) {
title = "";
}
return title;
}
/**
* Inserts the correct document description into the template.
* <P>
* This method can be called using <code><METHOD name="getDescription"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getDescription(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String requestedUri = cms.getRequestContext().getUri();
String description = cms.readProperty(requestedUri, C_PROPERTY_DESCRIPTION);
if(description == null) {
description = "";
}
return description;
}
/**
* Inserts the value of the given property in the template.
* <P>
* This method can be called using <code><METHOD name="getProperty"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent The name of the property.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getProperty(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String requestedUri = cms.getRequestContext().getUri();
String value = "";
try{
value = cms.readProperty(requestedUri, tagcontent);
}catch(Exception e){
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_INFO, "[CmsXmlTemplate] usermethod getProperty throwed an Exception getting "+
tagcontent+": "+e.toString());
}
}
if(value == null) {
value = "";
}
return value;
}
/**
* Inserts the correct document keyword into the template.
* <P>
* This method can be called using <code><METHOD name="getKeywords"></code>
* in the template file.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getKeywords(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String requestedUri = cms.getRequestContext().getUri();
String keywords = cms.readProperty(requestedUri, C_PROPERTY_KEYWORDS);
if(keywords == null) {
keywords = "";
}
return keywords;
}
// Gridnine AB Aug 5, 2002
public Object getEncoding(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
return cms.getRequestContext().getEncoding();
}
//Gridnine AB Sep 3, 2002
public Object setEncoding(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
if((tagcontent != null) && !"".equals(tagcontent)){
cms.getRequestContext().setEncoding(tagcontent.trim());
}
return "";
}
/**
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent May contain the parameter for framesets to work in the static export.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getUri(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
String res = cms.getRequestContext().getUri();
if(tagcontent == null || "".equals(tagcontent)){
return (cms.getLinkSubstitution(res)).getBytes();
}else{
return (cms.getLinkSubstitution(res+"?"+tagcontent)).getBytes();
}
}
/**
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Contains the parameter for framesets.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object getUriWithParameter(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException{
String query = new String();
// get the parameternames of the original request and get the values from the userObject
try{
Enumeration parameters = null;
if(cms.getMode() == cms.C_MODUS_EXPORT){
parameters = cms.getRequestContext().getRequest().getParameterNames();
}else{
parameters = ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getParameterNames();
}
StringBuffer paramQuery = new StringBuffer();
while(parameters.hasMoreElements()){
String name = (String)parameters.nextElement();
String value = (String)((Hashtable)userObject).get(name);
if(value != null && !"".equals(value)){
paramQuery.append(name+"="+value+"&");
}
}
if(paramQuery.length() > 0){
// add the parameters to the query string
query = paramQuery.substring(0,paramQuery.length()-1).toString();
}
} catch (Exception exc){
exc.printStackTrace();
}
// get the parameters in the tagcontent
if((tagcontent != null) && (!"".equals(tagcontent))){
if(tagcontent.startsWith("?")){
tagcontent = tagcontent.substring(1);
}
query = tagcontent +"&" + query;
}
return getUri(cms, query, doc, userObject);
}
/**
* Indicates if the current template class is able to stream it's results
* directly to the response oputput stream.
* <P>
* Classes must not set this feature, if they might throw special
* exception that cause HTTP errors (e.g. 404/Not Found), or if they
* might send HTTP redirects.
* <p>
* If a class sets this feature, it has to check the
* isStreaming() property of the RequestContext. If this is set
* to <code>true</code> the results must be streamed directly
* to the output stream. If it is <code>false</code> the results
* must not be streamed.
* <P>
* Complex classes that are able top include other subtemplates
* have to check the streaming ability of their subclasses here!
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if this class may stream it's results, <EM>false</EM> otherwise.
*/
public boolean isStreamable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return true;
}
/**
* Collect caching informations from the current template class.
* <P>
* Complex classes that are able to include other subtemplates
* have to check the streaming ability of their subclasses here!
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if this class may stream it's results, <EM>false</EM> otherwise.
*/
public CmsCacheDirectives collectCacheDirectives(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
// Frist build our own cache directives.
boolean isCacheable = isCacheable(cms, templateFile, elementName, parameters, templateSelector);
boolean isProxyPrivateCacheable = isProxyPrivateCacheable(cms, templateFile, elementName, parameters, templateSelector);
boolean isProxyPublicCacheable = isProxyPublicCacheable(cms, templateFile, elementName, parameters, templateSelector);
boolean isExportable = isExportable(cms, templateFile, elementName, parameters, templateSelector);
boolean isStreamable = isStreamable(cms, templateFile, elementName, parameters, templateSelector);
CmsCacheDirectives result = new CmsCacheDirectives(isCacheable, isProxyPrivateCacheable, isProxyPublicCacheable, isExportable, isStreamable);
// Collect all subelements of this page
CmsXmlTemplateFile doc = null;
Vector subtemplates = null;
try {
doc = this.getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector);
doc.init(cms, templateFile);
subtemplates = doc.getAllSubElements();
// Loop through all subelements and get their cache directives
int numSubtemplates = subtemplates.size();
for(int i = 0;i < numSubtemplates;i++) {
String elName = (String)subtemplates.elementAt(i);
String className = null;
String templateName = null;
className = getTemplateClassName(elName, doc, parameters);
templateName = getTemplateFileName(elName, doc, parameters);
if(className != null) {
I_CmsTemplate templClass = (I_CmsTemplate)CmsTemplateClassManager.getClassInstance(cms, className);
CmsCacheDirectives cd2 = templClass.collectCacheDirectives(cms, templateName, elName, parameters, null);
//result.merge(templClass.collectCacheDirectives(cms, templateName, elName, parameters, null));
result.merge(cd2);
/*debugPrint(elementName, result.m_cd);
System.err.println(" ");
System.err.println("* ");*/
} else {
// This template file includes a subelement not exactly defined.
// The name of it's template class is missing at the moment, so
// we cannot say anything about the cacheablility.
// Set it to false.
return new CmsCacheDirectives(false);
}
}
}
catch(CmsException e) {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_INFO, getClassName() + "Cannot determine cache directives for my template file " + templateFile + " (" + e + "). ");
A_OpenCms.log(C_OPENCMS_INFO, getClassName() + "Resuming normal operation, setting cacheability to false.");
return new CmsCacheDirectives(false);
}
}
return result;
}
/**
* gets the caching information from the current template class.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if this class may stream it's results, <EM>false</EM> otherwise.
*/
public CmsCacheDirectives getCacheDirectives(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
// First build our own cache directives.
CmsCacheDirectives result = new CmsCacheDirectives(true);
Vector para = new Vector();
para.add("cmsframe");
result.setCacheParameters(para);
return result;
}
/**
* gets the caching information for a specific methode.
* @param cms the cms object.
* @param methodName the name of the method for witch the MethodCacheDirectives are wanted.
*/
public CmsMethodCacheDirectives getMethodCacheDirectives(CmsObject cms, String methodName){
if("getTitle".equals(methodName) || "getUri".equals(methodName)
|| "getFileUri".equals(methodName)
|| "getDescription".equals(methodName)
|| "getKeywords".equals(methodName)
|| "getProperty".equals(methodName)
|| "getPathUri".equals(methodName)){
CmsMethodCacheDirectives mcd = new CmsMethodCacheDirectives(true);
mcd.setCacheUri(true);
return mcd;
}
if ("getFrameQueryString".equals(methodName)
|| "getQueryString".equals(methodName)
|| "getRequestIp".equals(methodName)
|| "getSessionId".equals(methodName)
|| "getUriWithParameter".equals(methodName)
|| "parameters".equals(methodName)
|| "getStylesheet".equals(methodName)){
return new CmsMethodCacheDirectives(false);
}
return null;
}
/**
* Tests, if the template cache is setted.
* @return <code>true</code> if setted, <code>false</code> otherwise.
*/
public final boolean isTemplateCacheSet() {
return m_cache != null;
}
/**
* For debugging purposes only.
* Prints out all parameters.
* <P>
* May be called from the template file using
* <code><METHOD name="parameters"></code>.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return Debugging information about all parameters.
*/
public String parameters(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) {
Hashtable param = (Hashtable)userObject;
Enumeration keys = param.keys();
String s = "";
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
s = s + "<B>" + key + "</B>: " + param.get(key) + "<BR>";
}
s = s + "<B>" + tagcontent + "</B><BR>";
return s;
}
/**
* Set the instance of template cache that should be used to store
* cacheable results of the subtemplates.
* If the template cache is not set, caching will be disabled.
* @param c Template cache to be used.
*/
public final void setTemplateCache(I_CmsTemplateCache c) {
m_cache = c;
}
/**
* Indicates if a previous cached result should be reloaded.
* <P>
* <em>not implemented.</em> Returns always <code>false</code>.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <code>false</code>
*/
public boolean shouldReload(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) {
return false;
}
/**
* Saves the dependencies for this elementvariante.
* We save the deps two ways.
* First we have an so called extern Hashtable where we use as key a resource
* (represented by a String) and as values an Vector with all ElementVariants
* that depend on this resource (again represented by a String in which we save
* the variant and the element it is in)
* The second saveplace is the elementvariant itselv. The intern way to save.
* There we store which resoucess affect this variant.
*
* @param cms The cms object.
* @param templateName.
* @param elementName only needed for getCachDirectives, if it is not used there it may be null
* @param templateSelector only needed for getCachDirectives, if it is not used there it may be null
* @param parameters.
* @param vfsDeps A vector (of CmsResource objects) with the resources that variant depends on.
* @param cosDeps A vector (of CmsContentDefinitions) with the cd-resources that variant depends on.
* @param cosClassDeps A vector (of Class objects) with the contentdefinitions that variant depends on.
*/
protected void registerVariantDeps(CmsObject cms, String templateName, String elementName,
String templateSelector, Hashtable parameters, Vector vfsDeps,
Vector cosDeps, Vector cosClassDeps) throws CmsException {
String cacheKey = getCacheDirectives(cms, templateName, elementName,
parameters, templateSelector).getCacheKey(cms, parameters);
if(cms.getRequestContext().isElementCacheEnabled() && (cacheKey != null) &&
(cms.getRequestContext().currentProject().equals(cms.onlineProject()) )) {
boolean exportmode = cms.getMode() == cms.C_MODUS_EXPORT;
Hashtable externVarDeps = cms.getVariantDependencies();
long exTimeForVariant = Long.MAX_VALUE;
long now = System.currentTimeMillis();
// this will be the entry for the extern hashtable
String variantEntry = getClass().getName() + "|"+ templateName +"|"+ cacheKey;
// the vector for the intern variant store. it contains the keys for the extern Hashtable
Vector allDeps = new Vector();
// first the dependencies for the cos system
if(cosDeps != null){
for (int i = 0; i < cosDeps.size(); i++){
A_CmsContentDefinition contentDef = (A_CmsContentDefinition)cosDeps.elementAt(i);
String key = cms.getSiteName() + cms.C_ROOTNAME_COS + "/"+contentDef.getClass().getName() +"/"+contentDef.getUniqueId(cms);
if(exportmode){
cms.getRequestContext().addDependency(key);
}
allDeps.add(key);
if(contentDef.isTimedContent()){
long time = ((I_CmsTimedContentDefinition)cosDeps.elementAt(i)).getPublicationDate();
if (time > now && time < exTimeForVariant){
exTimeForVariant = time;
}
time = ((I_CmsTimedContentDefinition)cosDeps.elementAt(i)).getPurgeDate();
if (time > now && time < exTimeForVariant){
exTimeForVariant = time;
}
time = ((I_CmsTimedContentDefinition)cosDeps.elementAt(i)).getAdditionalChangeDate();
if (time > now && time < exTimeForVariant){
exTimeForVariant = time;
}
}
}
}
// now for the Classes
if(cosClassDeps != null){
for(int i=0; i<cosClassDeps.size(); i++){
String key = cms.getSiteName() + cms.C_ROOTNAME_COS + "/" + ((Class)cosClassDeps.elementAt(i)).getName() +"/";
allDeps.add(key);
if(exportmode){
cms.getRequestContext().addDependency(key);
}
}
}
// now for the vfs
if(vfsDeps != null){
for(int i = 0; i < vfsDeps.size(); i++){
allDeps.add(((CmsResource)vfsDeps.elementAt(i)).getResourceName());
if(exportmode){
cms.getRequestContext().addDependency(((CmsResource)vfsDeps.elementAt(i)).getResourceName());
}
}
}
// now put them all in the extern store
for(int i=0; i<allDeps.size(); i++){
String key = (String)allDeps.elementAt(i);
Vector variantsForDep = (Vector)externVarDeps.get(key);
if (variantsForDep == null){
variantsForDep = new Vector();
}
if(!variantsForDep.contains(variantEntry)){
variantsForDep.add(variantEntry);
}
externVarDeps.put(key, variantsForDep);
}
// at last we have to fill the intern store. that means we have to
// put the alldeps vector in our variant that will be created later
// in the startproccessing method.
// Get current element.
CmsElementCache elementCache = cms.getRequestContext().getElementCache();
CmsElementDescriptor elKey = new CmsElementDescriptor(getClass().getName(), templateName);
A_CmsElement currElem = elementCache.getElementLocator().get(cms, elKey, parameters);
// add an empty variant with the vector to the element
CmsElementVariant emptyVar = new CmsElementVariant();
emptyVar.addDependencies(allDeps);
if(exTimeForVariant < Long.MAX_VALUE ){
emptyVar.mergeNextTimeout(exTimeForVariant);
}
Vector removedVar = currElem.addVariant(cacheKey, emptyVar);
if((removedVar != null) ){
// adding a new variant deleted this variant so we have to update the extern store
String key = (String)removedVar.firstElement();
CmsElementVariant oldVar = (CmsElementVariant)removedVar.lastElement();
Vector oldVarDeps = oldVar.getDependencies();
if (oldVarDeps != null){
String oldVariantEntry = getClass().getName() + "|"+ templateName +"|"+ key;
for(int i=0; i<oldVarDeps.size(); i++){
Vector externEntrys = (Vector)externVarDeps.get(oldVarDeps.elementAt(i));
if(externEntrys != null){
externEntrys.removeElement(oldVariantEntry);
}
}
}
}
// mark this element so it wont be deleted without updating the extern store
currElem.thisElementHasDepVariants();
}
}
/**
* Starts the processing of the given template file by calling the
* <code>getProcessedTemplateContent()</code> method of the content defintition
* of the corresponding content type.
* <P>
* Any exceptions thrown while processing the template will be caught,
* printed and and thrown again.
* <P>
* If element cache is enabled, <code>generateElementCacheVariant()</code>
* will be called instead of <code>getProcessedTemplateContent()</code> for
* generating a new element cache variant instead of the completely
* processed output data.
* This new variant will be stored in the current element using the cache key
* given by the cache directives.
*
* @param cms CmsObject Object for accessing system resources.
* @param xmlTemplateDocument XML parsed document of the content type "XML template file" or
* any derived content type.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return Content of the template and all subtemplates.
* @exception CmsException
*/
protected byte[] startProcessing(CmsObject cms, CmsXmlTemplateFile xmlTemplateDocument, String elementName, Hashtable parameters, String templateSelector) throws CmsException {
byte[] result = null;
if(cms.getRequestContext().isElementCacheEnabled()) {
CmsElementDefinitionCollection mergedElDefs = (CmsElementDefinitionCollection)parameters.get("_ELDEFS_");
// We are in element cache mode. Create a new variant instead of a completely processed subtemplate
CmsElementVariant variant = xmlTemplateDocument.generateElementCacheVariant(this, parameters, elementName, templateSelector);
// Get current element.
CmsElementCache elementCache = cms.getRequestContext().getElementCache();
CmsElementDescriptor elKey = new CmsElementDescriptor(getClass().getName(), xmlTemplateDocument.getAbsoluteFilename());
A_CmsElement currElem = elementCache.getElementLocator().get(cms, elKey, parameters);
// If this elemement is cacheable, store the new variant
if(currElem.getCacheDirectives().isInternalCacheable()) {
//currElem.addVariant(getKey(cms, xmlTemplateDocument.getAbsoluteFilename(), parameters, templateSelector), variant);
Vector removedVar = currElem.addVariant(currElem.getCacheDirectives().getCacheKey(cms, parameters), variant);
if((removedVar != null) && currElem.hasDependenciesVariants()){
// adding a new variant deleted this variant so we have to update the extern dependencies store
String key = (String)removedVar.firstElement();
CmsElementVariant oldVar = (CmsElementVariant)removedVar.lastElement();
Vector oldVarDeps = oldVar.getDependencies();
if (oldVarDeps != null){
String oldVariantEntry = getClass().getName() + "|"+ xmlTemplateDocument.getAbsoluteFilename() +"|"+ key;
for(int i=0; i<oldVarDeps.size(); i++){
Vector externEntrys = (Vector)cms.getVariantDependencies().get(oldVarDeps.elementAt(i));
if(externEntrys != null){
externEntrys.removeElement(oldVariantEntry);
}
}
}
}
}
result = ((CmsElementXml)currElem).resolveVariant(cms, variant, elementCache, mergedElDefs, elementName, parameters);
} else {
// Classic way. Element cache is not activated, so let's genereate the template as usual
// Try to process the template file
try {
// Gridnine AB Aug 1, 2002
//result = xmlTemplateDocument.getProcessedTemplateContent(this, parameters, templateSelector).getBytes();
result = xmlTemplateDocument.getProcessedTemplateContent(this, parameters, templateSelector).getBytes(
cms.getRequestContext().getEncoding());
}
catch(Throwable e) {
// There were errors while generating output for this template.
// Clear HTML cache and then throw exception again
xmlTemplateDocument.removeFromFileCache();
if(isCacheable(cms, xmlTemplateDocument.getAbsoluteFilename(), elementName, parameters, templateSelector)) {
m_cache.clearCache(getKey(cms, xmlTemplateDocument.getAbsoluteFilename(), parameters, templateSelector));
}
if(e instanceof CmsException) {
throw (CmsException)e;
}
else {
// under normal cirumstances, this should not happen.
// any exception should be caught earlier and replaced by
// corresponding CmsExceptions.
String errorMessage = "Exception while getting content for (sub)template " + elementName + ". " + e;
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage);
}
throw new CmsException(errorMessage);
}
}
}
// update the template selector if nescessary
if (templateSelector!=null) {
parameters.put(elementName+"._TEMPLATESELECTOR_",templateSelector);
}
return result;
}
/**
* Handles any occurence of an <code><ELEMENT></code> tag.
* <P>
* Every XML template class should use CmsXmlTemplateFile as
* the interface to the XML file. Since CmsXmlTemplateFile is
* an extension of A_CmsXmlContent by the additional tag
* <code><ELEMENT></code> this user method ist mandatory.
*
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document.
* @param userObj Hashtable with parameters.
* @return String or byte[] with the content of this subelement.
* @exception CmsException
*/
public Object templateElement(CmsObject cms, String tagcontent, A_CmsXmlContent doc, Object userObject) throws CmsException {
// Our own template file that wants to include a subelement
CmsXmlTemplateFile templateFile = (CmsXmlTemplateFile)doc;
// Indicates, if this is a request of a guest user. Needed for error outputs.
boolean isAnonymousUser = cms.anonymousUser().equals(cms.getRequestContext().currentUser());
// First create a copy of the parameter hashtable
Hashtable parameterHashtable = (Hashtable)((Hashtable)userObject).clone();
// Name of the template class that should be used to handle the subtemplate
String templateClass = getTemplateClassName(tagcontent, templateFile, parameterHashtable);
// Name of the subtemplate file.
String templateFilename = getTemplateFileName(tagcontent, templateFile, parameterHashtable);
// Name of the subtemplate template selector
String templateSelector = getTemplateSelector(tagcontent, templateFile, parameterHashtable);
// Results returned by the subtemplate class
byte[] result = null;
// Temporary object for loading the subtemplate class
Object loadedObject = null;
// subtemplate class to be used for the include
I_CmsTemplate subTemplate = null;
// Key for the cache
Object subTemplateKey = null;
// try to load the subtemplate class
try {
loadedObject = CmsTemplateClassManager.getClassInstance(cms, templateClass);
}
catch(CmsException e) {
// There was an error. First remove the template file from the file cache
templateFile.removeFromFileCache();
if(isAnonymousUser) {
// The current user is the anonymous user
return C_ERRORTEXT;
}
else {
// The current user is a system user, so we throw the exception again.
throw e;
}
}
// Check if the loaded object is really an instance of an OpenCms template class
if(!(loadedObject instanceof I_CmsTemplate)) {
String errorMessage = "Class " + templateClass + " is no OpenCms template class.";
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[CmsXmlTemplate] " + errorMessage);
}
throw new CmsException(errorMessage, CmsException.C_XML_NO_TEMPLATE_CLASS);
}
subTemplate = (I_CmsTemplate)loadedObject;
// Template class is now loaded. Next try to read the parameters
Vector parameterTags = null;
parameterTags = templateFile.getParameterNames(tagcontent);
if(parameterTags != null) {
int numParameterTags = parameterTags.size();
for(int i = 0;i < numParameterTags;i++) {
String paramName = (String)parameterTags.elementAt(i);
String paramValue = templateFile.getParameter(tagcontent, paramName);
if(!parameterHashtable.containsKey(paramName)) {
parameterHashtable.put(tagcontent + "." + paramName, paramValue);
}
}
}
// all parameters are now parsed. Finally give the own subelement name
// as parameter
// TODO: replace _ELEMENT_ by a constant
parameterHashtable.put("_ELEMENT_", tagcontent);
// Try to get the result from the cache
//if(subTemplate.isCacheable(cms, templateFilename, tagcontent, parameterHashtable, null)) {
if(subTemplate.collectCacheDirectives(cms, templateFilename, tagcontent, parameterHashtable, null).isInternalCacheable()) {
subTemplateKey = subTemplate.getKey(cms, templateFilename, parameterHashtable, null);
if(m_cache != null && m_cache.has(subTemplateKey) && (!subTemplate.shouldReload(cms, templateFilename, tagcontent, parameterHashtable, null))) {
result = m_cache.get(subTemplateKey);
if(cms.getRequestContext().isStreaming()) {
try {
cms.getRequestContext().getResponse().getOutputStream().write(result);
} catch(Exception e) {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error while streaming!");
}
}
}
}
}
// OK. let's call the subtemplate
if(result == null) {
try {
result = subTemplate.getContent(cms, templateFilename, tagcontent, parameterHashtable, templateSelector);
}
catch(Exception e) {
// Oh, oh..
// There were errors while getting the content of the subtemplate
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Could not generate output for template file \"" + templateFilename + "\" included as element \"" + tagcontent + "\".");
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + e);
}
// The anonymous user gets an error String instead of an exception
if(isAnonymousUser) {
if(cms.getRequestContext().isStreaming()) {
try {
cms.getRequestContext().getResponse().getOutputStream().write(C_ERRORTEXT.getBytes());
} catch(Exception e2) {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error while streaming!");
}
}
}
return C_ERRORTEXT;
}
else {
if(e instanceof CmsException) {
throw (CmsException)e;
}
else {
throw new CmsException("Error while executing getContent for subtemplate \"" + tagcontent + "\". " + e);
}
}
}
// Store the results in the template cache, if cacheable
//if(subTemplate.isCacheable(cms, templateFilename, tagcontent, parameterHashtable, null)) {
if(subTemplate.collectCacheDirectives(cms, templateFilename, tagcontent, parameterHashtable, null).isInternalCacheable() && m_cache != null) {
// we don't need to re-get the caching-key here since it already exists
m_cache.put(subTemplateKey, result);
}
}
// Gridnine AB Aug 5, 2002
return new CmsProcessedString(result, cms.getRequestContext().getEncoding());
}
/**
* Help method that handles any occuring error by writing
* an error message to the OpenCms logfile and throwing a
* CmsException of the type "unknown".
* @param errorMessage String with the error message to be printed.
* @exception CmsException
*/
protected void throwException(String errorMessage) throws CmsException {
throwException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION);
}
/**
* Help method that handles any occuring error by writing
* an error message to the OpenCms logfile and throwing a
* CmsException of the given type.
* @param errorMessage String with the error message to be printed.
* @param type Type of the exception to be thrown.
* @exception CmsException
*/
protected void throwException(String errorMessage, int type) throws CmsException {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage);
}
throw new CmsException(errorMessage, type);
}
/**
* Help method that handles any occuring error by writing
* an error message to the OpenCms logfile and re-throwing a
* caught exception.
* @param errorMessage String with the error message to be printed.
* @param e Exception to be re-thrown.
* @exception CmsException
*/
protected void throwException(String errorMessage, Exception e) throws CmsException {
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage);
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Exception: " + e);
}
if(e instanceof CmsException) {
throw (CmsException)e;
}
else {
throw new CmsException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION, e);
}
}
/**
* Create a new element for the element cache consisting of the current template
* class and the given template file.
* <P>
* Complex template classes that are able to include other (sub-)templates
* must generate a collection of element definitions for their possible
* subtemplates. This collection is part of the new element.
* @param cms CmsObject for accessing system resources.
* @param templateFile Name of the template file for the new element
* @param parameters All parameters of the current request
* @return New element for the element cache
*/
public A_CmsElement createElement(CmsObject cms, String templateFile, Hashtable parameters) {
CmsElementDefinitionCollection subtemplateDefinitions = new CmsElementDefinitionCollection();
String readAccessGroup = cms.C_GROUP_ADMIN;
int variantCachesize = 100;
// if the templateFile is null someone didnt set the Templatefile in the elementdefinition
// in this case we have to use the aktual body template when resolving the variant.
// In a body element there are no subelements and we dont care about access rights.
// So if if the Exception occurs becource of the template == null it is no error and
// we set the readAccessGroup = null (this will happen by getReadingpermittedGroup)
try {
CmsElementCache elementCache = cms.getRequestContext().getElementCache();
variantCachesize = elementCache.getVariantCachesize();
readAccessGroup = cms.getReadingpermittedGroup(cms.getRequestContext().currentProject().getId(),templateFile);
CmsXmlTemplateFile xmlTemplateDocument = getOwnTemplateFile(cms, templateFile, null, parameters, null);
Vector subtemplates = xmlTemplateDocument.getAllSubElementDefinitions();
int numSubtemplates = subtemplates.size();
for(int i = 0; i < numSubtemplates; i++) {
String elName = (String)subtemplates.elementAt(i);
String className = null;
String templateName = null;
String templateSelector = null;
if(xmlTemplateDocument.hasSubtemplateClass(elName)) {
className = xmlTemplateDocument.getSubtemplateClass(elName);
}
if(xmlTemplateDocument.hasSubtemplateFilename(elName)) {
templateName = xmlTemplateDocument.getSubtemplateFilename(elName);
}
if(xmlTemplateDocument.hasSubtemplateSelector(elName)) {
templateSelector = xmlTemplateDocument.getSubtemplateSelector(elName);
}
Hashtable templateParameters = xmlTemplateDocument.getParameters(elName);
if(className != null || templateName != null || templateSelector != null || templateParameters.size() > 0) {
if(className == null){
className = "com.opencms.template.CmsXmlTemplate";
}
if(templateName != null){
templateName = Utils.mergeAbsolutePath(templateFile, templateName);
}
CmsElementDefinition elDef = new CmsElementDefinition(elName, className, templateName, templateSelector, templateParameters);
subtemplateDefinitions.add(elDef);
}
}
} catch(Exception e) {
if(templateFile != null){
if(I_CmsLogChannels.C_PREPROCESSOR_IS_LOGGING && A_OpenCms.isLogging() ) {
A_OpenCms.log(C_OPENCMS_ELEMENTCACHE, getClassName() + "Could not generate my template cache element.");
A_OpenCms.log(C_OPENCMS_ELEMENTCACHE, getClassName() + e);
}
}else{
// no templateFile given, so let everyone read this
readAccessGroup = null;
}
}
CmsElementXml result = new CmsElementXml(getClass().getName(),
templateFile, readAccessGroup,
getCacheDirectives(cms, templateFile, null, parameters, null),
subtemplateDefinitions, variantCachesize);
return result;
}
}
|
package com.untamedears.PrisonPearl;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
public class PrisonPearl {
private short id;
private String imprisonedname;
private InventoryHolder holder;
private Item item;
public PrisonPearl(short id, String imprisonedname, InventoryHolder holder) {
this.id = id;
this.imprisonedname = imprisonedname;
this.holder = holder;
}
public short getID() {
return id;
}
public String getImprisonedName() {
return imprisonedname;
}
public Player getImprisonedPlayer() {
return Bukkit.getPlayerExact(imprisonedname);
}
public InventoryHolder getHolder() {
return holder;
}
public Entity getHolderEntity() {
if (holder instanceof Entity)
return (Entity)holder;
else
return null;
}
public BlockState getHolderBlockState() {
if (holder instanceof BlockState) {
return (BlockState)holder;
} else if (holder instanceof DoubleChest) {
return (BlockState)((DoubleChest)holder).getLeftSide();
} else {
return null;
}
}
public Location getLocation() {
if (holder != null) {
if (holder instanceof Entity) {
return ((Entity)holder).getLocation();
} else if (holder instanceof BlockState) {
return ((BlockState)holder).getLocation();
} else if (holder instanceof DoubleChest) {
return ((DoubleChest)holder).getLocation();
} else {
System.err.println("PrisonPearl " + id + " has an unexpected holder: " + holder);
return null;
}
} else if (item != null) {
return item.getLocation();
} else {
System.err.println("PrisonPearl " + id + " has no holder nor item");
return null;
}
}
public String getHolderName() {
Entity entity;
BlockState state;
if ((entity = getHolderEntity()) != null) {
if (entity instanceof Player) {
return ((Player)entity).getDisplayName();
} else {
System.err.println("PrisonPearl " + id + " is held by a non-player entity");
return "an unknown entity";
}
} else if ((state = getHolderBlockState()) != null) {
switch (state.getType()) {
case CHEST:
return "a chest";
case FURNACE:
return "a furnace";
case BREWING_STAND:
return "a brewing stand";
case DISPENSER:
return "a dispenser";
default:
System.err.println("PrisonPearl " + id + " is inside an unknown block");
return "an unknown block";
}
} else {
System.err.println("PrisonPearl " + id + " has no holder nor item");
return "unknown";
}
}
public String describeLocation() {
Location loc = getLocation();
Vector vec = loc.toVector();
String str = loc.getWorld().getName() + " " + vec.getBlockX() + " " + vec.getBlockY() + " " + vec.getBlockZ();
if (holder != null)
return "held by " + getHolderName() + " at " + str;
else
return "located at " + str;
}
public boolean verifyLocation() {
Location loc = getLocation();
if (item != null) {
Chunk chunk = loc.getChunk();
for (Entity entity : chunk.getEntities()) {
if (entity == item)
return true;
}
return false;
} else {
if (holder instanceof Player) {
if (!((Player)holder).isOnline())
return false;
} else if (holder instanceof BlockState) {
if (!((BlockState)holder).update(true))
return false;
} else if (holder instanceof DoubleChest) {
DoubleChest dc = (DoubleChest)holder;
if (!((BlockState)dc.getLeftSide()).update(true))
return false;
}
Inventory inv = holder.getInventory();
for (ItemStack item : inv.all(Material.ENDER_PEARL).values()) {
if (item.getDurability() == id)
return true;
}
return false;
}
}
public void setHolder(InventoryHolder holder) {
this.holder = holder;
item = null;
}
public void setItem(Item item) {
holder = null;
this.item = item;
}
}
|
package utilities;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.japi.pf.ReceiveBuilder;
import akka.japi.pf.UnitPFBuilder;
import com.fasterxml.jackson.databind.node.ObjectNode;
import drones.models.scheduler.messages.from.DroneStatusMessage;
import messages.*;
import drones.models.Fleet;
import drones.models.scheduler.Scheduler;
import drones.models.scheduler.SchedulerException;
import drones.models.scheduler.messages.from.AssignmentCompletedMessage;
import drones.models.scheduler.messages.from.AssignmentProgressedMessage;
import drones.models.scheduler.messages.from.AssignmentStartedMessage;
import drones.models.scheduler.messages.from.DroneAssignedMessage;
import play.Logger;
import play.libs.F;
import play.libs.Json;
import java.util.ArrayList;
import java.util.List;
public class MessageWebSocket extends AbstractActor {
public static Props props(ActorRef out) {
return Props.create(MessageWebSocket.class, out);
}
private final ActorRef out;
private static final List<F.Tuple<Class, String>> TYPENAMES;
private static final List<Class> IGNORETYPES;
static {
TYPENAMES = new ArrayList<>();
IGNORETYPES = new ArrayList<>();
TYPENAMES.add(new F.Tuple<>(BatteryPercentageChangedMessage.class, "batteryPercentageChanged"));
TYPENAMES.add(new F.Tuple<>(AltitudeChangedMessage.class, "altitudeChanged"));
TYPENAMES.add(new F.Tuple<>(LocationChangedMessage.class, "locationChanged"));
IGNORETYPES.add(FlyingStateChangedMessage.class);
IGNORETYPES.add(NavigationStateChangedMessage.class);
}
public MessageWebSocket(final ActorRef out) {
this.out = out;
// Scheduler
try {
Scheduler.subscribe(DroneAssignedMessage.class, self());
Scheduler.subscribe(AssignmentStartedMessage.class, self());
Scheduler.subscribe(AssignmentCompletedMessage.class, self());
Scheduler.subscribe(DroneStatusMessage.class, self());
Scheduler.subscribe(AssignmentProgressedMessage.class, self());
} catch (SchedulerException ex) {
Logger.error("Failed to subscribe to scheduler.", ex);
}
Fleet.getFleet().subscribe(self());
UnitPFBuilder<Object> builder = ReceiveBuilder.match(TYPENAMES.get(0)._1, s -> {
ObjectNode node = Json.newObject();
node.put("type", TYPENAMES.get(0)._2);
node.put("id", sender().path().name().split("-")[1]);
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
for(int i = 1; i < TYPENAMES.size(); i++){
final int index = i;
builder = builder.match(TYPENAMES.get(index)._1, s -> {
ObjectNode node = Json.newObject();
node.put("type", TYPENAMES.get(index)._2);
node.put("id", sender().path().name().split("-")[1]);
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
}
builder.match(DroneAssignedMessage.class, s -> {
ObjectNode node = Json.newObject();
node.put("type", "droneAssigned");
node.put("id", s.getAssignmentId());
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
builder.match(AssignmentCompletedMessage.class, s -> {
ObjectNode node = Json.newObject();
node.put("type", "assignmentCompleted");
node.put("id", s.getAssignmentId());
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
builder.match(AssignmentStartedMessage.class, s -> {
ObjectNode node = Json.newObject();
node.put("type", "assignmentStarted");
node.put("id", s.getAssignmentId());
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
builder.match(AssignmentProgressedMessage.class, s -> {
ObjectNode node = Json.newObject();
node.put("type", "assignmentProgressed");
node.put("id", s.getAssignmentId());
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
builder.match(DroneStatusMessage.class, s -> {
ObjectNode node = Json.newObject();
node.put("type", "droneStatusChanged");
node.put("id", s.getDroneId());
node.put("value", Json.toJson(s));
out.tell(node.toString(), self());
});
for (int i = 0; i < IGNORETYPES.size(); ++i)
builder = builder.match(IGNORETYPES.get(i), s -> {});
builder = builder.matchAny(o -> Logger.debug("[websocket] Unkown message type..." + o.getClass().getName()));
receive(builder.build());
}
@Override
public void postStop() throws Exception {
super.postStop();
Fleet.getFleet().unsubscribe(self());
// Scheduler
try {
Scheduler.unsubscribe(DroneAssignedMessage.class, self());
Scheduler.unsubscribe(AssignmentStartedMessage.class, self());
Scheduler.unsubscribe(AssignmentCompletedMessage.class, self());
Scheduler.unsubscribe(DroneStatusMessage.class, self());
Scheduler.unsubscribe(AssignmentProgressedMessage.class, self());
} catch (SchedulerException ex) {
Logger.error("Failed to unsubscribe from scheduler.", ex);
}
}
}
|
package com.sunstreaks.mypisd;
//changed within sourcetree!!
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.sunstreaks.mypisd.net.DataGrabber;
import com.sunstreaks.mypisd.net.Domain;
import com.sunstreaks.mypisd.net.PISDException;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends Activity {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[] {
"foo@example.com:hello", "bar@example.com:world" };
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
private boolean mRememberPassword;
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
private Spinner domainSpinner;
private CheckBox rememberPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the Spinner.
List<String> SpinnerArray = new ArrayList<String>();
for (Domain d : Domain.values()) {
SpinnerArray.add(d.name());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SpinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
domainSpinner = (Spinner) findViewById(R.id.domain_spinner);
domainSpinner.setAdapter(adapter);
//Set up the remember_password checkbox
rememberPassword = (CheckBox) findViewById(R.id.remember_password);
rememberPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (rememberPassword.isChecked()) {
mRememberPassword = true;
}
else {
mRememberPassword = false;
}
}
});
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
//mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
//Load stored username/password
SharedPreferences sharedPrefs = this.getPreferences(Context.MODE_PRIVATE);
mEmailView.setText(sharedPrefs.getString("email", mEmail));
mPasswordView.setText(sharedPrefs.getString("password", ""));
mRememberPassword = sharedPrefs.getBoolean("remember_password", false);
rememberPassword.setChecked(mRememberPassword);
domainSpinner.setSelection(sharedPrefs.getInt("domain", 0));
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} /*else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}*/
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
}
//requires @ if parent account selected
else if (domainSpinner.getSelectedItem().toString().equals("PARENT") && !mEmail.contains("@")) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
SharedPreferences sharedPrefs = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt("domain", domainSpinner.getSelectedItemPosition());
editor.putString("email", mEmail);
editor.putBoolean("remember_password", mRememberPassword);
editor.putString("password", mRememberPassword? mPassword: "");
editor.commit();
// Modified from default.
//mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// Simulate network access.
DataGrabber d = new DataGrabber(
Domain.valueOf(domainSpinner.getSelectedItem().toString()),
mEmail,
mPassword);
// Update the loading screen.
runOnUiThread(new Runnable() {
public void run() {
((TextView)mLoginStatusMessageView).setText(R.string.login_progress_mypisd);
}
});
d.login();
if (d.getEditureLogin() == -1) {
return false;
}
{
// Update the loading screen.
runOnUiThread(new Runnable() {
public void run() {
((TextView)mLoginStatusMessageView).setText(R.string.login_progress_gradebook);
}
});
String[] ptc = d.getPassthroughCredentials();
d.loginGradebook(ptc[0], ptc[1], mEmail, mPassword);
}
// Update the loading screen.
runOnUiThread(new Runnable() {
public void run() {
((TextView)mLoginStatusMessageView).setText(R.string.login_progress_downloading_data);
}
});
// No longer gets all class grades on load. Too slow!
//JSONArray classGrades = d.getAllClassGrades();
JSONArray gradeSummary = d.getGradeSummary();
// System.out.println(gradeSummary.toString());
// Store class grades in Shared Preferences.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("gradeSummary", gradeSummary.toString());
editor.commit();
Intent startMain = new Intent(LoginActivity.this, MainActivity.class);
startActivity(startMain);
} else {
System.err.println("No internet connection");
// Program exits mysteriously here.
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder popupBuilder = new AlertDialog.Builder(LoginActivity.this);
TextView myMsg = new TextView(LoginActivity.this);
myMsg.setText("No internet connection detected! Please find a connection and try again.");
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
popupBuilder.setView(myMsg);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PISDException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
|
import java.util.*;
import org.xbill.DNS.*;
public class lookup {
public static void
printAnswer(String name, Lookup lookup) {
System.out.print(name + ":");
int result = lookup.getResult();
if (result != Lookup.SUCCESSFUL)
System.out.print(" " + lookup.getErrorString());
System.out.println();
Name [] aliases = lookup.getAliases();
if (aliases.length > 0) {
System.out.print("# aliases: ");
for (int i = 0; i < aliases.length; i++) {
System.out.print(aliases[i]);
if (i < aliases.length - 1)
System.out.print(" ");
}
System.out.println();
}
if (lookup.getResult() == Lookup.SUCCESSFUL) {
Record [] answers = lookup.getAnswers();
for (int i = 0; i < answers.length; i++)
System.out.println(answers[i]);
}
}
public static void
main(String [] args) throws Exception {
int type = Type.A;
int start = 0;
if (args.length > 2 && args[0].equals("-t")) {
type = Type.value(args[1]);
if (type < 0)
throw new IllegalArgumentException("invalid type");
start = 2;
}
for (int i = start; i < args.length; i++) {
Lookup l = new Lookup(args[i], type);
l.run();
printAnswer(args[i], l);
}
}
}
|
package com.twistedmatrix.internet;
import java.util.ArrayList;
public class Deferred {
public static class AlreadyCalledError extends Error {
}
public static class Failure {
Throwable t;
public Failure(Throwable throwable) {
this.t = throwable;
}
public Throwable get() { return this.t; }
public Class trap(Class c) throws Throwable {
if (c.isInstance(this.t)) {
return c;
} else {
// XXX TODO: chain this Throwable, don't re-throw it.
throw this.t;
}
}
}
static class CallbackPair {
Callback callback;
Callback errback;
CallbackPair(Callback callback, Callback errback) {
if (null == callback) {
throw new Error("null callback");
}
if (null == errback) {
throw new Error("null errback");
}
this.callback = callback;
this.errback = errback;
}
}
/** A deferred callback is how most asynchronous events are handled.
* Callbacks generally return null unless you want to chanin them,
* in which the result of one callback is passed to the next. When
* adding an errBack, a Deferred.Failure is passed should something
* goes awry. A callback from AMP.callRemote is passed the response.
*/
public interface Callback<T> {
Object callback(T retval) throws Exception;
}
static class Passthru implements Callback {
public Object callback(Object obj) {
return obj;
}
}
public static final Callback passthru = new Passthru();
ArrayList<CallbackPair> callbacks;
Object result;
boolean calledYet;
int paused;
public Deferred() {
result = null;
calledYet = false;
paused = 0;
callbacks = new ArrayList<CallbackPair>();
}
public void pause() {
this.paused++;
}
public void unpause() {
this.paused
if (0 != this.paused) {
return;
}
if (this.calledYet) {
this.runCallbacks();
}
}
@SuppressWarnings("unchecked")
private void runCallbacks() {
if (0 == this.paused) {
ArrayList<CallbackPair> holder = this.callbacks;
this.callbacks = new ArrayList<CallbackPair>();
while (holder.size() != 0) {
CallbackPair cbp = holder.remove(0);
Callback theCallback;
if (this.result instanceof Failure) {
theCallback = cbp.errback;
} else {
theCallback = cbp.callback;
}
if (null == theCallback) {
throw new Error("null callback");
}
if (this.result instanceof Deferred) {
this.callbacks = holder;
} else {
try {
this.result = theCallback.callback(this.result);
} catch (Throwable t) {
// t.printStackTrace();
this.result = new Failure(t);
}
}
}
}
}
public void addCallbacks(Callback callback,
Callback errback) {
this.callbacks.add(new CallbackPair(callback, errback));
if (calledYet) {
this.runCallbacks();
}
}
public void addCallback(Callback callback) {
this.addCallbacks(callback, passthru);
}
public void addErrback(Callback<Failure> errback) {
this.addCallbacks(passthru, (Callback) errback);
}
public void addBoth(Callback callerrback) {
this.addCallbacks(callerrback, callerrback);
}
public void callback(Object result) {
if (calledYet) {
throw new AlreadyCalledError();
}
this.result = result;
this.calledYet = true;
runCallbacks();
}
public void errback(Failure result) {
callback(result);
}
public static Deferred succeed() {
Deferred self = new Deferred();
self.callback(null);
return self;
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.*;
import com.valkryst.VTerminal.font.Font;
import com.valkryst.VTerminal.misc.ImageCache;
import com.valkryst.VTerminal.misc.IntRange;
import com.valkryst.VTerminal.printer.RectanglePrinter;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.EventListener;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@ToString
public class Screen extends Component {
/** The panel on which the screen is displayed. */
@Getter @Setter private Panel parentPanel;
/** The non-layer components displayed on the screen. */
private Set<Component> components = new LinkedHashSet<>();
/** The layer components displayed on the screen. */
private Set<Layer> layerComponents = new LinkedHashSet<>();
/** The screen components displayed on the screen. */
private Set<Screen> screenComponents = new LinkedHashSet<>();
private ReentrantReadWriteLock componentsLock = new ReentrantReadWriteLock();
/**
* Constructs a new Screen.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public Screen(final @NonNull ScreenBuilder builder) {
super(builder);
setBackgroundColor(new Color(45, 45, 45, 255));
if (builder.getJsonObject() != null) {
parseJSON(builder.getJsonObject());
}
}
private void parseJSON(final @NonNull JSONObject jsonObject) {
final JSONArray components = (JSONArray) jsonObject.get("components");
if (components != null) {
for (final Object obj : components) {
final JSONObject arrayElement = (JSONObject) obj;
if (arrayElement != null) {
final ComponentBuilder componentBuilder = loadElementFromJSON(arrayElement, super.getRadio());
if (componentBuilder != null) {
if (componentBuilder instanceof LayerBuilder) {
layerComponents.add((Layer) componentBuilder.build());
} else {
this.components.add(componentBuilder.build());
}
}
}
}
}
}
private ComponentBuilder loadElementFromJSON(final @NonNull JSONObject jsonObject, final @NonNull Radio<String> radio) {
String componentType = (String) jsonObject.get("type");
if (componentType == null) {
return null;
}
componentType = componentType.toLowerCase();
switch (componentType) {
case "button": {
final ButtonBuilder buttonBuilder = new ButtonBuilder();
buttonBuilder.parse(jsonObject);
buttonBuilder.setRadio(radio);
return buttonBuilder;
}
case "check box": {
final CheckBoxBuilder checkBoxBuilder = new CheckBoxBuilder();
checkBoxBuilder.parse(jsonObject);
checkBoxBuilder.setRadio(radio);
return checkBoxBuilder;
}
case "label": {
final LabelBuilder labelBuilder = new LabelBuilder();
labelBuilder.parse(jsonObject);
labelBuilder.setRadio(radio);
return labelBuilder;
}
case "layer": {
final LayerBuilder layerBuilder = new LayerBuilder();
layerBuilder.parse(jsonObject);
layerBuilder.setRadio(radio);
return layerBuilder;
}
case "progress bar": {
final ProgressBarBuilder progressBarBuilder = new ProgressBarBuilder();
progressBarBuilder.parse(jsonObject);
progressBarBuilder.setRadio(radio);
return progressBarBuilder;
}
case "radio button": {
final RadioButtonBuilder radioButtonBuilder = new RadioButtonBuilder();
radioButtonBuilder.parse(jsonObject);
radioButtonBuilder.setRadio(radio);
return radioButtonBuilder;
}
case "radio button group": {
final RadioButtonGroup radioButtonGroup = new RadioButtonGroup();
final JSONArray radioButtons = (JSONArray) jsonObject.get("components");
if (radioButtons != null) {
for (final Object object : radioButtons) {
final JSONObject buttonJSON = (JSONObject) object;
final RadioButtonBuilder builder = (RadioButtonBuilder) loadElementFromJSON(buttonJSON, radio);
builder.setGroup(radioButtonGroup);
components.add(builder.build());
}
}
return null;
}
case "screen": {
final ScreenBuilder screenBuilder = new ScreenBuilder();
screenBuilder.parse(jsonObject);
screenBuilder.setRadio(radio);
return screenBuilder;
}
case "text field": {
final TextFieldBuilder textFieldBuilder = new TextFieldBuilder();
textFieldBuilder.parse(jsonObject);
textFieldBuilder.setRadio(radio);
return textFieldBuilder;
}
case "text area": {
final TextAreaBuilder textAreaBuilder = new TextAreaBuilder();
textAreaBuilder.parse(jsonObject);
textAreaBuilder.setRadio(radio);
return textAreaBuilder;
}
case "rectangle printer": {
final RectanglePrinter rectanglePrinter = new RectanglePrinter();
rectanglePrinter.printFromJSON(this, jsonObject);
return null;
}
default: {
throw new IllegalArgumentException("The element type '" + componentType + "' is not supported.");
}
}
}
@Override
public void draw(final @NonNull Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache) {
draw(gc, imageCache, getPosition());
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @param offset
* The x/y-axis (column/row) offsets to alter the position at which the
* screen is drawn.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache, final Point offset) {
componentsLock.readLock().lock();
// Draw non-layer components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
final AsciiString[] strings = super.getStrings();
final Thread threadA = new Thread(() -> {
for (int row = 0; row < getHeight() / 2; row++) {
strings[row].draw(gc, imageCache, row, offset);
}
});
final Thread threadB = new Thread(() -> {
for (int row = getHeight() / 2; row < getHeight(); row++) {
strings[row].draw(gc, imageCache, row, offset);
}
});
threadA.run();
threadB.run();
try {
threadA.join();
threadB.join();
} catch(final InterruptedException e) {
e.printStackTrace();
}
// Draw layer components onto the screen:
layerComponents.forEach(layer -> layer.draw(gc, imageCache, offset));
// Draw screen components onto the screen:
screenComponents.forEach(screen -> {
final Point position = screen.getPosition();
screen.draw(gc, imageCache, position);
});
componentsLock.readLock().unlock();
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point
* to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param position
* The x/y-axis (column/row) coordinates of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final Point position, int width, int height) {
boolean canProceed = isPositionValid(position);
canProceed &= width >= 0;
canProceed &= height >= 0;
if (canProceed) {
width += position.x;
height += position.y;
final Point writePosition = new Point(0, 0);
for (int column = position.x ; column < width ; column++) {
for (int row = position.y ; row < height ; row++) {
writePosition.setLocation(column, row);
write(character, writePosition);
}
}
}
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*/
public void clear(final char character) {
clear(character, new Point(0, 0), super.getWidth(), super.getHeight());
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinate to write to.
*
* @throws NullPointerException
* If the character is null.
*/
public void write(final @NonNull AsciiCharacter character, final Point position) {
if (isPositionValid(position)) {
super.getString(position.y).setCharacter(position.x, character);
}
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinates to write to.
*/
public void write(final char character, final Point position) {
if (isPositionValid(position)) {
super.getString(position.y).setCharacter(position.x, character);
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull AsciiString string, final Point position) {
if (isPositionValid(position)) {
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0; i < characters.length && i < super.getWidth(); i++) {
write(characters[i], new Point(position.x + i, position.y));
}
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull String string, final Point position) {
write(new AsciiString(string), position);
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a little different
* if there are blink effects or new updates to characters that haven't yet
* been drawn.
*
* This is an expensive operation as it essentially creates an in-memory
* screen and draws each AsciiCharacter onto that screen.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @return
* An image of the screen.
*
* @throws NullPointerException
* If the image cache is null.
*/
public BufferedImage screenshot(final @NonNull ImageCache imageCache) {
final Font font = imageCache.getFont();
final int width = this.getWidth() * font.getWidth();
final int height = this.getHeight() * font.getHeight();
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
draw(gc, imageCache);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setBackgroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setForegroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*
* @throws NullPointerException
* If the background or foreground color is null.
*/
public void setBackgroundAndForegroundColor(final @NonNull Color background, final @NonNull Color foreground) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(background);
string.setForegroundColor(foreground);
}
}
/**
* Adds a component to the screen and registers event listeners of the
* component, to the parent panel, if required.
*
* If the component is already present on the screen, then the component is
* not added.
*
* If the component is a screen and it has already been added to this screen,
* or any sub-screen of this screen, then the component is not added.
*
* @param component
* The component.
*/
public void addComponent(final Component component) {
componentsLock.writeLock().lock();
boolean containsComponent = containsComponent(component);
if (containsComponent) {
componentsLock.writeLock().unlock();
return;
}
// Add the component to one of the component lists:
if (component instanceof Screen) {
component.setScreen(this);
screenComponents.add((Screen) component);
} else if (component instanceof Layer) {
component.setScreen(this);
layerComponents.add((Layer) component);
} else {
component.setScreen(this);
components.add(component);
}
componentsLock.writeLock().unlock();
// Set up event listeners:
component.createEventListeners(parentPanel);
for (final EventListener eventListener : component.getEventListeners()) {
parentPanel.addListener(eventListener);
}
}
/**
* Adds one or more components to the screen.
*
* @param components
* The components.
*/
public void addComponents(final Component ... components) {
if (components == null) {
return;
}
for (final Component component : components) {
addComponent(component);
}
}
public void removeComponent(final Component component) {
componentsLock.writeLock().lock();
if (component == null) {
componentsLock.writeLock().unlock();
return;
}
if (component == this) {
componentsLock.writeLock().unlock();
throw new IllegalArgumentException("A screen cannot be removed from itself.");
}
if (component instanceof Screen) {
component.setScreen(null);
screenComponents.remove(component);
} else if (component instanceof Layer) {
component.setScreen(null);
layerComponents.remove(component);
} else {
component.setScreen(null);
components.remove(component);
}
componentsLock.writeLock().unlock();
for (final EventListener eventListener : component.getEventListeners()) {
parentPanel.removeListener(eventListener);
}
// Reset component's characters to empty cells.
final Point position = component.getPosition();
final IntRange redrawRange = new IntRange(position.x, position.x + component.getWidth());
for (int y = position.y ; y < position.y + component.getHeight() ; y++) {
final AsciiString string = super.getString(y);
string.setCharacters(' ', redrawRange);
string.setBackgroundColor(new Color(45, 45, 45, 255), redrawRange);
string.setForegroundColor(Color.WHITE, redrawRange);
string.setUnderlined(redrawRange, false);
string.setFlippedHorizontally(redrawRange, false);
string.setFlippedVertically(redrawRange, false);
}
}
/**
* Removes one or more components from the screen.
*
* @param components
* The components.
*/
public void removeComponents(final Component ... components) {
if (components == null) {
return;
}
for (final Component component : components) {
removeComponent(component);
}
}
/**
* Determines whether or not the screen contains a specific component.
*
* @param component
* The component.
*
* @return
* Whether or not the screen contains the component.
*/
public boolean containsComponent(final Component component) {
componentsLock.readLock().lock();
if (component == null) {
componentsLock.readLock().unlock();
return false;
}
if (component == this) {
componentsLock.readLock().unlock();
return false;
}
if (component instanceof Screen) {
if (screenComponents.contains(component)) {
componentsLock.readLock().unlock();
return true;
}
} else if (component instanceof Layer) {
if (layerComponents.contains(component)) {
componentsLock.readLock().unlock();
return true;
}
}
final boolean result = components.contains(component);
componentsLock.readLock().unlock();
return result;
}
/**
* Determines the total number of components.
*
* @return
* The total number of components.
*/
public int totalComponents() {
componentsLock.readLock().lock();
int sum = components.size();
sum += layerComponents.size();
sum += screenComponents.size();
componentsLock.readLock().unlock();
return sum;
}
/**
* Retrieves the first encountered component that uses the specified ID.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, the null is returned.
* Else the component is returned.
*/
public Component getComponentByID(final String id) {
componentsLock.readLock().lock();
for (final Component component : components) {
if (component.getId().equals(id)) {
componentsLock.readLock().unlock();
return component;
}
}
for (final Layer layer : layerComponents) {
if (layer.getId().equals(id)) {
componentsLock.readLock().unlock();
return layer;
}
}
for (final Screen screen : screenComponents) {
if (screen.getId().equals(id)) {
componentsLock.readLock().unlock();
return screen;
}
}
componentsLock.readLock().unlock();
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Button component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no button component matches the ID, then null is returned.
* Else the component is returned.
*/
public Button getButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Button) {
return (Button) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Check Box component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no check box component matches the ID, then null is returned.
* Else the component is returned.
*/
public CheckBox getCheckBoxByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof CheckBox) {
return (CheckBox) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Layer component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no layer component matches the ID, then null is returned.
* Else the component is returned.
*/
public Layer getLayerByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Layer) {
return (Layer) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* ProgressBar component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no progress bar component matches the ID, then null is returned.
* Else the component is returned.
*/
public ProgressBar getProgressBarByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof ProgressBar) {
return (ProgressBar) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* RadioButton component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no radio button component matches the ID, then null is returned.
* Else the component is returned.
*/
public RadioButton getRadioButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof RadioButton) {
return (RadioButton) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextArea component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text area component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextArea getTextAreaByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextArea) {
return (TextArea) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextField component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text field component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextField getTextFieldByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextField) {
return (TextField) component;
}
return null;
}
/**
* Retrieves a combined set of all components.
*
* @return
* A combined set of all components.
*/
public Set<Component> getComponents() {
componentsLock.readLock().lock();
final Set<Component> set = new LinkedHashSet<>(components);
set.addAll(layerComponents);
set.addAll(screenComponents);
componentsLock.readLock().unlock();
return set;
}
}
|
package tth;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
public class ThexOptimized
{
final int ZERO_BYTE_FILE = 0; //file with no data.
final int Block_Size = 64; //64k
final int Leaf_Size = 1024; //1k - don't change this.
private int Leaf_Count; //number of leafs.
private byte[][] HashValues; //array for hash values.
private FileInputStream FilePtr; //dest file stream pointer.
public byte[] GetTTH(String Filename) throws IOException {
byte[] TTH = null;
try
{
if (!new File(Filename).exists())
{
System.err.println("file doesn't exists " + Filename);
return null;
}
//open the file.
FilePtr = new FileInputStream(Filename);
//if the file is 0 byte long.
if (FilePtr.getChannel().size() == ZERO_BYTE_FILE)
{
Tiger TG = new Tiger();
TTH = TG.ComputeHash(new byte[] { 0 });
}
//the file is smaller then a single leaf.
else if (FilePtr.getChannel().size() <= Leaf_Size * Block_Size)
TTH = CompressSmallBlock();
//normal file.
else
{
Leaf_Count = (int)(FilePtr.getChannel().size() / Leaf_Size);
if (FilePtr.getChannel().size() % Leaf_Size > 0) Leaf_Count++;
GetLeafHash(); //get leafs hash from file.
System.err.println("===> [ Moving to internal hash. ]");
TTH = CompressHashBlock(HashValues, Leaf_Count); //get root TTH from hash array.
}
}
catch (Exception e)
{
System.err.println("error while trying to get TTH for file: " +
Filename + ". (" + e.getMessage() + ")");
TTH = null;
}
if (FilePtr != null) FilePtr.close();
return TTH;
}
private void GetLeafHash() throws IOException //gets the leafs from the file and hashes them.
{
int i;
int Blocks_Count = (int) Leaf_Count / (Block_Size * 2);
if (Leaf_Count % (Block_Size * 2) > 0) Blocks_Count++;
HashValues = new byte[Blocks_Count][];
byte[][] HashBlock = new byte[(int)Block_Size][];
for (i = 0; i < (int) Leaf_Count / (Block_Size * 2); i++) //loops threw the blocks.
{
for (int LeafIndex = 0; LeafIndex < (int) Block_Size; LeafIndex++) //creates new block.
HashBlock[LeafIndex] = GetNextLeafHash(); //extracts two leafs to a hash.
HashValues[i] = CompressHashBlock(HashBlock,Block_Size); //compresses the block to hash.
}
if (i < Blocks_Count) HashValues[i] = CompressSmallBlock(); //this block wasn't big enough.
Leaf_Count = Blocks_Count;
}
private byte[] GetNextLeafHash() throws IOException //reads 2 leafs from the file and returns their combined hash.
{
byte[] LeafA = new byte[Leaf_Size];
byte[] LeafB = new byte[Leaf_Size];
int DataSize = FilePtr.read(LeafA, 0, Leaf_Size);
//check if leaf is too small.
if (DataSize < Leaf_Size || FilePtr.getChannel().position() == FilePtr.getChannel().size()) {
return (LeafHash(ByteExtract(LeafA, DataSize)));
}
DataSize = FilePtr.read(LeafB,0,Leaf_Size);
if (DataSize < Leaf_Size)
LeafB = ByteExtract(LeafB,DataSize);
LeafA = LeafHash(LeafA);
LeafB = LeafHash(LeafB);
return InternalHash(LeafA,LeafB); //returns combined hash.
}
private byte[] CompressHashBlock(byte[][] HashBlock,int HashCount) //compresses hash blocks to hash.
{
if (HashBlock.length == 0) return null;
while (HashCount > 1) //until there's only 1 hash.
{
int TempBlockSize = (int) HashCount / 2;
if (HashCount % 2 > 0) TempBlockSize++;
byte[][] TempBlock = new byte[TempBlockSize][];
int HashIndex = 0;
for (int i = 0; i < (int) HashCount / 2; i++) //makes hash from pairs.
{
TempBlock[i] = InternalHash(HashBlock[HashIndex],HashBlock[HashIndex+1]);
HashIndex += 2;
}
//this one doesn't have a pair :(
if (HashCount % 2 > 0) TempBlock[TempBlockSize - 1] = HashBlock[HashCount - 1];
HashBlock = TempBlock;
HashCount = TempBlockSize;
}
return HashBlock[0];
}
private byte[] CompressSmallBlock() throws IOException //compress a small block to hash.
{
long DataSize = (long) (FilePtr.getChannel().size() - FilePtr.getChannel().position());
int LeafCount = (int) DataSize / (Leaf_Size * 2);
if (DataSize % (Leaf_Size * 2) > 0) LeafCount++;
byte[][] SmallBlock = new byte[LeafCount][];
//extracts leafs from file.
for (int i = 0; i < (int) DataSize / (Leaf_Size * 2); i++)
SmallBlock[i] = GetNextLeafHash();
if (DataSize % (Leaf_Size * 2) > 0) SmallBlock[LeafCount - 1] = GetNextLeafHash();
return CompressHashBlock(SmallBlock,LeafCount); //gets hash from the small block.
}
private byte[] InternalHash(byte[] LeafA,byte[] LeafB) //internal hash.
{
byte[] Data = new byte[LeafA.length + LeafB.length + 1];
Data[0] = 0x01; //internal hash mark.
//combines two leafs.
for (int i = 0; i < LeafA.length; i++) {
Data[i + 1] = LeafA[i];
}
for (int i = 0; i < LeafB.length; i++) {
Data[LeafA.length + 1 + i] = LeafB[i];
}
//gets tiger hash value for combined leaf hash.
Tiger TG = new Tiger();
TG.Initialize();
return TG.ComputeHash(Data);
}
private byte[] LeafHash(byte[] Raw_Data) //leaf hash.
{
byte[] Data = new byte[Raw_Data.length + 1];
Data[0] = 0x00; //leaf hash mark.
for (int i = 0; i < Raw_Data.length; i++) {
Data[i + 1] = Raw_Data[i];
}
//gets tiger hash value for leafs blocks.
Tiger TG = new Tiger();
TG.Initialize();
return TG.ComputeHash(Data);
}
private byte[] ByteExtract(byte[] Raw_Data,int Data_Length) //if we use the extra 0x00 in Raw_Data we will get wrong hash.
{
byte[] Data = new byte[Data_Length];
for (int i = 0; i < Data_Length; i++)
Data[i] = Raw_Data[i];
return Data;
}
public static void main(String[] args) {
ThexOptimized test = new ThexOptimized();
byte[] result;
Instant start;
Instant end;
try {
start = Instant.now();
result = test.GetTTH("C:\\Users\\Matthew\\Downloads\\Suits.S04E12.HDTV.x264-KILLERS[ettv]\\Suits.S04E12.HDTV.x264-KILLERS.mp4");
end = Instant.now();
System.out.println(Base32.encode(result));
System.out.println(Duration.between(start, end));
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package uk.org.opentrv.test.ETV;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.zip.GZIPInputStream;
import org.junit.Test;
import uk.org.opentrv.ETV.ETVPerHouseholdComputation.ETVPerHouseholdComputationInput;
import uk.org.opentrv.ETV.parse.NBulkInputs;
import uk.org.opentrv.ETV.parse.NBulkKWHParseByID;
import uk.org.opentrv.ETV.parse.OTLogActivityParse;
import uk.org.opentrv.ETV.parse.OTLogActivityParse.ValveLogParseResult;
import uk.org.opentrv.hdd.HDDUtil;
import uk.org.opentrv.test.hdd.DDNExtractorTest;
public class ETVParseTest
{
/**Sample 1 of bulk energy readings; too small a sample to extract a whole day's readings from. */
public static final String sampleN1 =
"house_id,received_timestamp,device_timestamp,energy,temperature\n" +
"1002,1456790560,1456790400,306.48,-3\n" +
"1002,1456791348,1456791300,306.48,-3\n" +
"1002,1456792442,1456792200,306.48,-3\n";
/**Test bulk gas meter parse basics. */
@Test public void testNBulkParseBasics() throws IOException
{
// Rudimentary test of bad-arg checking.
try { new NBulkKWHParseByID(-1, null); fail(); } catch(final IllegalArgumentException e) { }
// Check that just a header, or no matching entries, returns empty rather than an exception.
assertTrue(new NBulkKWHParseByID(0, new StringReader("house_id,received_timestamp,device_timestamp,energy,temperature")).getKWhByLocalDay().isEmpty());
// Check correct number of rows read with wrong/right ID chosen
// and only using data for full local-time day intervals.
assertEquals(0, new NBulkKWHParseByID(0, new StringReader(sampleN1)).getKWhByLocalDay().size());
assertEquals(0, new NBulkKWHParseByID(1002, new StringReader(sampleN1)).getKWhByLocalDay().size());
}
/**Name of the ETV sample bulk HDD data for EGLL. */
public static final String N_BULK_DATA_FORMAT_SAMPLE_CSV = "N-bulk-data-format-sample.csv";
/**Return a Reader for the ETV sample bulk HDD data for EGLL; never null. */
public static Reader getNBulk1CSVReader() throws IOException
{ return(HDDUtil.getASCIIResourceReader(ETVParseTest.class, N_BULK_DATA_FORMAT_SAMPLE_CSV)); }
/**Return a Supplier<Reader> for the ETV sample bulk HDD data for EGLL; never null. */
public static Supplier<Reader> NBulk1CSVReaderSupplier = HDDUtil.getASCIIResourceReaderSupplier(ETVParseTest.class, N_BULK_DATA_FORMAT_SAMPLE_CSV);
/**Test bulk gas meter parse on a more substantive sample. */
@Test public void testNBulkParse() throws IOException
{
// Check correct number of rows read with wrong/right ID chosen
// and only using data for full local-time day intervals.
assertEquals(0, new NBulkKWHParseByID(0, getNBulk1CSVReader()).getKWhByLocalDay().size());
final SortedMap<Integer, Float> kwhByLocalDay1002 = new NBulkKWHParseByID(1002, getNBulk1CSVReader()).getKWhByLocalDay();
assertEquals(1, kwhByLocalDay1002.size());
assertTrue(kwhByLocalDay1002.containsKey(20160301));
assertEquals(75.31f, kwhByLocalDay1002.get(20160301), 0.01f);
// Check correct ID extraction.
assertEquals(2, NBulkKWHParseByID.extractIDs(getNBulk1CSVReader()).size());
assertTrue(NBulkKWHParseByID.extractIDs(getNBulk1CSVReader()).contains(1001));
assertTrue(NBulkKWHParseByID.extractIDs(getNBulk1CSVReader()).contains(1002));
}
/**Name of the ETV sample bulk HDD data for EGLL. */
public static final String N_BULK_DATA_FORMAT_SAMPLE_CONCAT_CSV = "N-bulk-data-format-sample-concat.csv";
/**Return a Reader for the ETV sample bulk HDD data for EGLL; never null. */
public static Reader getNBulk1ConcatCSVReader() throws IOException
{ return(HDDUtil.getASCIIResourceReader(ETVParseTest.class, N_BULK_DATA_FORMAT_SAMPLE_CONCAT_CSV)); }
/**Test bulk gas meter parse on a more substantive sample of concatenated files. */
@Test public void testNBulkParseConcat() throws IOException
{
// Check correct number of rows read with wrong/right ID chosen
// and only using data for full local-time day intervals.
assertEquals(0, new NBulkKWHParseByID(0, getNBulk1ConcatCSVReader()).getKWhByLocalDay().size());
final SortedMap<Integer, Float> kwhByLocalDay1002 = new NBulkKWHParseByID(1002, getNBulk1CSVReader()).getKWhByLocalDay();
assertEquals(1, kwhByLocalDay1002.size());
assertTrue(kwhByLocalDay1002.containsKey(20160301));
assertEquals(75.31f, kwhByLocalDay1002.get(20160301), 0.01f);
// Check correct ID extraction.
assertEquals(2, NBulkKWHParseByID.extractIDs(getNBulk1CSVReader()).size());
assertTrue(NBulkKWHParseByID.extractIDs(getNBulk1CSVReader()).contains(1001));
assertTrue(NBulkKWHParseByID.extractIDs(getNBulk1CSVReader()).contains(1002));
}
/**Test bulk gas meter parse for multiple households at once. */
@Test public void testNBulkParseMulti() throws IOException
{
final Map<String, ETVPerHouseholdComputationInput> mhi =
NBulkInputs.gatherDataForAllHouseholds(
NBulk1CSVReaderSupplier,
DDNExtractorTest.getETVEGLLHDD2016H1CSVReader());
assertNotNull(mhi);
assertEquals(2, mhi.size());
assertTrue(mhi.containsKey("1001"));
assertTrue(mhi.containsKey("1002"));
assertEquals("1001", mhi.get("1001").getHouseID());
assertEquals("1002", mhi.get("1002").getHouseID());
}
/**Sample 2 of bulk energy readings; a few-days' values all at or close after midnight. */
public static final String sampleN2 =
"house_id,received_timestamp,device_timestamp,energy,temperature\n" +
"1002,1456790560,1456790400,306.48,-3\n" +
"1002,1456791348,1456791300,306.48,-3\n" +
"1002,1456877005,1456876800,381.79,-1\n" +
"1002,1456963400,1456963200,454.89,0\n" +
"1002,1457049600,1457049600,488.41,1\n" +
"1002,1457050500,1457050500,532.29,0\n";
/**Test that correct samples used when multiple eligible are present, for several days' data. */
@Test public void testNBulkParse2() throws IOException
{
// Check correct number of rows read with wrong/right ID chosen
// and only using data for full local-time day intervals.
assertEquals(0, new NBulkKWHParseByID(1001, new StringReader(sampleN2)).getKWhByLocalDay().size());
final SortedMap<Integer, Float> kwhByLocalDay1002 = new NBulkKWHParseByID(1002, new StringReader(sampleN2)).getKWhByLocalDay();
assertEquals(3, kwhByLocalDay1002.size());
// Check that the 00:00 samples are used
// even when other close/eligible ones are present.
assertTrue(kwhByLocalDay1002.containsKey(20160301));
assertEquals(75.31f, kwhByLocalDay1002.get(20160301), 0.01f);
assertTrue(kwhByLocalDay1002.containsKey(20160302));
assertEquals(73.1f, kwhByLocalDay1002.get(20160302), 0.01f);
assertTrue(kwhByLocalDay1002.containsKey(20160303));
assertEquals(33.52f, kwhByLocalDay1002.get(20160303), 0.01f);
// Check correct ID extraction.
assertEquals(1, NBulkKWHParseByID.extractIDs(new StringReader(sampleN2)).size());
assertEquals(1002, NBulkKWHParseByID.extractIDs(new StringReader(sampleN2)).iterator().next().intValue());
}
/**Sample 3 of bulk energy readings in UK; values around clocks going DST switch. */
public static final String sampleN3 =
"house_id,received_timestamp,device_timestamp,energy,temperature\n" +
"1002,1458864000,1458864000,10,0\n" + // TZ='Europe/London' date +%s --date='2016/03/25 00:00'
"1002,1458950400,1458950400,21,0\n" + // TZ='Europe/London' date +%s --date='2016/03/26 00:00'
"1002,1459036800,1459036800,33,0\n" + // TZ='Europe/London' date +%s --date='2016/03/27 00:00'
// Clocks go forward, so 23h interval here rather than usual 24h...
"1002,1459119600,1459119600,46,0\n" + // TZ='Europe/London' date +%s --date='2016/03/28 00:00'
// Offer up (wrong) 24h interval which should be ignored.
"1002,1459123200,1459123200,47,0\n"; // TZ='Europe/London' date +%s --date='2016/03/28 01:00'
// date --date='@2147483647'
// TZ='Europe/London' date
// date +%s
/**Test for correct behaviour around daylight-savings change.
* HDD runs local time midnight-to-midnight so the energy interval should do so too.
*/
@Test public void testNBulkParse3() throws IOException
{
// Check correct number of rows read with wrong/right ID chosen
// and only using data for full local-time day intervals.
assertEquals(0, new NBulkKWHParseByID(9999, new StringReader(sampleN3)).getKWhByLocalDay().size());
final SortedMap<Integer, Float> kwhByLocalDay1002 = new NBulkKWHParseByID(1002, new StringReader(sampleN3)).getKWhByLocalDay();
assertEquals(3, kwhByLocalDay1002.size());
// Check that the 00:00 samples are used
// even when other close/eligible ones are present.
assertTrue(kwhByLocalDay1002.containsKey(20160325));
assertEquals(11f, kwhByLocalDay1002.get(20160325), 0.01f);
assertTrue(kwhByLocalDay1002.containsKey(20160326));
assertEquals(12f, kwhByLocalDay1002.get(20160326), 0.01f);
assertTrue(kwhByLocalDay1002.containsKey(20160327));
assertEquals(13f, kwhByLocalDay1002.get(20160327), 0.01f);
}
/**Test for correct loading for a single household into input object. */
@Test public void testNBulkInputs() throws IOException
{
final ETVPerHouseholdComputationInput data = NBulkInputs.gatherData(1002, getNBulk1CSVReader(), DDNExtractorTest.getETVEGLLHDD201603CSVReader());
assertNotNull(data);
assertEquals("1002", data.getHouseID());
assertEquals(1, data.getKWhByLocalDay().size());
assertTrue(data.getKWhByLocalDay().containsKey(20160301));
assertEquals(75.31f, data.getKWhByLocalDay().get(20160301), 0.01f);
assertEquals(31, data.getHDDByLocalDay().size());
assertEquals(10.1f, data.getHDDByLocalDay().get(20160302), 0.01f);
assertEquals(7.9f, data.getHDDByLocalDay().get(20160329), 0.01f);
}
/**Return a stream for the ETV (ASCII) sample single-home bulk kWh consumption data; never null. */
public static InputStream getNBulkSHCSVStream()
{ return(ETVParseTest.class.getResourceAsStream("N-sample-GAS-2016-07.csv")); }
/**Return a Reader for the ETV sample single-home bulk HDD data for EGLL; never null. */
public static Reader getNBulkSHCSVReader() throws IOException
{ return(new InputStreamReader(getNBulkSHCSVStream(), "ASCII7")); }
/**Test for correct loading for a single household into input object from alternative bulk file. */
@Test public void testNBulkSHInputs() throws IOException
{
final ETVPerHouseholdComputationInput data = NBulkInputs.gatherData(5013, getNBulkSHCSVReader(), DDNExtractorTest.getETVEGLLHDD2016H1CSVReader());
assertNotNull(data);
assertEquals("5013", data.getHouseID());
assertEquals(187, data.getKWhByLocalDay().size());
assertEquals(182, data.getHDDByLocalDay().size());
assertTrue(data.getKWhByLocalDay().containsKey(20160216));
assertEquals(28.43f, data.getKWhByLocalDay().get(20160216), 0.01f);
assertTrue(data.getKWhByLocalDay().containsKey(20160319));
assertEquals(19.33f, data.getKWhByLocalDay().get(20160319), 0.01f);
// Data around DST switch.
assertEquals(17.10f, data.getKWhByLocalDay().get(20160320), 0.01f);
assertEquals(9.33f, data.getKWhByLocalDay().get(20160322), 0.01f);
assertEquals(10.11f, data.getKWhByLocalDay().get(20160325), 0.01f);
assertEquals(16.11f, data.getKWhByLocalDay().get(20160326), 0.015f); // Needs extra error margin...
assertEquals(9.00f, data.getKWhByLocalDay().get(20160327), 0.01f); // Spring forward...
assertEquals(12.66f, data.getKWhByLocalDay().get(20160328), 0.01f);
assertEquals(10.55f, data.getKWhByLocalDay().get(20160331), 0.01f);
}
/**Name of the ETV (ASCII) sample single-home bulk kWh consumption data all in 2016H1. */
public static final String N_SAMPLE_GAS_2016_06_CSV = "N-sample-GAS-2016-06.csv";
/**Return a Reader for the ETV sample bulk HDD data for EGLL; never null. */
public static Reader getNBulkSH2016H1CSVReader() throws IOException
{ return(HDDUtil.getASCIIResourceReader(ETVParseTest.class, N_SAMPLE_GAS_2016_06_CSV)); }
/**Return a Supplier<Reader> for the ETV sample bulk HDD data for EGLL; never null. */
public static Supplier<Reader> NBulkSH2016H1CSVReaderSupplier = HDDUtil.getASCIIResourceReaderSupplier(ETVParseTest.class, N_SAMPLE_GAS_2016_06_CSV);
/**Test for correct loading for a single household into input object from alternative bulk file (2016H1). */
@Test public void testNBulkSH2016HCInputs() throws IOException
{
final ETVPerHouseholdComputationInput data = NBulkInputs.gatherData(5013, getNBulkSH2016H1CSVReader(), DDNExtractorTest.getETVEGLLHDD2016H1CSVReader());
assertNotNull(data);
assertEquals("5013", data.getHouseID());
assertEquals(156, data.getKWhByLocalDay().size());
assertEquals(182, data.getHDDByLocalDay().size());
assertTrue(data.getKWhByLocalDay().containsKey(20160216));
assertEquals(28.43f, data.getKWhByLocalDay().get(20160216), 0.01f);
assertTrue(data.getKWhByLocalDay().containsKey(20160630));
assertFalse(data.getKWhByLocalDay().containsKey(20160701)); // Data runs up to 20160630.
}
/**Test bulk gas meter parse via multi-household route. */
@Test public void testNBulkSHMultiInputs() throws IOException
{
final Map<String, ETVPerHouseholdComputationInput> mhi =
NBulkInputs.gatherDataForAllHouseholds(
NBulkSH2016H1CSVReaderSupplier,
DDNExtractorTest.getETVEGLLHDD2016H1CSVReader());
assertNotNull(mhi);
assertEquals(1, mhi.size());
assertTrue(mhi.containsKey("5013"));
assertEquals("5013", mhi.get("5013").getHouseID());
}
/**Test bulk multi-household reader. */
@Test public void testNBulkMultiInputs() throws IOException
{
final Map<String, ETVPerHouseholdComputationInput> mhi =
NBulkInputs.gatherDataForAllHouseholds(
NBulk1CSVReaderSupplier,
DDNExtractorTest.getETVEGLLHDD2016H1CSVReader());
assertNotNull(mhi);
assertEquals(2, mhi.size());
assertTrue(mhi.containsKey("1001"));
assertTrue(mhi.containsKey("1002"));
assertEquals("1001", mhi.get("1001").getHouseID());
assertEquals("1002", mhi.get("1002").getHouseID());
}
/**Single valve log entry in canonical format. */
public static final String cValveLogSample =
"[ \"2016-03-31T05:18:45Z\", \"\", {\"@\":\"3015\",\"+\":1,\"v|%\":0,\"tT|C\":14,\"tS|C\":4} ]";
/**Single valve log entry in partially-decrypted format. */
public static final String pdValveLogSample =
|
package jdbm.helper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Serialization-related utility methods.
*
* @author <a href="mailto:boisvert@intalio.com">Alex Boisvert</a>
* @version $Id: Serialization.java,v 1.1 2002/05/31 06:33:20 boisvert Exp $
*/
public final class Serialization
{
/**
* Serialize the object into a byte array.
*/
public static byte[] serialize( Object obj )
throws IOException
{
ByteArrayOutputStream baos;
ObjectOutputStream oos;
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream( baos );
oos.writeObject( obj );
oos.close();
byte[] res = baos.toByteArray();
return res;
}
/**
* Deserialize an object from a byte array
*/
public static Object deserialize( byte[] buf )
throws ClassNotFoundException, IOException
{
ByteArrayInputStream bais;
ObjectInputStream ois;
bais = new ByteArrayInputStream( buf );
ois = new ObjectInputStream( bais );
return ois.readObject();
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.io;
import jodd.util.StringUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
class FileUtilTest {
protected String dataRoot;
protected String utfdataRoot;
@BeforeEach
void setUp() throws Exception {
if (dataRoot != null) {
return;
}
URL data = FileUtilTest.class.getResource("data");
dataRoot = data.getFile();
data = FileUtilTest.class.getResource("utf");
utfdataRoot = data.getFile();
}
@Test
void testFileManipulation() throws IOException {
FileUtil.copy(new File(dataRoot, "sb.data"), new File(dataRoot, "sb1.data"));
assertFalse(FileUtil.isNewer(new File(dataRoot, "sb.data"), new File(dataRoot, "sb1.data")));
assertFalse(FileUtil.isOlder(new File(dataRoot, "sb.data"), new File(dataRoot, "sb1.data")));
FileUtil.delete(new File(dataRoot, "sb1.data"));
}
@Test
void testString() {
String s = "This is a test file\nIt only has\nthree lines!!";
try {
FileUtil.writeString(new File(dataRoot, "test.txt"), s);
} catch (Exception ex) {
fail("FileUtil.writeString " + ex.toString());
}
String s2 = null;
try {
s2 = FileUtil.readString(dataRoot + "/test.txt");
} catch (Exception ex) {
fail("FileUtil.readString " + ex.toString());
}
assertEquals(s, s2);
// test unicode chars (i.e. greater then 255)
char[] buf = s.toCharArray();
buf[0] = 256;
s = new String(buf);
try {
FileUtil.writeString(dataRoot + "/test.txt", s);
} catch (Exception ex) {
fail("FileUtil.writeString " + ex.toString());
}
try {
s2 = FileUtil.readString(dataRoot + "/test.txt");
} catch (Exception ex) {
fail("FileUtil.readString " + ex.toString());
}
assertEquals(s.substring(1), s2.substring(1));
assertEquals(s.charAt(0), s2.charAt(0));
try {
FileUtil.delete(dataRoot + "/test.txt");
} catch (IOException ioex) {
fail("FileUtil.delete" + ioex.toString());
}
}
@Test
void testUnicodeString() {
String s = "This is a test file\nIt only has\nthree lines!!";
char[] buf = s.toCharArray();
buf[0] = 256;
s = new String(buf);
try {
FileUtil.writeString(dataRoot + "/test2.txt", s, "UTF-16");
} catch (Exception ex) {
fail("FileUtil.writeString " + ex.toString());
}
String s2 = null;
try {
s2 = FileUtil.readString(dataRoot + "/test2.txt", "UTF-16");
} catch (Exception ex) {
fail("FileUtil.readString " + ex.toString());
}
assertEquals(s, s2);
try {
FileUtil.delete(dataRoot + "/test2.txt");
} catch (IOException ioex) {
fail("FileUtil.delete" + ioex.toString());
}
}
@Test
void testFileManipulations() {
String root = dataRoot + "/file/";
String tmp = root + "tmp/";
String tmp2 = root + "xxx/";
String tmp3 = root + "zzz/";
// copy
try {
FileUtil.copyFile(root + "a.txt", root + "w.txt");
FileUtil.copyFile(root + "a.png", root + "w.png");
FileUtil.copyFile(root + "a.txt", root + "w.txt");
} catch (IOException ioex) {
fail(ioex.toString());
}
// mkdirs
try {
FileUtil.mkdir(tmp);
FileUtil.mkdirs(tmp + "x/");
FileUtil.copyFileToDir(root + "a.txt", tmp);
FileUtil.copyFileToDir(root + "a.png", tmp);
} catch (IOException ioex) {
fail(ioex.toString());
}
// don't overwrite
try {
FileUtil.copyFileToDir(root + "a.txt", tmp, FileUtil.params().setOverwrite(false));
fail("copy file don't overwrite");
} catch (IOException e) {
// ignore
}
// move
try {
FileUtil.moveFile(root + "w.txt", tmp + "w.txt");
FileUtil.moveFileToDir(root + "w.png", tmp);
} catch (IOException ioex) {
fail(ioex.toString());
}
try {
FileUtil.moveFileToDir(root + "w.png", tmp, FileUtil.cloneParams().setOverwrite(false));
fail("move file don't overwrite");
} catch (IOException e) {
// ignore
}
// delete
try {
FileUtil.deleteFile(tmp + "a.txt");
FileUtil.deleteFile(tmp + "a.png");
FileUtil.deleteFile(tmp + "w.txt");
FileUtil.deleteFile(tmp + "w.png");
} catch (IOException ioex) {
fail(ioex.toString());
}
try {
FileUtil.deleteFile(tmp + "a.txt");
fail("delete file strict delete");
} catch (IOException e) {
// ignore
}
// movedir
try {
FileUtil.moveDir(tmp, tmp2);
} catch (IOException ioex) {
fail(ioex.toString());
}
// copyDir
try {
FileUtil.copyDir(tmp2, tmp3);
} catch (IOException ioex) {
fail(ioex.toString());
}
// deleteDir
try {
FileUtil.deleteDir(tmp2);
FileUtil.deleteDir(tmp3);
} catch (IOException ioex) {
fail(ioex.toString());
}
}
@Test
void testBytes() {
try {
File file = new File(dataRoot + "/file/a.txt");
byte[] bytes = FileUtil.readBytes(dataRoot + "/file/a.txt");
assertEquals(file.length(), bytes.length);
String content = new String(bytes);
content = StringUtil.remove(content, '\r');
assertEquals("test file\n", content);
} catch (IOException ioex) {
fail(ioex.toString());
}
}
@Test
void testUTFReads() throws IOException {
String content = FileUtil.readUTFString(new File(utfdataRoot, "utf-8.txt"));
content = content.replace("\r\n", "\n");
String content8 = FileUtil.readString(new File(utfdataRoot, "utf-8.txt"), "UTF-8");
content8 = content8.replace("\r\n", "\n");
assertEquals(content, content8);
String content1 = FileUtil.readUTFString(new File(utfdataRoot, "utf-16be.txt"));
content1 = content1.replace("\r\n", "\n");
assertEquals(content, content1);
String content16 = FileUtil.readString(new File(utfdataRoot, "utf-16be.txt"), "UTF-16BE");
content16 = content16.replace("\r\n", "\n");
assertEquals(content, content16);
String content162 = FileUtil.readString(new File(utfdataRoot, "utf-16be.txt"), "UTF-16");
content162 = content162.replace("\r\n", "\n");
assertEquals(content, content162);
String content2 = FileUtil.readUTFString(new File(utfdataRoot, "utf-16le.txt"));
content2 = content2.replace("\r\n", "\n");
assertEquals(content, content2);
String content163 = FileUtil.readString(new File(utfdataRoot, "utf-16le.txt"), "UTF-16LE");
content163 = content163.replace("\r\n", "\n");
assertEquals(content, content163);
}
@ParameterizedTest (name = "{index} : FileUtil
@CsvSource(
{
"md5, 529a2cfd3346c7fe17b845b6ec90fcfd",
"sha1, 7687b985b2eeff4a981480cead1787bd3f26929c",
"sha256, b2a3dec0059df342e9b33721957fd54221ab7fb7daa99d9f35af729dc2568e51",
"sha384, 1eb67f4b35ae69bbd815dbceee9584c9a65b82e8a209b0a3ab9e6def0a74cf5915228ce32f6154ba5c9ee6dfc66f6414",
"sha512, 4b53d8ca344fc63dd0a69b2ef4c5275279b4c31a834d5e0501a0ab646d1cc56f15e45a019e3f46597be288924b8b6fba19e4ebad1552f5007d56e7f12c3cb1d2"
}
)
@DisplayName(value = "tests for digest-algorithms")
void testDigestAlgorithms(final String method, final String expected) throws Exception {
Method declaredMethod = FileUtil.class.getMethod(method, File.class);
File file = new File(FileUtilTest.class.getResource("data/file/a.png").toURI());
final String actual = (String) declaredMethod.invoke(null, file);
// asserts
assertEquals(expected, actual.toLowerCase());
}
}
|
package com.github.fhirschmann.clozegen.lib.generators;
import com.github.fhirschmann.clozegen.lib.generators.api.Gap;
import com.github.fhirschmann.clozegen.lib.generators.model.CollocationModel;
import com.github.fhirschmann.clozegen.lib.generators.api.GapGenerator;
import com.github.fhirschmann.clozegen.lib.util.CollectionUtils;
import com.github.fhirschmann.clozegen.lib.util.MiscUtils;
import com.github.fhirschmann.clozegen.lib.util.MultisetUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Lists;
import org.javatuples.Triplet;
/**
* Generates gaps based on collocations.
*
* <p>This implementation is based on the paper
* <i>Automatic Generation of Cloze Items for Prepositions</i> [1]
* by Lee et all.
*
* <p>[1] <b>J. Lee and S. Seneff</b>.<br/>
* Automatic generation of cloze items for prepositions.<br/>
* <i>In Eight Annual Conference of the International Speech Communication
* Association, 2007</i>.
*
* @author Fabian Hirschmann <fabian@hirschm.net>
*/
public class CollocationGapGenerator implements GapGenerator {
/** The model for this generator. */
private CollocationModel model;
/** The triplet (A, x, B) where x is the subject in question. */
private Triplet<String, String, String> triplet;
/**
* Creates a new collocation-based gap generator. The <code>tuple</code>
* must have an odd number of elements and the element in the middle of the
* list is the word a gap is generated for.
*
* @param tuple the tuple of words
* @param model the model for this generator
*/
public CollocationGapGenerator(final List<String> tuple,
final CollocationModel model) {
this.model = checkNotNull(model);
triplet = CollectionUtils.triListJoin(tuple);
}
/**
* Creates a new collocation-based gap generator.
*
* @param head a in (head, x, tail)
* @param x x in (head, x, tail)
* @param tail tail in (head, x, tail)
* @param model the model for this generator
*/
public CollocationGapGenerator(final String head, final String x, final String tail,
final CollocationModel model) {
this(Lists.newArrayList(head, x, tail), model);
}
@Override
public Gap generate(final int count) {
Gap gap = new Gap();
gap.addValidAnswers(triplet.getValue1());
// Collect a list of possible candidates for this gap
final Multiset<String> candidates = ConcurrentHashMultiset.create(
MultisetUtils.mergeMultiSets(model.getTails().get(triplet.getValue2()),
model.getHeads().get(triplet.getValue0())));
// Remove candidates p* which appear in the context (A, p*, B)
for (Entry<String> entry : candidates.entrySet()) {
if (model.getMultiset().contains(MiscUtils.WS_JOINER.join(
triplet.getValue0(), entry.getElement(), triplet.getValue2()))) {
candidates.remove(entry.getElement(), entry.getCount());
}
}
// Remove the correct answer from the candidate set
candidates.remove(triplet.getValue0(), candidates.count(triplet.getValue0()));
if (candidates.elementSet().size() > count - 2) {
final Set<String> invalidAnswers = Sets.newHashSet(
MultisetUtils.sortedElementList(candidates, count - 1));
gap.addInvalidAnswers(invalidAnswers);
} else {
gap = null;
}
return gap;
}
@Override
public String toString() {
final ToStringHelper str = Objects.toStringHelper(this);
str.add("tuple", triplet.toString());
str.add("model", model.toString());
return str.toString();
}
}
|
package org.libreplan.web.expensesheet;
import static org.libreplan.web.I18nHelper._;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.LogFactory;
import org.joda.time.LocalDate;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.common.exceptions.ValidationException;
import org.libreplan.business.expensesheet.entities.ExpenseSheet;
import org.libreplan.business.expensesheet.entities.ExpenseSheetLine;
import org.libreplan.business.orders.entities.Order;
import org.libreplan.business.orders.entities.OrderElement;
import org.libreplan.business.resources.entities.Resource;
import org.libreplan.business.users.entities.UserRole;
import org.libreplan.web.common.BaseCRUDController;
import org.libreplan.web.common.Level;
import org.libreplan.web.common.Util;
import org.libreplan.web.common.components.bandboxsearch.BandboxSearch;
import org.libreplan.web.common.entrypoints.IURLHandlerRegistry;
import org.libreplan.web.common.entrypoints.MatrixParameters;
import org.libreplan.web.security.SecurityUtils;
import org.libreplan.web.users.services.CustomTargetUrlResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.CheckEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Decimalbox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.Textbox;
/**
* Controller for CRUD actions over a {@link ExpenseSheet}
*
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class ExpenseSheetCRUDController extends
BaseCRUDController<ExpenseSheet> implements IExpenseSheetCRUDController {
private static final org.apache.commons.logging.Log LOG = LogFactory
.getLog(ExpenseSheetCRUDController.class);
@Autowired
private IExpenseSheetModel expenseSheetModel;
/*
* components editWindow
*/
private Datebox dateboxExpenseDate;
private Grid gridExpenseLines;
private BandboxSearch bandboxTasks;
private Decimalbox dboxValue;
private BandboxSearch bandboxResource;
private Textbox tbConcept;
private ExpenseSheetLineRenderer expenseSheetLineRenderer = new ExpenseSheetLineRenderer();
private IURLHandlerRegistry URLHandlerRegistry;
private boolean fromUserDashboard = false;
private boolean cancel = false;
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
checkUserHasProperRoleOrSendForbiddenCode();
URLHandlerRegistry.getRedirectorFor(IExpenseSheetCRUDController.class)
.register(this, page);
}
private void checkUserHasProperRoleOrSendForbiddenCode() throws IOException {
HttpServletRequest request = (HttpServletRequest) Executions
.getCurrent().getNativeRequest();
Map<String, String> matrixParams = MatrixParameters.extract(request);
// If it doesn't come from a entry point
if (matrixParams.isEmpty()) {
if (!SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_EXPENSES)) {
HttpServletResponse response = (HttpServletResponse) Executions
.getCurrent().getNativeResponse();
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
}
@Override
public void save() throws ValidationException {
expenseSheetModel.confirmSave();
}
@Override
protected void beforeSaving() throws ValidationException {
super.beforeSaving();
expenseSheetModel.generateExpenseSheetLineCodesIfIsNecessary();
}
private void loadComponentsEditWindow() {
tbConcept = (Textbox) editWindow.getFellowIfAny("tbConcept");
dateboxExpenseDate = (Datebox) editWindow.getFellowIfAny("dateboxExpenseDate");
dboxValue = (Decimalbox) editWindow.getFellowIfAny("dboxValue");
gridExpenseLines = (Grid) editWindow.getFellowIfAny("gridExpenseLines");
bandboxResource = (BandboxSearch) editWindow.getFellowIfAny("bandboxResource");
bandboxTasks = (BandboxSearch) editWindow.getFellowIfAny("bandboxTasks");
}
/*
* Operations in the list window
*/
public List<ExpenseSheet> getExpenseSheets() {
return expenseSheetModel.getExpenseSheets();
}
/*
* Operations in the create window
*/
public ExpenseSheet getExpenseSheet() {
return expenseSheetModel.getExpenseSheet();
}
public SortedSet<ExpenseSheetLine> getExpenseSheetLines() {
return expenseSheetModel.getExpenseSheetLines();
}
/**
* Adds a new {@link ExpenseSheetLine} to the list of rows
*
* @param rows
*/
public void addExpenseSheetLine() {
if (validateNewLine()) {
expenseSheetModel.addExpenseSheetLine();
reloadExpenseSheetLines();
reloadComponentsNewLine();
}
}
private void reloadComponentsNewLine() {
Util.reloadBindings(bandboxTasks);
Util.reloadBindings(bandboxResource);
Util.reloadBindings(tbConcept);
Util.reloadBindings(dboxValue);
}
private boolean validateNewLine() {
boolean result = true;
if (expenseSheetModel.getNewExpenseSheetLine().getDate() == null) {
result = false;
throw new WrongValueException(this.dateboxExpenseDate, _("must be not empty"));
}
if (expenseSheetModel.getNewExpenseSheetLine().getOrderElement() == null) {
result = false;
throw new WrongValueException(this.bandboxTasks, _("must be not empty"));
}
BigDecimal value = expenseSheetModel.getNewExpenseSheetLine().getValue();
if (value == null || value.compareTo(BigDecimal.ZERO) < 0) {
result = false;
throw new WrongValueException(this.dboxValue,
_("must be not empty and greater or equal than zero"));
}
return result;
}
public void confirmRemove(ExpenseSheetLine expenseSheetLine) {
try {
int status = Messagebox.show(
_("Confirm deleting {0}. Are you sure?",
getExpenseSheetLineName(expenseSheetLine)), _("Delete"), Messagebox.OK
| Messagebox.CANCEL, Messagebox.QUESTION);
if (Messagebox.OK == status) {
removeExpenseSheetLine(expenseSheetLine);
}
} catch (InterruptedException e) {
messagesForUser.showMessage(Level.ERROR, e.getMessage());
LOG.error(_("Error on showing removing element: ", expenseSheetLine.getId()), e);
}
}
private void removeExpenseSheetLine(ExpenseSheetLine expenseSheetLine) {
expenseSheetModel.removeExpenseSheetLine(expenseSheetLine);
reloadExpenseSheetLines();
}
private String getExpenseSheetLineName(ExpenseSheetLine expenseSheetLine) {
if (expenseSheetLine != null) {
LocalDate date = expenseSheetLine.getDate();
OrderElement task = expenseSheetLine.getOrderElement();
if (date != null && task != null) {
return _("expense line of the ") + task.getName() + " - " + date;
}
}
return _("item");
}
private void reloadExpenseSheetLines() {
if (gridExpenseLines != null) {
Util.reloadBindings(gridExpenseLines);
}
}
public void onCheckGenerateCode(Event e) {
CheckEvent ce = (CheckEvent) e;
if (ce.isChecked()) {
// we have to auto-generate the code for new objects
try {
expenseSheetModel.setCodeAutogenerated(ce.isChecked());
} catch (ConcurrentModificationException err) {
messagesForUser.showMessage(Level.ERROR, err.getMessage());
}
}
Util.reloadBindings(editWindow);
reloadExpenseSheetLines();
}
public ExpenseSheetLine getNewExpenseSheetLine() {
return expenseSheetModel.getNewExpenseSheetLine();
}
public List<Order> getOrders() {
return expenseSheetModel.getOrders();
}
public List<OrderElement> getTasks() {
return expenseSheetModel.getTasks();
}
public void setProject(Order project) {
expenseSheetModel.setSelectedProject(project);
Util.reloadBindings(bandboxTasks);
}
public Order getProject() {
return expenseSheetModel.getSelectedProject();
}
public ExpenseSheetLineRenderer getExpenseSheetLineRenderer() {
return expenseSheetLineRenderer;
}
/**
* RowRenderer for a @{ExpenseSheetLine} element
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class ExpenseSheetLineRenderer implements RowRenderer {
@Override
public void render(Row row, Object data) {
ExpenseSheetLine expenseSheetLine = (ExpenseSheetLine) data;
row.setValue(expenseSheetLine);
appendOrderElementInLines(row);
appendValueInLines(row);
appendConceptInLines(row);
appendDateInLines(row);
appendResourceInLines(row);
appendCode(row);
appendDeleteButton(row);
}
private void appendConceptInLines(Row row) {
final ExpenseSheetLine expenseSheetLine = (ExpenseSheetLine) row.getValue();
final Textbox txtConcept = new Textbox();
txtConcept.setWidth("160px");
Util.bind(txtConcept, new Util.Getter<String>() {
@Override
public String get() {
if (expenseSheetLine != null) {
return expenseSheetLine.getConcept();
}
return "";
}
}, new Util.Setter<String>() {
@Override
public void set(String value) {
if (expenseSheetLine != null) {
expenseSheetLine.setConcept(value);
}
}
});
row.appendChild(txtConcept);
}
private void appendDateInLines(Row row) {
final ExpenseSheetLine expenseSheetLine = (ExpenseSheetLine) row.getValue();
final Datebox dateboxExpense = new Datebox();
Util.bind(dateboxExpense, new Util.Getter<Date>() {
@Override
public Date get() {
if (expenseSheetLine != null) {
if (expenseSheetLine.getDate() != null) {
return expenseSheetLine.getDate().toDateTimeAtStartOfDay().toDate();
}
}
return null;
}
}, new Util.Setter<Date>() {
@Override
public void set(Date value) {
if (expenseSheetLine != null) {
LocalDate newDate = null;
if (value != null) {
newDate = LocalDate.fromDateFields(value);
}
expenseSheetModel.keepSortedExpenseSheetLines(expenseSheetLine,
newDate);
reloadExpenseSheetLines();
}
}
});
dateboxExpense.setConstraint("no empty:" + _("cannot be null or empty"));
row.appendChild(dateboxExpense);
}
private void appendResourceInLines(Row row) {
final ExpenseSheetLine expenseSheetLine = (ExpenseSheetLine) row.getValue();
final BandboxSearch bandboxSearch = BandboxSearch.create(
"ResourceInExpenseSheetBandboxFinder");
bandboxSearch.setSelectedElement(expenseSheetLine.getResource());
bandboxSearch.setSclass("bandbox-workreport-task");
bandboxSearch.setListboxWidth("450px");
EventListener eventListenerUpdateResource = new EventListener() {
@Override
public void onEvent(Event event) {
Listitem selectedItem = bandboxSearch.getSelectedItem();
setResourceInESL(selectedItem, expenseSheetLine);
}
};
bandboxSearch.setListboxEventListener(Events.ON_SELECT, eventListenerUpdateResource);
bandboxSearch.setListboxEventListener(Events.ON_OK, eventListenerUpdateResource);
bandboxSearch.setBandboxEventListener(Events.ON_CHANGING, eventListenerUpdateResource);
row.appendChild(bandboxSearch);
}
private void appendCode(final Row row) {
final ExpenseSheetLine line = (ExpenseSheetLine) row.getValue();
final Textbox code = new Textbox();
code.setWidth("170px");
code.setDisabled(getExpenseSheet().isCodeAutogenerated());
code.applyProperties();
if (line.getCode() != null) {
code.setValue(line.getCode());
}
code.addEventListener("onChange", new EventListener() {
@Override
public void onEvent(Event event) {
final ExpenseSheetLine line = (ExpenseSheetLine) row.getValue();
line.setCode(code.getValue());
}
});
code.setConstraint(checkConstraintLineCodes(line));
row.appendChild(code);
}
private void appendDeleteButton(final Row row) {
Button delete = new Button("", "/common/img/ico_borrar1.png");
delete.setHoverImage("/common/img/ico_borrar.png");
delete.setSclass("icono");
delete.setTooltiptext(_("Delete"));
delete.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event event) {
confirmRemove((ExpenseSheetLine) row.getValue());
}
});
row.appendChild(delete);
}
private void appendValueInLines(Row row) {
final ExpenseSheetLine expenseSheetLine = (ExpenseSheetLine) row.getValue();
final Decimalbox dbValue = new Decimalbox();
dbValue.setScale(2);
Util.bind(dbValue, new Util.Getter<BigDecimal>() {
@Override
public BigDecimal get() {
if (expenseSheetLine != null) {
return expenseSheetLine.getValue();
}
return BigDecimal.ZERO.setScale(2);
}
}, new Util.Setter<BigDecimal>() {
@Override
public void set(BigDecimal value) {
if (expenseSheetLine != null) {
expenseSheetLine.setValue(value);
}
}
});
dbValue.setConstraint(checkConstraintExpenseValue());
dbValue.setFormat(Util.getMoneyFormat());
row.appendChild(dbValue);
}
/**
* Append a Bandbox @{link OrderElement} to row
*
* @param row
*/
private void appendOrderElementInLines(Row row) {
final ExpenseSheetLine expenseSheetLine = (ExpenseSheetLine) row.getValue();
final BandboxSearch bandboxSearch = BandboxSearch
.create("OrderElementInExpenseSheetBandboxFinder");
bandboxSearch.setSelectedElement(expenseSheetLine.getOrderElement());
bandboxSearch.setSclass("bandbox-workreport-task");
bandboxSearch.setListboxWidth("450px");
EventListener eventListenerUpdateOrderElement = new EventListener() {
@Override
public void onEvent(Event event) {
Listitem selectedItem = bandboxSearch.getSelectedItem();
setOrderElementInESL(selectedItem, expenseSheetLine);
}
};
bandboxSearch
.setListboxEventListener(Events.ON_SELECT, eventListenerUpdateOrderElement);
bandboxSearch.setListboxEventListener(Events.ON_OK, eventListenerUpdateOrderElement);
bandboxSearch.setBandboxEventListener(Events.ON_CHANGING,
eventListenerUpdateOrderElement);
bandboxSearch.setBandboxConstraint("no empty:" + _("cannot be null or empty"));
row.appendChild(bandboxSearch);
}
private void setOrderElementInESL(Listitem selectedItem, ExpenseSheetLine line) {
OrderElement orderElement = (selectedItem == null ? null : (OrderElement) selectedItem
.getValue());
line.setOrderElement(orderElement);
}
private void setResourceInESL(Listitem selectedItem,
ExpenseSheetLine expenseSheetLine) {
Resource resource = (selectedItem == null ? null : (Resource) selectedItem.getValue());
expenseSheetLine.setResource(resource);
}
}
public Constraint checkConstraintExpenseValue() {
return new Constraint() {
@Override
public void validate(Component comp, Object value) throws WrongValueException {
BigDecimal expenseValue = (BigDecimal) value;
if (expenseValue == null || expenseValue.compareTo(BigDecimal.ZERO) < 0) {
throw new WrongValueException(comp, _("must be greater or equal than 0"));
}
}
};
}
public Constraint checkConstraintLineCodes(final ExpenseSheetLine line) {
return new Constraint() {
@Override
public void validate(Component comp, Object value) throws WrongValueException {
if (!getExpenseSheet().isCodeAutogenerated()) {
String code = (String) value;
if (code == null || code.isEmpty()) {
throw new WrongValueException(comp, _("The code cannot be empty."));
} else {
String oldCode = line.getCode();
line.setCode(code);
if (!getExpenseSheet().checkConstraintNonRepeatedExpenseSheetLinesCodes()) {
line.setCode(oldCode);
throw new WrongValueException(comp, _("The code must be unique."));
}
}
}
}
};
}
public Constraint checkConstraintExpendeCode() {
return new Constraint() {
@Override
public void validate(Component comp, Object value) throws WrongValueException {
if (!getExpenseSheet().isCodeAutogenerated()) {
String code = (String) value;
if (code == null || code.isEmpty()) {
throw new WrongValueException(comp,
_("The code cannot be empty and it must be unique."));
} else if (!getExpenseSheet().checkConstraintUniqueCode()) {
throw new WrongValueException(comp,
_("it already exists another expense sheet with the same code."));
}
}
}
};
}
public Date getExpenseSheetLineDate() {
if (expenseSheetModel.getNewExpenseSheetLine() != null) {
return (expenseSheetModel.getNewExpenseSheetLine().getDate() != null) ? expenseSheetModel
.getNewExpenseSheetLine().getDate().toDateTimeAtStartOfDay().toDate()
: null;
}
return null;
}
public void setExpenseSheetLineDate(Date date) {
if (expenseSheetModel.getNewExpenseSheetLine() != null) {
LocalDate localDate = null;
if (date != null) {
localDate = LocalDate.fromDateFields(date);
}
expenseSheetModel.getNewExpenseSheetLine().setDate(localDate);
}
}
@Override
protected void initCreate() {
initCreate(false);
}
@Override
protected void initEdit(ExpenseSheet expenseSheet) {
expenseSheetModel.prepareToEdit(expenseSheet);
loadComponentsEditWindow();
}
@Override
protected ExpenseSheet getEntityBeingEdited() {
return expenseSheetModel.getExpenseSheet();
}
@Override
public void delete(ExpenseSheet expenseSheet)
throws InstanceNotFoundException {
expenseSheetModel.removeExpenseSheet(expenseSheet);
}
@Override
protected String getEntityType() {
return _("Expense sheet");
}
@Override
protected String getPluralEntityType() {
return _("Expense sheets");
}
public String getCurrencySymbol() {
return Util.getCurrencySymbol();
}
public String getMoneyFormat() {
return Util.getMoneyFormat();
}
@Override
public void goToCreatePersonalExpenseSheet() {
state = CRUDControllerState.CREATE;
initCreate(true);
showEditWindow();
fromUserDashboard = true;
}
private void initCreate(boolean personal) {
expenseSheetModel.initCreate(personal);
loadComponentsEditWindow();
}
public String getResource() {
Resource resource = expenseSheetModel.getResource();
return resource == null ? "" : resource.getShortDescription();
}
@Override
public void goToEditPersonalExpenseSheet(ExpenseSheet expenseSheet) {
goToEditForm(expenseSheet);
fromUserDashboard = true;
}
@Override
protected void showListWindow() {
if (fromUserDashboard) {
String url = CustomTargetUrlResolver.USER_DASHBOARD_URL;
if (!cancel) {
url += "?expense_sheet_saved="
+ expenseSheetModel.getExpenseSheet().getCode();
}
Executions.getCurrent().sendRedirect(url);
} else {
super.showListWindow();
}
}
@Override
protected void cancel() {
cancel = true;
}
public String getType() {
return getType(expenseSheetModel.getExpenseSheet());
}
private String getType(ExpenseSheet expenseSheet) {
if (expenseSheet != null && expenseSheet.isPersonal()) {
return _("Personal");
}
return _("Regular");
}
public RowRenderer getExpenseSheetsRenderer() {
return new RowRenderer() {
@Override
public void render(Row row, Object data) throws Exception {
final ExpenseSheet expenseSheet = (ExpenseSheet) data;
row.setValue(expenseSheet);
Util.appendLabel(row, expenseSheet.getFirstExpense().toString());
Util.appendLabel(row, expenseSheet.getLastExpense().toString());
Util.appendLabel(row,
Util.addCurrencySymbol(expenseSheet.getTotal()));
Util.appendLabel(row, expenseSheet.getCode());
Util.appendLabel(row, expenseSheet.getDescription());
Util.appendLabel(row, getType(expenseSheet));
Util.appendOperationsAndOnClickEvent(row, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
goToEditForm(expenseSheet);
}
}, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
confirmDelete(expenseSheet);
}
});
}
};
}
}
|
package io.logspace.agent.api;
import java.io.IOException;
import java.io.InputStream;
public final class AgentControllerDescriptionFactory {
private static final String IMPLEMENTATION_PROPERTY_NAME = "logspace.configuration-deserializer";
private static final String DEFAULT_IMPLEMENTATION = "io.logspace.agent.api.json.AgentControllerDescriptionJsonDeserializer";
private AgentControllerDescriptionFactory() {
// hide utility class constructor
}
public static AgentControllerDescription fromJson(InputStream inputStream) throws IOException {
AgentControllerDescriptionDeserializer deserializer = getDeserializer();
return deserializer.fromJson(inputStream);
}
@SuppressWarnings("unchecked")
public static AgentControllerDescriptionDeserializer getDeserializer() {
String deserializerClassName = System.getProperty(IMPLEMENTATION_PROPERTY_NAME, DEFAULT_IMPLEMENTATION);
try {
Class<? extends AgentControllerDescriptionDeserializer> deserializerClass = (Class<? extends AgentControllerDescriptionDeserializer>) Class
.forName(deserializerClassName);
return deserializerClass.newInstance();
} catch (ClassNotFoundException e) {
if (DEFAULT_IMPLEMENTATION.equals(deserializerClassName)) {
throw new AgentControllerInitializationException("Could not load class '" + deserializerClassName
+ "' as deserializer for the logspace configuration. Is logspace-agent-json.jar part of the classpath?", e);
}
throw new AgentControllerInitializationException("Could not find class '" + deserializerClassName
+ "' as deserializer for the logspace configuration. Did you configure '" + IMPLEMENTATION_PROPERTY_NAME
+ "' properly?", e);
} catch (InstantiationException e) {
throw new AgentControllerInitializationException("Could not instantiate class '" + deserializerClassName
+ "' as deserializer for the logspace configuration. Does this class have a default constructor?", e);
} catch (IllegalAccessException e) {
throw new AgentControllerInitializationException("Could not access the constructor of class '" + deserializerClassName
+ "' as deserializer for the logspace configuration. Does this class have a default constructor?", e);
}
}
}
|
package com.inmobi.messaging.consumer.util;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import com.inmobi.databus.CheckpointProvider;
import com.inmobi.databus.files.FileMap;
import com.inmobi.databus.files.HadoopStreamFile;
import com.inmobi.databus.partition.PartitionCheckpoint;
import com.inmobi.databus.partition.PartitionCheckpointList;
import com.inmobi.databus.partition.PartitionId;
import com.inmobi.databus.readers.DatabusStreamWaitingReader;
import com.inmobi.messaging.ClientConfig;
import com.inmobi.messaging.consumer.databus.Checkpoint;
import com.inmobi.messaging.consumer.databus.CheckpointList;
import com.inmobi.messaging.consumer.databus.DatabusConsumerConfig;
import com.inmobi.messaging.consumer.databus.StreamType;
public class CheckpointUtil implements DatabusConsumerConfig {
private static final Log LOG = LogFactory.getLog(CheckpointUtil.class);
public CheckpointUtil() {
}
public static void prepareCheckpointList(String superKey,
CheckpointProvider provider,
Set<Integer> idList, Path streamDir, CheckpointList checkpointList)
throws IOException {
Checkpoint oldCheckpoint = null;
byte[] chkpointData = provider.read(superKey);
if (chkpointData != null) {
oldCheckpoint = new Checkpoint(chkpointData);
}
if (oldCheckpoint == null) {
LOG.info("Old checkpoint is not available nothing to prepare");
return;
}
Map<PartitionId, PartitionCheckpoint> partitionCheckpoints =
oldCheckpoint.getPartitionsCheckpoint();
for (Map.Entry<PartitionId, PartitionCheckpoint> entry :
partitionCheckpoints.entrySet()) {
Path tmpPathFile = new Path(entry.getValue().getStreamFile().toString()).
getParent();
//to get streamDir path form streamDirPath/YYYY/MM/DD/HH/MN)
for (int i = 0; i < 5; i++) {
tmpPathFile = tmpPathFile.getParent();
}
if ((streamDir).compareTo(tmpPathFile) == 0) {
Map<Integer, PartitionCheckpoint> thisChkpoint =
new TreeMap<Integer, PartitionCheckpoint>();
Calendar chkCal = Calendar.getInstance();
Date checkpointDate = DatabusStreamWaitingReader.getDateFromStreamDir(
streamDir,
new Path(entry.getValue().getStreamFile().toString()).getParent());
chkCal.setTime(checkpointDate);
int checkpointMin = chkCal.get(Calendar.MINUTE);
Calendar chkPrevHrCal = Calendar.getInstance();
chkPrevHrCal.setTime(checkpointDate);
chkPrevHrCal.add(Calendar.MINUTE, 1);
chkPrevHrCal.add(Calendar.HOUR, -1);
while (chkPrevHrCal.before(chkCal)) {
if (chkPrevHrCal.get(Calendar.MINUTE) == 0) {
break;
}
Path minDir = DatabusStreamWaitingReader.getMinuteDirPath(streamDir,
chkPrevHrCal.getTime());
FileStatus lastElement = getLast(minDir);
if (lastElement != null) {
thisChkpoint.put(chkPrevHrCal.get(Calendar.MINUTE),
new PartitionCheckpoint(new HadoopStreamFile(
lastElement.getPath().getParent(),
lastElement.getPath().getName(),
lastElement.getModificationTime()),
-1));
}
chkPrevHrCal.add(Calendar.MINUTE, 1);
}
Calendar chkHrCal = Calendar.getInstance();
chkHrCal.setTime(checkpointDate);
chkHrCal.set(Calendar.MINUTE, 0);
while (chkHrCal.before(chkCal)) {
Path minDir = DatabusStreamWaitingReader.getMinuteDirPath(streamDir,
chkHrCal.getTime());
FileStatus lastElement = getLast(minDir);
if (lastElement != null) {
thisChkpoint.put(chkHrCal.get(Calendar.MINUTE),
new PartitionCheckpoint(new HadoopStreamFile(
lastElement.getPath().getParent(),
lastElement.getPath().getName(),
lastElement.getModificationTime()),
-1));
}
chkHrCal.add(Calendar.MINUTE, 1);
}
thisChkpoint.put(checkpointMin, entry.getValue());
checkpointList.set(entry.getKey(), new PartitionCheckpointList(
thisChkpoint));
}
}
}
private static FileStatus getLast(final Path minDir)
throws IOException {
FileMap<HadoopStreamFile> fmap = new FileMap<HadoopStreamFile>() {
@Override
protected TreeMap<HadoopStreamFile, FileStatus> createFilesMap() {
return new TreeMap<HadoopStreamFile, FileStatus>();
}
@Override
protected HadoopStreamFile getStreamFile(String fileName) {
throw new RuntimeException("Not implemented");
}
@Override
protected HadoopStreamFile getStreamFile(FileStatus file) {
return HadoopStreamFile.create(file);
}
@Override
protected PathFilter createPathFilter() {
return new PathFilter() {
@Override
public boolean accept(Path path) {
if (path.getName().startsWith("_")) {
return false;
}
return true;
}
};
}
@Override
protected void buildList() throws IOException {
FileSystem fs = minDir.getFileSystem(new Configuration());
doRecursiveListing(fs, minDir, pathFilter, this);
}
};
fmap.build();
return fmap.getLastFile();
}
private static void doRecursiveListing(FileSystem fs, Path dir,
PathFilter pathFilter,
FileMap<HadoopStreamFile> fmap) throws IOException {
FileStatus[] fileStatuses = fs.listStatus(dir, pathFilter);
if (fileStatuses == null || fileStatuses.length == 0) {
LOG.debug("No files in directory:" + dir);
} else {
for (FileStatus file : fileStatuses) {
if (file.isDir()) {
doRecursiveListing(fs, file.getPath(), pathFilter, fmap);
} else {
fmap.addPath(file);
}
}
}
}
protected static CheckpointProvider createCheckpointProvider(
String checkpointProviderClassName, String chkpointDir) {
CheckpointProvider chkProvider = null;
try {
Class<?> clazz = Class.forName(checkpointProviderClassName);
Constructor<?> constructor = clazz.getConstructor(String.class);
chkProvider = (CheckpointProvider) constructor.newInstance(new Object[]
{chkpointDir});
} catch (Exception e) {
throw new IllegalArgumentException("Could not create checkpoint provider "
+ checkpointProviderClassName, e);
}
return chkProvider;
}
public static void run(String args[]) throws Exception {
if (args.length > 0) {
String confFile = args[0];
ClientConfig config;
CheckpointProvider checkpointProvider;
Set<Integer> idList = new TreeSet<Integer>();
config = ClientConfig.load(confFile);
String className = config.getString("consumer.className");
String chkpointProviderClassName = config.getString(
chkProviderConfig, DEFAULT_CHK_PROVIDER);
String databusCheckpointDir = config.getString(checkpointDirConfig,
DEFAULT_CHECKPOINT_DIR);
checkpointProvider = createCheckpointProvider(
chkpointProviderClassName, databusCheckpointDir);
for (int i = 0; i < 60; i++) {
idList.add(i);
}
String topicName = config.getString("topic.name", null);
String consumerName = config.getString("consumer.name", null);
String type = config.getString(databusStreamType, DEFAULT_STREAM_TYPE);
String [] databusRootDir = (config.getString(databusRootDirsConfig,
"hadoop.consumer.rootDirs")).split(",");
StreamType streamType = StreamType.valueOf(type);
String superKey = consumerName + "_" + topicName;
CheckpointList checkpointList = new CheckpointList(idList);
Path streamDir = null;
for (String databusRootDirPath : databusRootDir) {
if (className.compareTo(
"com.inmobi.messaging.consumer.databus.DatabusConsumer") == 0) {
streamDir = DatabusUtil.getStreamDir(streamType,
new Path(databusRootDirPath), topicName);
} else if (className.compareTo(
"com.inmobi.messaging.consumer.hadoop.HadoopConsumer") == 0) {
streamDir = new Path(databusRootDirPath);
} else {
System.out.println("mention consumer class name in the conf file");
System.exit(1);
}
CheckpointUtil.prepareCheckpointList(superKey, checkpointProvider, idList,
streamDir, checkpointList);
}
checkpointList.write(checkpointProvider, superKey);
checkpointList.read(checkpointProvider, superKey);
} else {
System.exit(1);
}
}
public static void main(String [] args) throws Exception {
run(args);
}
}
|
/* @java.file.header */
package org.gridgain.grid.kernal.portable;
import org.gridgain.grid.portable.*;
import org.jdk8.backport.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.*;
import static java.lang.reflect.Modifier.*;
import static org.gridgain.grid.kernal.portable.GridPortableMarshaller.*;
/**
* Portable class descriptor.
*/
class GridPortableClassDescriptor {
private static final ConcurrentMap<Class<?>, GridPortableClassDescriptor> CACHE = new ConcurrentHashMap8<>(256);
private static final int TOTAL_LEN_POS = 9;
private static final int COL_TYPE_ID = 100;
private static final int MAP_TYPE_ID = 200;
private final Mode mode;
private final int typeId;
private List<FieldInfo> fields;
private byte[] hdr;
static {
// Boxed primitives.
CACHE.put(Byte.class, new GridPortableClassDescriptor(Mode.BYTE, 1));
CACHE.put(Short.class, new GridPortableClassDescriptor(Mode.SHORT, 2));
CACHE.put(Integer.class, new GridPortableClassDescriptor(Mode.INT, 3));
CACHE.put(Long.class, new GridPortableClassDescriptor(Mode.LONG, 4));
CACHE.put(Float.class, new GridPortableClassDescriptor(Mode.FLOAT, 5));
CACHE.put(Double.class, new GridPortableClassDescriptor(Mode.DOUBLE, 6));
CACHE.put(Character.class, new GridPortableClassDescriptor(Mode.CHAR, 7));
CACHE.put(Boolean.class, new GridPortableClassDescriptor(Mode.BOOLEAN, 8));
// Other objects.
CACHE.put(String.class, new GridPortableClassDescriptor(Mode.STRING, 9));
CACHE.put(UUID.class, new GridPortableClassDescriptor(Mode.UUID, 10));
// Arrays with primitives.
CACHE.put(byte[].class, new GridPortableClassDescriptor(Mode.BYTE_ARR, 11));
CACHE.put(short[].class, new GridPortableClassDescriptor(Mode.SHORT_ARR, 12));
CACHE.put(int[].class, new GridPortableClassDescriptor(Mode.INT_ARR, 13));
CACHE.put(long[].class, new GridPortableClassDescriptor(Mode.LONG_ARR, 14));
CACHE.put(float[].class, new GridPortableClassDescriptor(Mode.FLOAT_ARR, 15));
CACHE.put(double[].class, new GridPortableClassDescriptor(Mode.DOUBLE_ARR, 16));
CACHE.put(char[].class, new GridPortableClassDescriptor(Mode.CHAR_ARR, 17));
CACHE.put(boolean[].class, new GridPortableClassDescriptor(Mode.BOOLEAN_ARR, 18));
// Arrays with boxed primitives.
CACHE.put(Byte[].class, new GridPortableClassDescriptor(Mode.BYTE_ARR, 11));
CACHE.put(Short[].class, new GridPortableClassDescriptor(Mode.SHORT_ARR, 12));
CACHE.put(Integer[].class, new GridPortableClassDescriptor(Mode.INT_ARR, 13));
CACHE.put(Long[].class, new GridPortableClassDescriptor(Mode.LONG_ARR, 14));
CACHE.put(Float[].class, new GridPortableClassDescriptor(Mode.FLOAT_ARR, 15));
CACHE.put(Double[].class, new GridPortableClassDescriptor(Mode.DOUBLE_ARR, 16));
CACHE.put(Character[].class, new GridPortableClassDescriptor(Mode.CHAR_ARR, 17));
CACHE.put(Boolean[].class, new GridPortableClassDescriptor(Mode.BOOLEAN_ARR, 18));
// Other arrays.
CACHE.put(String[].class, new GridPortableClassDescriptor(Mode.STRING_ARR, 19));
CACHE.put(UUID[].class, new GridPortableClassDescriptor(Mode.UUID_ARR, 20));
CACHE.put(Object[].class, new GridPortableClassDescriptor(Mode.OBJ_ARR, 21));
}
/**
* @param mode Mode.
* @param typeId Type ID.
*/
private GridPortableClassDescriptor(Mode mode, int typeId) {
assert mode != null;
this.mode = mode;
this.typeId = typeId;
}
/**
* @param cls Class.
*/
private GridPortableClassDescriptor(Class<?> cls) throws GridPortableException {
assert cls != null;
if (Collection.class.isAssignableFrom(cls)) {
mode = Mode.COL;
typeId = COL_TYPE_ID;
}
else if (Map.class.isAssignableFrom(cls)) {
mode = Mode.MAP;
typeId = MAP_TYPE_ID;
}
else {
if (GridPortableEx.class.isAssignableFrom(cls))
mode = Mode.PORTABLE_EX;
else {
mode = Mode.PORTABLE;
fields = new ArrayList<>();
GridPortableHeaderWriter hdrWriter = new GridPortableHeaderWriter();
for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) {
for (Field f : c.getDeclaredFields()) {
int mod = f.getModifiers();
if (!isStatic(mod) && !isTransient(mod)) {
f.setAccessible(true);
int offPos = hdrWriter.addField(f.getName());
fields.add(new FieldInfo(f, offPos));
}
}
}
hdr = hdrWriter.header();
}
typeId = cls.getSimpleName().hashCode(); // TODO: should be taken from config
}
}
/**
* @param cls Class.
* @return Class descriptor.
* @throws GridPortableException In case of error.
*/
static GridPortableClassDescriptor get(Class<?> cls) throws GridPortableException {
assert cls != null;
GridPortableClassDescriptor desc = CACHE.get(cls);
if (desc == null) {
GridPortableClassDescriptor old = CACHE.putIfAbsent(cls, desc = new GridPortableClassDescriptor(cls));
if (old != null)
desc = old;
}
return desc;
}
/**
* @param obj Object.
* @param writer Writer.
* @throws GridPortableException In case of error.
*/
void write(Object obj, GridPortableWriterImpl writer) throws GridPortableException {
assert obj != null;
assert writer != null;
writer.doWriteByte(OBJ);
writer.doWriteInt(typeId);
switch (mode) {
case BYTE:
writer.doWriteByte((byte)obj);
break;
case SHORT:
writer.doWriteShort((short)obj);
break;
case INT:
writer.doWriteInt((int)obj);
break;
case LONG:
writer.doWriteLong((long)obj);
break;
case FLOAT:
writer.doWriteFloat((float)obj);
break;
case DOUBLE:
writer.doWriteDouble((double)obj);
break;
case CHAR:
writer.doWriteChar((char)obj);
break;
case BOOLEAN:
writer.doWriteBoolean((boolean)obj);
break;
case STRING:
writer.doWriteString((String)obj);
break;
case UUID:
writer.doWriteUuid((UUID)obj);
break;
case BYTE_ARR:
writer.doWriteByteArray((byte[])obj);
break;
case SHORT_ARR:
writer.doWriteShortArray((short[])obj);
break;
case INT_ARR:
writer.doWriteIntArray((int[])obj);
break;
case LONG_ARR:
writer.doWriteLongArray((long[])obj);
break;
case FLOAT_ARR:
writer.doWriteFloatArray((float[])obj);
break;
case DOUBLE_ARR:
writer.doWriteDoubleArray((double[])obj);
break;
case CHAR_ARR:
writer.doWriteCharArray((char[])obj);
break;
case BOOLEAN_ARR:
writer.doWriteBooleanArray((boolean[])obj);
break;
case STRING_ARR:
writer.doWriteStringArray((String[])obj);
break;
case UUID_ARR:
writer.doWriteUuidArray((UUID[])obj);
break;
case OBJ_ARR:
writer.doWriteObjectArray((Object[])obj);
break;
case COL:
writer.doWriteCollection((Collection<?>)obj);
break;
case MAP:
writer.doWriteMap((Map<?, ?>)obj);
break;
case PORTABLE_EX:
writer.doWriteInt(obj.hashCode());
// Length.
writer.reserve(4);
// Header handles are not supported for GridPortableEx.
writer.doWriteInt(-1);
writePortableEx((GridPortableEx)obj, writer);
// Length.
writer.writeCurrentSize(TOTAL_LEN_POS);
break;
case PORTABLE:
writer.doWriteInt(obj.hashCode());
// Length.
writer.reserve(4);
writer.doWriteInt(-1); // TODO: Header handles.
writer.write(hdr);
for (FieldInfo info : fields) {
writer.writeCurrentSize(info.offPos);
try {
writer.doWriteObject(info.field.get(obj));
}
catch (IllegalAccessException e) {
throw new GridPortableException("Failed to get value for field: " + info.field, e);
}
}
// Length.
writer.writeCurrentSize(TOTAL_LEN_POS);
break;
default:
assert false : "Invalid mode: " + mode;
}
}
/**
* @param reader Reader.
* @return Object.
*/
Object read(GridPortableReaderImpl reader) throws GridPortableException {
assert reader != null;
switch (mode) {
case BYTE:
return reader.readByte();
case SHORT:
return reader.readShort();
case INT:
return reader.readInt();
case LONG:
return reader.readLong();
case FLOAT:
return reader.readFloat();
case DOUBLE:
return reader.readDouble();
case CHAR:
return reader.readChar();
case BOOLEAN:
return reader.readBoolean();
case STRING:
return reader.readString();
case UUID:
return reader.readUuid();
case BYTE_ARR:
return reader.readByteArray();
case SHORT_ARR:
return reader.readShortArray();
case INT_ARR:
return reader.readShortArray();
case LONG_ARR:
return reader.readLongArray();
case FLOAT_ARR:
return reader.readFloatArray();
case DOUBLE_ARR:
return reader.readDoubleArray();
case CHAR_ARR:
return reader.readCharArray();
case BOOLEAN_ARR:
return reader.readBooleanArray();
case STRING_ARR:
return reader.readStringArray();
case UUID_ARR:
return reader.readUuidArray();
case OBJ_ARR:
return reader.readObjectArray();
case COL:
return reader.readCollection();
case MAP:
return reader.readMap();
case PORTABLE_EX:
return null; // TODO
case PORTABLE:
return null; // TODO
default:
assert false : "Invalid mode: " + mode;
return null;
}
}
/**
* @param obj Object.
* @param writer Writer.
* @throws GridPortableException In case of error.
*/
private void writePortableEx(GridPortableEx obj, GridPortableWriterImpl writer) throws GridPortableException {
assert obj != null;
assert writer != null;
GridPortableWriterImpl writer0 = new GridPortableWriterImpl(writer);
obj.writePortable(writer0);
writer0.flush();
}
private static class FieldInfo {
private final Field field;
private final int offPos;
/**
* @param field Field.
* @param offPos Offset position.
*/
private FieldInfo(Field field, int offPos) {
this.field = field;
this.offPos = offPos;
}
}
private enum Mode {
BYTE,
SHORT,
INT,
LONG,
FLOAT,
DOUBLE,
CHAR,
BOOLEAN,
STRING,
UUID,
BYTE_ARR,
SHORT_ARR,
INT_ARR,
LONG_ARR,
FLOAT_ARR,
DOUBLE_ARR,
CHAR_ARR,
BOOLEAN_ARR,
STRING_ARR,
UUID_ARR,
OBJ_ARR,
COL,
MAP,
PORTABLE_EX,
PORTABLE
}
}
|
package im.status.ethereum.module;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebStorage;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import statusgo.SignalHandler;
import statusgo.Statusgo;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.Nullable;
class StatusModule extends ReactContextBaseJavaModule implements LifecycleEventListener, SignalHandler {
private static final String TAG = "StatusModule";
private static final String logsZipFileName = "Status-debug-logs.zip";
private static final String gethLogFileName = "geth.log";
private static final String statusLogFileName = "Status.log";
private static StatusModule module;
private ReactApplicationContext reactContext;
private boolean rootedDevice;
StatusModule(ReactApplicationContext reactContext, boolean rootedDevice) {
super(reactContext);
this.reactContext = reactContext;
this.rootedDevice = rootedDevice;
reactContext.addLifecycleEventListener(this);
}
@Override
public String getName() {
return "Status";
}
@Override
public void onHostResume() { // Activity `onResume`
module = this;
Statusgo.setMobileSignalHandler(this);
}
@Override
public void onHostPause() {
}
@Override
public void onHostDestroy() {
}
private boolean checkAvailability() {
// We wait at least 10s for getCurrentActivity to return a value,
// otherwise we give up
for (int attempts = 0; attempts < 100; attempts++) {
if (getCurrentActivity() != null) {
return true;
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
if (getCurrentActivity() != null) {
return true;
}
Log.d(TAG, "Activity doesn't exist");
return false;
}
}
Log.d(TAG, "Activity doesn't exist");
return false;
}
public void handleSignal(String jsonEvent) {
Log.d(TAG, "Signal event: " + jsonEvent);
WritableMap params = Arguments.createMap();
params.putString("jsonEvent", jsonEvent);
this.getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("gethEvent", params);
}
private File getLogsFile() {
final File pubDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
final File logFile = new File(pubDirectory, gethLogFileName);
return logFile;
}
private String prepareLogsFile(final Context context) {
final File logFile = getLogsFile();
try {
logFile.setReadable(true);
File parent = logFile.getParentFile();
if (!parent.canWrite()) {
return null;
}
if (!parent.exists()) {
parent.mkdirs();
}
logFile.createNewFile();
logFile.setWritable(true);
Log.d(TAG, "Can write " + logFile.canWrite());
Uri gethLogUri = Uri.fromFile(logFile);
String gethLogFilePath = logFile.getAbsolutePath();
Log.d(TAG, gethLogFilePath);
return gethLogFilePath;
} catch (Exception e) {
Log.d(TAG, "Can't create geth.log file! " + e.getMessage());
}
return null;
}
private String updateConfig(final String jsonConfigString, final String absRootDirPath, final String absKeystoreDirPath) throws JSONException {
final JSONObject jsonConfig = new JSONObject(jsonConfigString);
// retrieve parameters from app config, that will be applied onto the Go-side config later on
final String absDataDirPath = pathCombine(absRootDirPath, jsonConfig.getString("DataDir"));
final Boolean logEnabled = jsonConfig.getBoolean("LogEnabled");
final Context context = this.getReactApplicationContext();
final String gethLogFilePath = logEnabled ? prepareLogsFile(context) : null;
jsonConfig.put("DataDir", absDataDirPath);
jsonConfig.put("KeyStoreDir", absKeystoreDirPath);
jsonConfig.put("LogFile", gethLogFilePath);
return jsonConfig.toString();
}
private static void prettyPrintConfig(final String config) {
Log.d(TAG, "startNode() with config (see below)");
String configOutput = config;
final int maxOutputLen = 4000;
Log.d(TAG, "********************** NODE CONFIG ****************************");
while (!configOutput.isEmpty()) {
Log.d(TAG, "Node config:" + configOutput.substring(0, Math.min(maxOutputLen, configOutput.length())));
if (configOutput.length() > maxOutputLen) {
configOutput = configOutput.substring(maxOutputLen);
} else {
break;
}
}
Log.d(TAG, "******************* ENDOF NODE CONFIG *************************");
}
private String getTestnetDataDir(final String absRootDirPath) {
return pathCombine(absRootDirPath, "ethereum/testnet");
}
private String pathCombine(final String path1, final String path2) {
// Replace this logic with Paths.get(path1, path2) once API level 26+ becomes the minimum supported API level
final File file = new File(path1, path2);
return file.getAbsolutePath();
}
private void doStartNode(final String jsonConfigString) {
Activity currentActivity = getCurrentActivity();
final String absRootDirPath = currentActivity.getApplicationInfo().dataDir;
final String dataFolder = this.getTestnetDataDir(absRootDirPath);
Log.d(TAG, "Starting Geth node in folder: " + dataFolder);
try {
final File newFile = new File(dataFolder);
// todo handle error?
newFile.mkdir();
} catch (Exception e) {
Log.e(TAG, "error making folder: " + dataFolder, e);
}
final String ropstenFlagPath = pathCombine(absRootDirPath, "ropsten_flag");
final File ropstenFlag = new File(ropstenFlagPath);
if (!ropstenFlag.exists()) {
try {
final String chaindDataFolderPath = pathCombine(dataFolder, "StatusIM/lightchaindata");
final File lightChainFolder = new File(chaindDataFolderPath);
if (lightChainFolder.isDirectory()) {
String[] children = lightChainFolder.list();
for (int i = 0; i < children.length; i++) {
new File(lightChainFolder, children[i]).delete();
}
}
lightChainFolder.delete();
ropstenFlag.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String testnetDataDir = dataFolder;
String oldKeystoreDir = pathCombine(testnetDataDir, "keystore");
String newKeystoreDir = pathCombine(absRootDirPath, "keystore");
final File oldKeystore = new File(oldKeystoreDir);
if (oldKeystore.exists()) {
try {
final File newKeystore = new File(newKeystoreDir);
copyDirectory(oldKeystore, newKeystore);
if (oldKeystore.isDirectory()) {
String[] children = oldKeystore.list();
for (int i = 0; i < children.length; i++) {
new File(oldKeystoreDir, children[i]).delete();
}
}
oldKeystore.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
final String updatedJsonConfigString = this.updateConfig(jsonConfigString, absRootDirPath, newKeystoreDir);
prettyPrintConfig(updatedJsonConfigString);
String res = Statusgo.startNode(updatedJsonConfigString);
if (res.startsWith("{\"error\":\"\"")) {
Log.d(TAG, "StartNode result: " + res);
Log.d(TAG, "Geth node started");
}
else {
Log.e(TAG, "StartNode failed: " + res);
}
} catch (JSONException e) {
Log.e(TAG, "updateConfig failed: " + e.getMessage());
System.exit(1);
}
}
private String getOldExternalDir() {
File extStore = Environment.getExternalStorageDirectory();
return extStore.exists() ? pathCombine(extStore.getAbsolutePath(), "ethereum/testnet") : getNewInternalDir();
}
private String getNewInternalDir() {
Activity currentActivity = getCurrentActivity();
return pathCombine(currentActivity.getApplicationInfo().dataDir, "ethereum/testnet");
}
private void deleteDirectory(File folder) {
File[] files = folder.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
deleteDirectory(f);
} else {
f.delete();
}
}
}
folder.delete();
}
private void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create dir " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
@ReactMethod
public void shouldMoveToInternalStorage(Callback callback) {
String oldDir = getOldExternalDir();
String newDir = getNewInternalDir();
File oldDirFile = new File(oldDir);
File newDirFile = new File(newDir);
callback.invoke(oldDirFile.exists() && !newDirFile.exists());
}
@ReactMethod
public void moveToInternalStorage(Callback callback) {
String oldDir = getOldExternalDir();
String newDir = getNewInternalDir();
try {
File oldDirFile = new File(oldDir);
copyDirectory(oldDirFile, new File(newDir));
deleteDirectory(oldDirFile);
} catch (IOException e) {
Log.d(TAG, "Moving error: " + e);
}
callback.invoke();
}
@ReactMethod
public void startNode(final String config) {
Log.d(TAG, "startNode");
if (!checkAvailability()) {
Log.e(TAG, "[startNode] Activity doesn't exist, cannot start node");
System.exit(0);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
doStartNode(config);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void stopNode() {
Runnable r = new Runnable() {
@Override
public void run() {
Log.d(TAG, "stopNode");
String res = Statusgo.stopNode();
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void login(final String address, final String password, final Callback callback) {
Log.d(TAG, "login");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.login(address, password);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void verify(final String address, final String password, final Callback callback) {
Log.d(TAG, "verify");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Activity currentActivity = getCurrentActivity();
final String absRootDirPath = currentActivity.getApplicationInfo().dataDir;
final String newKeystoreDir = pathCombine(absRootDirPath, "keystore");
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.verifyAccountPassword(newKeystoreDir, address, password);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void loginWithKeycard(final String whisperPrivateKey, final String encryptionPublicKey, final Callback callback) {
Log.d(TAG, "loginWithKeycard");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.loginWithKeycard(whisperPrivateKey, encryptionPublicKey);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void createAccount(final String password, final Callback callback) {
Log.d(TAG, "createAccount");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.createAccount(password);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void sendDataNotification(final String dataPayloadJSON, final String tokensJSON, final Callback callback) {
Log.d(TAG, "sendDataNotification");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.sendDataNotification(dataPayloadJSON, tokensJSON);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
private Boolean zip(File[] _files, File zipFile, Stack<String> errorList) {
final int BUFFER = 0x8000;
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < _files.length; i++) {
final File file = _files[i];
if (file == null || !file.exists()) {
continue;
}
Log.v("Compress", "Adding: " + file.getAbsolutePath());
try {
FileInputStream fi = new FileInputStream(file);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(file.getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
errorList.push(e.getMessage());
}
}
out.close();
return true;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
return false;
}
}
private void dumpAdbLogsTo(final FileOutputStream statusLogStream) throws IOException {
final String filter = "logcat -d -b main ReactNativeJS:D StatusModule:D StatusService:D StatusNativeLogs:D *:S";
final java.lang.Process p = Runtime.getRuntime().exec(filter);
final java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
final java.io.BufferedWriter out = new java.io.BufferedWriter(new java.io.OutputStreamWriter(statusLogStream));
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
}
out.close();
in.close();
}
private void showErrorMessage(final String message) {
final Activity activity = getCurrentActivity();
new AlertDialog.Builder(activity)
.setTitle("Error")
.setMessage(message)
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.dismiss();
}
}).show();
}
@ReactMethod
public void sendLogs(final String dbJson) {
Log.d(TAG, "sendLogs");
if (!checkAvailability()) {
return;
}
final Context context = this.getReactApplicationContext();
final File logsTempDir = new File(context.getCacheDir(), "logs"); // This path needs to be in sync with android/app/src/main/res/xml/file_provider_paths.xml
logsTempDir.mkdir();
final File dbFile = new File(logsTempDir, "db.json");
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(dbFile));
outputStreamWriter.write(dbJson);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
showErrorMessage(e.getLocalizedMessage());
}
final File zipFile = new File(logsTempDir, logsZipFileName);
final File statusLogFile = new File(logsTempDir, statusLogFileName);
final File gethLogFile = getLogsFile();
try {
if (zipFile.exists() || zipFile.createNewFile()) {
final long usableSpace = zipFile.getUsableSpace();
if (usableSpace < 20 * 1024 * 1024) {
final String message = String.format("Insufficient space available on device (%s) to write logs.\nPlease free up some space.", android.text.format.Formatter.formatShortFileSize(context, usableSpace));
Log.e(TAG, message);
showErrorMessage(message);
return;
}
}
dumpAdbLogsTo(new FileOutputStream(statusLogFile));
final Stack<String> errorList = new Stack<String>();
final Boolean zipped = zip(new File[] {dbFile, gethLogFile, statusLogFile}, zipFile, errorList);
if (zipped && zipFile.exists()) {
Log.d(TAG, "Sending " + zipFile.getAbsolutePath() + " file through share intent");
final String providerName = context.getPackageName() + ".provider";
final Activity activity = getCurrentActivity();
zipFile.setReadable(true, false);
final Uri dbJsonURI = FileProvider.getUriForFile(activity, providerName, zipFile);
Intent intentShareFile = new Intent(Intent.ACTION_SEND);
intentShareFile.setType("application/json");
intentShareFile.putExtra(Intent.EXTRA_STREAM, dbJsonURI);
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Status.im logs");
intentShareFile.putExtra(Intent.EXTRA_TEXT,
String.format("Logs from %s GMT\n\nThese logs have been generated automatically by the user's request for debugging purposes.\n\n%s",
dateFormatGmt.format(new java.util.Date()),
errorList));
activity.startActivity(Intent.createChooser(intentShareFile, "Share Debug Logs"));
} else {
Log.d(TAG, "File " + zipFile.getAbsolutePath() + " does not exist");
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
showErrorMessage(e.getLocalizedMessage());
e.printStackTrace();
return;
}
finally {
dbFile.delete();
statusLogFile.delete();
zipFile.deleteOnExit();
}
}
@ReactMethod
public void addPeer(final String enode, final Callback callback) {
Log.d(TAG, "addPeer");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.addPeer(enode);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void recoverAccount(final String passphrase, final String password, final Callback callback) {
Log.d(TAG, "recoverAccount");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.recoverAccount(password, passphrase);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
private String createIdentifier() {
return UUID.randomUUID().toString();
}
@ReactMethod
public void hashTransaction(final String txArgsJSON, final Callback callback) {
Log.d(TAG, "hashTransaction");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.hashTransaction(txArgsJSON);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void sendTransactionWithSignature(final String txArgsJSON, final String signature, final Callback callback) {
Log.d(TAG, "sendTransactionWithSignature");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.sendTransactionWithSignature(txArgsJSON, signature);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void sendTransaction(final String txArgsJSON, final String password, final Callback callback) {
Log.d(TAG, "sendTransaction");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.sendTransaction(txArgsJSON, password);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void signMessage(final String rpcParams, final Callback callback) {
Log.d(TAG, "signMessage");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.signMessage(rpcParams);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void signTypedData(final String data, final String password, final Callback callback) {
Log.d(TAG, "signTypedData");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.signTypedData(data, password);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void setAdjustResize() {
Log.d(TAG, "setAdjustResize");
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
}
});
}
@ReactMethod
public void setAdjustPan() {
Log.d(TAG, "setAdjustPan");
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
});
}
@ReactMethod
public void setSoftInputMode(final int mode) {
Log.d(TAG, "setSoftInputMode");
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
activity.getWindow().setSoftInputMode(mode);
}
});
}
@SuppressWarnings("deprecation")
@ReactMethod
public void clearCookies() {
Log.d(TAG, "clearCookies");
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
} else {
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(activity);
cookieSyncManager.startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncManager.stopSync();
cookieSyncManager.sync();
}
}
@ReactMethod
public void clearStorageAPIs() {
Log.d(TAG, "clearStorageAPIs");
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
WebStorage storage = WebStorage.getInstance();
if (storage != null) {
storage.deleteAllData();
}
}
@ReactMethod
public void callRPC(final String payload, final Callback callback) {
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.callRPC(payload);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void callPrivateRPC(final String payload, final Callback callback) {
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.callPrivateRPC(payload);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void closeApplication() {
System.exit(0);
}
@ReactMethod
public void connectionChange(final String type, final boolean isExpensive) {
Log.d(TAG, "ConnectionChange: " + type + ", is expensive " + isExpensive);
Statusgo.connectionChange(type, isExpensive ? 1 : 0);
}
@ReactMethod
public void appStateChange(final String type) {
Log.d(TAG, "AppStateChange: " + type);
Statusgo.appStateChange(type);
}
private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
@ReactMethod
public void getDeviceUUID(final Callback callback) {
if (uniqueID == null) {
SharedPreferences sharedPrefs = this.getReactApplicationContext().getSharedPreferences(
PREF_UNIQUE_ID, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString();
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
}
}
callback.invoke(uniqueID);
}
private Boolean is24Hour() {
return android.text.format.DateFormat.is24HourFormat(this.reactContext.getApplicationContext());
}
@ReactMethod
public void extractGroupMembershipSignatures(final String signaturePairs, final Callback callback) {
Log.d(TAG, "extractGroupMembershipSignatures");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.extractGroupMembershipSignatures(signaturePairs);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void signGroupMembership(final String content, final Callback callback) {
Log.d(TAG, "signGroupMembership");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.signGroupMembership(content);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void enableInstallation(final String installationId, final Callback callback) {
Log.d(TAG, "enableInstallation");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.enableInstallation(installationId);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void disableInstallation(final String installationId, final Callback callback) {
Log.d(TAG, "disableInstallation");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String result = Statusgo.disableInstallation(installationId);
callback.invoke(result);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@ReactMethod
public void updateMailservers(final String enodes, final Callback callback) {
Log.d(TAG, "updateMailservers");
if (!checkAvailability()) {
callback.invoke(false);
return;
}
Runnable r = new Runnable() {
@Override
public void run() {
String res = Statusgo.updateMailservers(enodes);
callback.invoke(res);
}
};
StatusThreadPoolExecutor.getInstance().execute(r);
}
@Override
public @Nullable
Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
constants.put("is24Hour", this.is24Hour());
return constants;
}
@ReactMethod
public void isDeviceRooted(final Callback callback) {
callback.invoke(rootedDevice);
}
}
|
package de.geeksfactory.opacclient.apis;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.networking.HTTPClient;
import de.geeksfactory.opacclient.objects.CoverHolder;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.storage.MetaDataSource;
/**
* Abstract Base class for OpacApi implementations providing some helper methods
* for HTTP
*/
public abstract class BaseApi implements OpacApi {
protected DefaultHttpClient http_client;
/**
* Initializes HTTP client
*/
@Override
public void init(MetaDataSource metadata, Library library) {
http_client = HTTPClient.getNewHttpClient(library);
}
/**
* Perform a HTTP GET request to a given URL
*
* @param url
* URL to fetch
* @param encoding
* Expected encoding of the response body
* @param ignore_errors
* If true, status codes above 400 do not raise an exception
* @param cookieStore
* If set, the given cookieStore is used instead of the built-in
* one.
* @return Answer content
* @throws NotReachableException
* Thrown when server returns a HTTP status code greater or
* equal than 400.
*/
public String httpGet(String url, String encoding, boolean ignore_errors,
CookieStore cookieStore) throws ClientProtocolException,
IOException {
HttpGet httpget = new HttpGet(cleanUrl(url));
HttpResponse response;
try {
if (cookieStore != null) {
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE,
cookieStore);
response = http_client.execute(httpget, localContext);
} else {
response = http_client.execute(httpget);
}
} catch (ConnectTimeoutException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (IllegalStateException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
// TODO: Handly this well
throw e;
} catch (javax.net.ssl.SSLException e) {
// TODO: Handly this well
// Can be "Not trusted server certificate" or can be a
// aborted/interrupted handshake/connection
throw e;
} catch (InterruptedIOException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (IOException e) {
if (e.getMessage().contains("Request aborted")) {
e.printStackTrace();
throw new NotReachableException();
} else {
throw e;
}
}
if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
throw new NotReachableException();
}
String html = convertStreamToString(response.getEntity().getContent(),
encoding);
response.getEntity().consumeContent();
return html;
}
public String httpGet(String url, String encoding, boolean ignore_errors)
throws ClientProtocolException, IOException {
return httpGet(url, encoding, ignore_errors, null);
}
public String httpGet(String url, String encoding)
throws ClientProtocolException, IOException {
return httpGet(url, encoding, false, null);
}
@Deprecated
public String httpGet(String url) throws ClientProtocolException,
IOException {
return httpGet(url, getDefaultEncoding(), false, null);
}
public static String cleanUrl(String myURL) {
String[] parts = myURL.split("\\?");
String url = parts[0];
try {
if (parts.length > 1) {
url += "?";
List<NameValuePair> params = new ArrayList<NameValuePair>();
String[] pairs = parts[1].split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv.length > 1)
params.add(new BasicNameValuePair(URLDecoder.decode(
kv[0], "UTF-8"), URLDecoder.decode(kv[1],
"UTF-8")));
else
params.add(new BasicNameValuePair(URLDecoder.decode(
kv[0], "UTF-8"), ""));
}
url += URLEncodedUtils.format(params, "UTF-8");
}
return url;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return myURL;
}
}
public void downloadCover(CoverHolder item) {
if (item.getCover() == null)
return;
HttpGet httpget = new HttpGet(cleanUrl(item.getCover()));
HttpResponse response;
try {
response = http_client.execute(httpget);
if (response.getStatusLine().getStatusCode() >= 400) {
return;
}
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
item.setCoverBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
/**
* Perform a HTTP POST request to a given URL
*
* @param url
* URL to fetch
* @param data
* POST data to send
* @param encoding
* Expected encoding of the response body
* @param ignore_errors
* If true, status codes above 400 do not raise an exception
* @param cookieStore
* If set, the given cookieStore is used instead of the built-in
* one.
* @return Answer content
* @throws NotReachableException
* Thrown when server returns a HTTP status code greater or
* equal than 400.
*/
public String httpPost(String url, UrlEncodedFormEntity data,
String encoding, boolean ignore_errors, CookieStore cookieStore)
throws ClientProtocolException, IOException {
HttpPost httppost = new HttpPost(cleanUrl(url));
httppost.setEntity(data);
HttpResponse response = null;
try {
if (cookieStore != null) {
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE,
cookieStore);
response = http_client.execute(httppost, localContext);
} else {
response = http_client.execute(httppost);
}
} catch (ConnectTimeoutException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (IllegalStateException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
// TODO: Handly this well
throw e;
} catch (javax.net.ssl.SSLException e) {
// TODO: Handly this well
// Can be "Not trusted server certificate" or can be a
// aborted/interrupted handshake/connection
throw e;
} catch (InterruptedIOException e) {
e.printStackTrace();
throw new NotReachableException();
} catch (IOException e) {
if (e.getMessage().contains("Request aborted")) {
e.printStackTrace();
throw new NotReachableException();
} else {
throw e;
}
}
if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
throw new NotReachableException();
}
String html = convertStreamToString(response.getEntity().getContent(),
encoding);
response.getEntity().consumeContent();
return html;
}
public String httpPost(String url, UrlEncodedFormEntity data,
String encoding, boolean ignore_errors)
throws ClientProtocolException, IOException {
return httpPost(url, data, encoding, ignore_errors, null);
}
public String httpPost(String url, UrlEncodedFormEntity data,
String encoding) throws ClientProtocolException, IOException {
return httpPost(url, data, encoding, false, null);
}
@Deprecated
public String httpPost(String url, UrlEncodedFormEntity data)
throws ClientProtocolException, IOException {
return httpPost(url, data, getDefaultEncoding(), false, null);
}
/**
* Reads content from an InputStream into a string
*
* @param is
* InputStream to read from
* @return String content of the InputStream
*/
protected static String convertStreamToString(InputStream is,
String encoding) throws IOException {
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is, encoding));
} catch (UnsupportedEncodingException e1) {
reader = new BufferedReader(new InputStreamReader(is));
}
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected static String convertStreamToString(InputStream is)
throws IOException {
return convertStreamToString(is, "ISO-8859-1");
}
protected String getDefaultEncoding() {
return "ISO-8859-1";
}
/*
* Gets all values of all query parameters in an URL.
*/
public static Map<String, List<String>> getQueryParams(String url) {
try {
Map<String, List<String>> params = new HashMap<String, List<String>>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<String>();
params.put(key, values);
}
values.add(value);
}
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
/*
* Gets the value for every query parameter in the URL. If a parameter name
* occurs twice or more, only the first occurance is interpreted by this
* method
*/
public static Map<String, String> getQueryParamsFirst(String url) {
try {
Map<String, String> params = new HashMap<String, String>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
String values = params.get(key);
if (values == null) {
params.put(key, value);
}
}
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
}
|
package com.wizzardo.tools.collections.flow;
import com.wizzardo.tools.collections.flow.flows.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class FlowGrouping<K, T, A, B extends FlowGroup<K, T>> extends Flow<A, B> {
protected final Map<K, FlowGroup<K, T>> groups;
public FlowGrouping(Map<K, FlowGroup<K, T>> groups) {
this.groups = groups;
}
public <V> Flow<V, V> flatMap(Mapper<? super B, V> mapper) {
FlowContinue<V> continueCommand = new FlowContinue<V>(this);
then(new FlowFlatMap<K, V, B>(mapper, continueCommand));
return continueCommand;
}
public Map<K, List<T>> toMap() {
return toMap(Flow.<K, T>flowGroupListMapper());
}
public <V> Map<K, V> toMap(Mapper<? super B, V> mapper) {
return then(new FlowToMap<K, V, B>((Map<K, V>) groups, mapper)).startAndGet();
}
@Override
public FlowGrouping<K, T, B, B> filter(final Filter<? super B> filter) {
return this.then(new FlowGrouping<K, T, B, B>(new LinkedHashMap<K, FlowGroup<K, T>>()) {
@Override
public void process(B b) {
if (filter.allow(b)) {
groups.put(b.getKey(), b);
child.process(b);
}
}
});
}
@Override
public FlowGrouping<K, T, B, B> skip(final int number) {
return this.then(new FlowGrouping<K, T, B, B>(new LinkedHashMap<K, FlowGroup<K, T>>()) {
public int counter;
@Override
public void process(B b) {
if (counter >= number)
child.process(b);
else
counter++;
}
});
}
@Override
public FlowGrouping<K, T, B, B> limit(final int number) {
return this.then(new FlowGrouping<K, T, B, B>(new LinkedHashMap<K, FlowGroup<K, T>>()) {
public int counter;
@Override
public void process(B b) {
if (counter < number) {
counter++;
child.process(b);
}
}
});
}
@Override
public FlowGrouping<K, T, B, B> each(final Consumer<? super B> consumer) {
return this.then(new FlowGrouping<K, T, B, B>(groups) {
@Override
public void process(B b) {
consumer.consume(b);
Flow<B, ?> child = this.child;
if (child != null)
child.process(b);
}
});
}
public FlowGrouping<K, T, B, B> each(final ConsumerWithInt<? super B> consumer) {
return then(new FlowGrouping<K, T, B, B>(groups) {
int index = 0;
@Override
public void process(B b) {
consumer.consume(index++, b);
Flow<B, ?> child = this.child;
if (child != null)
child.process(b);
}
});
}
public Flow<B, T> merge() {
return then(new FlowMerge<B, T>());
}
public <V> Flow<B, V> merge(Mapper<? super B, ? extends Flow<? extends V, ? extends V>> mapper) {
return then(new FlowMapMerge<B, V>(mapper));
}
}
|
package de.geeksfactory.opacclient.apis;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.util.Base64;
import android.util.Log;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailledItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.Status;
import de.geeksfactory.opacclient.storage.MetaDataSource;
public class WinBiap extends BaseApi implements OpacApi {
protected String opac_url = "";
protected MetaDataSource metadata;
protected JSONObject data;
protected Library library;
protected List<List<NameValuePair>> query;
@Override
public void start() throws IOException, NotReachableException {
try {
metadata.open();
} catch (Exception e) {
throw new RuntimeException(e);
}
if (!metadata.hasMeta(library.getIdent())) {
metadata.close();
extract_meta();
} else {
metadata.close();
}
}
public void extract_meta() {
String html;
try {
html = httpGet(opac_url + "/search.aspx", getDefaultEncoding());
Document doc = Jsoup.parse(html);
Elements mediaGroupOptions = doc
.select("#ctl00_ContentPlaceHolderMain_searchPanel_ListBoxMediagroups_ListBoxMultiselection option");
Elements branchOptions = doc
.select("#ctl00_ContentPlaceHolderMain_searchPanel_MultiSelectionBranch_ListBoxMultiselection option");
try {
metadata.open();
} catch (Exception e) {
throw new RuntimeException(e);
}
metadata.clearMeta(library.getIdent());
for (Element option : mediaGroupOptions) {
metadata.addMeta(MetaDataSource.META_TYPE_CATEGORY,
library.getIdent(), option.attr("value"), option.text());
}
for (Element option : branchOptions) {
metadata.addMeta(MetaDataSource.META_TYPE_BRANCH,
library.getIdent(), option.attr("value"), option.text());
}
metadata.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void init(MetaDataSource metadata, Library lib) {
super.init(metadata, lib);
this.metadata = metadata;
this.library = lib;
this.data = lib.getData();
try {
this.opac_url = data.getString("baseurl");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
protected static final String CONTAINS = "8";
protected static final String FROM = "6";
protected static final String TO = "4";
protected static final String STARTS_WITH = "7";
protected static final String EQUALS = "1";
protected int addParameters(Map<String, String> query, String key,
String searchkey, String type, List<List<NameValuePair>> params,
int index) {
if (!query.containsKey(key) || query.get(key).equals(""))
return index;
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("c_" + index, "1"));
list.add(new BasicNameValuePair("m_" + index, "1"));
list.add(new BasicNameValuePair("f_" + index, searchkey)); // query
// property
list.add(new BasicNameValuePair("o_" + index, type)); // query type
list.add(new BasicNameValuePair("v_" + index, query.get(key))); // value
params.add(list);
return index + 1;
}
protected int addParametersManual(String c, String m, String f, String o,
String v, List<List<NameValuePair>> params, int index) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("c_" + index, c));
list.add(new BasicNameValuePair("m_" + index, m));
list.add(new BasicNameValuePair("f_" + index, f)); // query property
list.add(new BasicNameValuePair("o_" + index, o)); // query type
list.add(new BasicNameValuePair("v_" + index, v)); // value
params.add(list);
return index + 1;
}
@Override
public SearchRequestResult search(Map<String, String> query)
throws IOException, NotReachableException, OpacErrorException {
List<List<NameValuePair>> queryParams = new ArrayList<List<NameValuePair>>();
int index = 0;
index = addParameters(query, KEY_SEARCH_QUERY_FREE,
data.optString("KEY_SEARCH_QUERY_FREE", "2"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_AUTHOR,
data.optString("KEY_SEARCH_QUERY_AUTHOR", "3"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_TITLE,
data.optString("KEY_SEARCH_QUERY_TITLE", "12"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_KEYWORDA,
data.optString("KEY_SEARCH_QUERY_KEYWORDA", "24"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_AUDIENCE,
data.optString("KEY_SEARCH_QUERY_AUDIENCE", "25"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_SYSTEM,
data.optString("KEY_SEARCH_QUERY_SYSTEM", "26"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_ISBN,
data.optString("KEY_SEARCH_QUERY_ISBN", "29"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_PUBLISHER,
data.optString("KEY_SEARCH_QUERY_PUBLISHER", "32"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_BARCODE,
data.optString("KEY_SEARCH_QUERY_BARCODE", "46"), CONTAINS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_YEAR_RANGE_START,
data.optString("KEY_SEARCH_QUERY_BARCODE", "34"), FROM,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_YEAR_RANGE_END,
data.optString("KEY_SEARCH_QUERY_BARCODE", "34"), TO,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_CATEGORY,
data.optString("KEY_SEARCH_QUERY_CATEGORY", "42"), EQUALS,
queryParams, index);
index = addParameters(query, KEY_SEARCH_QUERY_BRANCH,
data.optString("KEY_SEARCH_QUERY_BRANCH", "48"), EQUALS,
queryParams, index);
if (index == 0) {
throw new OpacErrorException(
"Es wurden keine Suchkriterien eingegeben.");
}
// if (index > 4) {
// throw new OpacErrorException(
this.query = queryParams;
List<NameValuePair> params = new ArrayList<NameValuePair>();
start();
params.add(new BasicNameValuePair("cmd", "5"));
params.add(new BasicNameValuePair("sC", encode(queryParams, "=", "%%",
"++")));
params.add(new BasicNameValuePair("Sort", "Autor"));
String text = encode(params, "=", "&");
Log.d("opac", text);
String base64 = URLEncoder.encode(
Base64.encodeToString(text.getBytes("UTF-8"), Base64.NO_WRAP),
"UTF-8");
Log.d("opac", opac_url + "/search.aspx?data=" + base64);
String html = httpGet(opac_url + "/search.aspx?data=" + base64,
getDefaultEncoding(), false);
return parse_search(html, 1);
}
private SearchRequestResult parse_search(String html, int page)
throws OpacErrorException, UnsupportedEncodingException {
Document doc = Jsoup.parse(html);
if (doc.select(".alert h4").text().contains("Keine Treffer gefunden")) {
// no media found
return new SearchRequestResult(new ArrayList<SearchResult>(), 0,
page);
}
if (doc.select("errortype").size() > 0) {
// Error (e.g. 404)
throw new OpacErrorException(doc.select("errortype").text());
}
// Total count
String header = doc.select(".ResultHeader").text();
Pattern pattern = Pattern.compile("Die Suche ergab (\\d*) Treffer");
Matcher matcher = pattern.matcher(header);
int results_total = 0;
if (matcher.find()) {
results_total = Integer.parseInt(matcher.group(1));
} else {
Log.d("opac", html);
throw new OpacErrorException("Fehler beim Erkennen der Trefferzahl");
}
// Results
Elements trs = doc.select("#listview .ResultItem");
List<SearchResult> results = new ArrayList<SearchResult>();
for (Element tr : trs) {
SearchResult sr = new SearchResult();
String author = tr.select(".autor").text();
String title = tr.select(".title").text();
String titleAddition = tr.select(".titleZusatz").text();
String desc = tr.select(".smallDescription").text();
sr.setInnerhtml("<b>"
+ (author.equals("") ? "" : author + "<br />")
+ title
+ (titleAddition.equals("") ? "" : " - <i>" + titleAddition
+ "</i>") + "</b><br /><small>" + desc + "</small>");
String coverUrl = tr.select(".coverWrapper input").attr("src");
if (!coverUrl.contains("leer.gif"))
sr.setCover(coverUrl);
String link = tr.select("a[href^=detail.aspx]").attr("href");
String base64 = getQueryParamsFirst(link).get("data");
if (base64.contains("-"))
base64 = base64.substring(0, base64.indexOf("-") - 1);
String decoded = new String(Base64.decode(base64, Base64.NO_WRAP),
"UTF-8");
pattern = Pattern.compile("CatalogueId=(\\d*)");
matcher = pattern.matcher(decoded);
if (matcher.find()) {
sr.setId(matcher.group(1));
} else {
Log.d("opac", decoded);
throw new OpacErrorException("Fehler beim Erkennen eines Links");
}
if (tr.select(".mediaStatus").size() > 0) {
Element status = tr.select(".mediaStatus").first();
if (status.hasClass("StatusNotAvailable")) {
sr.setStatus(Status.RED);
} else if (status.hasClass("StatusAvailable")) {
sr.setStatus(Status.GREEN);
} else {
sr.setStatus(Status.YELLOW);
}
} else if (tr.select(".showCopies").size() > 0) { // Multiple copies
if (tr.nextElementSibling().select(".StatusNotAvailable")
.size() == 0) {
sr.setStatus(Status.GREEN);
} else if (tr.nextElementSibling().select(".StatusAvailable")
.size() == 0) {
sr.setStatus(Status.RED);
} else {
sr.setStatus(Status.YELLOW);
}
}
results.add(sr);
}
return new SearchRequestResult(results, results_total, page);
}
private String encode(List<List<NameValuePair>> list, String equals,
String separator, String separator2) {
if (list.size() > 0) {
String encoded = encode(list.get(0), equals, separator);
for (int i = 1; i < list.size(); i++) {
encoded += separator2;
encoded += encode(list.get(i), equals, separator);
}
return encoded;
} else {
return "";
}
}
private String encode(List<NameValuePair> list, String equals,
String separator) {
if (list.size() > 0) {
String encoded = list.get(0).getName() + equals
+ list.get(0).getValue();
for (int i = 1; i < list.size(); i++) {
encoded += separator;
encoded += list.get(i).getName() + equals
+ list.get(i).getValue();
}
return encoded;
} else {
return "";
}
}
@Override
public SearchRequestResult filterResults(Filter filter, Option option)
throws IOException, NotReachableException, OpacErrorException {
return null;
}
@Override
public SearchRequestResult searchGetPage(int page) throws IOException,
NotReachableException, OpacErrorException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cmd", "1"));
params.add(new BasicNameValuePair("sC", encode(query, "=", "%%", "++")));
params.add(new BasicNameValuePair("pI", String.valueOf(page - 1)));
params.add(new BasicNameValuePair("Sort", "Autor"));
String text = encode(params, "=", "&");
Log.d("opac", text);
String base64 = URLEncoder.encode(
Base64.encodeToString(text.getBytes("UTF-8"), Base64.NO_WRAP),
"UTF-8");
Log.d("opac", opac_url + "/search.aspx?data=" + base64);
String html = httpGet(opac_url + "/search.aspx?data=" + base64,
getDefaultEncoding(), false);
return parse_search(html, page);
}
@Override
public DetailledItem getResultById(String id, String homebranch)
throws IOException, NotReachableException, OpacErrorException {
String html = httpGet(opac_url + "/detail.aspx?Id=" + id,
getDefaultEncoding(), false);
return parse_result(html);
}
private DetailledItem parse_result(String html) {
Document doc = Jsoup.parse(html);
DetailledItem item = new DetailledItem();
item.setCover(doc.select(".cover").attr("src"));
String permalink = doc.select(".PermalinkTextarea").text();
item.setId(getQueryParamsFirst(permalink).get("Id"));
Elements trs = doc.select("#detail-center .DetailInformation tr");
for (Element tr : trs) {
String name = tr.select(".DetailInformationEntryName").text()
.replace(":", "");
String value = tr.select(".DetailInformationEntryContent").text();
if (name.equals("Titel")) {
item.setTitle(value);
} else if (name.equals("Stücktitel")) {
item.setTitle(item.getTitle() + " " + value);
} else {
item.addDetail(new Detail(name, value));
}
}
trs = doc.select(".detailCopies .tableCopies tr:not(.headerCopies)");
for (Element tr : trs) {
Map<String, String> copy = new HashMap<String, String>();
copy.put(DetailledItem.KEY_COPY_BARCODE, tr.select(".mediaBarcode")
.text().replace("
copy.put(DetailledItem.KEY_COPY_STATUS, tr.select(".mediaStatus")
.text());
copy.put(DetailledItem.KEY_COPY_LOCATION,
tr.select("#mediaItemLocationWrapper span").text());
item.addCopy(copy);
}
return item;
}
@Override
public DetailledItem getResult(int position) throws IOException,
OpacErrorException {
// Should not be called because every media has an ID
return null;
}
@Override
public ReservationResult reservation(DetailledItem item, Account account,
int useraction, String selection) throws IOException {
return null;
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String selection) throws IOException {
return null;
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction,
String selection) throws IOException {
return null;
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
return null;
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
return null;
}
@Override
public String[] getSearchFields() {
return new String[] { KEY_SEARCH_QUERY_FREE, KEY_SEARCH_QUERY_AUTHOR,
KEY_SEARCH_QUERY_TITLE, KEY_SEARCH_QUERY_KEYWORDA,
KEY_SEARCH_QUERY_AUDIENCE, KEY_SEARCH_QUERY_SYSTEM,
KEY_SEARCH_QUERY_ISBN, KEY_SEARCH_QUERY_PUBLISHER,
KEY_SEARCH_QUERY_BARCODE, KEY_SEARCH_QUERY_YEAR_RANGE_START,
KEY_SEARCH_QUERY_YEAR_RANGE_END, KEY_SEARCH_QUERY_BRANCH,
KEY_SEARCH_QUERY_CATEGORY };
}
@Override
public boolean isAccountSupported(Library library) {
return false;
}
@Override
public boolean isAccountExtendable() {
return false;
}
@Override
public String getAccountExtendableInfo(Account account) throws IOException,
NotReachableException {
return null;
}
@Override
public String getShareUrl(String id, String title) {
return opac_url + "/detail.aspx?Id=" + id;
}
@Override
public int getSupportFlags() {
return SUPPORT_FLAG_ENDLESS_SCROLLING;
}
}
|
package org.navalplanner.web.orders;
import static org.navalplanner.web.I18nHelper._;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.orders.entities.OrderLine;
import org.navalplanner.business.orders.entities.OrderLineGroup;
import org.navalplanner.business.orders.entities.SchedulingState;
import org.navalplanner.business.requirements.entities.CriterionRequirement;
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.navalplanner.web.common.IMessagesForUser;
import org.navalplanner.web.common.Level;
import org.navalplanner.web.common.Util;
import org.navalplanner.web.common.Util.Getter;
import org.navalplanner.web.common.Util.Setter;
import org.navalplanner.web.common.components.bandboxsearch.BandboxMultipleSearch;
import org.navalplanner.web.common.components.bandboxsearch.BandboxSearch;
import org.navalplanner.web.common.components.finders.FilterPair;
import org.navalplanner.web.orders.assigntemplates.TemplateFinderPopup;
import org.navalplanner.web.orders.assigntemplates.TemplateFinderPopup.IOnResult;
import org.navalplanner.web.templates.IOrderTemplatesControllerEntryPoints;
import org.navalplanner.web.tree.TreeController;
import org.zkoss.ganttz.IPredicate;
import org.zkoss.ganttz.util.ComponentsFinder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.KeyEvent;
import org.zkoss.zul.Button;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Treechildren;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.Vbox;
import org.zkoss.zul.api.Treecell;
import org.zkoss.zul.api.Treerow;
import org.zkoss.zul.impl.api.InputElement;
public class OrderElementTreeController extends TreeController<OrderElement> {
private Vbox orderElementFilter;
private BandboxMultipleSearch bdFiltersOrderElement;
private Datebox filterStartDateOrderElement;
private Datebox filterFinishDateOrderElement;
private Textbox filterNameOrderElement;
private OrderElementTreeitemRenderer renderer = new OrderElementTreeitemRenderer();
private final IOrderModel orderModel;
private final OrderElementController orderElementController;
private transient IPredicate predicate;
@Resource
private IOrderTemplatesControllerEntryPoints orderTemplates;
private final IMessagesForUser messagesForUser;
public List<org.navalplanner.business.labels.entities.Label> getLabels() {
return orderModel.getLabels();
}
@Override
public OrderElementTreeitemRenderer getRenderer() {
return renderer;
}
public OrderElementTreeController(IOrderModel orderModel,
OrderElementController orderElementController,
IMessagesForUser messagesForUser) {
super(OrderElement.class);
this.orderModel = orderModel;
this.orderElementController = orderElementController;
this.messagesForUser = messagesForUser;
}
public OrderElementController getOrderElementController() {
return orderElementController;
}
@Override
protected OrderElementTreeModel getModel() {
return orderModel.getOrderElementTreeModel();
}
public void createTemplateFromSelectedOrderElement() {
if (tree.getSelectedCount() == 1) {
createTemplate(getSelectedNode());
} else {
showSelectAnElementMessageBox();
}
}
public void editSelectedOrderElement() {
if (tree.getSelectedCount() == 1) {
showEditionOrderElement(tree.getSelectedItem());
} else {
showSelectAnElementMessageBox();
}
}
public void moveSelectedOrderElementUp() {
if (tree.getSelectedCount() == 1) {
Treeitem item = tree.getSelectedItem();
up((OrderElement)item.getValue());
Treeitem brother = (Treeitem) item.getPreviousSibling();
if (brother != null) {
brother.setSelected(true);
}
} else {
showSelectAnElementMessageBox();
}
}
public void moveSelectedOrderElementDown() {
if (tree.getSelectedCount() == 1) {
Treeitem item = tree.getSelectedItem();
down((OrderElement)item.getValue());
Treeitem brother = (Treeitem) item.getNextSibling();
if (brother != null) {
brother.setSelected(true);
}
} else {
showSelectAnElementMessageBox();
}
}
public void indentSelectedOrderElement() {
if (tree.getSelectedCount() == 1) {
indent(getSelectedNode());
} else {
showSelectAnElementMessageBox();
}
}
public void unindentSelectedOrderElement() {
if (tree.getSelectedCount() == 1) {
unindent(getSelectedNode());
} else {
showSelectAnElementMessageBox();
}
}
public void deleteSelectedOrderElement() {
if (tree.getSelectedCount() == 1) {
remove(getSelectedNode());
} else {
showSelectAnElementMessageBox();
}
}
private void showSelectAnElementMessageBox() {
try {
Messagebox.show(_("Choose a task "
+ "to operate on it"));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private boolean isTemplateCreationConfirmed() {
try {
int status = Messagebox
.show(
_("Still not saved changes would be lost."
+ " Are you sure you want to go to create a template?"),
"Confirm", Messagebox.YES | Messagebox.NO,
Messagebox.QUESTION);
return Messagebox.YES == status;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void createFromTemplate() {
templateFinderPopup.openForSubElemenetCreation(tree, "after_pointer",
new IOnResult<OrderElementTemplate>() {
@Override
public void found(OrderElementTemplate template) {
OrderLineGroup parent = (OrderLineGroup) getModel()
.getRoot();
orderModel.createFrom(parent, template);
getModel().addNewlyAddedChildrenOf(parent);
}
});
}
private void createTemplate(OrderElement selectedNode) {
if (!isTemplateCreationConfirmed()) {
return;
}
if (!selectedNode.isNewObject()) {
orderTemplates.goToCreateTemplateFrom(selectedNode);
} else {
notifyTemplateCantBeCreated();
}
}
private void notifyTemplateCantBeCreated() {
try {
Messagebox
.show(
_("Templates can only be created from already existent tasks.\n"
+ "Newly tasks cannot be used."),
_("Operation cannot be done"), Messagebox.OK,
Messagebox.INFORMATION);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void notifyDateboxCantBeCreated(final String dateboxName,
final String codeOrderElement) {
try {
Messagebox.show(_("the " + dateboxName
+ "datebox of the task " + codeOrderElement
+ " could not be created.\n"),
_("Operation cannot be done"), Messagebox.OK,
Messagebox.INFORMATION);
} catch (InterruptedException e) {
}
}
protected void filterByPredicateIfAny() {
if (predicate != null) {
filterByPredicate();
}
}
private void filterByPredicate() {
OrderElementTreeModel orderElementTreeModel = orderModel
.getOrderElementsFilteredByPredicate(predicate);
tree.setModel(orderElementTreeModel.asTree());
tree.invalidate();
}
void doEditFor(Order order) {
Util.reloadBindings(tree);
}
public void disabledCodeBoxes(boolean disabled) {
Set<Treeitem> childrenSet = new HashSet<Treeitem>();
Treechildren treeChildren = tree.getTreechildren();
if (treeChildren != null) {
childrenSet.addAll((Collection<Treeitem>) treeChildren.getItems());
}
for (Treeitem each : childrenSet) {
disableCodeBoxes(each, disabled);
}
}
private void disableCodeBoxes(Treeitem item, boolean disabled) {
Treerow row = item.getTreerow();
InputElement codeBox = (InputElement) ((Treecell) row.getChildren()
.get(1)).getChildren().get(0);
codeBox.setDisabled(disabled);
codeBox.invalidate();
Set<Treeitem> childrenSet = new HashSet<Treeitem>();
Treechildren children = item.getTreechildren();
if (children != null) {
childrenSet.addAll((Collection<Treeitem>) children.getItems());
}
for (Treeitem each : childrenSet) {
disableCodeBoxes(each, disabled);
}
}
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
orderElementFilter.getChildren().clear();
appendExpandCollapseButton();
// Configuration of the order elements filter
Component filterComponent = Executions.createComponents(
"/orders/_orderElementTreeFilter.zul", orderElementFilter,
new HashMap<String, String>());
filterComponent.setVariable("treeController", this, true);
bdFiltersOrderElement = (BandboxMultipleSearch) filterComponent
.getFellow("bdFiltersOrderElement");
filterStartDateOrderElement = (Datebox) filterComponent
.getFellow("filterStartDateOrderElement");
filterFinishDateOrderElement = (Datebox) filterComponent
.getFellow("filterFinishDateOrderElement");
filterNameOrderElement = (Textbox) filterComponent
.getFellow("filterNameOrderElement");
templateFinderPopup = (TemplateFinderPopup) comp
.getFellow("templateFinderPopupAtTree");
}
private void appendExpandCollapseButton() {
List<Component> children = orderElementFilter.getParent().getChildren();
// Is already added?
Button button = (Button) ComponentsFinder.findById("expandAllButton", children);
if (button != null) {
return;
}
// Append expand/collapse button
final Button expandAllButton = new Button();
expandAllButton.setId("expandAllButton");
expandAllButton.setClass("planner-command");
expandAllButton.setTooltiptext(_("Expand/Collapse all"));
expandAllButton.setImage("/common/img/ico_expand.png");
expandAllButton.addEventListener("onClick", new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
if (expandAllButton.getSclass().equals("planner-command")) {
expandAll();
expandAllButton.setSclass("planner-command clicked");
} else {
collapseAll();
expandAllButton.setSclass("planner-command");
}
}
});
children.add(expandAllButton);
}
public void expandAll() {
Set<Treeitem> childrenSet = new HashSet<Treeitem>();
Treechildren children = tree.getTreechildren();
if(children != null) {
childrenSet.addAll((Collection<Treeitem>) children.getItems());
}
for(Treeitem each: childrenSet) {
expandAll(each);
}
}
private void expandAll(Treeitem item) {
item.setOpen(true);
Set<Treeitem> childrenSet = new HashSet<Treeitem>();
Treechildren children = item.getTreechildren();
if(children != null) {
childrenSet.addAll((Collection<Treeitem>) children.getItems());
}
for(Treeitem each: childrenSet) {
expandAll(each);
}
}
public void collapseAll() {
Treechildren children = tree.getTreechildren();
for(Treeitem each: (Collection<Treeitem>) children.getItems()) {
each.setOpen(false);
}
}
private enum Navigation {
LEFT, UP, RIGHT, DOWN;
public static Navigation getIntentFrom(KeyEvent keyEvent) {
return values()[keyEvent.getKeyCode() - 37];
}
}
private Map<OrderElement, Textbox> orderElementCodeTextboxes = new HashMap<OrderElement, Textbox>();
public Map<OrderElement, Textbox> getOrderElementCodeTextboxes() {
return orderElementCodeTextboxes;
}
public class OrderElementTreeitemRenderer extends Renderer {
private class KeyboardNavigationHandler {
void registerKeyboardListener(final InputElement inputElement) {
inputElement.setCtrlKeys("#up#down");
inputElement.addEventListener("onCtrlKey", new EventListener() {
private Treerow treerow = getCurrentTreeRow();
@Override
public void onEvent(Event event) throws Exception {
Navigation navigation = Navigation
.getIntentFrom((KeyEvent) event);
moveFocusTo(inputElement, navigation, treerow);
}
});
}
private void moveFocusTo(InputElement inputElement,
Navigation navigation, Treerow treerow) {
List<InputElement> boxes = getBoxes(treerow);
int position = boxes.indexOf(inputElement);
switch (navigation) {
case UP:
focusGoUp(treerow, position);
break;
case DOWN:
focusGoDown(treerow, position);
break;
case LEFT:
if (position == 0) {
focusGoUp(treerow, boxes.size() - 1);
} else {
if (boxes.get(position - 1).isDisabled()) {
moveFocusTo(boxes.get(position - 1),
Navigation.LEFT, treerow);
} else {
boxes.get(position - 1).focus();
}
}
break;
case RIGHT:
if (position == boxes.size() - 1) {
focusGoDown(treerow, 0);
} else {
if (boxes.get(position + 1).isDisabled()) {
moveFocusTo(boxes.get(position + 1),
Navigation.RIGHT, treerow);
} else {
boxes.get(position + 1).focus();
}
}
break;
}
}
private void focusGoUp(Treerow treerow, int position) {
Treeitem parent = (Treeitem) treerow.getParent();
List treeItems = parent.getParent().getChildren();
int myPosition = parent.indexOf();
if (myPosition > 0) {
// the current node is not the first brother
Treechildren treechildren = ((Treeitem) treeItems
.get(myPosition - 1)).getTreechildren();
if (treechildren == null
|| treechildren.getChildren().size() == 0) {
// the previous brother doesn't have children,
// or it has children but they are unloaded
Treerow upTreerow = ((Treeitem) treeItems
.get(myPosition - 1)).getTreerow();
focusCorrectBox(upTreerow, position, Navigation.LEFT);
}
else {
// we have to move to the last child of the previous
// brother
Treerow upTreerow = findLastTreerow((Treeitem) treeItems
.get(myPosition - 1));
while (!upTreerow.isVisible()) {
upTreerow = (Treerow) ((Treeitem) upTreerow
.getParent().getParent().getParent())
.getTreerow();
}
focusCorrectBox(upTreerow, position, Navigation.LEFT);
}
}
else {
// the node is the first brother
if (parent.getParent().getParent() instanceof Treeitem) {
// the node has a parent, so we move up to it
Treerow upTreerow = ((Treeitem) parent.getParent()
.getParent()).getTreerow();
focusCorrectBox(upTreerow, position, Navigation.LEFT);
}
}
}
private Treerow findLastTreerow(Treeitem item) {
if (item.getTreechildren() == null) {
return item.getTreerow();
}
List children = item.getTreechildren().getChildren();
Treeitem lastchild = (Treeitem) children
.get(children.size() - 1);
return findLastTreerow(lastchild);
}
private void focusGoDown(Treerow treerow, int position) {
Treeitem parent = (Treeitem) treerow.getParent();
focusGoDown(parent, position, false);
}
private void focusGoDown(Treeitem parent, int position,
boolean skipChildren) {
if (parent.getTreechildren() == null || skipChildren) {
// Moving from a node to its brother
List treeItems = parent.getParent().getChildren();
int myPosition = parent.indexOf();
if (myPosition < treeItems.size() - 1) {
// the current node is not the last one
Treerow downTreerow = ((Treeitem) treeItems
.get(myPosition + 1)).getTreerow();
focusCorrectBox(downTreerow, position, Navigation.RIGHT);
} else {
// the node is the last brother
if (parent.getParent().getParent() instanceof Treeitem) {
focusGoDown((Treeitem) parent.getParent()
.getParent(), position, true);
}
}
} else {
// Moving from a parent node to its children
Treechildren treechildren = parent.getTreechildren();
if (treechildren.getChildren().size() == 0) {
// the children are unloaded yet
focusGoDown(parent, position, true);
return;
}
Treerow downTreerow = ((Treeitem) treechildren
.getChildren().get(0)).getTreerow();
if (!downTreerow.isVisible()) {
// children are loaded but not visible
focusGoDown(parent, position, true);
return;
}
focusCorrectBox(downTreerow, position, Navigation.RIGHT);
}
}
private void focusCorrectBox(Treerow treerow, int position,
Navigation whereIfDisabled) {
List<InputElement> boxes = getBoxes(treerow);
if (boxes.get(position).isDisabled()) {
moveFocusTo(boxes.get(position), whereIfDisabled, treerow);
}
else {
boxes.get(position).focus();
}
}
private List<InputElement> getBoxes(Treerow row) {
InputElement codeBox = (InputElement) ((Treecell) row
.getChildren().get(1)).getChildren().get(0);
InputElement nameBox = (InputElement) ((Treecell) row
.getChildren().get(2)).getChildren().get(0);
InputElement hoursBox = (InputElement) ((Treecell) row
.getChildren().get(3)).getChildren().get(0);
InputElement initDateBox = (InputElement) ((Hbox) ((Treecell) row
.getChildren().get(4)).getChildren().get(0))
.getChildren().get(0);
InputElement endDateBox = (InputElement) ((Hbox) ((Treecell) row
.getChildren().get(5)).getChildren().get(0))
.getChildren().get(0);
return Arrays.asList(codeBox, nameBox, hoursBox, initDateBox,
endDateBox);
}
}
private Map<OrderElement, Intbox> hoursIntBoxByOrderElement = new HashMap<OrderElement, Intbox>();
private KeyboardNavigationHandler navigationHandler = new KeyboardNavigationHandler();
public OrderElementTreeitemRenderer() {
}
@Override
protected void addDescriptionCell(OrderElement element) {
addTaskNameCell(element);
}
private void addTaskNameCell(final OrderElement orderElementForThisRow) {
int[] path = getModel().getPath(orderElementForThisRow);
String cssClass = "depth_" + path.length;
Textbox textBox = Util.bind(new Textbox(),
new Util.Getter<String>() {
@Override
public String get() {
return orderElementForThisRow.getName();
}
}, new Util.Setter<String>() {
@Override
public void set(String value) {
orderElementForThisRow.setName(value);
}
});
if (readOnly) {
textBox.setDisabled(true);
}
addCell(cssClass, textBox);
navigationHandler.registerKeyboardListener(textBox);
}
@Override
protected SchedulingState getSchedulingStateFrom(
OrderElement currentElement) {
return currentElement.getSchedulingState();
}
@Override
protected void onDoubleClickForSchedulingStateCell(
final OrderElement currentOrderElement) {
IOrderElementModel model = orderModel
.getOrderElementModel(currentOrderElement);
orderElementController.openWindow(model);
updateOrderElementHours(currentOrderElement);
}
protected void addCodeCell(final OrderElement orderElement) {
Textbox textBoxCode = new Textbox();
Util.bind(textBoxCode, new Util.Getter<String>() {
@Override
public String get() {
return orderElement.getCode();
}
}, new Util.Setter<String>() {
@Override
public void set(String value) {
orderElement.setCode(value);
}
});
textBoxCode.setConstraint(new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
if (!orderElement.isFormatCodeValid((String) value)) {
throw new WrongValueException(
comp,
_("Value is not valid.\n Code cannot contain chars like '_' \n and should not be empty"));
}
}
});
if (orderModel.isCodeAutogenerated() || readOnly) {
textBoxCode.setDisabled(true);
}
addCell(textBoxCode);
navigationHandler.registerKeyboardListener(textBoxCode);
orderElementCodeTextboxes.put(orderElement, textBoxCode);
}
void addInitDateCell(final OrderElement currentOrderElement) {
DynamicDatebox dinamicDatebox = new DynamicDatebox(
currentOrderElement, new DynamicDatebox.Getter<Date>() {
@Override
public Date get() {
return currentOrderElement.getInitDate();
}
}, new DynamicDatebox.Setter<Date>() {
@Override
public void set(Date value) {
currentOrderElement.setInitDate(value);
}
});
if (readOnly) {
dinamicDatebox.setDisabled(true);
}
addDateCell(dinamicDatebox, _("init"), currentOrderElement);
navigationHandler.registerKeyboardListener(dinamicDatebox
.getDateTextBox());
}
void addEndDateCell(final OrderElement currentOrderElement) {
DynamicDatebox dinamicDatebox = new DynamicDatebox(
currentOrderElement, new DynamicDatebox.Getter<Date>() {
@Override
public Date get() {
return currentOrderElement.getDeadline();
}
}, new DynamicDatebox.Setter<Date>() {
@Override
public void set(Date value) {
currentOrderElement.setDeadline(value);
}
});
if (readOnly) {
dinamicDatebox.setDisabled(true);
}
addDateCell(dinamicDatebox, _("end"), currentOrderElement);
navigationHandler.registerKeyboardListener(dinamicDatebox
.getDateTextBox());
}
void addHoursCell(final OrderElement currentOrderElement) {
Intbox intboxHours = buildHoursIntboxFor(currentOrderElement);
hoursIntBoxByOrderElement.put(currentOrderElement, intboxHours);
if (readOnly) {
intboxHours.setDisabled(true);
}
Treecell cellHours = addCell(intboxHours);
setReadOnlyHoursCell(currentOrderElement, intboxHours, cellHours);
navigationHandler.registerKeyboardListener(intboxHours);
}
private void addDateCell(final DynamicDatebox dinamicDatebox,
final String dateboxName,
final OrderElement currentOrderElement) {
Component cell = Executions.getCurrent().createComponents(
"/common/components/dynamicDatebox.zul", null, null);
try {
dinamicDatebox.doAfterCompose(cell);
} catch (Exception e) {
notifyDateboxCantBeCreated(dateboxName, currentOrderElement
.getCode());
}
registerFocusEvent(dinamicDatebox.getDateTextBox());
addCell(cell);
}
private Intbox buildHoursIntboxFor(
final OrderElement currentOrderElement) {
Intbox result = new Intbox();
if (currentOrderElement instanceof OrderLine) {
OrderLine orderLine = (OrderLine) currentOrderElement;
Util.bind(result, getHoursGetterFor(currentOrderElement),
getHoursSetterFor(orderLine));
result.setConstraint(getHoursConstraintFor(orderLine));
} else {
// If it's a container hours cell is not editable
Util.bind(result, getHoursGetterFor(currentOrderElement));
}
return result;
}
private Getter<Integer> getHoursGetterFor(
final OrderElement currentOrderElement) {
return new Util.Getter<Integer>() {
@Override
public Integer get() {
return currentOrderElement.getWorkHours();
}
};
}
private Constraint getHoursConstraintFor(final OrderLine orderLine) {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
if (!orderLine.isTotalHoursValid((Integer) value)) {
throw new WrongValueException(
comp,
_("Value is not valid, taking into account the current list of HoursGroup"));
}
}
};
}
private Setter<Integer> getHoursSetterFor(final OrderLine orderLine) {
return new Util.Setter<Integer>() {
@Override
public void set(Integer value) {
orderLine.setWorkHours(value);
List<OrderElement> parentNodes = getModel().getParents(
orderLine);
// Remove the last element because it's an
// Order node, not an OrderElement
parentNodes.remove(parentNodes.size() - 1);
for (OrderElement node : parentNodes) {
Intbox intbox = hoursIntBoxByOrderElement.get(node);
intbox.setValue(node.getWorkHours());
}
}
};
}
@Override
protected void addOperationsCell(final Treeitem item,
final OrderElement currentOrderElement) {
addCell(createEditButton(currentOrderElement, item),
createRemoveButton(currentOrderElement));
}
private Button createEditButton(final OrderElement currentOrderElement,
final Treeitem item) {
Button editbutton = createButton("/common/img/ico_editar1.png",
_("Edit"), "/common/img/ico_editar.png", "icono",
new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
showEditionOrderElement(item);
}
});
return editbutton;
}
}
@Override
protected boolean isPredicateApplied() {
return predicate != null;
}
/**
* Apply filter to order elements in current order
*/
public void onApplyFilter() {
OrderElementPredicate predicate = createPredicate();
this.predicate = predicate;
if (predicate != null) {
filterByPredicate(predicate);
} else {
showAllOrderElements();
}
}
private OrderElementPredicate createPredicate() {
List<FilterPair> listFilters = (List<FilterPair>) bdFiltersOrderElement
.getSelectedElements();
Date startDate = filterStartDateOrderElement.getValue();
Date finishDate = filterFinishDateOrderElement.getValue();
String name = filterNameOrderElement.getValue();
if (listFilters.isEmpty() && startDate == null && finishDate == null
&& name == null) {
return null;
}
return new OrderElementPredicate(listFilters, startDate, finishDate,
name);
}
private void filterByPredicate(OrderElementPredicate predicate) {
OrderElementTreeModel orderElementTreeModel = orderModel
.getOrderElementsFilteredByPredicate(predicate);
tree.setModel(orderElementTreeModel.asTree());
tree.invalidate();
}
public void showAllOrderElements() {
this.predicate = null;
tree.setModel(orderModel.getOrderElementTreeModel().asTree());
tree.invalidate();
}
@Override
protected boolean isNewButtonDisabled() {
if(readOnly) {
return true;
}
return isPredicateApplied();
}
/**
* Clear {@link BandboxSearch} for Labels, and initializes
* {@link IPredicate}
*/
public void clear() {
selectDefaultTab();
bdFiltersOrderElement.clear();
predicate = null;
}
Tab tabGeneralData;
private TemplateFinderPopup templateFinderPopup;
private void selectDefaultTab() {
tabGeneralData.setSelected(true);
}
@Override
protected String createTooltipText(OrderElement elem) {
StringBuilder tooltipText = new StringBuilder();
tooltipText.append(elem.getName() + ". ");
if ((elem.getDescription() != null)
&& (!elem.getDescription().equals(""))) {
tooltipText.append(elem.getDescription());
tooltipText.append(". ");
}
if ((elem.getLabels() != null) && (!elem.getLabels().isEmpty())) {
tooltipText.append(" " + _("Labels") + ":");
tooltipText.append(StringUtils.join(elem.getLabels(), ","));
tooltipText.append(".");
}
if ((elem.getCriterionRequirements() != null)
&& (!elem.getCriterionRequirements().isEmpty())) {
ArrayList<String> criterionNames = new ArrayList<String>();
for(CriterionRequirement each:elem.getCriterionRequirements()) {
if (each.isValid()) {
criterionNames.add(each.getCriterion().getName());
}
}
if (!criterionNames.isEmpty()) {
tooltipText.append(" " + _("Criteria") + ":");
tooltipText.append(StringUtils.join(criterionNames, ","));
tooltipText.append(".");
}
}
// To calculate other unit advances implement
// getOtherAdvancesPercentage()
tooltipText.append(" " + _("Advance") + ":" + elem.getAdvancePercentage());
tooltipText.append(".");
// tooltipText.append(elem.getAdvancePercentage());
return tooltipText.toString();
}
public void showEditionOrderElement(final Treeitem item) {
OrderElement currentOrderElement = (OrderElement) item.getValue();
markModifiedTreeitem(item.getTreerow());
IOrderElementModel model = orderModel
.getOrderElementModel(currentOrderElement);
orderElementController.openWindow(model);
updateOrderElementHours(currentOrderElement);
}
private void updateOrderElementHours(OrderElement orderElement) {
if ((!readOnly) && (orderElement instanceof OrderLine)) {
Intbox boxHours = (Intbox) getRenderer().hoursIntBoxByOrderElement
.get(orderElement);
boxHours.setValue(orderElement.getWorkHours());
Treecell tc = (Treecell) boxHours.getParent();
setReadOnlyHoursCell(orderElement, boxHours, tc);
boxHours.invalidate();
}
}
private void setReadOnlyHoursCell(OrderElement orderElement,
Intbox boxHours, Treecell tc) {
if ((!readOnly) && (orderElement instanceof OrderLine)) {
if (orderElement.getHoursGroups().size() > 1) {
boxHours.setReadonly(true);
tc
.setTooltiptext(_("Not editable for containing more that an hours group."));
} else {
boxHours.setReadonly(false);
tc.setTooltiptext("");
}
}
}
public Treeitem getTreeitemByOrderElement(OrderElement element) {
List<Treeitem> listItems = new ArrayList<Treeitem>(this.tree.getItems());
for (Treeitem item : listItems) {
OrderElement orderElement = (OrderElement) item.getValue();
if (orderElement.getId().equals(element.getId())) {
return item;
}
}
return null;
}
/**
* Operations to filter the orders by multiple filters
*/
public Constraint checkConstraintFinishDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date finishDate = (Date) value;
if ((finishDate != null)
&& (filterStartDateOrderElement.getValue() != null)
&& (finishDate.compareTo(filterStartDateOrderElement
.getValue()) < 0)) {
filterFinishDateOrderElement.setValue(null);
throw new WrongValueException(comp,
_("must be greater than start date"));
}
}
};
}
public Constraint checkConstraintStartDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date startDate = (Date) value;
if ((startDate != null)
&& (filterFinishDateOrderElement.getValue() != null)
&& (startDate.compareTo(filterFinishDateOrderElement
.getValue()) > 0)) {
filterStartDateOrderElement.setValue(null);
throw new WrongValueException(comp,
_("must be lower than finish date"));
}
}
};
}
@Override
protected void remove(OrderElement element) {
boolean alreadyInUse = orderModel.isAlreadyInUse(element);
if (alreadyInUse) {
messagesForUser
.showMessage(
Level.ERROR,
_(
"You can not remove the task \"{0}\" because of this or any of its children are already in use in some work reports",
element.getName()));
} else {
super.remove(element);
orderElementCodeTextboxes.remove(element);
}
}
@Override
protected void refreshHoursBox(OrderElement node) {
List<OrderElement> parentNodes = getModel().getParents(node);
// Remove the last element because it's an
// Order node, not an OrderElement
parentNodes.remove(parentNodes.size() - 1);
for (OrderElement parent : parentNodes) {
getRenderer().hoursIntBoxByOrderElement.get(parent)
.setValue(parent.getWorkHours());
}
}
}
|
package io.openvidu.java.client.test;
import static org.junit.Assert.assertThrows;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.openvidu.java.client.ConnectionProperties;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ConnectionPropertiesTest extends TestCase {
public ConnectionPropertiesTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(ConnectionPropertiesTest.class);
}
public void testWebrtcFromJsonSuccess() {
String jsonString = "{'type':'WEBRTC','data':'MY_CUSTOM_STRING','record':false,'role':'SUBSCRIBER','kurentoOptions':{'videoMaxRecvBandwidth':333,'videoMinRecvBandwidth':333,'videoMaxSendBandwidth':333,'videoMinSendBandwidth':333,'allowedFilters':['CustomFilter']},'customIceServers':[{'url':'turn:turn-domain.com:443','username':'MY_CUSTOM_STRING','credential':'MY_CUSTOM_STRING'}]}";
JsonObject originalJson = new Gson().fromJson(jsonString, JsonObject.class);
Map<String, ?> map = mapFromJsonString(jsonString);
ConnectionProperties.Builder builder = ConnectionProperties.fromJson(map);
ConnectionProperties props = builder.build();
JsonObject finalJson = props.toJson("MY_CUSTOM_STRING");
finalJson = removeIpcamProps(finalJson);
assertEquals(originalJson, finalJson);
}
public void testIpcamFromJsonSuccess() {
String jsonString = "{'type':'IPCAM','data':'MY_CUSTOM_STRING','record':false,'rtspUri':'rtsp://your.camera.ip.sdp','adaptativeBitrate':false,'onlyPlayWithSubscribers':false,'networkCache':333}";
JsonObject originalJson = new Gson().fromJson(jsonString, JsonObject.class);
Map<String, ?> map = mapFromJsonString(jsonString);
ConnectionProperties.Builder builder = ConnectionProperties.fromJson(map);
ConnectionProperties props = builder.build();
JsonObject finalJson = props.toJson("MY_CUSTOM_STRING");
finalJson = removeWebrtcProps(finalJson);
assertEquals(originalJson, finalJson);
jsonString = "{'type':'IPCAM','rtspUri':'rtsp://your.camera.ip.sdp'}";
ConnectionProperties.fromJson(mapFromJsonString(jsonString)).build();
jsonString = "{'type':'IPCAM','rtspUri':'rtsps://your.camera.ip.sdp'}";
ConnectionProperties.fromJson(mapFromJsonString(jsonString)).build();
jsonString = "{'type':'IPCAM','rtspUri':'file://your.camera.ip.sdp'}";
ConnectionProperties.fromJson(mapFromJsonString(jsonString)).build();
jsonString = "{'type':'IPCAM','rtspUri':'http://your.camera.ip.sdp'}";
ConnectionProperties.fromJson(mapFromJsonString(jsonString)).build();
jsonString = "{'type':'IPCAM','rtspUri':'https://your.camera.ip.sdp'}";
ConnectionProperties.fromJson(mapFromJsonString(jsonString)).build();
}
public void testFromJsonError() {
Map<String, ?> map = mapFromJsonString("{'type':'NOT_EXISTS'}");
assertException(map, "type");
map = mapFromJsonString("{'data':4000}");
assertException(map, "");
map = mapFromJsonString("{'record':4000}");
assertException(map, "record");
map = mapFromJsonString("{'role':'NOT_EXISTS'}");
assertException(map, "role");
map = mapFromJsonString("{'kurentoOptions':{'allowedFilters':[{'OBJECT_NOT_EXPECTED':true}]}}");
assertException(map, "kurentoOptions");
map = mapFromJsonString("{'customIceServers':[{'url':'NOT_A_VALID_URI'}]}");
assertException(map, "customIceServers");
map = mapFromJsonString("{'type':'IPCAM','rtspUri':'NOT_A_VALID_RTSP_URI'}");
assertException(map, "rtspUri");
map = mapFromJsonString("{'type':'IPCAM','rtspUri':'filse://your.camera.ip.sdp'}");
assertException(map, "rtspUri");
}
private JsonObject removeIpcamProps(JsonObject json) {
json.remove("session");
json.remove("adaptativeBitrate");
json.remove("networkCache");
json.remove("onlyPlayWithSubscribers");
json.remove("rtspUri");
return json;
}
private JsonObject removeWebrtcProps(JsonObject json) {
json.remove("session");
json.remove("kurentoOptions");
json.remove("role");
json.remove("customIceServers");
return json;
}
private Map<String, ?> mapFromJsonString(String json) {
return new Gson().fromJson(json, Map.class);
}
private void assertException(Map<String, ?> params, String containsError) {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> ConnectionProperties.fromJson(params));
assertTrue(exception.getMessage().contains(containsError));
}
}
|
package org.eclipse.dawnsci.plotting.api.region;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.eclipse.dawnsci.plotting.api.IPlottingSystem;
import org.eclipse.dawnsci.plotting.api.region.IRegion.RegionType;
import org.eclipse.swt.graphics.Color;
/**
* Class containing utility methods for regions to avoid duplication
* @author Matthew Gerring
*
*/
public class RegionUtils {
/**
* Call to get a unique region name
* @param nameStub
* @param system
* @return
*/
public static String getUniqueName(final String nameStub, final IRegionSystem system, final String... usedNames) {
int i = 1;
@SuppressWarnings("unchecked")
final List<String> used = (List<String>) (usedNames!=null ? Arrays.asList(usedNames) : Collections.emptyList());
while(system.getRegion(nameStub+" "+i)!=null || used.contains(nameStub+" "+i)) {
++i;
if (i>10000) break; // something went wrong!
}
return nameStub+" "+i;
}
/**
*
* @param plotter
* @return
*/
public static Color getUniqueColor(IRegion.RegionType type, IRegionSystem plotter, Collection<Color> colours) {
final Collection<Color> used = new HashSet<Color>(7);
for (IRegion reg : plotter.getRegions()) {
if (reg.getRegionType()!=type) continue;
used.add(reg.getRegionColor());
}
for (Color color : colours) {
if (!used.contains(color)) return color;
}
return colours.iterator().next();
}
/**
* Creates a region (first deleting it if one with that name exists)
* @param string
* @param xaxis
* @return
* @throws Exception
*/
public static final IRegion replaceCreateRegion(final IRegionSystem system,
final String name,
final RegionType type) throws Exception {
if (system.getRegion(name)!=null) {
system.removeRegion(system.getRegion(name));
}
return system.createRegion(name, type);
}
public static String[] getRegionNames(IPlottingSystem<?> system) {
return getRegionNames(system, null);
}
public static String[] getRegionNames(IPlottingSystem<?> system, RegionType type) {
final Collection<IRegion> regions = system.getRegions();
if (regions==null || regions.size()<1) return null;
final List<String> names = new ArrayList<String>(7);
for (IRegion region : regions) {
if (type!=null && region.getRegionType()!=type) continue;
names.add(region.getName());
}
return names.toArray(new String[names.size()]);
}
/**
* Method attempts to make the best IRegion it
* can for the ROI.
*
* @param plottingSystem
* @param roi
* @param roiName
* @return
public static IRegion createRegion( final IPlottingSystem<Composite> plottingSystem,
final IROI roi,
final String roiName) throws Exception {
IRegion region = plottingSystem.getRegion(roiName);
if (region != null && region.isVisible()) {
region.setROI(roi);
return region;
}
RegionType type = null;
if (roi instanceof LinearROI) {
type = RegionType.LINE;
} else if (roi instanceof RectangularROI) {
if (roi instanceof PerimeterBoxROI) {
type = RegionType.PERIMETERBOX;
} else if (roi instanceof XAxisBoxROI){
type = RegionType.XAXIS;
} else if (roi instanceof YAxisBoxROI){
type = RegionType.YAXIS;
} else {
type = RegionType.BOX;
}
} else if (roi instanceof SectorROI) {
if(roi instanceof RingROI){
type = RegionType.RING;
} else {
type = RegionType.SECTOR;
}
} else if (roi instanceof CircularROI) {
type = RegionType.CIRCLE;
} else if (roi instanceof CircularFitROI) {
type = RegionType.CIRCLEFIT;
} else if (roi instanceof EllipticalROI) {
type = RegionType.ELLIPSE;
} else if (roi instanceof EllipticalFitROI) {
type = RegionType.ELLIPSEFIT;
} else if (roi instanceof PointROI) {
type = RegionType.POINT;
}
if (type==null) return null;
IRegion newRegion = plottingSystem.createRegion(roiName, type);
newRegion.setROI(roi);
plottingSystem.addRegion(newRegion);
return newRegion;
}
*/
}
|
package org.eclipse.mylar.bugzilla.ui.editor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import javax.security.auth.login.LoginException;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.CompareUI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylar.bugzilla.core.Attribute;
import org.eclipse.mylar.bugzilla.core.BugPost;
import org.eclipse.mylar.bugzilla.core.BugReport;
import org.eclipse.mylar.bugzilla.core.BugzillaException;
import org.eclipse.mylar.bugzilla.core.BugzillaPlugin;
import org.eclipse.mylar.bugzilla.core.BugzillaRepository;
import org.eclipse.mylar.bugzilla.core.Comment;
import org.eclipse.mylar.bugzilla.core.IBugzillaBug;
import org.eclipse.mylar.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylar.bugzilla.core.Operation;
import org.eclipse.mylar.bugzilla.core.PossibleBugzillaFailureException;
import org.eclipse.mylar.bugzilla.core.compare.BugzillaCompareInput;
import org.eclipse.mylar.bugzilla.core.internal.HtmlStreamTokenizer;
import org.eclipse.mylar.bugzilla.ui.OfflineView;
import org.eclipse.mylar.bugzilla.ui.WebBrowserDialog;
import org.eclipse.mylar.bugzilla.ui.actions.RefreshBugzillaReportsAction;
import org.eclipse.mylar.bugzilla.ui.favorites.actions.AddToFavoritesAction;
import org.eclipse.mylar.bugzilla.ui.outline.BugzillaOutlineNode;
import org.eclipse.mylar.bugzilla.ui.outline.BugzillaReportSelection;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.tasklist.ui.views.TaskListView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.internal.Workbench;
/**
* An editor used to view a bug report that exists on a server. It uses a
* <code>BugReport</code> object to store the data.
*/
public class ExistingBugEditor extends AbstractBugEditor
{
protected Set<String> removeCC = new HashSet<String>();
protected BugzillaCompareInput compareInput;
protected Button compareButton;
protected Button[] radios;
protected Control[] radioOptions;
protected List keyWordsList;
protected Text keywordsText;
protected List ccList;
protected Text ccText;
protected Text addCommentsText;
protected BugReport bug;
public String getNewCommentText(){
return addCommentsTextBox.getText();
}
/**
* Creates a new <code>ExistingBugEditor</code>.
*/
public ExistingBugEditor() {
super();
// Set up the input for comparing the bug report to the server
CompareConfiguration config = new CompareConfiguration();
config.setLeftEditable(false);
config.setRightEditable(false);
config.setLeftLabel("Local Bug Report");
config.setRightLabel("Remote Bug Report");
config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT));
config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT));
compareInput = new BugzillaCompareInput(config);
}
@SuppressWarnings("deprecation")
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
if (!(input instanceof ExistingBugEditorInput))
throw new PartInitException("Invalid Input: Must be ExistingBugEditorInput");
ExistingBugEditorInput ei = (ExistingBugEditorInput) input;
setSite(site);
setInput(input);
bugzillaInput = ei;
model = BugzillaOutlineNode.parseBugReport(bugzillaInput.getBug());
bug = ei.getBug();
restoreBug();
isDirty = false;
updateEditorTitle();
}
/**
* This overrides the existing implementation in order to add
* an "add to favorites" option to the context menu.
*
* @see org.eclipse.mylar.bugzilla.ui.AbstractBugEditor#createContextMenu()
*/
@Override
protected void createContextMenu() {
contextMenuManager = new MenuManager("#BugEditor");
contextMenuManager.setRemoveAllWhenShown(true);
contextMenuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.add(new AddToFavoritesAction(ExistingBugEditor.this));
manager.add(new Separator());
manager.add(cutAction);
manager.add(copyAction);
manager.add(pasteAction);
manager.add(new Separator());
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
if (currentSelectedText == null ||
currentSelectedText.getSelectionText().length() == 0) {
copyAction.setEnabled(false);
}
else {
copyAction.setEnabled(true);
}
}
});
getSite().registerContextMenu("#BugEditor", contextMenuManager,
getSite().getSelectionProvider());
}
@Override
protected void addRadioButtons(Composite buttonComposite) {
int i = 0;
Button selected = null;
radios = new Button[bug.getOperations().size()];
radioOptions = new Control[bug.getOperations().size()];
for (Iterator<Operation> it = bug.getOperations().iterator(); it.hasNext(); ) {
Operation o = it.next();
radios[i] = new Button(buttonComposite, SWT.RADIO);
radios[i].setFont(TEXT_FONT);
GridData radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
if (!o.hasOptions() && !o.isInput())
radioData.horizontalSpan = 4;
else
radioData.horizontalSpan = 3;
radioData.heightHint = 20;
String opName = o.getOperationName();
opName = opName.replaceAll("</.*>", "");
opName = opName.replaceAll("<.*>", "");
radios[i].setText(opName);
radios[i].setLayoutData(radioData);
radios[i].setBackground(background);
radios[i].addSelectionListener(new RadioButtonListener());
radios[i].addListener(SWT.FocusIn, new GenericListener());
if (o.hasOptions()) {
radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
radioData.horizontalSpan = 1;
radioData.heightHint = 20;
radioData.widthHint = 100;
radioOptions[i] = new Combo(
buttonComposite,
SWT.NO_BACKGROUND
| SWT.MULTI
| SWT.V_SCROLL
| SWT.READ_ONLY);
radioOptions[i].setFont(TEXT_FONT);
radioOptions[i].setLayoutData(radioData);
radioOptions[i].setBackground(background);
Object [] a = o.getOptionNames().toArray();
Arrays.sort(a);
for (int j = 0; j < a.length; j++) {
((Combo)radioOptions[i]).add((String) a[j]);
}
((Combo)radioOptions[i]).select(0);
((Combo)radioOptions[i]).addSelectionListener(new RadioButtonListener());
} else if(o.isInput()){
radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
radioData.horizontalSpan = 1;
radioData.widthHint = 120;
radioOptions[i] = new Text(
buttonComposite,
SWT.BORDER | SWT.SINGLE);
radioOptions[i].setFont(TEXT_FONT);
radioOptions[i].setLayoutData(radioData);
radioOptions[i].setBackground(background);
((Text)radioOptions[i]).setText(o.getInputValue());
((Text)radioOptions[i]).addModifyListener(new RadioButtonListener());
}
if (i == 0 || o.isChecked()) {
if(selected != null)
selected.setSelection(false);
selected = radios[i];
radios[i].setSelection(true);
if(o.hasOptions() && o.getOptionSelection() != null){
int j = 0;
for(String s: ((Combo)radioOptions[i]).getItems()){
if(s.compareTo(o.getOptionSelection()) == 0){
((Combo)radioOptions[i]).select(j);
}
j++;
}
}
bug.setSelectedOperation(o);
}
i++;
}
}
@Override
protected void addActionButtons(Composite buttonComposite) {
super.addActionButtons(buttonComposite);
compareButton = new Button(buttonComposite, SWT.NONE);
compareButton.setFont(TEXT_FONT);
GridData compareButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
compareButtonData.widthHint = 100;
compareButtonData.heightHint = 20;
compareButton.setText("Compare");
compareButton.setLayoutData(compareButtonData);
compareButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
OpenCompareEditorJob compareJob = new OpenCompareEditorJob("Comparing bug with remote server...");
compareJob.schedule();
}
});
compareButton.addListener(SWT.FocusIn, new GenericListener());
// TODO used for spell checking. Add back when we want to support this
// checkSpellingButton = new Button(buttonComposite, SWT.NONE);
// checkSpellingButton.setFont(TEXT_FONT);
// compareButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
// compareButtonData.widthHint = 100;
// compareButtonData.heightHint = 20;
// checkSpellingButton.setText("CheckSpelling");
// checkSpellingButton.setLayoutData(compareButtonData);
// checkSpellingButton.addListener(SWT.Selection, new Listener() {
// public void handleEvent(Event e) {
// checkSpelling();
// checkSpellingButton.addListener(SWT.FocusIn, new GenericListener());
}
/**
* @return Returns the compareInput.
*/
public BugzillaCompareInput getCompareInput() {
return compareInput;
}
@Override
public IBugzillaBug getBug() {
return bug;
}
@Override
protected String getTitleString() {
return bug.getLabel() + ": " + checkText(bug.getAttribute("Summary").getNewValue());
}
private String toCommaSeparatedList(String[] strings) {
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < strings.length; i++) {
buffer.append(strings[i]);
if (i != strings.length - 1) {
buffer.append(",");
}
}
return buffer.toString();
}
@Override
protected void submitBug() {
submitButton.setEnabled(false);
ExistingBugEditor.this.showBusy(true);
final BugPost form = new BugPost();
// set the url for the bug to be submitted to
setURL(form, "process_bug.cgi");
// go through all of the attributes and add them to the bug post
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
if (a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && !a.isHidden()) {
String value = a.getNewValue();
// add the attribute to the bug post
form.add(a.getParameterName(), checkText(value));
}
else if(a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && a.isHidden()) {
// we have a hidden attribute and we should send it back.
form.add(a.getParameterName(), a.getValue());
}
}
// make sure that the comment is broken up into 80 character lines
bug.setNewNewComment(formatText(bug.getNewNewComment()));
// add the summary to the bug post
form.add("short_desc", bug.getAttribute("Summary").getNewValue());
if(removeCC != null && removeCC.size() > 0){
String[] s = new String[removeCC.size()];
form.add("cc", toCommaSeparatedList(removeCC.toArray(s)));
form.add("removecc", "true");
}
// add the operation to the bug post
Operation o = bug.getSelectedOperation();
if (o == null)
form.add("knob", "none");
else {
form.add("knob", o.getKnobName());
if(o.hasOptions()) {
String sel = o.getOptionValue(o.getOptionSelection());
form.add(o.getOptionName(), sel);
} else if (o.isInput()){
String sel = o.getInputValue();
form.add(o.getInputName(), sel);
}
}
form.add("form_name", "process_bug");
// add the new comment to the bug post if there is some text in it
if(bug.getNewNewComment().length() != 0) {
form.add("comment", bug.getNewNewComment());
}
final WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
protected void execute(final IProgressMonitor monitor)
throws CoreException {
try {
form.post();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable(){
public void run() {
// TODO what do we do if the editor is closed
if (ExistingBugEditor.this != null
&& !ExistingBugEditor.this.isDisposed()) {
changeDirtyStatus(false);
BugzillaPlugin.getDefault().getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.closeEditor(ExistingBugEditor.this, true);
}
OfflineView.removeReport(bug);
}
});
} catch (final BugzillaException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
BugzillaPlugin.getDefault().logAndShowExceptionDetailsDialog(
e,
"occurred while posting the bug.",
"I/O Error");
}
});
submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
} catch (final PossibleBugzillaFailureException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
WebBrowserDialog.openAcceptAgreement(null,
"Possible Bugzilla Failure",
"Bugzilla may not have posted your bug.\n" + e.getMessage(),
form.getError());
BugzillaPlugin.log(e);
}
});
submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
} catch (final LoginException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(null,
"Login Error",
"Bugzilla could not post your bug since your login name or password is incorrect.\nPlease check your settings in the bugzilla preferences. ");
}
});
submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
}
}
};
Job job = new Job("Submitting Bug"){
@Override
protected IStatus run(IProgressMonitor monitor) {
try{
op.run(monitor);
} catch (Exception e){
MylarPlugin.log(e, "Failed to submit bug");
return new Status(Status.ERROR, "org.eclipse.mylar.bugzilla.ui", Status.ERROR, "Failed to submit bug", e);
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run() {
if(TaskListView.getDefault() != null &&
TaskListView.getDefault().getViewer() != null){
new RefreshBugzillaReportsAction().run();
}
}
});
return Status.OK_STATUS;
}
};
job.schedule();
}
@Override
protected void createDescriptionLayout() {
// Description Area
Composite descriptionComposite = new Composite(infoArea, SWT.NONE);
GridLayout descriptionLayout = new GridLayout();
descriptionLayout.numColumns = 4;
descriptionComposite.setLayout(descriptionLayout);
descriptionComposite.setBackground(background);
GridData descriptionData = new GridData(GridData.FILL_BOTH);
descriptionData.horizontalSpan = 1;
descriptionData.grabExcessVerticalSpace = false;
descriptionComposite.setLayoutData(descriptionData);
// End Description Area
StyledText t = newLayout(descriptionComposite, 4, "Description:", HEADER);
t.addListener(SWT.FocusIn, new DescriptionListener());
t = newLayout(descriptionComposite, 4, bug.getDescription(), VALUE);
t.setFont(COMMENT_FONT);
t.addListener(SWT.FocusIn, new DescriptionListener());
texts.add(textsindex, t);
textHash.put(bug.getDescription(), t);
textsindex++;
}
@Override
protected void createCommentLayout() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// Additional (read-only) Comments Area
Composite addCommentsComposite = new Composite(infoArea, SWT.NONE);
GridLayout addCommentsLayout = new GridLayout();
addCommentsLayout.numColumns = 4;
addCommentsComposite.setLayout(addCommentsLayout);
addCommentsComposite.setBackground(background);
GridData addCommentsData = new GridData(GridData.FILL_BOTH);
addCommentsData.horizontalSpan = 1;
addCommentsData.grabExcessVerticalSpace = false;
addCommentsComposite.setLayoutData(addCommentsData);
// End Additional (read-only) Comments Area
StyledText t = null;
for (Iterator<Comment> it = bug.getComments().iterator(); it.hasNext(); ) {
Comment comment = it.next();
String commentHeader = "Additional comment #" + comment.getNumber() + " from "
+ comment.getAuthorName() + " on "
+ df.format(comment.getCreated());
t = newLayout(addCommentsComposite, 4, commentHeader, HEADER);
t.addListener(SWT.FocusIn, new CommentListener(comment));
t = newLayout(addCommentsComposite, 4, comment.getText(), VALUE);
t.setFont(COMMENT_FONT);
t.addListener(SWT.FocusIn, new CommentListener(comment));
//code for outline
texts.add(textsindex, t);
textHash.put(comment, t);
textsindex++;
}
// Additional Comments Text
Composite addCommentsTitleComposite =
new Composite(addCommentsComposite, SWT.NONE);
GridLayout addCommentsTitleLayout = new GridLayout();
addCommentsTitleLayout.horizontalSpacing = 0;
addCommentsTitleLayout.marginWidth = 0;
addCommentsTitleComposite.setLayout(addCommentsTitleLayout);
addCommentsTitleComposite.setBackground(background);
GridData addCommentsTitleData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
addCommentsTitleData.horizontalSpan = 4;
addCommentsTitleData.grabExcessVerticalSpace = false;
addCommentsTitleComposite.setLayoutData(addCommentsTitleData);
newLayout(
addCommentsTitleComposite,
4,
"Additional Comments:",
HEADER).addListener(SWT.FocusIn, new NewCommentListener());
addCommentsText =
new Text(
addCommentsComposite,
SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
addCommentsText.setFont(COMMENT_FONT);
GridData addCommentsTextData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
addCommentsTextData.horizontalSpan = 4;
addCommentsTextData.widthHint = DESCRIPTION_WIDTH;
addCommentsTextData.heightHint = DESCRIPTION_HEIGHT;
addCommentsText.setLayoutData(addCommentsTextData);
addCommentsText.setText(bug.getNewComment());
addCommentsText.addListener(SWT.KeyUp, new Listener() {
public void handleEvent(Event event) {
String sel = addCommentsText.getText();
if (!(bug.getNewNewComment().equals(sel))) {
bug.setNewNewComment(sel);
changeDirtyStatus(true);
}
validateInput();
}
});
addCommentsText.addListener(SWT.FocusIn, new NewCommentListener());
// End Additional Comments Text
addCommentsTextBox = addCommentsText;
this.createSeparatorSpace(addCommentsComposite);
}
@Override
protected void addKeywordsList(String keywords, Composite attributesComposite) {
newLayout(attributesComposite, 1, "Keywords:", PROPERTY);
keywordsText = new Text(attributesComposite, SWT.BORDER);
keywordsText.setFont(TEXT_FONT);
keywordsText.setEditable(false);
keywordsText.setForeground(foreground);
keywordsText.setBackground(JFaceColors.getErrorBackground(display));
GridData keywordsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
keywordsData.horizontalSpan = 2;
keywordsData.widthHint = 200;
keywordsText.setLayoutData(keywordsData);
keywordsText.setText(keywords);
keywordsText.addListener(SWT.FocusIn, new GenericListener());
keyWordsList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
keyWordsList.setFont(TEXT_FONT);
GridData keyWordsTextData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
keyWordsTextData.horizontalSpan = 1;
keyWordsTextData.widthHint = 125;
keyWordsTextData.heightHint = 40;
keyWordsList.setLayoutData(keyWordsTextData);
// initialize the keywords list with valid values
java.util.List<String> keywordList = bug.getKeywords();
if (keywordList != null) {
for (Iterator<String> it = keywordList.iterator(); it.hasNext(); ) {
String keyword = it.next();
keyWordsList.add(keyword);
}
// get the selected keywords for the bug
StringTokenizer st = new StringTokenizer(keywords, ",", false);
ArrayList<Integer> indicies = new ArrayList<Integer>();
while (st.hasMoreTokens()) {
String s = st.nextToken().trim();
int index = keyWordsList.indexOf(s);
if (index != -1)
indicies.add(new Integer(index));
}
// select the keywords that were selected for the bug
int length = indicies.size();
int[] sel = new int[length];
for (int i = 0; i < length; i++) {
sel[i] = indicies.get(i).intValue();
}
keyWordsList.select(sel);
}
keyWordsList.addSelectionListener(new KeywordListener());
keyWordsList.addListener(SWT.FocusIn, new GenericListener());
}
@Override
protected void addCCList(String ccValue, Composite attributesComposite) {
newLayout(attributesComposite, 1, "Add CC:", PROPERTY);
ccText = new Text(attributesComposite, SWT.BORDER);
ccText.setFont(TEXT_FONT);
ccText.setEditable(true);
ccText.setForeground(foreground);
ccText.setBackground(background);
GridData ccData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
ccData.horizontalSpan = 1;
ccData.widthHint = 200;
ccText.setLayoutData(ccData);
ccText.setText(ccValue);
ccText.addListener(SWT.FocusIn, new GenericListener());
ccText.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
changeDirtyStatus(true);
Attribute a = bug.getAttributeForKnobName("newcc");
if(a != null){
a.setNewValue(ccText.getText());
}
}
});
newLayout(attributesComposite, 1, "CC: (Select to remove)", PROPERTY);
ccList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
ccList.setFont(TEXT_FONT);
GridData ccListData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
ccListData.horizontalSpan = 1;
ccListData.widthHint = 125;
ccListData.heightHint = 40;
ccList.setLayoutData(ccListData);
// initialize the keywords list with valid values
Set<String> ccs = bug.getCC();
if (ccs != null) {
for (Iterator<String> it = ccs.iterator(); it.hasNext(); ) {
String cc = it.next();
ccList.add(HtmlStreamTokenizer.unescape(cc));
}
}
ccList.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
changeDirtyStatus(true);
for(String cc: ccList.getItems()){
int index = ccList.indexOf(cc);
if(ccList.isSelected(index)){
removeCC.add(cc);
} else {
removeCC.remove(cc);
}
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
ccList.addListener(SWT.FocusIn, new GenericListener());
}
@Override
protected void updateBug() {
// go through all of the attributes and update the main values to the new ones
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
if(a.getNewValue().compareTo(a.getValue()) != 0){
bug.setHasChanged(true);
}
a.setValue(a.getNewValue());
}
if(bug.getNewComment().compareTo(bug.getNewNewComment()) != 0){
bug.setHasChanged(true);
}
// Update some other fields as well.
bug.setNewComment(bug.getNewNewComment());
}
@Override
protected void restoreBug() {
if(bug == null)
return;
// go through all of the attributes and restore the new values to the main ones
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
a.setNewValue(a.getValue());
}
// Restore some other fields as well.
bug.setNewNewComment(bug.getNewComment());
}
/**
* This job opens a compare editor to compare the current state of the bug
* in the editor with the bug on the server.
*/
protected class OpenCompareEditorJob extends Job {
public OpenCompareEditorJob(String name) {
super(name);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
final BugReport serverBug;
try {
serverBug = BugzillaRepository.getInstance().getBug(bug.getId());
// If no bug was found on the server, throw an exception so that the
// user gets the same message that appears when there is a problem reading the server.
if (serverBug == null)
throw new Exception();
} catch (Exception e) {
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(Workbench.getInstance().getActiveWorkbenchWindow().getShell(),
"Could not open bug.", "Bug #" + bug.getId() + " could not be read from the server.");
}
});
return new Status(IStatus.OK, IBugzillaConstants.PLUGIN_ID, IStatus.OK, "Could not get the bug report from the server.", null);
}
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
compareInput.setTitle("Bug #" + bug.getId());
compareInput.setLeft(bug);
compareInput.setRight(serverBug);
CompareUI.openCompareEditor(compareInput);
}
});
return new Status(IStatus.OK, IBugzillaConstants.PLUGIN_ID, IStatus.OK, "", null);
}
}
/**
* Class to handle the selection change of the keywords.
*/
protected class KeywordListener implements SelectionListener {
/*
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent arg0) {
changeDirtyStatus(true);
// get the selected keywords and create a string to submit
StringBuffer keywords = new StringBuffer();
String [] sel = keyWordsList.getSelection();
// allow unselecting 1 keyword when it is the only one selected
if(keyWordsList.getSelectionCount() == 1) {
int index = keyWordsList.getSelectionIndex();
String keyword = keyWordsList.getItem(index);
if (bug.getAttribute("Keywords").getNewValue().equals(keyword))
keyWordsList.deselectAll();
}
for(int i = 0; i < keyWordsList.getSelectionCount(); i++) {
keywords.append(sel[i]);
if (i != keyWordsList.getSelectionCount()-1) {
keywords.append(",");
}
}
bug.getAttribute("Keywords").setNewValue(keywords.toString());
// update the keywords text field
keywordsText.setText(keywords.toString());
}
/*
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent arg0) {
// no need to listen to this
}
}
/**
* A listener for selection of the description field.
*/
protected class DescriptionListener implements Listener {
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), "Description", true, bug.getSummary()))));
}
}
/**
* A listener for selection of a comment.
*/
protected class CommentListener implements Listener {
/** The comment that this listener is for. */
private Comment comment;
/**
* Creates a new <code>CommentListener</code>.
* @param comment The comment that this listener is for.
*/
public CommentListener(Comment comment) {
this.comment = comment;
}
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), comment.getCreated().toString(), comment, bug.getSummary()))));
}
}
/**
* A listener for selection of the textbox where a new comment is entered
* in.
*/
protected class NewCommentListener implements Listener {
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), "New Comment", false, bug.getSummary()))));
}
}
/**
* Class to handle the selection change of the radio buttons.
*/
protected class RadioButtonListener implements SelectionListener, ModifyListener {
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
Button selected = null;
for (int i = 0; i < radios.length; i++) {
if (radios[i].getSelection())
selected = radios[i];
}
// determine the operation to do to the bug
for (int i = 0; i < radios.length; i++) {
if (radios[i] != e.widget && radios[i] != selected){
radios[i].setSelection(false);
}
if (e.widget == radios[i]) {
Operation o = bug.getOperation(radios[i].getText());
bug.setSelectedOperation(o);
ExistingBugEditor.this.changeDirtyStatus(true);
}
else if(e.widget == radioOptions[i]) {
Operation o = bug.getOperation(radios[i].getText());
o.setOptionSelection(((Combo)radioOptions[i]).getItem(((Combo)radioOptions[i]).getSelectionIndex()));
if(bug.getSelectedOperation() != null)
bug.getSelectedOperation().setChecked(false);
o.setChecked(true);
bug.setSelectedOperation(o);
radios[i].setSelection(true);
if(selected != null && selected != radios[i]){
selected.setSelection(false);
}
ExistingBugEditor.this.changeDirtyStatus(true);
}
}
validateInput();
}
public void modifyText(ModifyEvent e) {
Button selected = null;
for (int i = 0; i < radios.length; i++) {
if (radios[i].getSelection())
selected = radios[i];
}
// determine the operation to do to the bug
for (int i = 0; i < radios.length; i++) {
if (radios[i] != e.widget && radios[i] != selected){
radios[i].setSelection(false);
}
if (e.widget == radios[i]) {
Operation o = bug.getOperation(radios[i].getText());
bug.setSelectedOperation(o);
ExistingBugEditor.this.changeDirtyStatus(true);
}
else if(e.widget == radioOptions[i]) {
Operation o = bug.getOperation(radios[i].getText());
o.setInputValue(((Text)radioOptions[i]).getText());
if(bug.getSelectedOperation() != null)
bug.getSelectedOperation().setChecked(false);
o.setChecked(true);
bug.setSelectedOperation(o);
radios[i].setSelection(true);
if(selected != null && selected != radios[i]){
selected.setSelection(false);
}
ExistingBugEditor.this.changeDirtyStatus(true);
}
}
validateInput();
}
}
private void validateInput() {
Operation o = bug.getSelectedOperation();
if(o != null && o.getKnobName().compareTo("resolve") == 0 && (addCommentsText.getText() == null || addCommentsText.getText().equals(""))){
submitButton.setEnabled(false);
} else{
submitButton.setEnabled(true);
}
}
@Override
public void handleSummaryEvent() {
String sel = summaryText.getText();
Attribute a = getBug().getAttribute("Summary");
if (!(a.getNewValue().equals(sel))) {
a.setNewValue(sel);
changeDirtyStatus(true);
}
}
// TODO used for spell checking. Add back when we want to support this
// protected Button checkSpellingButton;
// private void checkSpelling() {
// SpellingContext context= new SpellingContext();
// context.setContentType(Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT));
// IDocument document = new Document(addCommentsTextBox.getText());
// ISpellingProblemCollector collector= new SpellingProblemCollector(document);
// EditorsUI.getSpellingService().check(document, context, collector, new NullProgressMonitor());
// private class SpellingProblemCollector implements ISpellingProblemCollector {
// private IDocument document;
// private SpellingDialog spellingDialog;
// public SpellingProblemCollector(IDocument document){
// this.document = document;
// spellingDialog = new SpellingDialog(Display.getCurrent().getActiveShell(), "Spell Checking", document);
// /*
// * @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept(org.eclipse.ui.texteditor.spelling.SpellingProblem)
// */
// public void accept(SpellingProblem problem) {
// try {
// int line= document.getLineOfOffset(problem.getOffset()) + 1;
// String word= document.get(problem.getOffset(), problem.getLength());
// System.out.println(word);
// for(ICompletionProposal proposal : problem.getProposals()){
// System.out.println(">>>" + proposal.getDisplayString());
// spellingDialog.open(word, problem.getProposals());
// } catch (BadLocationException x) {
// // drop this SpellingProblem
// /*
// * @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#beginCollecting()
// */
// public void beginCollecting() {
// /*
// * @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#endCollecting()
// */
// public void endCollecting() {
// MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Spell Checking Finished", "The spell check has finished");
}
|
package org.eclipse.mylyn.internal.tasks.ui.actions;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.mylyn.internal.tasks.ui.ITasksUiConstants;
import org.eclipse.mylyn.internal.tasks.ui.wizards.NewLocalTaskWizard;
import org.eclipse.mylyn.internal.tasks.ui.wizards.NewTaskWizard;
import org.eclipse.mylyn.tasks.core.RepositoryTaskData;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.TaskSelection;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.mylyn.tasks.ui.editors.AbstractRepositoryTaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
/**
* @author Mik Kersten
* @author Eugene Kuleshov
*/
public class NewTaskAction extends Action implements IViewActionDelegate, IExecutableExtension {
public static final String ID = "org.eclipse.mylyn.tasklist.ui.repositories.actions.create";
private boolean skipRepositoryPage = false;
private boolean localTask = false;
private boolean supportsTaskSelection;
@Override
public void run() {
showWizard(null);
}
public int showWizard(TaskSelection taskSelection) {
IWizard wizard;
List<TaskRepository> repositories = TasksUiPlugin.getRepositoryManager().getAllRepositories();
if (localTask) {
wizard = new NewLocalTaskWizard(taskSelection);
} else if (repositories.size() == 1) {
// NOTE: this click-saving should be generalized
TaskRepository taskRepository = repositories.get(0);
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(taskRepository.getConnectorKind());
wizard = createNewTaskWizard(connectorUi, taskRepository, taskSelection);
} else if (skipRepositoryPage) {
TaskRepository taskRepository = TasksUiUtil.getSelectedRepository();
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(taskRepository.getConnectorKind());
wizard = createNewTaskWizard(connectorUi, taskRepository, taskSelection);
} else {
wizard = new NewTaskWizard(taskSelection);
}
if (wizard.canFinish()) {
wizard.performFinish();
if (!supportsTaskSelection) {
handleSelection(taskSelection);
}
return Dialog.OK;
}
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if (shell != null && !shell.isDisposed()) {
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.setBlockOnOpen(true);
int result = dialog.open();
if (result == Dialog.OK) {
if (wizard instanceof NewTaskWizard) {
supportsTaskSelection = ((NewTaskWizard) wizard).supportsTaskSelection();
}
if (!supportsTaskSelection) {
handleSelection(taskSelection);
}
}
return result;
} else {
return Dialog.CANCEL;
}
}
// API-3.0: remove legacy support
@SuppressWarnings("deprecation")
private IWizard createNewTaskWizard(AbstractRepositoryConnectorUi connectorUi, TaskRepository taskRepository,
TaskSelection taskSelection) {
IWizard wizard = connectorUi.getNewTaskWizard(taskRepository, taskSelection);
if (wizard == null) {
// API-3.0: remove legacy support
wizard = connectorUi.getNewTaskWizard(taskRepository);
supportsTaskSelection = false;
} else {
supportsTaskSelection = true;
}
return wizard;
}
// API-3.0: remove method when AbstractRepositoryConnector.getNewTaskWizard(TaskRepository) is removed
private void handleSelection(final TaskSelection taskSelection) {
if (taskSelection == null) {
return;
}
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (page == null) {
return;
}
RepositoryTaskData taskData = taskSelection.getTaskData();
String summary = taskData.getSummary();
String description = taskData.getDescription();
if (page.getActiveEditor() instanceof TaskEditor) {
TaskEditor taskEditor = (TaskEditor) page.getActiveEditor();
if (taskEditor.getActivePageInstance() instanceof AbstractRepositoryTaskEditor) {
AbstractRepositoryTaskEditor repositoryTaskEditor = (AbstractRepositoryTaskEditor) taskEditor.getActivePageInstance();
repositoryTaskEditor.setSummaryText(summary);
repositoryTaskEditor.setDescriptionText(description);
return;
}
}
Clipboard clipboard = new Clipboard(page.getWorkbenchWindow().getShell().getDisplay());
clipboard.setContents(new Object[] { summary + "\n" + description },
new Transfer[] { TextTransfer.getInstance() });
MessageDialog.openInformation(
page.getWorkbenchWindow().getShell(),
ITasksUiConstants.TITLE_DIALOG,
"This connector does not provide a rich task editor for creating tasks.\n\n"
+ "The error contents have been placed in the clipboard so that you can paste them into the entry form.");
}
});
}
public void run(IAction action) {
run();
}
public void init(IViewPart view) {
}
public void selectionChanged(IAction action, ISelection selection) {
}
public void setInitializationData(IConfigurationElement config, String propertyName, Object data)
throws CoreException {
if ("skipFirstPage".equals(data)) {
this.skipRepositoryPage = true;
}
if ("local".equals(data)) {
this.localTask = true;
}
}
}
|
package org.eclipse.xtext.parsetree.reconstr.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.ILeafNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.util.ITextRegionWithLineInformation;
import org.eclipse.xtext.util.Pair;
import com.google.inject.Inject;
/**
* @author meysholdt - Initial contribution and API
* @author Jan Koehnlein
*/
public class DefaultCommentAssociater extends AbstractCommentAssociater {
@Inject
protected TokenUtil tokenUtil;
@Override
public Map<ILeafNode, EObject> associateCommentsWithSemanticEObjects(EObject model, Set<ICompositeNode> roots) {
Map<ILeafNode, EObject> mapping = new HashMap<ILeafNode, EObject>();
for (ICompositeNode rootNode : roots)
associateCommentsWithSemanticEObjects(mapping, rootNode);
return mapping;
}
/**
* This implementation associates each comment with the next following semantic token's EObject, except for the
* case, where a line of the document ends by a semantic element followed by a comment. Then, the comment is
* associated with this preceding semantic token.
*/
protected void associateCommentsWithSemanticEObjects(Map<ILeafNode, EObject> mapping, ICompositeNode rootNode) {
// System.out.println(EmfFormatter.objToStr(rootNode));
EObject currentEObject = null;
List<ILeafNode> currentComments = new ArrayList<ILeafNode>();
NodeIterator nodeIterator = new NodeIterator(rootNode);
// rewind to previous token with token owner
while (nodeIterator.hasPrevious() && currentEObject == null) {
INode node = nodeIterator.previous();
if (tokenUtil.isToken(node)) {
currentEObject = tokenUtil.getTokenOwner(node);
}
}
while (nodeIterator.hasNext()) {
INode node = nodeIterator.next();
if (tokenUtil.isCommentNode(node)) {
currentComments.add((ILeafNode) node);
}
boolean isToken = tokenUtil.isToken(node);
if ((node instanceof ILeafNode || isToken) && currentEObject != null) {
ITextRegionWithLineInformation textRegion = node.getTextRegionWithLineInformation();
if (textRegion.getLineNumber() != textRegion.getEndLineNumber()) {
// found a newline -> associating existing comments with currentEObject
addMapping(mapping, currentComments, currentEObject);
currentEObject = null;
}
}
if (isToken) {
Pair<List<ILeafNode>, List<ILeafNode>> leadingAndTrailingHiddenTokens = tokenUtil
.getLeadingAndTrailingHiddenTokens(node);
for (ILeafNode leadingHiddenNode : leadingAndTrailingHiddenTokens.getFirst()) {
if (tokenUtil.isCommentNode(leadingHiddenNode)) {
currentComments.add(leadingHiddenNode);
}
}
nodeIterator.prune();
currentEObject = tokenUtil.getTokenOwner(node);
if (currentEObject != null) {
addMapping(mapping, currentComments, currentEObject);
if (node.getOffset() > rootNode.getEndOffset()) {
// found next EObject outside rootNode
break;
}
}
}
}
if (!currentComments.isEmpty()) {
if (currentEObject != null) {
addMapping(mapping, currentComments, currentEObject);
} else {
EObject objectForRemainingComments = getEObjectForRemainingComments(rootNode);
if (objectForRemainingComments != null) {
addMapping(mapping, currentComments, objectForRemainingComments);
}
}
}
}
protected void addMapping(Map<ILeafNode, EObject> mapping, List<ILeafNode> currentComments, EObject currentEObject) {
for (ILeafNode l : currentComments)
mapping.put(l, currentEObject);
currentComments.clear();
}
protected EObject getEObjectForRemainingComments(ICompositeNode rootNode) {
TreeIterator<INode> i = rootNode.getAsTreeIterable().iterator();
while (i.hasNext()) {
INode o = i.next();
if (o.hasDirectSemanticElement())
return o.getSemanticElement();
}
return null;
}
}
|
package org.mwc.debrief.lite.menu;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.mwc.debrief.lite.DebriefLiteApp;
import org.mwc.debrief.lite.gui.LiteStepControl;
import org.mwc.debrief.lite.gui.LiteStepControl.SliderControls;
import org.mwc.debrief.lite.gui.LiteStepControl.TimeLabel;
import org.mwc.debrief.lite.gui.custom.RangeSlider;
import org.mwc.debrief.lite.map.GeoToolMapRenderer;
import org.mwc.debrief.lite.properties.PropertiesDialog;
import org.pushingpixels.flamingo.api.common.CommandButtonDisplayState;
import org.pushingpixels.flamingo.api.common.FlamingoCommand.FlamingoCommandToggleGroup;
import org.pushingpixels.flamingo.api.common.JCommandButton;
import org.pushingpixels.flamingo.api.common.RichTooltip;
import org.pushingpixels.flamingo.api.common.RichTooltip.RichTooltipBuilder;
import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon;
import org.pushingpixels.flamingo.api.ribbon.JRibbon;
import org.pushingpixels.flamingo.api.ribbon.JRibbonBand;
import org.pushingpixels.flamingo.api.ribbon.JRibbonComponent;
import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority;
import org.pushingpixels.flamingo.api.ribbon.RibbonTask;
import MWC.GUI.CanvasType;
import MWC.GUI.Layers;
import MWC.GUI.StepperListener;
import MWC.GUI.ToolParent;
import MWC.GUI.Tools.Swing.MyMetalToolBarUI.ToolbarOwner;
import MWC.GUI.Undo.UndoBuffer;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.TacticalData.temporal.ControllablePeriod;
import MWC.TacticalData.temporal.PlotOperations;
import MWC.TacticalData.temporal.TimeManager;
import junit.framework.TestCase;
public class DebriefRibbonTimeController
{
/**
* Class that binds the Time Filter and Time Label. It is used to update the date formatting.
*
*/
protected static class DateFormatBinder
{
protected LiteStepControl stepControl;
protected JLabel minimumValue;
protected JLabel maximumValue;
protected RangeSlider slider;
protected TimeManager timeManager;
public String getDateFormat()
{
return stepControl.getDateFormat();
}
public void updateFilterDateFormat()
{
final Date low = RangeSlider.toDate(slider.getValue()).getTime();
final Date high = RangeSlider.toDate(slider.getUpperValue()).getTime();
final SimpleDateFormat formatter = new SimpleDateFormat(stepControl
.getDateFormat());
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
minimumValue.setText(formatter.format(low));
maximumValue.setText(formatter.format(high));
}
public void updateTimeDateFormat(final String format,
final boolean updateTimeLabel, final boolean updateFilters)
{
if (updateTimeLabel)
{
stepControl.setDateFormat(format);
}
if (updateFilters)
{
updateFilterDateFormat();
}
}
}
private static class LiteSliderControls implements SliderControls
{
private final RangeSlider slider;
private LiteSliderControls(final RangeSlider slider)
{
this.slider = slider;
}
@Override
public HiResDate getToolboxEndTime()
{
final long val = slider.getUpperDate().getTimeInMillis();
return new HiResDate(val);
}
@Override
public HiResDate getToolboxStartTime()
{
final long val = slider.getLowerDate().getTimeInMillis();
return new HiResDate(val);
}
@Override
public void setEnabled(final boolean enabled)
{
slider.setEnabled(enabled);
}
@Override
public void setToolboxEndTime(final HiResDate val)
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(val.getDate().getTime());
slider.setMaximum(cal);
slider.setUpperDate(cal);
}
@Override
public void setToolboxStartTime(final HiResDate val)
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(val.getDate().getTime());
slider.setMinimum(cal);
slider.setLowerDate(cal);
}
}
private static abstract class LiteStepperListener implements StepperListener
{
private final JCommandButton _playBtn;
private LiteStepperListener(final JCommandButton playCommandButton)
{
_playBtn = playCommandButton;
}
@Override
public void newTime(final HiResDate oldDTG, final HiResDate newDTG,
final CanvasType canvas)
{
// ignore
}
@Override
public void steppingModeChanged(final boolean on)
{
if (_playBtn != null)
{
updatePlayBtnUI(_playBtn, !on);
}
}
}
protected static class ShowFormatAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
private final JPopupMenu menu;
private ShowFormatAction(final JPopupMenu theMenu)
{
this.menu = theMenu;
}
@Override
public void actionPerformed(final ActionEvent e)
{
// Get the event source
final Component component = (Component) e.getSource();
menu.show(component, 0, 0);
// Get the location of the point 'on the screen'
final Point p = component.getLocationOnScreen();
menu.setLocation(p.x, p.y + component.getHeight());
}
}
/**
* utility class to handle converting between slider range and time values
*
* @author ian
*
*/
private static class SliderConverter
{
private int range;
private long origin;
// have one minute steps
private final int step = 1000;
public int getCurrentAt(final long now)
{
return (int) Math.round((double)(now - origin) / step);
}
public int getEnd()
{
return range;
}
public int getStart()
{
return 0;
}
public long getTimeAt(final int position)
{
return origin + (position * step);
}
public void init(final long start, final long end)
{
origin = start;
range = (int) ((end - start) / step);
}
}
public static class SliderConverterTest extends TestCase
{
public void testConverter()
{
final SliderConverter test = new SliderConverter();
test.init(1240423198490L, 1240427422390L);
final int originalStep = 21;
final long originalTime = test.getTimeAt(originalStep);
final long roundedTime = originalTime / 1000L * 1000L;
final int newStep = test.getCurrentAt(roundedTime);
assertEquals("Rounding slider converter", originalStep, newStep);
}
}
private static class SliderListener implements ChangeListener
{
final private PlotOperations operations;
final private TimeManager timeManager;
private SliderListener(final PlotOperations operations,
final TimeManager time)
{
this.operations = operations;
timeManager = time;
}
@Override
public void stateChanged(final ChangeEvent e)
{
final RangeSlider slider = (RangeSlider) e.getSource();
final Date low = RangeSlider.toDate(slider.getValue()).getTime();
final Date high = RangeSlider.toDate(slider.getUpperValue()).getTime();
formatBinder.updateFilterDateFormat();
operations.setPeriod(new TimePeriod.BaseTimePeriod(new HiResDate(low),
new HiResDate(high)));
final HiResDate currentTime = timeManager.getTime();
if (currentTime != null)
{
Date oldTime = currentTime.getDate();
if (oldTime.before(low))
{
oldTime = low;
}
if (oldTime.after(high))
{
oldTime = high;
}
label.setRange(low.getTime(), high.getTime());
label.setValue(oldTime.getTime());
// and enable those buttons
}
operations.performOperation(ControllablePeriod.FILTER_TO_TIME_PERIOD);
}
}
private static final String START_TEXT = "Start playing";
private static final String STOP_TEXT = "Stop playing";
private static final String STOP_IMAGE = "icons/24/media_stop.png";
private static final String PLAY_IMAGE = "icons/24/media_play.png";
public static JPanel topButtonsPanel;
private static final String[] timeFormats = new String[]
{"mm:ss.SSS", "HHmm.ss", "HHmm", "ddHHmm", "ddHHmm:ss", "yy/MM/dd HH:mm",
"yy/MM/dd hh:mm:ss"};
private static SliderConverter converter = new SliderConverter();
private static DateFormatBinder formatBinder = new DateFormatBinder();
private static TimeLabel label;
private static JCheckBoxMenuItem[] _menuItem;
protected static void addTimeControllerTab(final JRibbon ribbon,
final GeoToolMapRenderer _geoMapRenderer,
final LiteStepControl stepControl, final TimeManager timeManager,
final PlotOperations operations, final Layers layers,
final UndoBuffer undoBuffer, final Runnable normalPainter,
final Runnable snailPainter)
{
final JRibbonBand displayMode = createDisplayMode(normalPainter,
snailPainter);
final JRibbonBand filterToTime = createFilterToTime(stepControl, operations,
timeManager);
final JRibbonBand control = createControl(stepControl, timeManager, layers,
undoBuffer, operations);
final RibbonTask timeTask = new RibbonTask("Time", displayMode, control,
filterToTime);
ribbon.addTask(timeTask);
}
public static void assignThisTimeFormat(final String format,
final boolean updateTimeLabel, final boolean updateFilters)
{
if (_menuItem != null && format != null)
{
for (int i = 0; i < _menuItem.length; i++)
{
_menuItem[i].setSelected(format.equals(_menuItem[i].getText()));
}
if (formatBinder != null)
{
formatBinder.updateTimeDateFormat(format, updateTimeLabel,
updateFilters);
}
}
}
private static JRibbonBand createControl(final LiteStepControl stepControl,
final TimeManager timeManager, final Layers layers,
final UndoBuffer undoBuffer, final PlotOperations operations)
{
final JRibbonBand control = new JRibbonBand("Control", null);
final JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
controlPanel.setPreferredSize(new Dimension(500, 80));
topButtonsPanel = new JPanel();
topButtonsPanel.setLayout(new BoxLayout(topButtonsPanel, BoxLayout.X_AXIS));
final JCommandButton behindCommandButton = MenuUtils.addCommandButton(
"Behind", "icons/24/media_beginning.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
timeManager.setTime(control, HiResDate.min(operations.getPeriod()
.getStartDTG(), timeManager.getPeriod().getStartDTG()), true);
}
}, CommandButtonDisplayState.SMALL, "Move to start time");
final JCommandButton rewindCommandButton = MenuUtils.addCommandButton(
"Rewind", "icons/24/media_rewind.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(false, true);
}
}, CommandButtonDisplayState.SMALL, "Large step backwards");
final JCommandButton backCommandButton = MenuUtils.addCommandButton("Back",
"icons/24/media_back.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(false, false);
}
}, CommandButtonDisplayState.SMALL, "Small step backwards");
final JCommandButton playCommandButton = MenuUtils.addCommandButton("Play",
PLAY_IMAGE, new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
// ignore, we define the action once we've finished creating the button
}
}, CommandButtonDisplayState.SMALL, START_TEXT);
playCommandButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
// what state are we in?
final boolean isPlaying = stepControl.isPlaying();
stepControl.startStepping(!isPlaying);
// now update the play button UI
updatePlayBtnUI(playCommandButton, isPlaying);
}
});
final JCommandButton recordCommandButton = MenuUtils.addCommandButton(
"Record", "icons/24/media_record.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
JOptionPane.showMessageDialog(null,
"Record to PPT not yet implemented.");
}
}, CommandButtonDisplayState.SMALL, "Start recording");
final JCommandButton forwardCommandButton = MenuUtils.addCommandButton(
"Forward", "icons/24/media_forward.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(true, false);
}
}, CommandButtonDisplayState.SMALL, "Small step forwards");
final JCommandButton fastForwardCommandButton = MenuUtils.addCommandButton(
"Fast Forward", "icons/24/media_fast_forward.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(true, true);
}
}, CommandButtonDisplayState.SMALL, "Large step forwards");
final JCommandButton endCommandButton = MenuUtils.addCommandButton("End",
"icons/24/media_end.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
timeManager.setTime(control, HiResDate.max(operations.getPeriod()
.getEndDTG(), timeManager.getPeriod().getEndDTG()), true);
}
}, CommandButtonDisplayState.SMALL, "Move to end time");
final JCommandButton propertiesCommandButton = MenuUtils.addCommandButton(
"Properties", "icons/16/properties.png", new AbstractAction()
{
private static final long serialVersionUID = 1973993003498667463L;
@Override
public void actionPerformed(final ActionEvent arg0)
{
ToolbarOwner owner = null;
final ToolParent parent = stepControl.getParent();
if (parent instanceof ToolbarOwner)
{
owner = (ToolbarOwner) parent;
}
final PropertiesDialog dialog = new PropertiesDialog(stepControl
.getInfo(), layers, undoBuffer, parent, owner);
dialog.setSize(400, 500);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}, CommandButtonDisplayState.SMALL, "Edit time-step properties");
// we need to give the menu to the command popup
final JPopupMenu menu = new JPopupMenu();
final JCommandButton formatCommandButton = MenuUtils.addCommandButton(
"Format", "icons/24/gears_view.png", new ShowFormatAction(menu),
CommandButtonDisplayState.SMALL, "Format time control");
final JLabel timeLabel = new JLabel(LiteStepControl.timeFormat)
{
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(final Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
timeLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
timeLabel.setForeground(new Color(0, 255, 0));
_menuItem = new JCheckBoxMenuItem[timeFormats.length];
for (int i = 0; i < timeFormats.length; i++)
{
_menuItem[i] = new JCheckBoxMenuItem(timeFormats[i]);
}
resetDateFormat();
final ActionListener selfAssignFormat = new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
final String format = e.getActionCommand();
assignThisTimeFormat(format, true, false);
}
};
for (int i = 0; i < timeFormats.length; i++)
{
_menuItem[i].addActionListener(selfAssignFormat);
menu.add(_menuItem[i]);
}
topButtonsPanel.add(behindCommandButton);
topButtonsPanel.add(rewindCommandButton);
topButtonsPanel.add(backCommandButton);
topButtonsPanel.add(playCommandButton);
topButtonsPanel.add(recordCommandButton);
topButtonsPanel.add(forwardCommandButton);
topButtonsPanel.add(fastForwardCommandButton);
topButtonsPanel.add(endCommandButton);
topButtonsPanel.add(new JLabel(" | "));
topButtonsPanel.add(propertiesCommandButton);
topButtonsPanel.add(timeLabel);
topButtonsPanel.add(formatCommandButton);
controlPanel.add(topButtonsPanel);
final JSlider timeSlider = new JSlider();
timeSlider.setPreferredSize(new Dimension(420, 30));
timeSlider.setEnabled(false);
label = new TimeLabel()
{
@Override
public void setFontSize(final int newSize)
{
final Font originalFont = timeLabel.getFont();
final Font newFont = new Font(originalFont.getName(), originalFont
.getStyle(), newSize);
timeLabel.setFont(newFont);
}
@Override
public void setRange(final long start, final long end)
{
// ok, we can use time slider
timeSlider.setEnabled(true);
// and we can use the buttons
DebriefLiteApp.setState(DebriefLiteApp.ACTIVE_STATE);
converter.init(start, end);
timeSlider.setMinimum(converter.getStart());
timeSlider.setMaximum(converter.getEnd());
}
@Override
public void setValue(final long time)
{
// find the value
final int value = converter.getCurrentAt(time);
timeSlider.setValue(value);
}
@Override
public void setValue(final String text)
{
final int completeSize = 17;
final int diff = completeSize - text.length();
String newText = text;
for (int i = 0; i < diff / 2; i++)
{
newText = " " + newText + " ";
}
if (newText.length() < completeSize)
{
newText = newText + " ";
}
timeLabel.setText(newText);
}
};
stepControl.setTimeLabel(label);
// we also need to listen to the slider
timeSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(final ChangeEvent e)
{
final int pos = timeSlider.getValue();
final long time = converter.getTimeAt(pos);
if (timeManager.getTime() == null || timeManager.getTime().getDate()
.getTime() != time)
{
timeManager.setTime(timeSlider, new HiResDate(time), true);
}
}
});
// ok, start off with the buttons disabled
setButtonsEnabled(topButtonsPanel, false);
// we also need to listen out for the stepper control mode changing
stepControl.addStepperListener(new LiteStepperListener(playCommandButton)
{
@Override
public void reset()
{
// move the slider to the start
timeSlider.setValue(0);
label.setValue(LiteStepControl.timeFormat);
// ok, do some disabling
DebriefLiteApp.setState(DebriefLiteApp.INACTIVE_STATE);
timeSlider.setEnabled(false);
}
});
control.addRibbonComponent(new JRibbonComponent(topButtonsPanel));
control.addRibbonComponent(new JRibbonComponent(timeSlider));
control.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
control));
return control;
}
private static JRibbonBand createDisplayMode(final Runnable normalPainter,
final Runnable snailPainter)
{
final JRibbonBand displayMode = new JRibbonBand("Display Mode", null);
final FlamingoCommandToggleGroup displayModeGroup =
new FlamingoCommandToggleGroup();
MenuUtils.addCommandToggleButton("Normal", "icons/48/normal.png",
new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
normalPainter.run();
}
}, displayMode, RibbonElementPriority.TOP, true, displayModeGroup,
true);
MenuUtils.addCommandToggleButton("Snail", "icons/48/snail.png",
new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
snailPainter.run();
}
}, displayMode, RibbonElementPriority.TOP, true, displayModeGroup,
false);
displayMode.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
displayMode));
return displayMode;
}
private static JRibbonBand createFilterToTime(
final LiteStepControl stepControl, final PlotOperations operations,
final TimeManager timeManager)
{
final JRibbonBand timePeriod = new JRibbonBand("Filter to time", null);
final Calendar start = new GregorianCalendar(1995, 11, 12);
final Calendar end = new GregorianCalendar(1995, 11, 12);
// Now we create the components for the sliders
final JLabel minimumValue = new JLabel();
final JLabel maximumValue = new JLabel();
final RangeSlider slider = new RangeSlider(start, end);
formatBinder.stepControl = stepControl;
formatBinder.maximumValue = maximumValue;
formatBinder.minimumValue = minimumValue;
formatBinder.slider = slider;
formatBinder.timeManager = timeManager;
formatBinder.updateFilterDateFormat();
slider.addChangeListener(new SliderListener(operations, timeManager));
slider.setEnabled(false);
slider.setPreferredSize(new Dimension(250, 200));
final JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.Y_AXIS));
sliderPanel.setPreferredSize(new Dimension(250, 200));
// Label's panel
final JPanel valuePanel = new JPanel();
valuePanel.setLayout(new BoxLayout(valuePanel, BoxLayout.X_AXIS));
valuePanel.add(minimumValue);
valuePanel.add(Box.createGlue());
valuePanel.add(maximumValue);
valuePanel.setPreferredSize(new Dimension(250, 200));
timePeriod.addRibbonComponent(new JRibbonComponent(slider));
timePeriod.addRibbonComponent(new JRibbonComponent(valuePanel));
// tie in to the stepper
final SliderControls iSlider = new LiteSliderControls(slider);
stepControl.setSliderControls(iSlider);
// listen out for time being reset
// we also need to listen out for the stepper control mode changing
stepControl.addStepperListener(new LiteStepperListener(null)
{
@Override
public void reset()
{
minimumValue.setText(" ");
maximumValue.setText(" ");
}
});
return timePeriod;
}
public static void resetDateFormat()
{
final String defaultFormat = LiteStepControl.timeFormat;
if (defaultFormat != null)
{
DebriefRibbonTimeController.assignThisTimeFormat(defaultFormat, false,
false);
formatBinder.stepControl.setDateFormat(defaultFormat);
formatBinder.updateFilterDateFormat();
}
if (label != null)
{
label.setValue(defaultFormat);
}
}
/**
* convenience class to bulk enable/disable controls in a panel
*
* @param panel
* @param enabled
*/
public static void setButtonsEnabled(final JPanel panel,
final boolean enabled)
{
final Component[] items = panel.getComponents();
for (final Component item : items)
{
final boolean state = item.isEnabled();
if (state != enabled)
{
item.setEnabled(enabled);
}
}
}
public static void updatePlayBtnUI(final JCommandButton playCommandButton,
final boolean isPlaying)
{
final String image;
if (isPlaying)
image = PLAY_IMAGE;
else
image = STOP_IMAGE;
final String tooltip = isPlaying ? STOP_TEXT : START_TEXT;
final RichTooltipBuilder builder = new RichTooltipBuilder();
final RichTooltip richTooltip = builder.setTitle("Timer")
.addDescriptionSection(tooltip).build();
playCommandButton.setActionRichTooltip(richTooltip);
// switch the icon
final Image playStopinImage = MenuUtils.createImage(image);
final ImageWrapperResizableIcon imageIcon = ImageWrapperResizableIcon
.getIcon(playStopinImage, MenuUtils.ICON_SIZE_16);
playCommandButton.setExtraText(tooltip);
playCommandButton.setIcon(imageIcon);
}
}
|
package org.gluu.persist.couchbase.model;
import com.couchbase.client.java.query.dsl.Expression;
public class ConvertedExpression {
private Expression expression;
private boolean consistency;
private ConvertedExpression(Expression expression) {
this.expression = expression;
}
private ConvertedExpression(Expression expression, boolean consistency) {
this.expression = expression;
this.consistency = consistency;
}
public static ConvertedExpression build(Expression expression, boolean consistency) {
return new ConvertedExpression(expression, consistency);
}
public Expression expression() {
return expression;
}
public boolean consistency() {
return consistency;
}
public void consistency(boolean consistency) {
this.consistency = consistency;
}
}
|
package ua.com.fielden.platform.web.test.server;
import static java.lang.String.format;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchOnly;
import static ua.com.fielden.platform.utils.Pair.pair;
import static ua.com.fielden.platform.web.PrefDim.mkDim;
import static ua.com.fielden.platform.web.centre.api.actions.impl.EntityActionBuilder.action;
import static ua.com.fielden.platform.web.centre.api.context.impl.EntityCentreContextSelector.context;
import static ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.construction.options.DefaultValueOptions.multi;
import static ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.construction.options.DefaultValueOptions.single;
import static ua.com.fielden.platform.web.centre.api.resultset.PropDef.mkProp;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import ua.com.fielden.platform.basic.autocompleter.AbstractSearchEntityByKeyWithCentreContext;
import ua.com.fielden.platform.basic.config.Workflows;
import ua.com.fielden.platform.criteria.generator.ICriteriaGenerator;
import ua.com.fielden.platform.domaintree.IServerGlobalDomainTreeManager;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.EntityManipulationAction;
import ua.com.fielden.platform.entity.factory.EntityFactory;
import ua.com.fielden.platform.entity.factory.ICompanionObjectFinder;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICompleted;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICompoundCondition0;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IWhere0;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.sample.domain.ITgPersistentCompositeEntity;
import ua.com.fielden.platform.sample.domain.ITgPersistentEntityWithProperties;
import ua.com.fielden.platform.sample.domain.ITgPersistentStatus;
import ua.com.fielden.platform.sample.domain.MiDetailsCentre;
import ua.com.fielden.platform.sample.domain.MiTgEntityWithPropertyDependency;
import ua.com.fielden.platform.sample.domain.MiTgFetchProviderTestEntity;
import ua.com.fielden.platform.sample.domain.MiTgPersistentEntityWithProperties;
import ua.com.fielden.platform.sample.domain.MiTgPersistentEntityWithProperties1;
import ua.com.fielden.platform.sample.domain.MiTgPersistentEntityWithProperties2;
import ua.com.fielden.platform.sample.domain.MiTgPersistentEntityWithProperties3;
import ua.com.fielden.platform.sample.domain.MiTgPersistentEntityWithProperties4;
import ua.com.fielden.platform.sample.domain.TgCentreInvokerWithCentreContext;
import ua.com.fielden.platform.sample.domain.TgCentreInvokerWithCentreContextProducer;
import ua.com.fielden.platform.sample.domain.TgCreatePersistentStatusAction;
import ua.com.fielden.platform.sample.domain.TgCreatePersistentStatusActionProducer;
import ua.com.fielden.platform.sample.domain.TgDummyAction;
import ua.com.fielden.platform.sample.domain.TgDummyActionProducer;
import ua.com.fielden.platform.sample.domain.TgEntityForColourMaster;
import ua.com.fielden.platform.sample.domain.TgEntityForColourMasterProducer;
import ua.com.fielden.platform.sample.domain.TgEntityWithPropertyDependency;
import ua.com.fielden.platform.sample.domain.TgEntityWithPropertyDependencyProducer;
import ua.com.fielden.platform.sample.domain.TgExportFunctionalEntity;
import ua.com.fielden.platform.sample.domain.TgExportFunctionalEntityProducer;
import ua.com.fielden.platform.sample.domain.TgFetchProviderTestEntity;
import ua.com.fielden.platform.sample.domain.TgFunctionalEntityWithCentreContext;
import ua.com.fielden.platform.sample.domain.TgFunctionalEntityWithCentreContextProducer;
import ua.com.fielden.platform.sample.domain.TgIRStatusActivationFunctionalEntity;
import ua.com.fielden.platform.sample.domain.TgIRStatusActivationFunctionalEntityProducer;
import ua.com.fielden.platform.sample.domain.TgISStatusActivationFunctionalEntity;
import ua.com.fielden.platform.sample.domain.TgISStatusActivationFunctionalEntityProducer;
import ua.com.fielden.platform.sample.domain.TgONStatusActivationFunctionalEntity;
import ua.com.fielden.platform.sample.domain.TgONStatusActivationFunctionalEntityProducer;
import ua.com.fielden.platform.sample.domain.TgPersistentCompositeEntity;
import ua.com.fielden.platform.sample.domain.TgPersistentEntityWithProperties;
import ua.com.fielden.platform.sample.domain.TgPersistentEntityWithPropertiesProducer;
import ua.com.fielden.platform.sample.domain.TgPersistentStatus;
import ua.com.fielden.platform.sample.domain.TgSRStatusActivationFunctionalEntity;
import ua.com.fielden.platform.sample.domain.TgSRStatusActivationFunctionalEntityProducer;
import ua.com.fielden.platform.sample.domain.TgStatusActivationFunctionalEntity;
import ua.com.fielden.platform.sample.domain.TgStatusActivationFunctionalEntityProducer;
import ua.com.fielden.platform.security.user.IUserProvider;
import ua.com.fielden.platform.security.user.User;
import ua.com.fielden.platform.serialisation.jackson.entities.EntityWithInteger;
import ua.com.fielden.platform.swing.menu.MiWithConfigurationSupport;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.web.app.AbstractWebUiConfig;
import ua.com.fielden.platform.web.app.IWebUiConfig;
import ua.com.fielden.platform.web.centre.CentreContext;
import ua.com.fielden.platform.web.centre.EntityCentre;
import ua.com.fielden.platform.web.centre.IQueryEnhancer;
import ua.com.fielden.platform.web.centre.api.EntityCentreConfig;
import ua.com.fielden.platform.web.centre.api.actions.EntityActionConfig;
import ua.com.fielden.platform.web.centre.api.crit.defaults.assigners.IValueAssigner;
import ua.com.fielden.platform.web.centre.api.crit.defaults.mnemonics.SingleCritOtherValueMnemonic;
import ua.com.fielden.platform.web.centre.api.extra_fetch.IExtraFetchProviderSetter;
import ua.com.fielden.platform.web.centre.api.impl.EntityCentreBuilder;
import ua.com.fielden.platform.web.centre.api.query_enhancer.IQueryEnhancerSetter;
import ua.com.fielden.platform.web.centre.api.resultset.ICustomPropsAssignmentHandler;
import ua.com.fielden.platform.web.centre.api.resultset.scrolling.impl.ScrollConfig;
import ua.com.fielden.platform.web.centre.api.resultset.summary.ISummaryCardLayout;
import ua.com.fielden.platform.web.centre.api.top_level_actions.ICentreTopLevelActions;
import ua.com.fielden.platform.web.centre.api.top_level_actions.ICentreTopLevelActionsWithRunConfig;
import ua.com.fielden.platform.web.config.EntityManipulationWebUiConfig;
import ua.com.fielden.platform.web.interfaces.ILayout.Device;
import ua.com.fielden.platform.web.minijs.JsCode;
import ua.com.fielden.platform.web.test.matchers.ContextMatcher;
import ua.com.fielden.platform.web.test.server.master_action.NewEntityAction;
import ua.com.fielden.platform.web.test.server.master_action.NewEntityActionWebUiConfig;
import ua.com.fielden.platform.web.view.master.EntityMaster;
import ua.com.fielden.platform.web.view.master.api.IMaster;
import ua.com.fielden.platform.web.view.master.api.actions.MasterActions;
import ua.com.fielden.platform.web.view.master.api.actions.post.IPostAction;
import ua.com.fielden.platform.web.view.master.api.actions.pre.IPreAction;
import ua.com.fielden.platform.web.view.master.api.impl.SimpleMasterBuilder;
import ua.com.fielden.platform.web.view.master.api.with_centre.impl.MasterWithCentreBuilder;
import com.google.inject.Inject;
/**
* App-specific {@link IWebUiConfig} implementation.
*
* @author TG Team
*
*/
public class WebUiConfig extends AbstractWebUiConfig {
private final String domainName;
private final String path;
public WebUiConfig(final String domainName, final Workflows workflow, final String path) {
super("TG Test and Demo Application", workflow, new String[0]);
if (StringUtils.isEmpty(domainName) || StringUtils.isEmpty(path)) {
throw new IllegalArgumentException("Both the domain name and application binding path should be specified.");
}
this.domainName = domainName;
this.path = path;
}
@Override
public String getDomainName() {
return domainName;
}
@Override
public String getPath() {
return path;
}
/**
* Configures the {@link WebUiConfig} with custom centres and masters.
*/
@Override
public void initConfiguration() {
// Add entity centres.
final EntityCentre<TgFetchProviderTestEntity> fetchProviderTestCentre = new EntityCentre<>(MiTgFetchProviderTestEntity.class, "TgFetchProviderTestEntity",
EntityCentreBuilder.centreFor(TgFetchProviderTestEntity.class)
.addCrit("property").asMulti().autocompleter(TgPersistentEntityWithProperties.class).setDefaultValue(multi().string().setValues("KE*").value()).
setLayoutFor(Device.DESKTOP, Optional.empty(), "[[]]")
.addProp("property")
.setFetchProvider(EntityUtils.fetch(TgFetchProviderTestEntity.class).with("additionalProperty"))
// .addProp("additionalProp")
.build(), injector(), null);
configApp().addCentre(MiTgFetchProviderTestEntity.class, fetchProviderTestCentre);
final EntityCentre<TgPersistentEntityWithProperties> detailsCentre = createEntityCentre(MiDetailsCentre.class, "Details Centre", createEntityCentreConfig(false, true, true));
final EntityCentre<TgEntityWithPropertyDependency> propDependencyCentre = new EntityCentre<>(MiTgEntityWithPropertyDependency.class, "Property Dependency Example",
EntityCentreBuilder.centreFor(TgEntityWithPropertyDependency.class)
.runAutomatically()
.addCrit("property").asMulti().text().also()
.addCrit("dependentProp").asMulti().text()
.setLayoutFor(Device.DESKTOP, Optional.empty(), "[['center-justified', 'start', ['margin-right: 40px', 'flex'], ['flex']]]")
.addProp("this").also()
.addProp("property").also()
.addProp("dependentProp")
.addPrimaryAction(EntityActionConfig.createMasterInDialogInvocationActionConfig())
.build(), injector(), (centre) -> {
// ... please implement some additional hooks if necessary -- for e.g. centre.getFirstTick().setWidth(...), add calculated properties through domain tree API, etc.
centre.getSecondTick().setWidth(TgEntityWithPropertyDependency.class, "", 60);
centre.getSecondTick().setWidth(TgEntityWithPropertyDependency.class, "property", 60);
centre.getSecondTick().setWidth(TgEntityWithPropertyDependency.class, "dependentProp", 60);
return centre;
});
final EntityCentre<TgPersistentEntityWithProperties> entityCentre = createEntityCentre(MiTgPersistentEntityWithProperties.class, "TgPersistentEntityWithProperties", createEntityCentreConfig(true, true, false));
final EntityCentre<TgPersistentEntityWithProperties> entityCentre1 = createEntityCentre(MiTgPersistentEntityWithProperties1.class, "TgPersistentEntityWithProperties 1", createEntityCentreConfig(false, false, false));
final EntityCentre<TgPersistentEntityWithProperties> entityCentre2 = createEntityCentre(MiTgPersistentEntityWithProperties2.class, "TgPersistentEntityWithProperties 2", createEntityCentreConfig(false, false, false));
final EntityCentre<TgPersistentEntityWithProperties> entityCentre3 = createEntityCentre(MiTgPersistentEntityWithProperties3.class, "TgPersistentEntityWithProperties 3", createEntityCentreConfig(false, false, false));
final EntityCentre<TgPersistentEntityWithProperties> entityCentre4 = createEntityCentre(MiTgPersistentEntityWithProperties4.class, "TgPersistentEntityWithProperties 4", createEntityCentreConfig(false, false, false));
configApp().addCentre(MiTgPersistentEntityWithProperties.class, entityCentre);
configApp().addCentre(MiTgPersistentEntityWithProperties1.class, entityCentre1);
configApp().addCentre(MiTgPersistentEntityWithProperties2.class, entityCentre2);
configApp().addCentre(MiTgPersistentEntityWithProperties3.class, entityCentre3);
configApp().addCentre(MiTgPersistentEntityWithProperties4.class, entityCentre4);
configApp().addCentre(MiDetailsCentre.class, detailsCentre);
configApp().addCentre(MiTgEntityWithPropertyDependency.class, propDependencyCentre);
//Add custom view
final CustomTestView customView = new CustomTestView();
configApp().addCustomView(customView);
// app.addCentre(new EntityCentre(MiTimesheet.class, "Timesheet"));
// Add custom views.
// app.addCustomView(new MyProfile(), true);
// app.addCustomView(new CustomWebView(new CustomWebModel()));
final String mr = "'margin-right: 20px', 'width:300px'";
final String fmr = "'flex', 'margin-right: 20px'";
final String actionMr = "'margin-top: 20px', 'margin-left: 20px', 'width: 110px'";
// Add entity masters.
final SimpleMasterBuilder<TgPersistentEntityWithProperties> smb = new SimpleMasterBuilder<TgPersistentEntityWithProperties>();
@SuppressWarnings("unchecked")
final IMaster<TgPersistentEntityWithProperties> masterConfig = smb.forEntity(TgPersistentEntityWithProperties.class)
// PROPERTY EDITORS
.addProp("entityProp.entityProp").asAutocompleter().withProps(pair("desc", true))
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("entityProp").asAutocompleter().withMatcher(ContextMatcher.class)
.withProps(pair("desc", true),
pair("compositeProp", false),
pair("booleanProp", false))
.withAction(
action(TgExportFunctionalEntity.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "self.setEditorValue4Property('requiredValidatedProp', functionalEntity, 'value');\n"
+ "self.setEditorValue4Property('entityProp', functionalEntity, 'parentEntity');\n"
)) // self.retrieve()
.postActionError(new PostActionError(""))
.icon("trending-up")
.shortDesc("Export")
.longDesc("Export action")
.build())
.also()
.addProp("key").asSinglelineText()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("bigDecimalProp").asDecimal()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("stringProp").asSinglelineText().skipValidation()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("stringProp").asMultilineText()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("dateProp").asDateTimePicker()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("booleanProp").asCheckbox()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("compositeProp").asAutocompleter()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("requiredValidatedProp").asSpinner()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("status").asAutocompleter()
.withAction(
action(TgCreatePersistentStatusAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "self.setEditorValue4Property('status', functionalEntity, 'status');\n"
)) // self.retrieve()
.postActionError(new PostActionError(""))
.icon("add-circle")
.shortDesc("Create Status")
.longDesc("Creates new status and assignes it back to the Status property")
.build())
.also()
.addAction(MasterActions.REFRESH)
.icon("highlight-off")
.shortDesc("CANCEL")
.longDesc("Cancels any changes and closes the master (if in dialog)")
// ENTITY CUSTOM ACTIONS
.addAction(
action(TgExportFunctionalEntity.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "self.setEditorValue4Property('requiredValidatedProp', functionalEntity, 'value');\n"
+ "self.setEditorValue4Property('entityProp', functionalEntity, 'parentEntity');\n"
)) // self.retrieve()
.postActionError(new PostActionError(""))
.icon("trending-up")
.shortDesc("Export")
.longDesc("Export action")
.build())
.addAction(MasterActions.VALIDATE)
.addAction(MasterActions.SAVE)
.addAction(MasterActions.EDIT)
.addAction(MasterActions.VIEW)
.setLayoutFor(Device.DESKTOP, Optional.empty(), (
" ['padding:20px', "
+ format("[[%s], [%s], [%s], [%s], ['flex']],", fmr, fmr, fmr, fmr)
+ format("[[%s], [%s], [%s], [%s], ['flex']],", fmr, fmr, fmr, fmr)
+ format("[['flex']],")
+ format("['margin-top: 20px', 'wrap', [%s],[%s],[%s],[%s],[%s],[%s]]", actionMr, actionMr, actionMr, actionMr, actionMr, actionMr)
+ " ]"))
.setLayoutFor(Device.TABLET, Optional.empty(), ("['padding:20px',"
+ "[[fmr], [fmr], ['flex']],"
+ "[[fmr], [fmr], ['flex']],"
+ "[[fmr], [fmr], ['flex']],"
+ "[['flex'], ['flex']],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]")
.replace("fmr", fmr)
.replace("actionMr", actionMr))
.setLayoutFor(Device.MOBILE, Optional.empty(), ("['padding:20px',"
+ "[[fmr], ['flex']],"
+ "[[fmr], ['flex']],"
+ "[[fmr], ['flex']],"
+ "[[fmr], ['flex']],"
+ "[[fmr], ['flex']],"
+ "[['flex']],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]")
.replace("fmr", fmr)
.replace("actionMr", actionMr))
.done();
final IMaster<TgEntityForColourMaster> masterConfigForColour = new SimpleMasterBuilder<TgEntityForColourMaster>().forEntity(TgEntityForColourMaster.class)
// PROPERTY EDITORS
.addProp("colourProp").asColour()
.withAction(
action(TgDummyAction.class)
.withContext(context().withMasterEntity().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build())
.also()
.addProp("booleanProp").asCheckbox()
.also()
.addProp("stringProp").asSinglelineText().skipValidation()
.also()
.addAction(MasterActions.REFRESH)
// */.icon("trending-up") SHORT-CUT
.shortDesc("REFRESH2")
.longDesc("REFRESH2 action")
// ENTITY CUSTOM ACTIONS
.addAction(
action(TgExportFunctionalEntity.class)
.withContext(context().withMasterEntity().build())
.icon("trending-up")
.shortDesc("Export")
.longDesc("Export action")
.build())
.addAction(MasterActions.VALIDATE).addAction(MasterActions.SAVE).addAction(MasterActions.EDIT).addAction(MasterActions.VIEW)
.setLayoutFor(Device.DESKTOP, Optional.empty(), ("['padding:20px', "
+ "[[fmr], ['flex']],"
+ "[['flex']],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]").replaceAll("fmr", fmr).replaceAll("actionMr", actionMr)).setLayoutFor(Device.TABLET, Optional.empty(), ("['padding:20px',"
+ "[[fmr],['flex']],"
+ "[['flex']],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]").replaceAll("fmr", fmr).replaceAll("actionMr", actionMr)).setLayoutFor(Device.MOBILE, Optional.empty(), ("['padding:20px',"
+ "[['flex']],"
+ "[['flex']],"
+ "[['flex']],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]").replaceAll("fmr", fmr).replaceAll("actionMr", actionMr)).done();
final IMaster<TgEntityWithPropertyDependency> masterConfigForPropDependencyExample = new SimpleMasterBuilder<TgEntityWithPropertyDependency>()
.forEntity(TgEntityWithPropertyDependency.class)
.addProp("property").asSinglelineText()
.also()
.addProp("dependentProp").asSinglelineText()
.also()
.addAction(MasterActions.REFRESH)
// */.icon("trending-up") SHORT-CUT
.shortDesc("CANCEL")
.longDesc("Cancel action")
.addAction(MasterActions.VALIDATE)
.addAction(MasterActions.SAVE)
.addAction(MasterActions.EDIT)
.addAction(MasterActions.VIEW)
.setLayoutFor(Device.DESKTOP, Optional.empty(), (
" ['padding:20px', "
+ format("[[%s], ['flex']],", fmr)
+ format("['margin-top: 20px', 'wrap', [%s],[%s],[%s],[%s],[%s]]", actionMr, actionMr, actionMr, actionMr, actionMr)
+ " ]"))
.done();
final IMaster<TgFunctionalEntityWithCentreContext> masterConfigForFunctionalEntity = new SimpleMasterBuilder<TgFunctionalEntityWithCentreContext>()
.forEntity(TgFunctionalEntityWithCentreContext.class) // forEntityWithSaveOnActivate
.addProp("valueToInsert").asSinglelineText()
.also()
.addProp("withBrackets").asCheckbox()
.also()
.addAction(MasterActions.REFRESH)
// */.icon("trending-up") SHORT-CUT
.shortDesc("CANCEL")
.longDesc("Cancel action")
.addAction(MasterActions.VALIDATE)
.addAction(MasterActions.SAVE)
.addAction(MasterActions.EDIT)
.addAction(MasterActions.VIEW)
.setLayoutFor(Device.DESKTOP, Optional.empty(), ("['vertical', 'justified', 'margin:20px', "
+ "[[mr], [mr]], "
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]").replaceAll("mr", mr).replaceAll("actionMr", actionMr))
.setLayoutFor(Device.TABLET, Optional.empty(), ("['vertical', 'margin:20px',"
+ "['horizontal', 'justified', ['flex', 'margin-right: 20px'], [mr]],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]").replaceAll("mr", mr).replaceAll("actionMr", actionMr))
.setLayoutFor(Device.MOBILE, Optional.empty(), ("['margin:20px',"
+ "['justified', ['flex', 'margin-right: 20px'], ['flex']],"
+ "['margin-top: 20px', 'wrap', [actionMr],[actionMr],[actionMr],[actionMr],[actionMr]]"
+ "]").replaceAll("actionMr", actionMr))
.done();
final EntityMaster<TgPersistentEntityWithProperties> entityMaster = new EntityMaster<TgPersistentEntityWithProperties>(
TgPersistentEntityWithProperties.class,
TgPersistentEntityWithPropertiesProducer.class,
masterConfig,
injector());
final EntityMaster<NewEntityAction> functionalMasterWithEmbeddedPersistentMaster = NewEntityActionWebUiConfig.createMaster(injector(), entityMaster);
final EntityMaster<EntityManipulationAction> entityManipulationActionMaster = EntityManipulationWebUiConfig.createMaster(injector());
final EntityMaster<TgEntityForColourMaster> clourMaster = new EntityMaster<TgEntityForColourMaster>(TgEntityForColourMaster.class, TgEntityForColourMasterProducer.class, masterConfigForColour, injector());
configApp().
addMaster(EntityManipulationAction.class, entityManipulationActionMaster).
addMaster(EntityWithInteger.class, new EntityMaster<EntityWithInteger>(EntityWithInteger.class, null, injector())). // efs(EntityWithInteger.class).with("prop")
addMaster(TgPersistentEntityWithProperties.class, entityMaster).
addMaster(NewEntityAction.class, functionalMasterWithEmbeddedPersistentMaster).
addMaster(TgEntityWithPropertyDependency.class, new EntityMaster<TgEntityWithPropertyDependency>(
TgEntityWithPropertyDependency.class,
TgEntityWithPropertyDependencyProducer.class,
masterConfigForPropDependencyExample,
injector())).
addMaster(TgEntityForColourMaster.class, clourMaster).
addMaster(EntityWithInteger.class, new EntityMaster<EntityWithInteger>(
EntityWithInteger.class,
null,
injector())). // efs(EntityWithInteger.class).with("prop")
addMaster(TgPersistentEntityWithProperties.class, entityMaster).
addMaster(TgFunctionalEntityWithCentreContext.class, new EntityMaster<TgFunctionalEntityWithCentreContext>(
TgFunctionalEntityWithCentreContext.class,
TgFunctionalEntityWithCentreContextProducer.class,
masterConfigForFunctionalEntity,
injector())).
addMaster(TgCentreInvokerWithCentreContext.class, new EntityMaster<TgCentreInvokerWithCentreContext>(
TgCentreInvokerWithCentreContext.class,
TgCentreInvokerWithCentreContextProducer.class,
new MasterWithCentreBuilder<TgCentreInvokerWithCentreContext>().forEntityWithSaveOnActivate(TgCentreInvokerWithCentreContext.class).withCentre(detailsCentre).done(),
injector())).
addMaster(TgPersistentCompositeEntity.class, new EntityMaster<TgPersistentCompositeEntity>(
TgPersistentCompositeEntity.class,
null,
injector())).
addMaster(TgExportFunctionalEntity.class, EntityMaster.noUiFunctionalMaster(TgExportFunctionalEntity.class, TgExportFunctionalEntityProducer.class, injector())).
addMaster(TgDummyAction.class, EntityMaster.noUiFunctionalMaster(TgDummyAction.class, TgDummyActionProducer.class, injector())).
addMaster(TgCreatePersistentStatusAction.class, new EntityMaster<TgCreatePersistentStatusAction>(
TgCreatePersistentStatusAction.class,
TgCreatePersistentStatusActionProducer.class,
masterConfigForTgCreatePersistentStatusAction(), // TODO need to provide functional entity master configuration
injector())).
addMaster(TgStatusActivationFunctionalEntity.class, new EntityMaster<TgStatusActivationFunctionalEntity>(
TgStatusActivationFunctionalEntity.class,
TgStatusActivationFunctionalEntityProducer.class,
null,
injector())).
addMaster(TgISStatusActivationFunctionalEntity.class, new EntityMaster<TgISStatusActivationFunctionalEntity>(
TgISStatusActivationFunctionalEntity.class,
TgISStatusActivationFunctionalEntityProducer.class,
null,
injector())).
addMaster(TgIRStatusActivationFunctionalEntity.class, new EntityMaster<TgIRStatusActivationFunctionalEntity>(
TgIRStatusActivationFunctionalEntity.class,
TgIRStatusActivationFunctionalEntityProducer.class,
null,
injector())).
addMaster(TgONStatusActivationFunctionalEntity.class, new EntityMaster<TgONStatusActivationFunctionalEntity>(
TgONStatusActivationFunctionalEntity.class,
TgONStatusActivationFunctionalEntityProducer.class,
null,
injector())).
addMaster(TgSRStatusActivationFunctionalEntity.class, new EntityMaster<TgSRStatusActivationFunctionalEntity>(
TgSRStatusActivationFunctionalEntity.class,
TgSRStatusActivationFunctionalEntityProducer.class,
null,
injector())).
done();
// here comes main menu configuration
// it has two purposes -- one is to provide a high level navigation structure for the application,
// another is to bind entity centre (and potentially other views) to respective menu items
configMobileMainMenu()
.addModule("Fleet Mobile")
.description("Fleet Mobile")
.icon("mobile-menu:fleet")
.detailIcon("menu-detailed:fleet")
.bgColor("#00D4AA")
.captionBgColor("#00AA88")
.master(entityMaster)
//.centre(entityCentre)
// .view(null)
.done()
.addModule("DDS Mobile")
.description("DDS Mobile")
.icon("mobile-menu:divisional-daily-management")
.detailIcon("menu-detailed:divisional-daily-management")
.bgColor("#00D4AA")
.captionBgColor("#00AA88")
//.master(entityMaster)
.centre(entityCentre)
//.view(null)
.done();
configDesktopMainMenu()
.addModule("Fleet")
.description("Fleet")
.icon("menu:fleet")
.detailIcon("menu-detailed:fleet")
.bgColor("#00D4AA")
.captionBgColor("#00AA88")
.view(null)
.done()
.addModule("Import utilities")
.description("Import utilities")
.icon("menu:import-utilities")
.detailIcon("menu-detailed:import-utilities")
.bgColor("#5FBCD3")
.captionBgColor("#2C89A0")
.menu().addMenuItem("First view").description("First view description").view(null).done()
.addMenuItem("Second view").description("Second view description").view(null).done()
.addMenuItem("Entity Centre 1").description("Entity centre description").centre(entityCentre1).done()
.addMenuItem("Entity Centre 2").description("Entity centre description").centre(entityCentre2).done()
.addMenuItem("Entity Centre 3").description("Entity centre description").centre(entityCentre3).done()
.addMenuItem("Entity Centre 4").description("Entity centre description").centre(entityCentre4).done()
.addMenuItem("Third view").description("Third view description").view(null).done().done()
/*.menu()
.addMenuItem("Entity Centre").description("Entity centre description").centre(entityCentre).done()*/
.done()
.addModule("Division daily management")
.description("Division daily management")
.icon("menu:divisional-daily-management")
.detailIcon("menu-detailed:divisional-daily-management")
.bgColor("#CFD8DC")
.captionBgColor("#78909C")
.menu()
.addMenuItem("Entity Centre").description("Entity centre description").centre(entityCentre).done()
.addMenuItem("Custom View").description("Custom view description").view(customView).done()
.addMenuItem("Property Dependency Example").description("Property Dependency Example description").centre(propDependencyCentre).done()
.done().done()
.addModule("Accidents")
.description("Accidents")
.icon("menu:accidents")
.detailIcon("menu-detailed:accidents")
.bgColor("#FF9943")
.captionBgColor("#C87137")
.view(null)
.done()
.addModule("Maintenance")
.description("Maintenance")
.icon("menu:maintenance")
.detailIcon("menu-detailed:maintenance")
.bgColor("#00AAD4")
.captionBgColor("#0088AA")
.view(null)
.done()
.addModule("User")
.description("User")
.icon("menu:user")
.detailIcon("menu-detailed:user")
.bgColor("#FFE680")
.captionBgColor("#FFD42A")
.view(null)
.done()
.addModule("Online reports")
.description("Online reports")
.icon("menu:online-reports")
.detailIcon("menu-detailed:online-reports")
.bgColor("#00D4AA")
.captionBgColor("#00AA88").
view(null)
.done()
.addModule("Fuel")
.description("Fuel")
.icon("menu:fuel")
.detailIcon("menu-detailed:fuel")
.bgColor("#FFE680")
.captionBgColor("#FFD42A")
.view(null)
.done()
.addModule("Organisational")
.description("Organisational")
.icon("menu:organisational")
.detailIcon("menu-detailed:organisational")
.bgColor("#2AD4F6")
.captionBgColor("#00AAD4")
.view(null)
.done()
.addModule("Preventive maintenance")
.description("Preventive maintenance")
.icon("menu:preventive-maintenance")
.detailIcon("menu-detailed:preventive-maintenance")
.bgColor("#F6899A")
.captionBgColor("#D35F5F")
.view(null)
.done()
.setLayoutFor(Device.DESKTOP, null, "[[[{rowspan: 2,colspan: 2}], [], [], [{colspan: 2}]],[[{rowspan: 2,colspan: 2}], [], []],[[], [], [{colspan: 2}]]]")
.setLayoutFor(Device.TABLET, null, "[[[{rowspan: 2,colspan: 2}], [], []],[[{rowspan: 2,colspan: 2}]],[[], []],[[{rowspan: 2,colspan: 2}], [], []],[[{colspan: 2}]]]")
.setLayoutFor(Device.MOBILE, null, "[[[], []],[[], []],[[], []],[[], []],[[], []]]").minCellWidth(100).minCellHeight(148).done();
}
private static IMaster<TgCreatePersistentStatusAction> masterConfigForTgCreatePersistentStatusAction() {
final String layout = ""
+ "['vertical', 'padding:20px', "
+ " ['vertical', "
+ " ['width:300px', 'flex'], "
+ " ['width:300px', 'flex']"
+ " ],"
+ " ['horizontal', 'margin-top: 20px', 'justify-content: center', 'wrap', ['margin: 10px', 'width: 110px', 'flex'], ['margin: 10px', 'width: 110px', 'flex']]"
+ "]";
final IMaster<TgCreatePersistentStatusAction> config =
new SimpleMasterBuilder<TgCreatePersistentStatusAction>().forEntity(TgCreatePersistentStatusAction.class)
.addProp("statusCode").asSinglelineText()
.also()
.addProp("desc").asMultilineText()
.also()
.addAction(MasterActions.REFRESH).shortDesc("CANCLE").longDesc("Cancles the action")
.addAction(MasterActions.SAVE)
.setLayoutFor(Device.DESKTOP, Optional.empty(), layout)
.setLayoutFor(Device.TABLET, Optional.empty(), layout)
.setLayoutFor(Device.MOBILE, Optional.empty(), layout)
.done();
return config;
}
public static class TgPersistentEntityWithProperties_UserParamAssigner implements IValueAssigner<SingleCritOtherValueMnemonic<User>, TgPersistentEntityWithProperties> {
private final IUserProvider userProvider;
@Inject
public TgPersistentEntityWithProperties_UserParamAssigner(final IUserProvider userProvider) {
this.userProvider = userProvider;
}
@Override
public Optional<SingleCritOtherValueMnemonic<User>> getValue(final CentreContext<TgPersistentEntityWithProperties, ?> entity, final String name) {
final SingleCritOtherValueMnemonic<User> mnemonic = single().entity(User.class)./* TODO not applicable on query generation level not().*/setValue(userProvider.getUser())./* TODO not applicable on query generation level canHaveNoValue(). */value();
return Optional.of(mnemonic);
}
}
public static class EntityPropValueMatcherForCentre extends AbstractSearchEntityByKeyWithCentreContext<TgPersistentEntityWithProperties> {
@Inject
public EntityPropValueMatcherForCentre(final ITgPersistentEntityWithProperties dao) {
super(dao);
}
@Override
protected EntityResultQueryModel<TgPersistentEntityWithProperties> completeEqlBasedOnContext(final CentreContext<TgPersistentEntityWithProperties, ?> context, final String searchString, final ICompoundCondition0<TgPersistentEntityWithProperties> incompleteEql) {
System.out.println("EntityPropValueMatcherForCentre: CONTEXT == " + getContext());
return incompleteEql.model();
}
}
public static class KeyPropValueMatcherForCentre extends AbstractSearchEntityByKeyWithCentreContext<TgPersistentEntityWithProperties> {
@Inject
public KeyPropValueMatcherForCentre(final ITgPersistentEntityWithProperties dao) {
super(dao);
}
@Override
protected EntityResultQueryModel<TgPersistentEntityWithProperties> completeEqlBasedOnContext(final CentreContext<TgPersistentEntityWithProperties, ?> context, final String searchString, final ICompoundCondition0<TgPersistentEntityWithProperties> incompleteEql) {
System.out.println("KeyPropValueMatcherForCentre: CONTEXT == " + getContext());
return incompleteEql.model();
}
}
public static class CritOnlySingleEntityPropValueMatcherForCentre extends AbstractSearchEntityByKeyWithCentreContext<TgPersistentEntityWithProperties> {
@Inject
public CritOnlySingleEntityPropValueMatcherForCentre(final ITgPersistentEntityWithProperties dao) {
super(dao);
}
@Override
protected EntityResultQueryModel<TgPersistentEntityWithProperties> completeEqlBasedOnContext(final CentreContext<TgPersistentEntityWithProperties, ?> context, final String searchString, final ICompoundCondition0<TgPersistentEntityWithProperties> incompleteEql) {
System.out.println("CritOnlySingleEntityPropValueMatcherForCentre: CONTEXT == " + getContext());
return incompleteEql.model();
}
}
public static class CompositePropValueMatcherForCentre extends AbstractSearchEntityByKeyWithCentreContext<TgPersistentCompositeEntity> {
@Inject
public CompositePropValueMatcherForCentre(final ITgPersistentCompositeEntity dao) {
super(dao);
}
@Override
protected EntityResultQueryModel<TgPersistentCompositeEntity> completeEqlBasedOnContext(final CentreContext<TgPersistentCompositeEntity, ?> context, final String searchString, final ICompoundCondition0<TgPersistentCompositeEntity> incompleteEql) {
System.out.println("CompositePropValueMatcherForCentre: CONTEXT == " + getContext());
return incompleteEql.model();
}
}
private static class PreAction implements IPreAction {
private final String code;
public PreAction(final String code) {
this.code = code;
}
@Override
public JsCode build() {
return new JsCode(code);
}
}
private static class PostActionSuccess implements IPostAction {
private final String code;
public PostActionSuccess(final String code) {
this.code = code;
}
@Override
public JsCode build() {
return new JsCode(code);
}
}
private static class PostActionError implements IPostAction {
private final String code;
public PostActionError(final String code) {
this.code = code;
}
@Override
public JsCode build() {
return new JsCode(code);
}
}
private static class CustomPropsAssignmentHandler implements ICustomPropsAssignmentHandler<AbstractEntity<?>> {
@Override
public void assignValues(final AbstractEntity<?> entity) {
// entity.set("customProp", "OK");
}
}
private static class DetailsCentreQueryEnhancer implements IQueryEnhancer<TgPersistentEntityWithProperties> {
private final EntityFactory entityFactory;
private final IWebUiConfig webUiConfig;
private final ICompanionObjectFinder companionFinder;
private final IServerGlobalDomainTreeManager serverGdtm;
private final IUserProvider userProvider;
private final ICriteriaGenerator critGenerator;
@Inject
public DetailsCentreQueryEnhancer(final EntityFactory entityFactory, final IWebUiConfig webUiConfig, final ICompanionObjectFinder companionFinder, final IServerGlobalDomainTreeManager serverGdtm, final IUserProvider userProvider, final ICriteriaGenerator critGenerator) {
this.entityFactory = entityFactory;
this.webUiConfig = webUiConfig;
this.companionFinder = companionFinder;
this.serverGdtm = serverGdtm;
this.userProvider = userProvider;
this.critGenerator = critGenerator;
}
@Override
public ICompleted<TgPersistentEntityWithProperties> enhanceQuery(final IWhere0<TgPersistentEntityWithProperties> where, final Optional<CentreContext<TgPersistentEntityWithProperties, ?>> context) {
if (context.get().getMasterEntity() != null) {
System.out.println("DetailsCentreQueryEnhancer: master entity holder == " + context.get().getMasterEntity());
final TgCentreInvokerWithCentreContext funcEntity = (TgCentreInvokerWithCentreContext) context.get().getMasterEntity();
System.out.println("DetailsCentreQueryEnhancer: restored masterEntity: " + funcEntity);
System.out.println("DetailsCentreQueryEnhancer: restored masterEntity (centre context): " + funcEntity.getContext());
System.out.println("DetailsCentreQueryEnhancer: restored masterEntity (centre context's selection criteria): " + funcEntity.getContext().getSelectionCrit().get("tgPersistentEntityWithProperties_critOnlyBigDecimalProp"));
System.out.println("DetailsCentreQueryEnhancer: restored masterEntity (centre context's selection criteria): " + funcEntity.getContext().getSelectionCrit().get("tgPersistentEntityWithProperties_bigDecimalProp_from"));
}
return where.val(1).eq().val(1);
}
}
private static class TgPersistentEntityWithPropertiesQueryEnhancer implements IQueryEnhancer<TgPersistentEntityWithProperties> {
private final ITgPersistentStatus coStatus;
private final ITgPersistentEntityWithProperties coEntity;
@Inject
public TgPersistentEntityWithPropertiesQueryEnhancer(final ITgPersistentStatus statusCo, final ITgPersistentEntityWithProperties coEntity) {
this.coStatus = statusCo;
this.coEntity = coEntity;
}
@Override
public ICompleted<TgPersistentEntityWithProperties> enhanceQuery(final IWhere0<TgPersistentEntityWithProperties> where, final Optional<CentreContext<TgPersistentEntityWithProperties, ?>> context) {
System.err.println("CONTEXT IN QUERY ENHANCER == " + context.get());
if (!context.get().getSelectedEntities().isEmpty()) {
final Long id = (Long) context.get().getSelectedEntities().get(0).get("id");
final TgPersistentEntityWithProperties justUpdatedEntity = coEntity.findById(id, fetchOnly(TgPersistentEntityWithProperties.class).with("status"));
return where.prop("status").eq().val(justUpdatedEntity.getStatus());
}
return where.prop("status").eq().val(coStatus.findByKey("IS"));
}
}
private EntityCentreConfig<TgPersistentEntityWithProperties> createEntityCentreConfig(final boolean isComposite, final boolean runAutomatically, final boolean withQueryEnhancer) {
final String centreMr = "['margin-right: 40px', 'flex']";
final String centreMrLast = "['flex']";
final ICentreTopLevelActionsWithRunConfig<TgPersistentEntityWithProperties> partialCentre = EntityCentreBuilder.centreFor(TgPersistentEntityWithProperties.class);
ICentreTopLevelActions<TgPersistentEntityWithProperties> actionConf = (runAutomatically ? partialCentre.runAutomatically() : partialCentre)
.hasEventSourceAt("/entity-centre-events")
.enforcePostSaveRefresh()
.addTopAction(
action(EntityManipulationAction.class).
withContext(context().withSelectionCrit().build()).
icon("add-circle-outline").
shortDesc("Add new").
longDesc("Start coninuous creatio of entities").
build()
// action(NewEntityAction.class).
// withContext(context().withCurrentEntity().build()).// the current entity could potentially be used to demo "copy" functionality
// icon("add-circle").
// shortDesc("Add new").
// longDesc("Start coninuous creatio of entities").
// build()
).also()
.addTopAction(action(NewEntityAction.class).
withContext(context().withCurrentEntity().build()).// the current entity could potentially be used to demo "copy" functionality
icon("add-circle").
shortDesc("Add new").
longDesc("Start coninuous creatio of entities").
build())
.also();
if (isComposite) {
actionConf = actionConf.addTopAction(
action(TgCentreInvokerWithCentreContext.class)
.withContext(context().withSelectionCrit().withSelectedEntities().build())
.icon("assignment-ind")
.shortDesc("Function 4")
.longDesc("Functional context-dependent action 4")
.prefDimForView(mkDim("document.body.clientWidth / 4", "400"))
.withNoParentCentreRefresh()
.build()
).also();
}
@SuppressWarnings("unchecked")
final IQueryEnhancerSetter<TgPersistentEntityWithProperties> beforeEnhancerConf = actionConf
.addTopAction(
action(TgFunctionalEntityWithCentreContext.class).
withContext(context().withSelectedEntities().build()).
preAction(new IPreAction() {
@Override
public JsCode build() {
return new JsCode(" return confirm('Are you sure you want to proceed?');\n");
}
}).
icon("assignment-ind").
shortDesc("Function 1").
longDesc("Functional context-dependent action 1").
prefDimForView(mkDim(300, 200)).
build()
)
.also()
.addTopAction(
action(TgFunctionalEntityWithCentreContext.class).
withContext(context().withSelectedEntities().build()).
icon("assignment-returned").
shortDesc("Function 2").
longDesc("Functional context-dependent action 2").
build()
)
.also()
.addTopAction(
action(TgFunctionalEntityWithCentreContext.class).
withContext(context().withCurrentEntity().build()).
icon("assignment").
shortDesc("Function 3").
longDesc("Functional context-dependent action 3").
build()
)
.addCrit("this").asMulti().autocompleter(TgPersistentEntityWithProperties.class)
.withMatcher(KeyPropValueMatcherForCentre.class, context().withSelectedEntities()./*withMasterEntity().*/build())
.withProps(pair("desc", true), pair("booleanProp", false), pair("compositeProp", true), pair("compositeProp.desc", true))
/.setDefaultValue(multi().string().not().setValues("A*", "B*").canHaveNoValue().value())
.also()
.addCrit("stringProp").asMulti().text()
/.setDefaultValue(multi().string().not().setValues("DE*", "ED*").canHaveNoValue().value())
.also()
.addCrit("integerProp").asRange().integer()
/.setDefaultValue(range().integer().not().setFromValueExclusive(1).setToValueExclusive(2).canHaveNoValue().value())
.also()
.addCrit("entityProp").asMulti().autocompleter(TgPersistentEntityWithProperties.class)
.withMatcher(EntityPropValueMatcherForCentre.class, context().withSelectedEntities()./*withMasterEntity().*/build())
.lightDesc()
/.setDefaultValue(multi().string().not().setValues("C*", "D*").canHaveNoValue().value())
.also()
.addCrit("bigDecimalProp").asRange().decimal()
/.setDefaultValue(range().decimal().not().setFromValueExclusive(new BigDecimal(3).setScale(5) ).setToValueExclusive(new BigDecimal(4).setScale(5)).canHaveNoValue().value())
.also()
.addCrit("booleanProp").asMulti().bool()
/.setDefaultValue(multi().bool().not().setIsValue(false).setIsNotValue(false).canHaveNoValue().value())
.also()
.addCrit("dateProp").asRange().date()
// */.setDefaultValue(range().date().not().next()./* TODO not applicable on query generation level dayAndAfter().exclusiveFrom().exclusiveTo().*/canHaveNoValue().value())
/.setDefaultValue(range().date().not().setFromValueExclusive(new Date(1000000000L)).setToValueExclusive(new Date(2000000000L)).canHaveNoValue().value())
.also()
.addCrit("compositeProp").asMulti().autocompleter(TgPersistentCompositeEntity.class).withMatcher(CompositePropValueMatcherForCentre.class, context().withSelectedEntities()./*withMasterEntity().*/build())
/.setDefaultValue(multi().string().not().setValues("DEFAULT_KEY 10").canHaveNoValue().value())
.also()
.addCrit("critOnlyDateProp").asSingle().date()
.setDefaultValue(single().date().setValue(new Date(1000000000L)).value())
.also()
.addCrit("critOnlyEntityProp").asSingle().autocompleter(TgPersistentEntityWithProperties.class)
.withMatcher(CritOnlySingleEntityPropValueMatcherForCentre.class, context().withSelectedEntities()./*withMasterEntity().*/build())
.lightDesc()
.setDefaultValue(single().entity(TgPersistentEntityWithProperties.class).setValue(injector().getInstance(ITgPersistentEntityWithProperties.class).findByKey("KEY8")).value())
.also()
.addCrit("userParam").asSingle().autocompleter(User.class)
.withProps(pair("base", false), pair("basedOnUser", false))
.withDefaultValueAssigner(TgPersistentEntityWithProperties_UserParamAssigner.class)
.also()
.addCrit("critOnlyIntegerProp").asSingle().integer()
.setDefaultValue(single().integer().setValue(1).value())
.also()
.addCrit("critOnlyBigDecimalProp").asSingle().decimal()
.setDefaultValue(single().decimal().setValue(new BigDecimal(3).setScale(5) ).value())
.also()
.addCrit("critOnlyBooleanProp").asSingle().bool()
.setDefaultValue(single().bool().setValue(false).value())
.also()
.addCrit("critOnlyStringProp").asSingle().text()
.setDefaultValue(single().text().setValue("DE*").value())
.also()
.addCrit("status").asMulti().autocompleter(TgPersistentStatus.class)
.setDefaultValue(multi().string().not().canHaveNoValue().value())
.setLayoutFor(Device.DESKTOP, Optional.empty(),
// ("[['center-justified', 'start', mrLast]]")
("[['center-justified', 'start', mr, mr, mrLast]," +
"['center-justified', 'start', mr, mr, mrLast]," +
"['center-justified', 'start', mr, mr, mrLast]," +
"['center-justified', 'start', mr, mr, mrLast]," +
"['center-justified', 'start', mr, mr, mrLast]," +
"['center-justified', 'start', mrLast]]")
.replaceAll("mrLast", centreMrLast).replaceAll("mr", centreMr)
)
.setLayoutFor(Device.TABLET, Optional.empty(),
("[['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]," +
"['center-justified', 'start', mr, mrLast]]")
.replaceAll("mrLast", centreMrLast).replaceAll("mr", centreMr)
)
.setLayoutFor(Device.MOBILE, Optional.empty(),
("[['center-justified', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]," +
"['center-justified', 'start', mrLast]]")
.replaceAll("mrLast", centreMrLast).replaceAll("mr", centreMr)
)
//.hideCheckboxes()
//.notScrollable()
.withScrollingConfig(ScrollConfig.configScroll().withFixedCheckboxesPrimaryActionsAndFirstProps(1).withFixedSecondaryActions().withFixedHeader().done())
.setPageCapacity(20)
.setVisibleRowsCount(10)
.addProp("this").minWidth(60).withSummary("kount", "COUNT(SELF)", "Count:Number of entities").withAction(EntityActionConfig.createMasterInDialogInvocationActionConfig())
.also()
.addProp("desc").minWidth(200).
withAction(action(TgFunctionalEntityWithCentreContext.class).
withContext(context().withSelectedEntities().build()).
icon("assignment-turned-in").
shortDesc("Function 5").
longDesc("Functional context-dependent action 5").
build())
.also()
.addProp(mkProp("DR", "Defect Radio", String.class)).width(26).
withAction(action(TgStatusActivationFunctionalEntity.class).
withContext(context().withCurrentEntity().build()).
icon("assignment-turned-in").
shortDesc("Change Status to DR").
longDesc("Change Status to DR").
build())
.also()
.addProp(mkProp("IS", "In Service", String.class)).width(26).
withAction(action(TgISStatusActivationFunctionalEntity.class).
withContext(context().withCurrentEntity().build()).
icon("assignment-turned-in").
shortDesc("Change Status to IS").
longDesc("Change Status to IS").
build())
.also()
.addProp(mkProp("IR", "In Repair", String.class)).width(26).
withAction(action(TgIRStatusActivationFunctionalEntity.class).
withContext(context().withCurrentEntity().build()).
icon("assignment-turned-in").
shortDesc("Change Status to IR").
longDesc("Change Status to IR").
build())
.also()
.addProp(mkProp("ON", "On Road Defect Station", String.class)).width(26).
withAction(action(TgONStatusActivationFunctionalEntity.class).
withContext(context().withCurrentEntity().build()).
icon("assignment-turned-in").
shortDesc("Change Status to ON").
longDesc("Change Status to ON").
build())
.also()
.addProp(mkProp("SR", "Defect Smash Repair", String.class)).width(26).
withAction(action(TgSRStatusActivationFunctionalEntity.class).
withContext(context().withCurrentEntity().build()).
icon("assignment-turned-in").
shortDesc("Change Status to SR").
longDesc("Change Status to SR").
build())
.also()
.addProp("integerProp").minWidth(42).withTooltip("desc").withSummary("sum_of_int", "SUM(integerProp)", "Sum of int. prop:Sum of integer property")
.also()
.addProp("bigDecimalProp").minWidth(68).withSummary("max_of_dec", "MAX(bigDecimalProp)", "Max of decimal:Maximum of big decimal property")
.withSummary("min_of_dec", "MIN(bigDecimalProp)", "Min of decimal:Minimum of big decimal property")
.withSummary("sum_of_dec", "sum(bigDecimalProp)", "Sum of decimal:Sum of big decimal property")
.also()
.addProp("entityProp").minWidth(40)
.also()
.addProp("booleanProp").minWidth(49)
.also()
.addProp("dateProp").minWidth(130)
.also()
.addProp("compositeProp").minWidth(110)
.also()
.addProp("stringProp").minWidth(50)
// .setCollapsedCardLayoutFor(Device.DESKTOP, Optional.empty(),
// + "[['flex', 'select:property=this'], ['flex', 'select:property=desc'], ['flex', 'select:property=integerProp'], ['flex', 'select:property=bigDecimalProp']],"
// + "[['flex', 'select:property=entityProp'], ['flex', 'select:property=booleanProp'], ['flex', 'select:property=dateProp'], ['flex', 'select:property=compositeProp']]"
// .withExpansionLayout(
// + "[['flex', 'select:property=stringProp']]"
// .setCollapsedCardLayoutFor(Device.TABLET, Optional.empty(),
// + "[['flex', 'select:property=this'], ['flex', 'select:property=desc'], ['flex', 'select:property=integerProp']],"
// + "[['flex', 'select:property=bigDecimalProp'], ['flex', 'select:property=entityProp'], ['flex', 'select:property=booleanProp']]"
// .withExpansionLayout(
// + "[['flex', 'select:property=dateProp'],['flex', 'select:property=compositeProp']],"
// + "[['flex', 'select:property=stringProp']]"
// .setCollapsedCardLayoutFor(Device.MOBILE, Optional.empty(),
// + "[['flex', 'select:property=this'], ['flex', 'select:property=desc']],"
// + "[['flex', 'select:property=integerProp'], ['flex', 'select:property=bigDecimalProp']]"
// .withExpansionLayout(
// + "[['flex', 'select:property=entityProp'], ['flex', 'select:property=booleanProp']],"
// + "[['flex', 'select:property=dateProp'], ['flex', 'select:property=compositeProp']],"
// + "[['flex', 'select:property=stringProp']]"
// .also()
// .addProp("status")
// .also()
// .addProp(mkProp("Custom Prop", "Custom property with String type", String.class))
// .also()
// .addProp(mkProp("Custom Prop 2", "Custom property 2 with concrete value", "OK2"))
.addPrimaryAction(action(EntityManipulationAction.class).
withContext(context().withCurrentEntity().withSelectionCrit().build()).
icon("editor:mode-edit").
shortDesc("Edit entity").
longDesc("Opens master for editing this entity").
build())
// .addPrimaryAction(
// EntityActionConfig.createMasterInvocationActionConfig()
//EntityActionConfig.createMasterInDialogInvocationActionConfig()
// action(TgFunctionalEntityWithCentreContext.class).
// withContext(context().withSelectedEntities().build()).
// icon("assignment-turned-in").
// shortDesc("Function 2.5").
// longDesc("Functional context-dependent action 2.5").
// build()
//) // EntityActionConfig.createMasterInvocationActionConfig() |||||||||||| actionOff().build()
.also()
/*.addSecondaryAction(
EntityActionConfig.createMasterInDialogInvocationActionConfig()
).also()*/
.addSecondaryAction(
action(TgDummyAction.class)
.withContext(context().withSelectedEntities().build())
.postActionSuccess(new PostActionSuccess(""
+ "console.log('ACTION PERFORMED RECEIVING RESULT: ', functionalEntity);\n"
))
.icon("accessibility")
.shortDesc("Dummy")
.longDesc("Dummy action, simply prints its result into console.")
.build()
)
.also()
.addSecondaryAction(
action(TgFunctionalEntityWithCentreContext.class).
withContext(context().withSelectedEntities().build()).
icon("assignment-turned-in").
shortDesc("Function 3").
longDesc("Functional context-dependent action 3").
build()
)
.also()
.addSecondaryAction(
action(TgFunctionalEntityWithCentreContext.class).
withContext(context().withSelectedEntities().build()).
icon("attachment").
shortDesc("Function 4").
longDesc("Functional context-dependent action 4").
build()
)
.setCustomPropsValueAssignmentHandler(CustomPropsAssignmentHandler.class)
.setRenderingCustomiser(TestRenderingCustomiser.class);
final IExtraFetchProviderSetter<TgPersistentEntityWithProperties> afterQueryEnhancerConf;
if (withQueryEnhancer) {
afterQueryEnhancerConf = beforeEnhancerConf.setQueryEnhancer(DetailsCentreQueryEnhancer.class, context().withMasterEntity().build());
} else {
afterQueryEnhancerConf = beforeEnhancerConf;
}
// .setQueryEnhancer(TgPersistentEntityWithPropertiesQueryEnhancer.class, context().withCurrentEntity().build())
final ISummaryCardLayout<TgPersistentEntityWithProperties> scl = afterQueryEnhancerConf.setFetchProvider(EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("status"))
.setSummaryCardLayoutFor(Device.DESKTOP, Optional.empty(), "['width:350px', [['flex', 'select:property=kount'], ['flex', 'select:property=sum_of_int']],[['flex', 'select:property=max_of_dec'],['flex', 'select:property=min_of_dec']], [['flex', 'select:property=sum_of_dec']]]")
.setSummaryCardLayoutFor(Device.TABLET, Optional.empty(), "['width:350px', [['flex', 'select:property=kount'], ['flex', 'select:property=sum_of_int']],[['flex', 'select:property=max_of_dec'],['flex', 'select:property=min_of_dec']], [['flex', 'select:property=sum_of_dec']]]")
.setSummaryCardLayoutFor(Device.MOBILE, Optional.empty(), "['width:350px', [['flex', 'select:property=kount'], ['flex', 'select:property=sum_of_int']],[['flex', 'select:property=max_of_dec'],['flex', 'select:property=min_of_dec']], [['flex', 'select:property=sum_of_dec']]]");
// .also()
// .addProp("status").order(3).desc().withAction(null)
// .also()
// .addProp(mkProp("ON", "Defect ON road", "ON")).withAction(action(null).withContext(context().withCurrentEntity().withSelectionCrit().build()).build())
// .also()
// .addProp(mkProp("OF", "Defect OFF road", "OF")).withAction(actionOff().build())
// .also()
// .addProp(mkProp("IS", "In service", "IS")).withAction(null)
// if (isComposite) {
// return scl.addInsertionPoint(
// action(TgCentreInvokerWithCentreContext.class)
// .withContext(context().withSelectionCrit().withSelectedEntities().build())
// .icon("assignment-ind")
// .shortDesc("Insertion Point")
// .longDesc("Functional context-dependent Insertion Point")
// .prefDimForView(mkDim("document.body.clientWidth / 4", "400"))
// .withNoParentCentreRefresh()
// .build(),
// InsertionPoints.RIGHT)
// .build();
return scl.build();
}
private EntityCentre<TgPersistentEntityWithProperties> createEntityCentre(final Class<? extends MiWithConfigurationSupport<?>> miType, final String name, final EntityCentreConfig<TgPersistentEntityWithProperties> entityCentreConfig) {
final EntityCentre<TgPersistentEntityWithProperties> entityCentre = new EntityCentre<>(miType, name, entityCentreConfig, injector(), (centre) -> {
// ... please implement some additional hooks if necessary -- for e.g. centre.getFirstTick().setWidth(...), add calculated properties through domain tree API, etc.
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "", 60);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "desc", 200);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "integerProp", 42);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "bigDecimalProp", 68);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "entityProp", 40);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "booleanProp", 49);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "dateProp", 130);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "compositeProp", 110);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "stringProp", 50);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "status", 30);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "customProp", 30);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "customProp2", 30);
// final int statusWidth = 26; // TODO does not matter below 18px -- still remain 18px, +20+20 as padding
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "dR", statusWidth);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "iS", statusWidth);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "iR", statusWidth);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "oN", statusWidth);
// centre.getSecondTick().setWidth(TgPersistentEntityWithProperties.class, "sR", statusWidth);
return centre;
});
return entityCentre;
}
}
|
package org.jenkins.tools.test.dao;
import com.google.appengine.api.datastore.*;
import org.jenkins.tools.test.model.*;
import java.util.*;
import java.util.logging.Logger;
/**
* @author fcamblor
*/
public enum PluginCompatResultDAO {
INSTANCE;
public static interface CoreMatcher {
Query enhanceSearchCoreQuery(Query query);
Query enhanceSearchResultQuery(Query query, Map<Key, MavenCoordinates> coords);
public static enum All implements CoreMatcher {
INSTANCE;
public Query enhanceSearchCoreQuery(Query query){ return query; }
public Query enhanceSearchResultQuery(Query query, Map<Key, MavenCoordinates> coords){ return query; }
}
public static class Parameterized implements CoreMatcher {
private List<MavenCoordinates> cores;
public Parameterized(List<MavenCoordinates> cores){
this.cores = cores;
}
public Query enhanceSearchCoreQuery(Query query){
if(this.cores.size() == 0){
return query;
}
List<String> gavs = new ArrayList<String>(cores.size());
for(MavenCoordinates coord : cores){
gavs.add(coord.toGAV());
}
return query.addFilter(Mappings.MavenCoordinatesProperties.gav.name(), Query.FilterOperator.IN, gavs);
}
public Query enhanceSearchResultQuery(Query query, Map<Key, MavenCoordinates> coords){
if(coords.size() == 0){
return query;
} else {
return query.addFilter(Mappings.PluginCompatResultProperties.coreCoordsKey.name(),
Query.FilterOperator.IN, new ArrayList<Key>(coords.keySet()));
}
}
}
}
public static interface PluginMatcher {
public Query enhanceSearchPluginQuery(Query query);
public Query enhanceSearchResultQuery(Query query, Map<Key, PluginInfos> pluginInfos);
public static enum All implements PluginMatcher {
INSTANCE;
public Query enhanceSearchPluginQuery(Query query){ return query; }
public Query enhanceSearchResultQuery(Query query, Map<Key, PluginInfos> pluginInfos){ return query; }
}
public static class Parameterized implements PluginMatcher {
private List<String> pluginNames;
public Parameterized(List<String> pluginNames){
this.pluginNames = pluginNames;
}
public Query enhanceSearchPluginQuery(Query query){
if(this.pluginNames.size() == 0){
return query;
}
return query.addFilter(Mappings.PluginInfosProperties.pluginName.name(), Query.FilterOperator.IN, pluginNames);
}
public Query enhanceSearchResultQuery(Query query, Map<Key, PluginInfos> pluginInfos){
if(pluginInfos.size() == 0){
return query;
} else {
return query.addFilter(Mappings.PluginCompatResultProperties.pluginInfosKey.name(),
Query.FilterOperator.IN, new ArrayList<Key>(pluginInfos.keySet()));
}
}
}
}
private static final Logger log = Logger.getLogger(PluginCompatResultDAO.class.getName());
public Key persist(PluginInfos pluginInfos, PluginCompatResult result){
Key coreCoordinatesEntityKey = createCoreCoordsIfNotExist(result.coreCoordinates);
Key pluginInfosEntityKey = createPluginInfosIfNotExist(pluginInfos);
Entity resultToPersist = Mappings.toEntity(result, result.coreCoordinates, coreCoordinatesEntityKey, pluginInfos, pluginInfosEntityKey);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key resultKey = datastore.put(resultToPersist);
log.info("Plugin compat result stored with key : "+resultKey);
return resultKey;
}
private List<Entity> executePaginatedQueries(DatastoreService service, Query query, int limit){
List<Entity> results = new ArrayList<Entity>();
PreparedQuery pq = service.prepare(query);
QueryResultList<Entity> qrl = pq.asQueryResultList(FetchOptions.Builder.withLimit(limit));
results.addAll(qrl);
while(qrl.size() == limit){
Cursor cursor = qrl.getCursor();
qrl = pq.asQueryResultList(FetchOptions.Builder.withLimit(limit).startCursor(cursor));
results.addAll(qrl);
}
return results;
}
public PluginCompatReport search(PluginMatcher pluginMatcher, CoreMatcher coreMatcher){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query searchCoresQuery = new Query(Mappings.CORE_MAVEN_COORDS_KIND);
searchCoresQuery = coreMatcher.enhanceSearchCoreQuery(searchCoresQuery);
List<Entity> coreEntities = executePaginatedQueries(datastore, searchCoresQuery, 1000);
Map<Key, MavenCoordinates> cores = Mappings.mavenCoordsFromEntity(coreEntities);
Query searchPluginsQuery = new Query(Mappings.PluginInfosProperties.KIND);
searchPluginsQuery = pluginMatcher.enhanceSearchPluginQuery(searchPluginsQuery);
List<Entity> pluginInfoEntities = executePaginatedQueries(datastore, searchPluginsQuery, 1000);
Map<Key, PluginInfos> pluginInfos = Mappings.pluginInfosFromEntity(pluginInfoEntities);
Query searchResultsQuery = new Query(Mappings.PluginCompatResultProperties.KIND);
if((pluginMatcher == PluginMatcher.All.INSTANCE && coreMatcher == CoreMatcher.All.INSTANCE)
|| (pluginMatcher == PluginMatcher.All.INSTANCE || coreMatcher == CoreMatcher.All.INSTANCE)){
coreMatcher.enhanceSearchResultQuery(searchResultsQuery, cores);
pluginMatcher.enhanceSearchResultQuery(searchResultsQuery, pluginInfos);
} else {
// Yeah that's not really well object oriented...
searchResultsQuery.addFilter(Mappings.PluginCompatResultProperties.computedCoreAndPlugin.name(),
Query.FilterOperator.IN, cartesianProductOfCoreAndPlugins(cores, pluginInfos));
}
List<Entity> results = executePaginatedQueries(datastore, searchResultsQuery, 1000);
PluginCompatReport report = Mappings.pluginCompatReportFromResultsEntities(results, cores, pluginInfos);
return report;
}
public SortedSet<MavenCoordinates> findAllCores(){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query searchCoresQuery = new Query(Mappings.CORE_MAVEN_COORDS_KIND);
List<Entity> coreEntities = executePaginatedQueries(datastore, searchCoresQuery, 1000);
Map<Key, MavenCoordinates> cores = Mappings.mavenCoordsFromEntity(coreEntities);
return new TreeSet<MavenCoordinates>(cores.values());
}
public SortedSet<String> findAllPluginInfoNames(){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query searchPluginInfosQuery = new Query(Mappings.PluginInfosProperties.KIND);
List<Entity> pluginInfosEntities = executePaginatedQueries(datastore, searchPluginInfosQuery, 1000);
Map<Key, PluginInfos> pluginInfos = Mappings.pluginInfosFromEntity(pluginInfosEntities);
SortedSet<String> names = new TreeSet<String>(new Comparator<String>() {
public int compare(String s, String s1) {
return s.compareToIgnoreCase(s1);
}
});
for(PluginInfos pi : pluginInfos.values()){
names.add(pi.pluginName);
}
return names;
}
public long purgeResults(){
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
long deletedLines = 0;
deletedLines += DAOUtils.purgeEntities(Mappings.CORE_MAVEN_COORDS_KIND);
deletedLines += DAOUtils.purgeEntities(Mappings.PluginInfosProperties.KIND);
deletedLines += DAOUtils.purgeEntities(Mappings.PluginCompatResultProperties.KIND);
return deletedLines;
}
private List<String> cartesianProductOfCoreAndPlugins(Map<Key, MavenCoordinates> cores, Map<Key, PluginInfos> pluginInfos) {
List<String> computedCoreAndPlugins = new ArrayList<String>(cores.values().size() * pluginInfos.values().size());
for(MavenCoordinates coords : cores.values()){
for(PluginInfos pi : pluginInfos.values()){
computedCoreAndPlugins.add(Mappings.computeCoreAndPlugin(coords, pi));
}
}
return computedCoreAndPlugins;
}
private Key createPluginInfosIfNotExist(PluginInfos pluginInfos) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
List<Entity> pluginInfosEntities = datastore.prepare(
new Query(Mappings.PluginInfosProperties.KIND)
.addFilter(Mappings.PluginInfosProperties.pluginName.name(), Query.FilterOperator.EQUAL, pluginInfos.pluginName)
.addFilter(Mappings.PluginInfosProperties.pluginVersion.name(), Query.FilterOperator.EQUAL, pluginInfos.pluginVersion)
.addFilter(Mappings.PluginInfosProperties.pluginUrl.name(), Query.FilterOperator.EQUAL, pluginInfos.pluginUrl)
).asList(FetchOptions.Builder.withDefaults());
Key result = null;
if(pluginInfosEntities.size() == 0){
// Coordinate doesn't exist : let's create it !
Entity pluginInfoEntity = Mappings.toEntity(pluginInfos);
result = datastore.put(pluginInfoEntity);
} else {
result = pluginInfosEntities.get(0).getKey();
}
return result;
}
private Key createCoreCoordsIfNotExist(MavenCoordinates coreCoords){
return searchAndEventuallyCreateCoords(Mappings.CORE_MAVEN_COORDS_KIND, coreCoords);
}
private Key searchAndEventuallyCreateCoords(String kind, MavenCoordinates coords){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
List<Entity> coordsEntities = datastore.prepare(
new Query(kind)
.addFilter(Mappings.MavenCoordinatesProperties.gav.name(), Query.FilterOperator.EQUAL, coords.toGAV())
).asList(FetchOptions.Builder.withDefaults());
Key result = null;
if(coordsEntities.size() == 0){
// Coordinate doesn't exist : let's create it !
Entity coordsEntity = Mappings.toEntity(coords, kind);
result = datastore.put(coordsEntity);
} else {
result = coordsEntities.get(0).getKey();
}
return result;
}
}
|
package org.jetbrains.plugins.groovy.compiler.generator;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.lang.parser.parsing.util.FinalWrapper;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclarations;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrClassDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrInterfaceDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GroovyToJavaGenerator implements SourceGeneratingCompiler//, ClassPostProcessingCompiler
{
private static final Map<String, String> typesToInitialValues = new HashMap<String, String>();
static {
typesToInitialValues.put("String", "\"\"");
typesToInitialValues.put("boolean", "false");
typesToInitialValues.put("int", "0");
typesToInitialValues.put("short", "0");
typesToInitialValues.put("long", "0L");
typesToInitialValues.put("byte", "0");
typesToInitialValues.put("char", "'c'");
typesToInitialValues.put("double", "0D");
typesToInitialValues.put("float", "0F");
typesToInitialValues.put("void", "");
}
private static final String[] JAVA_MODIFIERS = new String[]{
PsiModifier.PUBLIC,
PsiModifier.PROTECTED,
PsiModifier.PRIVATE,
PsiModifier.PACKAGE_LOCAL,
PsiModifier.STATIC,
PsiModifier.ABSTRACT,
PsiModifier.FINAL,
PsiModifier.NATIVE,
PsiModifier.SYNCHRONIZED,
PsiModifier.STRICTFP,
PsiModifier.TRANSIENT,
PsiModifier.VOLATILE
};
public GenerationItem[] getGenerationItems(CompileContext context) {
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
VirtualFileManager.getInstance().refresh(false);
}
});
}
}, ModalityState.NON_MODAL);
VirtualFile[] files = context.getCompileScope().getFiles(GroovyFileType.GROOVY_FILE_TYPE, true);
List<GenerationItem> generationItems = new ArrayList<GenerationItem>();
GenerationItem item;
for (VirtualFile file : files) {
final GroovyFile myPsiFile = findPsiFile(file);
GrTopStatement[] statements = getTopStatementsInReadAction(myPsiFile);
boolean needCreateTopLevelClass = !needsCreateClassFromFileName(statements);
String prefix = getJavaClassPackage(statements);
//top level class
VirtualFile virtualFile;
if (needCreateTopLevelClass) {
virtualFile = myPsiFile.getVirtualFile();
assert virtualFile != null;
generationItems.add(new GenerationItemImpl(prefix + virtualFile.getNameWithoutExtension() + "." + "java", context.getModuleByFile(virtualFile), new TimestampValidityState(file.getTimeStamp())));
}
final FinalWrapper<GrTypeDefinition[]> typeDefWrapper = new FinalWrapper<GrTypeDefinition[]>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
typeDefWrapper.myValue = myPsiFile.getTypeDefinitions();
}
});
GrTypeDefinition[] typeDefinitions = typeDefWrapper.myValue;
for (GrTypeDefinition typeDefinition : typeDefinitions) {
item = new GenerationItemImpl(prefix + typeDefinition.getNameIdentifierGroovy().getText() + "." + "java", context.getModuleByFile(file), new TimestampValidityState(file.getTimeStamp()));
generationItems.add(item);
}
}
return generationItems.toArray(new GenerationItem[generationItems.size()]);
}
public GenerationItem[] generate(CompileContext context, GenerationItem[] itemsToGenerate, VirtualFile outputRootDirectory) {
// VirtualFile[] children = outputRootDirectory.getChildren();
// for (final VirtualFile child : children) {
// ApplicationManager.getApplication().invokeAndWait(new Runnable() {
// public void run() {
// ApplicationManager.getApplication().runWriteAction(new Runnable() {
// public void run() {
// try {
// child.delete(this);
// } catch (IOException e) {
// e.printStackTrace();
// }, ModalityState.NON_MODAL);
VirtualFile[] files = context.getCompileScope().getFiles(GroovyFileType.GROOVY_FILE_TYPE, true);
List<GenerationItem> generatedItems = new ArrayList<GenerationItem>();
Map<String, GenerationItem> myPathsToItemsMap = new HashMap<String, GenerationItem>();
//puts items witch can be generated
for (GenerationItem item : itemsToGenerate) {
myPathsToItemsMap.put(item.getPath(), item);
}
for (VirtualFile groovyFile : files) {
//generate java classes form groovy source files
VirtualFile itemFile = VirtualFileManager.getInstance().findFileByUrl(groovyFile.getUrl());
assert itemFile != null;
List<String> generatedJavaFilesRelPaths = generateItems(context, itemFile, outputRootDirectory);
for (String relPath : generatedJavaFilesRelPaths) {
GenerationItem generationItem = myPathsToItemsMap.get(relPath);
if (generationItem != null)
generatedItems.add(generationItem);
}
}
return generatedItems.toArray(new GenerationItem[0]);
}
private GroovyFile findPsiFile(final VirtualFile virtualFile) {
final Project project = VfsUtil.guessProjectForFile(virtualFile);
assert project != null;
final GroovyFile[] myFindPsiFile = new GroovyFile[1];
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
myFindPsiFile[0] = (GroovyFile) PsiManager.getInstance(project).findFile(virtualFile);
}
});
assert myFindPsiFile[0] != null;
return myFindPsiFile[0];
}
//virtualFile -> PsiFile
private List<String> generateItems(CompileContext context, final VirtualFile item, final VirtualFile outputRootDirectory) {
GroovyFile myPsiFile = findPsiFile(item);
Module module = context.getModuleByFile(item);
List<String> generatedJavaFilesRelPaths = generate(context, myPsiFile, module, outputRootDirectory);
assert generatedJavaFilesRelPaths != null;
return generatedJavaFilesRelPaths;
}
private List<String> generate(CompileContext context, final GroovyFile myPsiFile, Module module, VirtualFile outputRootDirectory) {
List<String> generatedItemsRelativePaths = new ArrayList<String>();
final StringBuffer text = new StringBuffer();
GrTopStatement[] statements = getTopStatementsInReadAction(myPsiFile);
//there is member on top level
boolean isOnlyInnerTypeDef = needsCreateClassFromFileName(statements);
//prefix defines structure of directories tree
String prefix = "";
if (statements.length != 0 && statements[0] instanceof GrPackageDefinition) {
prefix = getJavaClassPackage(statements);
}
if (statements.length != 0 && !isOnlyInnerTypeDef) {
VirtualFile virtualFile = myPsiFile.getVirtualFile();
assert virtualFile != null;
String fileDefinitionName = virtualFile.getNameWithoutExtension();
String topLevelGeneratedItemPath = createJavaSourceFile(context, outputRootDirectory, myPsiFile, text, fileDefinitionName, null, prefix);
generatedItemsRelativePaths.add(topLevelGeneratedItemPath);
}
final FinalWrapper<GrTypeDefinition[]> typeDefWrapper = new FinalWrapper<GrTypeDefinition[]>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
typeDefWrapper.myValue = myPsiFile.getTypeDefinitions();
}
});
GrTypeDefinition[] typeDefinitions = typeDefWrapper.myValue;
String generatedItemPath;
for (final GrTypeDefinition typeDefinition : typeDefinitions) {
text.setLength(0);
PsiElement element = typeDefinition.getNameIdentifierGroovy();
generatedItemPath = createJavaSourceFile(context, outputRootDirectory, myPsiFile, text, element.getText(), typeDefinition, prefix);
generatedItemsRelativePaths.add(generatedItemPath);
}
return generatedItemsRelativePaths;
}
/* @return prefix;
* prefix = (path + File.separator) | ""
*/
private String getJavaClassPackage(GrTopStatement[] statements) {
String prefix = "";
if (statements != null && statements.length > 0 && statements[0] instanceof GrPackageDefinition) {
prefix = ((GrPackageDefinition) statements[0]).getPackageName();
prefix = prefix.replace(".", File.separator);
prefix += File.separator;
}
return prefix;
}
private String createJavaSourceFile(CompileContext context, VirtualFile outputRootDirectory, GroovyFile myPsiFile, StringBuffer text, String typeDefinitionName, GrTypeDefinition typeDefinition, String prefix) {
writeTypeDefinition(text, typeDefinitionName, typeDefinition);
VirtualFile virtualFile = myPsiFile.getVirtualFile();
assert virtualFile != null;
// String generatedFileRelativePath = prefix + typeDefinitionName + "." + "java";
String fileShortName = typeDefinitionName + "." + "java";
createGeneratedFile(context, text, outputRootDirectory.getPath(), prefix, fileShortName, myPsiFile);
return prefix + typeDefinitionName + "." + "java";
}
private GrStatement[] getStatementsInReadAction(final GrTypeDefinition typeDefinition) {
if (typeDefinition == null) return new GrStatement[0];
final FinalWrapper<GrStatement[]> statementsWrapper = new FinalWrapper<GrStatement[]>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
statementsWrapper.myValue = typeDefinition.getStatements();
}
});
if (statementsWrapper.myValue == null) return new GrStatement[0];
return statementsWrapper.myValue;
}
private GrTopStatement[] getTopStatementsInReadAction(final GroovyFile myPsiFile) {
if (myPsiFile == null) return new GrTopStatement[0];
final FinalWrapper<GrTopStatement[]> statementsWrapper = new FinalWrapper<GrTopStatement[]>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
statementsWrapper.myValue = myPsiFile.getTopStatements();
}
});
return statementsWrapper.myValue;
}
private boolean needsCreateClassFromFileName(GrTopStatement[] statements) {
boolean isOnlyInnerTypeDef = true;
for (GrTopStatement statement : statements) {
if (!(statement instanceof GrTypeDefinition || statement instanceof GrImportStatement || statement instanceof GrPackageDefinition)) {
isOnlyInnerTypeDef = false;
break;
}
}
return isOnlyInnerTypeDef;
}
private void writeTypeDefinition(StringBuffer text, String typeDefinitionName, GrTypeDefinition typeDefinition) {
GrStatement[] statements = getStatementsInReadAction(typeDefinition);
Map<String, String> classNameToQualifiedName = new HashMap<String, String>();
// List<GrImportStatement> importStatements = new ArrayList<GrImportStatement>();
// for (GrTopStatement statement : statements) {
// if (statement instanceof GrImportStatement)
// importStatements.add((GrImportStatement) statement);
// fillClassNameToQualifiedNameMap(importStatements.toArray(new GrImportStatement[0]), classNameToQualifiedName);
if (typeDefinition instanceof GrClassDefinition) text.append("class");
else if (typeDefinition instanceof GrInterfaceDefinition) text.append("interface");
else text.append("class");
text.append(" ");
text.append(typeDefinitionName);
text.append(" ");
if (typeDefinition != null) {
final PsiClassType[] extendsClassesTypes = typeDefinition.getExtendsListTypes();
if (extendsClassesTypes.length > 0) {
text.append("extends ");
final FinalWrapper<String> canonicalTextWrapper = new FinalWrapper<String>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
canonicalTextWrapper.myValue = extendsClassesTypes[0].getCanonicalText();
}
});
String canonicalText = canonicalTextWrapper.myValue;
text.append(canonicalText);
text.append(" ");
}
PsiClassType[] implementsClassTypes = typeDefinition.getImplementsListTypes();
if (implementsClassTypes.length > 0) {
text.append("implements ");
PsiClassType implementsClassType;
int i = 0;
while (i < implementsClassTypes.length) {
if (i > 0) text.append(", ");
implementsClassType = implementsClassTypes[i];
assert implementsClassType != null;
final FinalWrapper<String> implementTypeWrapper = new FinalWrapper<String>();
final PsiClassType implementsClassType1 = implementsClassType;
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
implementTypeWrapper.myValue = implementsClassType1.getCanonicalText();
}
});
String implTypeCanonicalText = implementTypeWrapper.myValue;
text.append(implTypeCanonicalText);
}
text.append(" ");
}
}
text.append(" ");
text.append("{");
for (GrTopStatement statement : statements) {
if (statement instanceof GrMethod) {
if (((GrMethod) statement).isConstructor()) {
writeConstructor(text, (GrMethod) statement);
text.append("\n");
}
writeMethod(text, (GrMethod) statement);
text.append("\n");
}
if (statement instanceof GrVariableDeclarations) {
writeVariableDeclarations(text, (GrVariableDeclarations) statement);
}
}
text.append("}");
}
private void writeConstructor(StringBuffer text, GrMethod constructor) {
text.append("public ");
//append constructor name
text.append(constructor.getName());
GrParameter[] parameterList = constructor.getParameters();
text.append("(");
String paramType;
GrTypeElement paramTypeElement;
//writes parameters
int i = 0;
while (i < parameterList.length) {
if (i > 0) text.append(", "); //append ','
GrParameter parameter = parameterList[i];
paramTypeElement = parameter.getTypeElementGroovy();
paramType = getResolvedType(/*classNameToQualifiedName, */paramTypeElement);
text.append(paramType);
text.append(" ");
text.append(parameter.getName());
i++;
}
text.append(")");
text.append("{");
text.append("}");
}
private void writeVariableDeclarations(StringBuffer text, GrVariableDeclarations variableDeclarations) {
GrTypeElement varTypeElement = variableDeclarations.getTypeElementGroovy();
String varQualifiedTypeName = getResolvedType(varTypeElement);
String initValueToText;
if (typesToInitialValues.containsKey(varQualifiedTypeName))
initValueToText = typesToInitialValues.get(varQualifiedTypeName);
else
initValueToText = "null";
//append method name
PsiModifierList modifierList = variableDeclarations.getModifierList();
GrVariable[] grVariables = variableDeclarations.getVariables();
GrVariable variable;
int i = 0;
while (i < grVariables.length) {
variable = grVariables[i];
writeModifiers(text, modifierList);
//type
text.append(varQualifiedTypeName);
text.append(" ");
//var name
text.append(variable.getName());
text.append(" = ");
text.append(initValueToText);
text.append(";\n");
i++;
}
}
private void writeMethod(StringBuffer text, GrMethod method) {
GrTypeElement typeElement = method.getReturnTypeElementGroovy();
String qualifiedTypeName = getResolvedType(typeElement);
// text.append("public ");
PsiModifierList modifierList = method.getModifierList();
writeModifiers(text, modifierList);
//append qualified type name
text.append(qualifiedTypeName);
text.append(" ");
//append method name
text.append(method.getName());
GrParameter[] parameterList = method.getParameters();
text.append("(");
String paramType;
GrTypeElement paramTypeElement;
//writes parameters
int i = 0;
while (i < parameterList.length) {
if (i > 0) text.append(", "); //append ','
GrParameter parameter = parameterList[i];
paramTypeElement = parameter.getTypeElementGroovy();
paramType = getResolvedType(paramTypeElement);
text.append(paramType);
text.append(" ");
text.append(parameter.getName());
i++;
}
text.append(")");
text.append("{");
text.append("return ");
if (typesToInitialValues.containsKey(qualifiedTypeName))
text.append(typesToInitialValues.get(qualifiedTypeName));
else
text.append("null");
text.append(";");
text.append("}");
}
private void writeModifiers(StringBuffer text, PsiModifierList modifierList) {
for (String modifierType : JAVA_MODIFIERS) {
if (modifierList.hasModifierProperty(modifierType)) {
text.append(modifierType);
text.append(" ");
}
}
}
private String getResolvedType(GrTypeElement typeElement) {
String methodType;
if (typeElement == null) {
methodType = "Object";
} else {
final PsiType type = typeElement.getType();
final FinalWrapper<String> resolverTypeWrapper = new FinalWrapper<String>();
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
resolverTypeWrapper.myValue = type.getCanonicalText();
}
});
String resolvedType = resolverTypeWrapper.myValue;
methodType = resolvedType == null ? "<dimaskin>" : resolvedType;
}
return methodType;
}
private void createGeneratedFile(CompileContext context, StringBuffer text, String outputDir, String prefix, String generatedItemPath, GroovyFile myGroovyFile) {
assert prefix != null;
String prefixWithoutSeparator = prefix;
if (!"".equals(prefix)) {
prefixWithoutSeparator = prefix.substring(0, prefix.length() - File.separator.length());
new File(outputDir, prefixWithoutSeparator).mkdirs();
}
File myFile;
if (!"".equals(prefix))
myFile = new File(outputDir + File.separator + prefixWithoutSeparator, generatedItemPath);
else
myFile = new File(outputDir, generatedItemPath);
// if (myFile.exists()) {
// VirtualFile virtualFile = myGroovyFile.getVirtualFile();
// assert virtualFile != null;
// String url = virtualFile.getUrl();
// context.addMessage(
// CompilerMessageCategory.ERROR,
// GroovyBundle.message("Class") + " " + myFile.getName() + " " + GroovyBundle.message("already.exist"),
// url,
// return;
BufferedWriter writer = null;
try {
Writer fileWriter = new FileWriter(myFile);
writer = new BufferedWriter(fileWriter);
writer.write(text.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert writer != null;
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("");
}
}
@NotNull
public String getDescription() {
return "Groovy to java source code generator";
}
//TODO
public boolean validateConfiguration(CompileScope scope) {
// scope.getFiles(GroovyFileType.GROOVY_FILE_TYPE, true);
return true;
}
//todo: change it
public ValidityState createValidityState(DataInputStream is) throws IOException {
return new ValidityState() {
public boolean equalsTo(ValidityState otherState) {
return this.equals(otherState);
}
public void save(DataOutputStream os) throws IOException {
}
};
}
/*
@NotNull
public FileProcessingCompiler.ProcessingItem[] getProcessingItems(CompileContext context)
{
return new FileProcessingCompiler.ProcessingItem[0]; //To change body of implemented methods use File | Settings | File Templates.
}
public FileProcessingCompiler.ProcessingItem[] process(CompileContext context, FileProcessingCompiler.ProcessingItem[] items)
{
return new FileProcessingCompiler.ProcessingItem[0]; //To change body of implemented methods use File | Settings | File Templates.
}
*/
class GenerationItemImpl implements GenerationItem {
final String myPath;
ValidityState myState;
final Module myModule;
public GenerationItemImpl(String myPath, Module myModule, ValidityState myState) {
this.myModule = myModule;
this.myState = myState;
this.myPath = myPath;
}
public String getPath() {
return myPath;
}
public ValidityState getValidityState() {
return myState;
}
public Module getModule() {
return myModule;
}
}
}
|
package edu.cornell.pserc.util.tdouble;
import java.util.concurrent.Future;
import cern.colt.list.tdouble.DoubleArrayList;
import cern.colt.list.tint.IntArrayList;
import cern.colt.matrix.tdcomplex.DComplexFactory1D;
import cern.colt.matrix.tdcomplex.DComplexMatrix1D;
import cern.colt.matrix.tdouble.DoubleFactory1D;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import cern.colt.matrix.tdouble.DoubleMatrix2D;
import cern.colt.matrix.tint.IntFactory1D;
import cern.colt.matrix.tint.IntMatrix1D;
import cern.jet.math.tdouble.DoubleFunctions;
import cern.jet.math.tint.IntFunctions;
import edu.emory.mathcs.utils.ConcurrencyUtils;
/**
*
* @author Richard Lincoln (r.w.lincoln@gmail.com)
*
*/
public class Djp_util {
public static IntFunctions ifunc = IntFunctions.intFunctions;
public static DoubleFunctions dfunc = DoubleFunctions.functions;
/**
* Machine epsilon.
*/
public double EPS = 1e-15;
/**
*
* @param stop
* @return
*/
public static int[] irange(int stop) {
return irange(0, stop);
}
/**
*
* @param start
* @param stop
* @return
*/
public static int[] irange(int start, int stop) {
return irange(start, stop, 1);
}
/**
*
* @param start
* @param stop
* @param step
* @return
*/
public static int[] irange(int start, int stop, int step) {
int[] r = new int[stop - start];
int v = start;
for (int i = 0; i < r.length; i++) {
r[i] = v;
v += step;
}
return r;
}
/**
*
* @param stop
* @return
*/
public static double[] drange(int stop) {
return drange(0, stop);
}
/**
*
* @param start
* @param stop
* @return
*/
public static double[] drange(int start, int stop) {
return drange(start, stop, 1);
}
/**
*
* @param start
* @param stop
* @param step
* @return
*/
public static double[] drange(int start, int stop, int step) {
double[] r = new double[stop - start];
int v = start;
for (int i = 0; i < r.length; i++) {
r[i] = v;
v += step;
}
return r;
}
/**
*
* @param n
* @return
*/
public static int[] zeros(int size) {
final int[] values = new int[size];
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_1D())) {
nthreads = Math.min(nthreads, size);
Future<?>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
values[i] = 0;
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
values[i] = 0;
}
}
return values;
}
/**
*
* @param size array length
* @return an integer array with all elements = 1.
*/
public static int[] ones(int size) {
final int[] values = new int[size];
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_1D())) {
nthreads = Math.min(nthreads, size);
Future<?>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
values[i] = 1;
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
values[i] = 1;
}
}
return values;
}
/**
*
* @param d
* @return
*/
public static int[] inta(final DoubleMatrix1D d) {
int size = (int) d.size();
final int[] values = new int[size];
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_1D())) {
nthreads = Math.min(nthreads, size);
Future<?>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
values[i] = (int) d.getQuick(i);
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
values[i] = (int) d.getQuick(i);
}
}
return values;
}
/**
*
* @param d
* @return
*/
public static IntMatrix1D intm(final DoubleMatrix1D d) {
int size = (int) d.size();
final IntMatrix1D values = IntFactory1D.dense.make(size);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_1D())) {
nthreads = Math.min(nthreads, size);
Future<?>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
values.setQuick(i, (int) d.getQuick(i));
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
values.setQuick(i, (int) d.getQuick(i));
}
}
return values;
}
/**
*
* @param d
* @return
*/
public static DoubleMatrix1D dbla(final int[] ix) {
int size = ix.length;
final DoubleMatrix1D values = DoubleFactory1D.dense.make(size);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_1D())) {
nthreads = Math.min(nthreads, size);
Future<?>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
values.setQuick(i, ix[i]);
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
values.setQuick(i, ix[i]);
}
}
return values;
}
/**
*
* @param d
* @return
*/
public static DoubleMatrix1D dblm(final IntMatrix1D ix) {
int size = (int) ix.size();
final DoubleMatrix1D values = DoubleFactory1D.dense.make(size);
int nthreads = ConcurrencyUtils.getNumberOfThreads();
if ((nthreads > 1) && (size >= ConcurrencyUtils.getThreadsBeginN_1D())) {
nthreads = Math.min(nthreads, size);
Future<?>[] futures = new Future[nthreads];
int k = size / nthreads;
for (int j = 0; j < nthreads; j++) {
final int firstIdx = j * k;
final int lastIdx = (j == nthreads - 1) ? size : firstIdx + k;
futures[j] = ConcurrencyUtils.submit(new Runnable() {
public void run() {
for (int i = firstIdx; i < lastIdx; i++) {
values.setQuick(i, ix.getQuick(i));
}
}
});
}
ConcurrencyUtils.waitForCompletion(futures);
} else {
for (int i = 0; i < size; i++) {
values.setQuick(i, ix.getQuick(i));
}
}
return values;
}
/**
*
* @param t
* @return
*/
public static int max(int[] t) {
int maximum = t[0];
for (int i=1; i < t.length; i++)
if (t[i] > maximum)
maximum = t[i];
return maximum;
}
/**
*
* @param a
* @param b
* @return
*/
public static int[] cat(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
/**
*
* @param a
* @return
*/
public static int[] nonzero(IntMatrix1D a) {
IntArrayList indexList = new IntArrayList();
int size = (int) a.size();
int rem = size % 2;
if (rem == 1) {
int value = a.getQuick(0);
if (value != 0)
indexList.add(0);
}
for (int i = rem; i < size; i += 2) {
int value = a.getQuick(i);
if (value != 0)
indexList.add(i);
value = a.getQuick(i + 1);
if (value != 0)
indexList.add(i + 1);
}
indexList.trimToSize();
return indexList.elements();
}
/**
*
* @param a
* @return
*/
public static int[] nonzero(DoubleMatrix1D a) {
IntArrayList indexList = new IntArrayList();
int size = (int) a.size();
int rem = size % 2;
if (rem == 1) {
double value = a.getQuick(0);
if (value != 0)
indexList.add(0);
}
for (int i = rem; i < size; i += 2) {
double value = a.getQuick(i);
if (value != 0)
indexList.add(i);
value = a.getQuick(i + 1);
if (value != 0)
indexList.add(i + 1);
}
indexList.trimToSize();
return indexList.elements();
}
/**
*
* @param r
* @param theta
* @return
*/
public static DComplexMatrix1D polar(DoubleMatrix1D r, DoubleMatrix1D theta) {
return polar(r, theta, true);
}
/**
*
* @param r polar radius.
* @param theta polar angle.
* @param radians is 'theta' expressed in radians.
* @return complex polar representation.
*/
@SuppressWarnings("static-access")
public static DComplexMatrix1D polar(DoubleMatrix1D r, DoubleMatrix1D theta, boolean radians) {
DoubleMatrix1D real = theta.copy();
DoubleMatrix1D imag = theta.copy();
if (!radians) {
real.assign(dfunc.chain(dfunc.mult(Math.PI), dfunc.div(180)));
imag.assign(dfunc.chain(dfunc.mult(Math.PI), dfunc.div(180)));
}
real.assign(dfunc.cos);
imag.assign(dfunc.sin);
real.assign(r, dfunc.mult);
imag.assign(r, dfunc.mult);
DComplexMatrix1D cmplx = DComplexFactory1D.dense.make((int) r.size());
cmplx.assignReal(real);
cmplx.assignImaginary(imag);
return cmplx;
}
/**
*
* @param x
* @return [x(1)-x(0) x(2)-x(1) ... x(n)-x(n-1)]
*/
@SuppressWarnings("static-access")
public static IntMatrix1D diff(IntMatrix1D x) {
int size = (int) x.size() -1;
IntMatrix1D d = IntFactory1D.dense.make(size);
for (int i = 0; i < size; i++)
d.set(i, ifunc.minus.apply(x.get(i+1), x.get(i)));
return d;
}
/**
*
* @param x a vector of integers.
* @return true if any element of vector x is a nonzero number.
*/
public static boolean any(IntMatrix1D x) {
IntArrayList indexList = new IntArrayList();
x.getNonZeros(indexList, new IntArrayList());
return indexList.size() > 0;
}
/**
*
* @param x a vector of doubles.
* @return true if any element of vector x is a nonzero number.
*/
public static boolean any(DoubleMatrix1D x) {
IntArrayList indexList = new IntArrayList();
x.getNonZeros(indexList, new DoubleArrayList());
return indexList.size() > 0;
}
/**
*
* @param x
* @return
*/
public static IntMatrix1D any(DoubleMatrix2D x) {
int cols = x.columns();
IntMatrix1D y = IntFactory1D.dense.make(cols);
for (int i = 0; i < cols; i++) {
int a = any(x.viewColumn(i)) ? 1 : 0;
y.set(i, a);
}
return y;
}
/**
*
* @param x a vector of integers.
* @return true if all elements of 'x' are nonzero.
*/
public static boolean all(IntMatrix1D x) {
IntArrayList indexList = new IntArrayList();
x.getNonZeros(indexList, null);
return x.size() == indexList.size();
}
/**
*
* @param x a vector of doubles.
* @return true if all elements of 'x' are nonzero.
*/
public static boolean all(DoubleMatrix1D x) {
IntArrayList indexList = new IntArrayList();
x.getNonZeros(indexList, null);
return x.size() == indexList.size();
}
/**
*
* @param real real component, may be null
* @param imaginary, imaginary component, may be null
* @return a complex vector
*/
public static DComplexMatrix1D complex(DoubleMatrix1D real, DoubleMatrix1D imaginary) {
DComplexMatrix1D cmplx = DComplexFactory1D.dense.make((int) real.size());
if (real != null)
cmplx.assignReal(real);
if (imaginary != null)
cmplx.assignImaginary(imaginary);
return cmplx;
}
}
|
package org.jkiss.dbeaver.ext.derby.model;
import org.eclipse.core.runtime.IConfigurationElement;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.generic.model.*;
import org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel;
import org.jkiss.dbeaver.model.DBPErrorAssistant;
import org.jkiss.dbeaver.model.exec.DBCExecutionPurpose;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.utils.CommonUtils;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* DerbyMetaModel
*/
public class DerbyMetaModel extends GenericMetaModel
{
private Pattern ERROR_POSITION_PATTERN = Pattern.compile(" at line ([0-9]+), column ([0-9]+)\\.");
public DerbyMetaModel(IConfigurationElement cfg) {
super(cfg);
}
public String getViewDDL(DBRProgressMonitor monitor, GenericTable sourceObject) throws DBException {
try (JDBCSession session = sourceObject.getDataSource().getDefaultContext(true).openSession(monitor, DBCExecutionPurpose.META, "Read view definition")) {
return JDBCUtils.queryString(session, "SELECT v.VIEWDEFINITION from SYS.SYSVIEWS v,SYS.SYSTABLES t,SYS.SYSSCHEMAS s\n" +
"WHERE v.TABLEID=t.TABLEID AND t.SCHEMAID=s.SCHEMAID AND s.SCHEMANAME=? AND t.TABLENAME=?", sourceObject.getContainer().getName(), sourceObject.getName());
} catch (SQLException e) {
throw new DBException(e, sourceObject.getDataSource());
}
}
/*
@Override
public String getProcedureDDL(DBRProgressMonitor monitor, GenericProcedure sourceObject) throws DBException {
JDBCSession session = sourceObject.getDataSource().getDefaultContext(true).openSession(monitor, DBCExecutionPurpose.META, "Read procedure definition");
try {
return JDBCUtils.queryString(session, "SELECT pg_get_functiondef(p.oid) FROM PG_CATALOG.PG_PROC P, PG_CATALOG.PG_NAMESPACE NS\n" +
"WHERE ns.oid=p.pronamespace and ns.nspname=? AND p.proname=?", sourceObject.getContainer().getName(), sourceObject.getName());
} catch (SQLException e) {
throw new DBException(e, sourceObject.getDataSource());
} finally {
session.close();
}
}
*/
@Override
public boolean supportsSequences(GenericDataSource dataSource) {
return true;
}
@Override
public List<GenericSequence> loadSequences(DBRProgressMonitor monitor, GenericObjectContainer container) throws DBException {
try (JDBCSession session = container.getDataSource().getDefaultContext(true).openSession(monitor, DBCExecutionPurpose.META, "Read procedure definition")) {
try (JDBCPreparedStatement dbStat = session.prepareStatement(
"SELECT seq.SEQUENCENAME,seq.CURRENTVALUE,seq.MINIMUMVALUE,seq.MAXIMUMVALUE,seq.INCREMENT\n" +
"FROM sys.SYSSEQUENCES seq,sys.SYSSCHEMAS s\n" +
"WHERE seq.SCHEMAID=s.SCHEMAID AND s.SCHEMANAME=?")) {
dbStat.setString(1, container.getName());
try (JDBCResultSet dbResult = dbStat.executeQuery()) {
List<GenericSequence> result = new ArrayList<GenericSequence>();
while (dbResult.next()) {
GenericSequence sequence = new GenericSequence(
container,
JDBCUtils.safeGetString(dbResult, 1),
"",
JDBCUtils.safeGetLong(dbResult, 2),
JDBCUtils.safeGetLong(dbResult, 3),
JDBCUtils.safeGetLong(dbResult, 4),
JDBCUtils.safeGetLong(dbResult, 5));
result.add(sequence);
}
return result;
}
}
} catch (SQLException e) {
throw new DBException(e, container.getDataSource());
}
}
@Override
public DBPErrorAssistant.ErrorPosition getErrorPosition(Throwable error) {
String message = error.getMessage();
if (!CommonUtils.isEmpty(message)) {
Matcher matcher = ERROR_POSITION_PATTERN.matcher(message);
if (matcher.find()) {
DBPErrorAssistant.ErrorPosition pos = new DBPErrorAssistant.ErrorPosition();
pos.line = Integer.parseInt(matcher.group(1)) - 1;
pos.position = Integer.parseInt(matcher.group(2)) - 1;
return pos;
}
}
return null;
}
}
|
package org.python.pydev.ui.interpreters;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.python.copiedfromeclipsesrc.JDTNotAvailableException;
import org.python.pydev.core.ExtensionHelper;
import org.python.pydev.core.FullRepIterable;
import org.python.pydev.core.IInterpreterInfo;
import org.python.pydev.core.IInterpreterManager;
import org.python.pydev.core.IModule;
import org.python.pydev.core.IPythonNature;
import org.python.pydev.core.IPythonPathNature;
import org.python.pydev.core.ISystemModulesManager;
import org.python.pydev.core.IToken;
import org.python.pydev.core.MisconfigurationException;
import org.python.pydev.core.NotConfiguredInterpreterException;
import org.python.pydev.core.Tuple;
import org.python.pydev.core.docutils.StringUtils;
import org.python.pydev.core.log.Log;
import org.python.pydev.core.structure.FastStringBuffer;
import org.python.pydev.core.uiutils.AsynchronousProgressMonitorDialog;
import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.plugin.nature.PythonNature;
import org.python.pydev.plugin.nature.PythonNatureListenersManager;
import org.python.pydev.ui.pythonpathconf.InterpreterInfo;
/**
* Does not write directly in INTERPRETER_PATH, just loads from it and works with it.
*
* @author Fabio Zadrozny
*/
public abstract class AbstractInterpreterManager implements IInterpreterManager {
/**
* This is the cache, that points from an interpreter to its information.
*/
protected Map<String, InterpreterInfo> exeToInfo = new HashMap<String, InterpreterInfo>();
private Preferences prefs;
private String[] interpretersFromPersistedString;
private IInterpreterInfo[] interpreterInfosFromPersistedString;
/**
* This is used to keep the builtin completions
*/
protected final Map<String, IToken[]> builtinCompletions = new HashMap<String, IToken[]>();
/**
* This is used to keep the builtin module
*/
protected final Map<String, IModule> builtinMod = new HashMap<String, IModule>();
public void clearBuiltinCompletions(String projectInterpreterName) {
this.builtinCompletions.remove(projectInterpreterName);
}
public IToken[] getBuiltinCompletions(String projectInterpreterName) {
//Cache with the internal name.
projectInterpreterName = getInternalName(projectInterpreterName);
if(projectInterpreterName == null){
return null;
}
IToken[] toks = this.builtinCompletions.get(projectInterpreterName);
if(toks == null || toks.length == 0){
IModule builtMod = getBuiltinMod(projectInterpreterName);
if(builtMod != null){
toks = builtMod.getGlobalTokens();
this.builtinCompletions.put(projectInterpreterName, toks);
}
}
return this.builtinCompletions.get(projectInterpreterName);
}
public IModule getBuiltinMod(String projectInterpreterName){
//Cache with the internal name.
projectInterpreterName = getInternalName(projectInterpreterName);
if(projectInterpreterName == null){
return null;
}
IModule mod = builtinMod.get(projectInterpreterName);
if(mod != null){
return mod;
}
try {
InterpreterInfo interpreterInfo = this.getInterpreterInfo(projectInterpreterName, null);
ISystemModulesManager modulesManager = interpreterInfo.getModulesManager();
mod = modulesManager.getBuiltinModule("__builtin__", false);
if(mod == null){
//Python 3.0 has builtins and not __builtin__
mod = modulesManager.getBuiltinModule("builtins", false);
}
if(mod != null){
builtinMod.put(projectInterpreterName, mod);
}
} catch (MisconfigurationException e) {
Log.log(e);
}
return builtinMod.get(projectInterpreterName);
}
private String getInternalName(String projectInterpreterName) {
if(IPythonNature.DEFAULT_INTERPRETER.equals(projectInterpreterName)){
//if it's the default, let's translate it to the outside world
try {
return this.getDefaultInterpreter();
} catch (NotConfiguredInterpreterException e) {
Log.log(e);
return projectInterpreterName;
}
}
return projectInterpreterName;
}
public void clearBuiltinMod(String projectInterpreterName) {
this.builtinMod.remove(projectInterpreterName);
}
/**
* Constructor
*/
@SuppressWarnings("unchecked")
public AbstractInterpreterManager(Preferences prefs) {
this.prefs = prefs;
prefs.setDefault(getPreferenceName(), "");
prefs.addPropertyChangeListener(new Preferences.IPropertyChangeListener(){
public void propertyChange(PropertyChangeEvent event) {
clearCaches();
}
});
IInterpreterInfo[] interpreterInfos = this.getInterpreterInfos();
for (IInterpreterInfo interpreterInfo : interpreterInfos) {
this.exeToInfo.put(interpreterInfo.getExecutableOrJar(), (InterpreterInfo) interpreterInfo);
}
List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER);
for (IInterpreterObserver observer : participants) {
observer.notifyInterpreterManagerRecreated(this);
}
}
public void clearCaches() {
builtinMod.clear();
builtinCompletions.clear();
interpretersFromPersistedString = null;
interpreterInfosFromPersistedString = null;
}
/**
* @return the preference name where the options for this interpreter manager should be stored
*/
protected abstract String getPreferenceName();
/**
* @throws NotConfiguredInterpreterException
* @see org.python.pydev.core.IInterpreterManager#getDefaultInterpreter()
*/
public String getDefaultInterpreter() throws NotConfiguredInterpreterException {
IInterpreterInfo[] interpreters = getInterpreterInfos();
if(interpreters.length > 0){
String interpreter = interpreters[0].getExecutableOrJar();
if(interpreter == null){
throw new NotConfiguredInterpreterException("The configured interpreter is null, some error happened getting it.\n" +getNotConfiguredInterpreterMsg());
}
return interpreter;
}else{
throw new NotConfiguredInterpreterException(FullRepIterable.getLastPart(this.getClass().getName())+":"+getNotConfiguredInterpreterMsg());
}
}
public void setInfos(List<IInterpreterInfo> infos) {
synchronized(exeToInfo){
this.exeToInfo.clear();
for(IInterpreterInfo info:infos){
exeToInfo.put(info.getExecutableOrJar(), (InterpreterInfo) info);
}
}
}
/**
* @return a message to show to the user when there is no configured interpreter
*/
protected abstract String getNotConfiguredInterpreterMsg();
public IInterpreterInfo[] getInterpreterInfos() {
if(interpreterInfosFromPersistedString == null){
interpreterInfosFromPersistedString = getInterpretersFromPersistedString(getPersistedString());
}
return interpreterInfosFromPersistedString;
}
/**
* @see org.python.pydev.core.IInterpreterManager#hasInfoOnInterpreter(java.lang.String)
*/
public boolean hasInfoOnInterpreter(String interpreter){
if(interpreter == null){
InterpreterInfo info;
try {
info = (InterpreterInfo) exeToInfo.get(getDefaultInterpreter());
} catch (NotConfiguredInterpreterException e) {
return false;
}
return info != null;
}
try {
return getInterpreterInfo(interpreter, null) != null;
} catch (MisconfigurationException e) {
return false;
}
}
/**
* @see org.python.pydev.core.IInterpreterManager#getDefaultInterpreterInfo(org.eclipse.core.runtime.IProgressMonitor)
*/
public InterpreterInfo getDefaultInterpreterInfo(IProgressMonitor monitor) throws MisconfigurationException{
String interpreter = getDefaultInterpreter();
return getInterpreterInfo(interpreter, monitor);
}
/**
* Given an executable, should create the interpreter info that corresponds to it
*
* @param executable the executable that should be used to create the info
* @param monitor a monitor to keep track of the info
*
* @return the interpreter info for the executable
* @throws CoreException
* @throws JDTNotAvailableException
*/
protected abstract Tuple<InterpreterInfo,String> internalCreateInterpreterInfo(String executable, IProgressMonitor monitor) throws CoreException, JDTNotAvailableException;
/**
* Creates the information for the passed interpreter.
*/
public IInterpreterInfo createInterpreterInfo(String executable, IProgressMonitor monitor){
monitor.worked(5);
//ok, we have to get the info from the executable (and let's cache results for future use)...
Tuple<InterpreterInfo,String> tup = null;
InterpreterInfo info;
try {
tup = internalCreateInterpreterInfo(executable, monitor);
if(tup == null){
//Canceled (in the dialog that asks the user to choose the valid paths)
return null;
}
info = tup.o1;
} catch (RuntimeException e) {
PydevPlugin.log(e);
throw e;
} catch (Exception e) {
PydevPlugin.log(e);
throw new RuntimeException(e);
}
if(info.executableOrJar == null || info.executableOrJar.trim().length() == 0){
//it is null or empty
final String title = "Invalid interpreter:"+executable;
final String msg = "Unable to get information on interpreter!";
String reasonCreation = "The interpreter (or jar): '"+executable+"' is not valid - info.executable found: "+info.executableOrJar+"\n";
if(tup != null){
reasonCreation += "The standard output gotten from the executed shell was: >>"+tup.o2+"<<";
}
final String reason = reasonCreation;
try {
final Display disp = Display.getDefault();
disp.asyncExec(new Runnable(){
public void run() {
ErrorDialog.openError(null, title, msg, new Status(Status.ERROR, PydevPlugin.getPluginID(), 0, reason, null));
}
});
} catch (Throwable e) {
// ignore error communication error
}
throw new RuntimeException(reason);
}
return info;
}
/**
* Creates the interpreter info from the output. Checks for errors.
*/
protected static InterpreterInfo createInfoFromOutput(IProgressMonitor monitor, Tuple<String, String> outTup) {
if(outTup.o1 == null || outTup.o1.trim().length() == 0){
throw new RuntimeException(
"No output was in the standard output when trying to create the interpreter info.\n" +
"The error output contains:>>"+outTup.o2+"<<");
}
InterpreterInfo info = InterpreterInfo.fromString(outTup.o1);
return info;
}
/**
* @throws MisconfigurationException
* @see org.python.pydev.core.IInterpreterManager#getInterpreterInfo(java.lang.String)
*/
public InterpreterInfo getInterpreterInfo(String nameOrExecutableOrJar, IProgressMonitor monitor) throws MisconfigurationException {
synchronized(lock){
for(IInterpreterInfo info:this.exeToInfo.values()){
if(info != null){
if(info.matchNameBackwardCompatible(nameOrExecutableOrJar)){
return (InterpreterInfo) info;
}
}
}
}
throw new MisconfigurationException(
StringUtils.format("Interpreter: %s not found", nameOrExecutableOrJar));
}
/**
* Called when an interpreter should be added.
*
* @see org.python.pydev.core.IInterpreterManager#addInterpreter(java.lang.String)
*/
public void addInterpreterInfo(IInterpreterInfo info2) {
InterpreterInfo info = (InterpreterInfo) info2;
exeToInfo.put(info.executableOrJar, info);
}
private Object lock = new Object();
//little cache...
private String persistedCache;
private IInterpreterInfo [] persistedCacheRet;
/**
* @see org.python.pydev.core.IInterpreterManager#getInterpretersFromPersistedString(java.lang.String)
*/
public IInterpreterInfo[] getInterpretersFromPersistedString(String persisted) {
synchronized(lock){
if(persisted == null || persisted.trim().length() == 0){
return new IInterpreterInfo[0];
}
if(persistedCache == null || persistedCache.equals(persisted) == false){
List<IInterpreterInfo> ret = new ArrayList<IInterpreterInfo>();
try {
List<InterpreterInfo> list = new ArrayList<InterpreterInfo>();
String[] strings = persisted.split("&&&&&");
//first, get it...
for (String string : strings) {
try {
list.add(InterpreterInfo.fromString(string));
} catch (Exception e) {
//ok, its format might have changed
String errMsg = "Interpreter storage changed.\r\n" +
"Please restore it (window > preferences > Pydev > Interpreter)";
PydevPlugin.log(errMsg, e);
return new IInterpreterInfo[0];
}
}
//then, put it in cache
for (InterpreterInfo info: list) {
if(info != null && info.executableOrJar != null){
ret.add(info);
}
}
//and at last, restore the system info
for (final InterpreterInfo info: list) {
try {
ISystemModulesManager systemModulesManager = (ISystemModulesManager) PydevPlugin.readFromWorkspaceMetadata(info.getExeAsFileSystemValidPath());
info.setModulesManager(systemModulesManager);
} catch (Exception e) {
PydevPlugin.logInfo(new RuntimeException("Restoring info for: "+info.getExecutableOrJar(), e));
//if it does not work it (probably) means that the internal storage format changed among versions,
//so, we have to recreate that info.
final Display def = Display.getDefault();
def.syncExec(new Runnable(){
public void run() {
Shell shell = def.getActiveShell();
ProgressMonitorDialog dialog = new AsynchronousProgressMonitorDialog(shell);
dialog.setBlockOnOpen(false);
try {
dialog.run(false, false, new IRunnableWithProgress(){
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Updating the interpreter info (internal format changed or corrupted).", 100);
//ok, maybe its file-format changed... let's re-create it then.
info.restorePythonpath(monitor);
//after restoring it, let's save it.
PydevPlugin.writeToWorkspaceMetadata(info.getModulesManager(), info.getExeAsFileSystemValidPath());
monitor.done();
}}
);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
System.out.println("Finished restoring information for: "+info.executableOrJar+" at: "+info.getExeAsFileSystemValidPath());
}
}
} catch (Exception e) {
PydevPlugin.log(e);
//ok, some error happened (maybe it's not configured)
return new IInterpreterInfo[0];
}
persistedCache = persisted;
persistedCacheRet = ret.toArray(new IInterpreterInfo[0]);
}
}
return persistedCacheRet;
}
/**
* @see org.python.pydev.core.IInterpreterManager#getStringToPersist(IInterpreterInfo[])
*/
public String getStringToPersist(IInterpreterInfo[] executables) {
FastStringBuffer buf = new FastStringBuffer();
for (IInterpreterInfo info : executables) {
if(info!=null){
buf.append(info.toString());
buf.append("&&&&&");
}
}
return buf.toString();
}
String persistedString;
public String getPersistedString() {
if(persistedString == null){
persistedString = prefs.getString(getPreferenceName());
}
return persistedString;
}
public void setPersistedString(String s) {
persistedString = s;
prefs.setValue(getPreferenceName(), s);
}
/**
* This method persists all the modules managers that are within this interpreter manager
* (so, all the SystemModulesManagers will be saved -- and can be later restored).
*/
public void saveInterpretersInfoModulesManager() {
for(InterpreterInfo info : this.exeToInfo.values()){
ISystemModulesManager modulesManager = info.getModulesManager();
Object pythonPathHelper = modulesManager.getPythonPathHelper();
if(!(pythonPathHelper instanceof PythonPathHelper)){
continue;
}
PythonPathHelper pathHelper = (PythonPathHelper) pythonPathHelper;
List<String> pythonpath = pathHelper.getPythonpath();
if(pythonpath == null || pythonpath.size() == 0){
continue;
}
PydevPlugin.writeToWorkspaceMetadata(modulesManager, info.getExeAsFileSystemValidPath());
}
}
/**
* @return whether this interpreter manager can be used to get info on the specified nature
*/
public final boolean canGetInfoOnNature(IPythonNature nature) {
try {
return nature.getInterpreterType() == this.getInterpreterType();
} catch (CoreException e) {
throw new RuntimeException(e);
}
}
/**
* @see org.python.pydev.core.IInterpreterManager#hasInfoOnDefaultInterpreter(IPythonNature)
*/
public boolean hasInfoOnDefaultInterpreter(IPythonNature nature) {
if(!canGetInfoOnNature(nature)){
throw new RuntimeException("Cannot get info on the requested nature");
}
try {
InterpreterInfo info = (InterpreterInfo) exeToInfo.get(getDefaultInterpreter());
return info != null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @see org.python.pydev.core.IInterpreterManager#restorePythopathForAllInterpreters(org.eclipse.core.runtime.IProgressMonitor)
*/
@SuppressWarnings("unchecked")
public void restorePythopathForInterpreters(IProgressMonitor monitor, Set<String> interpretersNamesToRestore) {
synchronized(lock){
for(String interpreter:exeToInfo.keySet()){
if(interpretersNamesToRestore != null){
if(!interpretersNamesToRestore.contains(interpreter)){
continue; //only restore the ones specified
}
}
InterpreterInfo info;
try {
info = getInterpreterInfo(interpreter, monitor);
info.restorePythonpath(monitor); //that's it, info.modulesManager contains the SystemModulesManager
List<IInterpreterObserver> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_INTERPRETER_OBSERVER);
for (IInterpreterObserver observer : participants) {
try {
observer.notifyDefaultPythonpathRestored(this, interpreter, monitor);
} catch (Exception e) {
PydevPlugin.log(e);
}
}
} catch (MisconfigurationException e1) {
PydevPlugin.log(e1);
}
}
FastStringBuffer buf = new FastStringBuffer();
//Also notify that all the natures had the pythonpath changed (it's the system pythonpath, but still,
//clients need to know about it)
List<IPythonNature> pythonNatures = PythonNature.getAllPythonNatures();
for (IPythonNature nature : pythonNatures) {
try {
//If they have the same type of the interpreter manager, notify.
if (this.getInterpreterType() == nature.getInterpreterType()) {
IPythonPathNature pythonPathNature = nature.getPythonPathNature();
//There's a catch here: if the nature uses some variable defined in the string substitution
//from the interpreter info, we need to do a full build instead of only making a notification.
String complete = pythonPathNature.getProjectExternalSourcePath(false) +
pythonPathNature.getProjectSourcePath(false);
PythonNature n = (PythonNature) nature;
String projectInterpreterName = n.getProjectInterpreterName();
if(IPythonNature.DEFAULT_INTERPRETER.equals(projectInterpreterName)){
//if it's the default, let's translate it to the outside world
projectInterpreterName = this.getDefaultInterpreter();
}
InterpreterInfo info = exeToInfo.get(projectInterpreterName);
boolean makeCompleteRebuild = false;
if(info != null){
Properties stringSubstitutionVariables = info.getStringSubstitutionVariables();
if(stringSubstitutionVariables!=null){
Enumeration<Object> keys = stringSubstitutionVariables.keys();
while(keys.hasMoreElements()){
Object key = keys.nextElement();
buf.clear();
buf.append("${");
buf.append(key.toString());
buf.append("}");
if(complete.indexOf(buf.toString()) != -1){
makeCompleteRebuild = true;
break;
}
}
}
}
if(!makeCompleteRebuild){
//just notify that it changed
if(nature instanceof PythonNature){
((PythonNature) nature).clearCaches();
}
PythonNatureListenersManager.notifyPythonPathRebuilt(nature.getProject(), nature);
}else{
//Rebuild the whole info.
nature.rebuildPath();
}
}
} catch (Throwable e) {
PydevPlugin.log(e);
}
}
}
}
public boolean isConfigured() {
try {
String defaultInterpreter = getDefaultInterpreter();
if(defaultInterpreter == null){
return false;
}
if(defaultInterpreter.length() == 0){
return false;
}
} catch (NotConfiguredInterpreterException e) {
return false;
}
return true;
}
}
|
package com.intellij.util;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.StaticGetter;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
import java.util.Map;
/**
* @author max
*/
public class EventDispatcher<T extends EventListener> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.EventDispatcher");
private T myMulticaster;
private final List<T> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
@NotNull private final Class<T> myListenerClass;
@Nullable private final Map<String, Object> myMethodReturnValues;
@NotNull
public static <T extends EventListener> EventDispatcher<T> create(@NotNull Class<T> listenerClass) {
return new EventDispatcher<T>(listenerClass, null);
}
@NotNull
public static <T extends EventListener> EventDispatcher<T> create(@NotNull Class<T> listenerClass, @NotNull Map<String, Object> methodReturnValues) {
assertNonVoidMethodReturnValuesAreDeclared(methodReturnValues, listenerClass);
return new EventDispatcher<T>(listenerClass, methodReturnValues);
}
private static void assertNonVoidMethodReturnValuesAreDeclared(@NotNull Map<String, Object> methodReturnValues,
@NotNull Class<?> listenerClass) {
List<Method> declared = new ArrayList<Method>(ReflectionUtil.getClassPublicMethods(listenerClass));
for (final Map.Entry<String, Object> entry : methodReturnValues.entrySet()) {
final String methodName = entry.getKey();
Method found = ContainerUtil.find(declared, new Condition<Method>() {
@Override
public boolean value(Method m) {
return methodName.equals(m.getName());
}
});
assert found != null : "Method " + methodName + " must be declared in " + listenerClass;
assert !found.getReturnType().equals(void.class) :
"Method " + methodName + " must be non-void if you want to specify what its proxy should return";
Object returnValue = entry.getValue();
assert ReflectionUtil.boxType(found.getReturnType()).isAssignableFrom(returnValue.getClass()) :
"You specified that method " +
methodName + " proxy will return " + returnValue +
" but its return type is " + found.getReturnType() + " which is incompatible with " + returnValue.getClass();
declared.remove(found);
}
for (Method method : declared) {
assert method.getReturnType().equals(void.class) :
"Method "+method+" returns "+method.getReturnType()+" and yet you didn't specify what its proxy should return";
}
}
private EventDispatcher(@NotNull Class<T> listenerClass, @Nullable Map<String, Object> methodReturnValues) {
myListenerClass = listenerClass;
myMethodReturnValues = methodReturnValues;
}
@NotNull
static <T> T createMulticaster(@NotNull Class<T> listenerClass,
@Nullable final Map<String, Object> methodReturnValues,
final Getter<? extends Iterable<T>> listeners) {
LOG.assertTrue(listenerClass.isInterface(), "listenerClass must be an interface");
InvocationHandler handler = new InvocationHandler() {
@Override
@NonNls
public Object invoke(Object proxy, final Method method, final Object[] args) {
@NonNls String methodName = method.getName();
if (method.getDeclaringClass().getName().equals("java.lang.Object")) {
return handleObjectMethod(proxy, args, methodName);
}
else if (methodReturnValues != null && methodReturnValues.containsKey(methodName)) {
return methodReturnValues.get(methodName);
}
else {
dispatchVoidMethod(listeners.get(), method, args);
return null;
}
}
};
//noinspection unchecked
return (T)Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class[]{listenerClass}, handler);
}
@Nullable
public static Object handleObjectMethod(Object proxy, Object[] args, String methodName) {
if (methodName.equals("toString")) {
return "Multicaster";
}
else if (methodName.equals("hashCode")) {
return System.identityHashCode(proxy);
}
else if (methodName.equals("equals")) {
return proxy == args[0] ? Boolean.TRUE : Boolean.FALSE;
}
else {
LOG.error("Incorrect Object's method invoked for proxy:" + methodName);
return null;
}
}
@NotNull
public T getMulticaster() {
T multicaster = myMulticaster;
if (multicaster == null) {
// benign race
myMulticaster = multicaster = createMulticaster(myListenerClass, myMethodReturnValues, new StaticGetter<Iterable<T>>(myListeners));
}
return multicaster;
}
private static <T> void dispatchVoidMethod(@NotNull Iterable<T> listeners, @NotNull Method method, Object[] args) {
method.setAccessible(true);
for (T listener : listeners) {
try {
method.invoke(listener, args);
}
catch (AbstractMethodError ignored) {
// Do nothing. This listener just does not implement something newly added yet.
// AbstractMethodError is normally wrapped in InvocationTargetException,
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
final Throwable cause = e.getCause();
ExceptionUtil.rethrowUnchecked(cause);
if (!(cause instanceof AbstractMethodError)) { // AbstractMethodError means this listener doesn't implement some new method in interface
LOG.error(cause);
}
}
}
}
public void addListener(@NotNull T listener) {
myListeners.add(listener);
}
/**
* CAUTION: do not use in pair with {@link #removeListener(EventListener)}: a memory leak can occur.
* In case a listener is removed, it's disposable stays in disposable hierarchy, preventing the listener from being gc'ed.
*/
public void addListener(@NotNull final T listener, @NotNull Disposable parentDisposable) {
addListener(listener);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
removeListener(listener);
}
});
}
public void removeListener(@NotNull T listener) {
myListeners.remove(listener);
}
public boolean hasListeners() {
return !myListeners.isEmpty();
}
@NotNull
public List<T> getListeners() {
return myListeners;
}
}
|
package dae.prefabs.lights;
import com.jme3.asset.AssetManager;
import com.jme3.light.PointLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.LightControl;
import com.jme3.scene.shape.Sphere;
import dae.prefabs.Prefab;
/**
*
* @author Koen Samyn
*/
public class PointLightPrefab extends Prefab {
private PointLight pointLight;
private Spatial pointLightSphere;
private Material lightMaterial;
private ColorRGBA pointLightColor;
private float pointLightIntensity;
public PointLightPrefab() {
pointLight = new PointLight();
pointLight.setRadius(1.0f);
setCategory("Light");
setType("PointLight");
setLayerName("lights");
LightControl lightControl = new LightControl(pointLight);
this.addControl(lightControl);
}
@Override
public void create(String name, AssetManager manager, String extraInfo) {
setName(name);
pointLight.setPosition(this.getLocalTranslation());
pointLightColor = pointLight.getColor().clone();
lightMaterial = manager.loadMaterial("/Materials/LightMaterial.j3m");
Sphere s = new Sphere(12, 12, 0.15f);
Geometry g = new Geometry("pointlightgizmo", s);
g.setMaterial(manager.loadMaterial("/Materials/LightGizmoMaterial.j3m"));
attachChild(g);
adaptLightSphere();
}
/**
* @return the radius
*/
public float getRadius() {
return pointLight.getRadius();
}
/**
* @param radius the radius to set
*/
public void setRadius(float radius) {
pointLight.setRadius(radius);
adaptLightSphere();
}
/**
* @return the pointLightColor
*/
public ColorRGBA getPointLightColor() {
return pointLightColor;
}
/**
* @param pointLightColor the pointLightColor to set
*/
public void setPointLightColor(ColorRGBA pointLightColor) {
this.pointLightColor = pointLightColor;
this.pointLight.setColor(pointLightColor.mult(pointLightIntensity));
}
private void adaptLightSphere() {
Sphere sphere = new Sphere(12, 12, pointLight.getRadius());
Geometry innerCone = new Geometry("lightSphere", sphere);
innerCone.setMaterial(lightMaterial);
if (this.pointLightSphere != null) {
pointLightSphere.removeFromParent();
}
pointLightSphere = innerCone;
if (isSelected()) {
attachChild(pointLightSphere);
}
}
@Override
public void setParent(Node parent) {
super.setParent(parent);
if (parent != null) {
parent.addLight(this.pointLight);
}
}
@Override
public boolean removeFromParent() {
Node parentNode = this.getParent();
parentNode.removeLight(this.pointLight);
return super.removeFromParent();
}
@Override
public void setSelected(boolean selected) {
super.setSelected(selected);
if (pointLightSphere == null) {
return;
}
if (selected) {
attachChild(pointLightSphere);
} else {
pointLightSphere.removeFromParent();
}
}
/**
* @return the pointLightIntensity
*/
public float getPointLightIntensity() {
return pointLightIntensity;
}
/**
* @param pointLightIntensity the pointLightIntensity to set
*/
public void setPointLightIntensity(float pointLightIntensity) {
this.pointLightIntensity = pointLightIntensity;
this.pointLight.setColor(pointLightColor.mult(pointLightIntensity));
}
}
|
package edu.wheaton.simulator.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import edu.wheaton.simulator.simulation.GUIToAgentFacade;
import edu.wheaton.simulator.simulation.end.SimulationEnder;
import edu.wheaton.simulator.statistics.StatisticsManager;
public class ScreenManager implements Manager{
private HashMap<String, Screen> screens;
private Display d;
private JPanel[][] grid;
private SimulationEnder se;
private StatisticsManager statMan;
private GUIToAgentFacade facade;
private boolean simulationIsRunning;
private ArrayList<SpawnCondition> spawnConditions;
//for determining when components should be disabled while running a sim.
private boolean hasStarted;
public ScreenManager(Display d) {
spawnConditions = new ArrayList<SpawnCondition>();
screens = new HashMap<String, Screen>();
this.d = d;
this.d.setJMenuBar(makeMenuBar());
se = new SimulationEnder();
statMan = new StatisticsManager();
screens.put("Title", new TitleScreen(this));
screens.put("New Simulation", new NewSimulationScreen(this));
screens.put("Edit Simulation", new EditSimScreen(this));
screens.put("Fields", new FieldScreen(this));
screens.put("Edit Fields", new EditFieldScreen(this));
screens.put("Entities", new EntityScreen(this));
screens.put("Edit Entities", new EditEntityScreen(this));
screens.put("Spawning", new SpawningScreen(this));
screens.put("View Simulation", new ViewSimScreen(this));
screens.put("Statistics", new StatisticsScreen(this));
screens.put("Grid Setup", new SetupScreen(this));
}
public ScreenManager(){
this(new Display());
}
@Override
public Screen getScreen(String screenName) {
return screens.get(screenName);
}
@Override
public void update(Screen update) {
d.updateDisplay(update);
}
public void setGrid(JPanel[][] grid){
this.grid = grid;
}
public JPanel[][] getGrid(){
return grid;
}
@Override
public void setFacade(int x, int y) {
facade = new GUIToAgentFacade(x, y);
}
@Override
public GUIToAgentFacade getFacade() {
return facade;
}
@Override
public SimulationEnder getEnder() {
return se;
}
public StatisticsManager getStatManager(){
return statMan;
}
public static String getGUIname(){
return GUI.getNameOfSim();
}
public static int getGUIheight(){
return GUI.getGridHeight();
}
public static int getGUIwidth(){
return GUI.getGridWidth();
}
@Override
public void updateGUIManager(String nos, int width, int height){
GUI.setNameOfSim(nos);
GUI.setGridWidth(width);
GUI.setGridHeight(height);
}
public boolean isRunning() {
return simulationIsRunning;
}
public void setRunning(boolean b) {
simulationIsRunning = b;
}
public void setStarted(boolean b) {
hasStarted = b;
}
@Override
public boolean hasStarted() {
return hasStarted;
}
@Override
public ArrayList<SpawnCondition> getSpawnConditions() {
return spawnConditions;
}
@Override
public void loadScreen(Screen s){
s.load();
}
private JMenuBar makeMenuBar() {
JMenuBar menuBar = new JMenuBar();
menuBar.setEnabled(true);
menuBar.setVisible(true);
menuBar.add(makeFileMenu(this));
menuBar.add(makeHelpMenu(this));
return menuBar;
}
private static JMenu makeFileMenu(final ScreenManager sm) {
JMenu menu = new JMenu("File");
JMenuItem newSimulation = new JMenuItem("New Simulation");
newSimulation.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
sm.update(sm.getScreen("New Simulation"));
}
});
menu.add(newSimulation);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
sm.setRunning(false);
System.exit(0);
}
});
menu.add(exit);
return menu;
}
private static JMenu makeHelpMenu(final ScreenManager sm) {
JMenu menu = new JMenu("Help");
return menu;
}
}
|
package org.apache.tapestry.junit;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import org.apache.tapestry.IAsset;
import org.apache.tapestry.IBinding;
import org.apache.tapestry.IComponent;
import org.apache.tapestry.IMessages;
import org.apache.tapestry.IEngine;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.INamespace;
import org.apache.tapestry.IPage;
import org.apache.tapestry.IRender;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.engine.IPageLoader;
import org.apache.tapestry.event.ChangeObserver;
import org.apache.tapestry.event.PageDetachListener;
import org.apache.tapestry.event.PageRenderListener;
import org.apache.tapestry.event.PageValidateListener;
import org.apache.tapestry.spec.BaseLocatable;
import org.apache.tapestry.spec.IComponentSpecification;
/**
* Fake implementation of {@link IPage} used during unit testing.
*
* @author Howard Lewis Ship
* @version $Id$
* @since 2.0.4
*
**/
public class MockPage extends BaseLocatable implements IPage
{
private IEngine _engine;
private Locale locale;
private IComponentSpecification _specification;
public void detach()
{
}
public IEngine getEngine()
{
return _engine;
}
public ChangeObserver getChangeObserver()
{
return null;
}
public Locale getLocale()
{
return locale;
}
public void setLocale(Locale locale)
{
this.locale = locale;
}
public IComponent getNestedComponent(String path)
{
return null;
}
public void attach(IEngine value)
{
}
public void renderPage(IMarkupWriter writer, IRequestCycle cycle)
{
}
public void setChangeObserver(ChangeObserver value)
{
}
public void validate(IRequestCycle cycle)
{
}
public IMarkupWriter getResponseWriter(OutputStream out)
{
return null;
}
public void beginResponse(IMarkupWriter writer, IRequestCycle cycle)
{
}
public IRequestCycle getRequestCycle()
{
return null;
}
public void setRequestCycle(IRequestCycle cycle)
{
}
public Object getVisit()
{
return null;
}
public void addPageRenderListener(PageRenderListener listener)
{
}
public void addAsset(String name, IAsset asset)
{
}
public void addComponent(IComponent component)
{
}
public Map getAssets()
{
return null;
}
public IAsset getAsset(String name)
{
return null;
}
public IBinding getBinding(String name)
{
return null;
}
public Collection getBindingNames()
{
return null;
}
public Map getBindings()
{
return null;
}
public IComponent getComponent(String id)
{
return null;
}
public IComponent getContainer()
{
return null;
}
public void setContainer(IComponent value)
{
}
public String getExtendedId()
{
return null;
}
public String getId()
{
return null;
}
public void setId(String value)
{
}
public String getIdPath()
{
return null;
}
/**
* Returns this (it is, after all, MockPage, not MockComponent).
*
**/
public IPage getPage()
{
return this;
}
public void setPage(IPage value)
{
}
public IComponentSpecification getSpecification()
{
return _specification;
}
public void setSpecification(IComponentSpecification value)
{
_specification = value;
}
public void setBinding(String name, IBinding binding)
{
}
public Map getComponents()
{
return null;
}
public void finishLoad(
IRequestCycle cycle,
IPageLoader loader,
IComponentSpecification specification)
{
}
/**
* Gets the string source from the engine, gets the strings
* from the string source, and invokes
* {@link org.apache.tapestry.IComponentStrings#getString(String)}.
*
**/
public String getString(String key)
{
return getMessages().getMessage(key);
}
public void render(IMarkupWriter writer, IRequestCycle cycle)
{
}
public void setEngine(IEngine engine)
{
_engine = engine;
}
public void removePageDetachListener(PageDetachListener listener)
{
}
public void removePageRenderListener(PageRenderListener listener)
{
}
public INamespace getNamespace()
{
return null;
}
public void setNamespace(INamespace namespace)
{
}
public void beginPageRender()
{
}
public void endPageRender()
{
}
public void addBody(IRender element)
{
}
public void renderBody(IMarkupWriter writer, IRequestCycle cycle)
{
}
public String getQualifiedName()
{
return null;
}
public String getPageName()
{
return null;
}
public void setPageName(String pageName)
{
}
public Object getGlobal()
{
return null;
}
public IMessages getMessages()
{
return _engine.getComponentMessagesSource().getMessages(this);
}
public void addPageDetachListener(PageDetachListener listener)
{
}
public void addPageValidateListener(PageValidateListener listener)
{
}
public void removePageValidateListener(PageValidateListener listener)
{
}
public String getMessage(String key)
{
return getString(key);
}
public void setProperty(String propertyName, Object value)
{
}
public Object getProperty(String propertyName)
{
return null;
}
}
|
package fi.tnie.db.expr;
import java.util.Map.Entry;
import fi.tnie.db.expr.op.AndPredicate;
import fi.tnie.db.expr.op.Comparison;
import fi.tnie.db.meta.Column;
import fi.tnie.db.meta.ForeignKey;
public class ForeignKeyJoinCondition
extends JoinCondition {
private static final long serialVersionUID = -4566688892782028829L;
private ForeignKey foreignKey;
private AbstractTableReference referencing;
private AbstractTableReference referenced;
private Predicate condition;
/**
* No-argument constructor for GWT Serialization
*/
@SuppressWarnings("unused")
private ForeignKeyJoinCondition() {
}
public ForeignKeyJoinCondition(ForeignKey foreignKey, AbstractTableReference referencing, AbstractTableReference referenced) {
super();
this.foreignKey = foreignKey;
this.referencing = referencing;
this.referenced = referenced;
}
@Override
public void traverseContent(VisitContext vc, ElementVisitor v) {
getCondition().traverse(vc, v);
}
private Predicate getCondition() {
if (this.condition == null) {
Predicate jp = null;
for (Entry<Column, Column> e : foreignKey.columns().entrySet()) {
Column a = e.getKey();
Column b = e.getValue();
jp = AndPredicate.newAnd(jp, Comparison.eq(
new ColumnReference(referencing, a),
new ColumnReference(referenced, b)));
}
this.condition = jp;
}
return this.condition;
}
@Override
public Predicate parenthesize() {
return new ParenthesizedPredicate(this);
}
}
|
package org.mwg;
import org.junit.Assert;
import org.junit.Test;
import org.mwg.importer.ImporterActions;
import org.mwg.importer.ImporterPlugin;
import org.mwg.task.Action;
import org.mwg.task.Task;
import org.mwg.task.TaskContext;
import org.mwg.task.TaskResult;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import static org.mwg.importer.ImporterActions.readFiles;
import static org.mwg.importer.ImporterActions.readLines;
import static org.mwg.task.Actions.*;
public class ImporterTest {
@Test
public void testReadLines() {
final SimpleDateFormat dateFormat = new SimpleDateFormat("d/MM/yyyy|HH:mm");
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
g.connect(connectionResult -> {
Node newNode = g.newNode(0, 0);
//final Task t = readLines("/Users/duke/dev/mwDB/plugins/importer/src/test/resources/smarthome/smarthome_1.T15.txt")
final Task t = readLines("smarthome/smarthome_mini_1.T15.txt")
.foreach(
ifThen(ctx -> !ctx.result().get(0).toString().startsWith("1:Date"),
then(context -> {
String[] line = context.result().get(0).toString().split(" ");
try {
long time = dateFormat.parse(line[0] + "|" + line[1]).getTime();
double value = Double.parseDouble(line[2]);
newNode.jump(time, timedNode -> {
timedNode.setProperty("value", Type.DOUBLE, value);
context.continueWith(context.wrap(timedNode));
});
} catch (ParseException e) {
e.printStackTrace();
context.continueWith(null);
}
})
));
t.execute(g, null);
});
}
@Test
public void testReadFilesStaticMethod() {
File fileChecked = new File(this.getClass().getClassLoader().getResource("smarthome").getPath());
final File[] subFiles = fileChecked.listFiles();
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
g.connect(new Callback<Boolean>() {
@Override
public void on(Boolean connectionResult) {
final int[] nbFile = new int[1];
Task t = readFiles("smarthome").foreach(then(new Action() {
@Override
public void eval(TaskContext context) {
String filePath = (String) context.result().get(0);
Assert.assertEquals(subFiles[nbFile[0]].getAbsolutePath(), filePath);
nbFile[0]++;
context.continueWith(null);
}
}));
t.execute(g, null);
Assert.assertEquals(subFiles.length, nbFile[0]);
}
});
}
@Test
public void testReadFilesActionWithTemplate() {
File fileChecked = new File(this.getClass().getClassLoader().getResource("smarthome").getPath());
final File[] subFiles = fileChecked.listFiles();
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
g.connect(new Callback<Boolean>() {
@Override
public void on(Boolean connectionResult) {
final int[] nbFile = new int[1];
Task t = inject("smarthome")
.asGlobalVar("fileName")
.action(ImporterActions.READFILES, "{{fileName}}")
.foreach(then(new Action() {
@Override
public void eval(TaskContext context) {
String file = (String) context.result().get(0);
Assert.assertEquals(subFiles[nbFile[0]].getAbsolutePath(), file);
nbFile[0]++;
context.continueWith(null);
}
}));
t.execute(g, null);
Assert.assertEquals(subFiles.length, nbFile[0]);
}
});
}
@Test
public void testReadFilesOnFile() throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
URL urlFIle = this.getClass().getClassLoader().getResource("smarthome/readme.md");
URL urlFIle2 = this.getClass().getClassLoader().getResource(URLDecoder.decode("folder with spaces in name/aFile.txt","UTF-8"));
File expectecFile = new File(urlFIle.toURI());
File expectedFile2 = new File(urlFIle2.toURI());
g.connect(new Callback<Boolean>() {
@Override
public void on(Boolean connectionResult) {
final int[] nbFile = new int[1];
Task t = readFiles(urlFIle.getPath()).foreach(then(new Action() {
@Override
public void eval(TaskContext context) {
String file = (String) context.result().get(0);
Assert.assertEquals(expectecFile.getAbsolutePath(), file);
nbFile[0]++;
context.continueWith(null);
}
})).action(ImporterActions.READFILES,urlFIle2.getPath()).foreach(then(new Action(){
@Override
public void eval(TaskContext context) {
String file = (String) context.result().get(0);
try {
Assert.assertEquals(URLDecoder.decode(expectedFile2.getAbsolutePath(), "UTF-8"), file);
}catch (UnsupportedEncodingException ex) {
Assert.fail(ex.getMessage());
}
nbFile[0]++;
context.continueWith(null);
}
}));
t.execute(g, null);
Assert.assertEquals(2, nbFile[0]);
}
});
}
@Test
public void testReadFileOnUnknowFile() {
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
g.connect(connectionResult -> {
Task t = readFiles("nonexistent-file.txt");
boolean exceptionCaught = false;
try {
t.execute(g, null);
} catch (RuntimeException exception) {
exceptionCaught = true;
}
Assert.assertTrue(exceptionCaught);
});
}
@Test
public void testReadFileOnIncorrectVar() {
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
g.connect(new Callback<Boolean>() {
@Override
public void on(Boolean connectionResult) {
Task t = action(ImporterActions.READFILES, "{{incorrectVarName}}");
boolean exceptionCaught = false;
try {
t.execute(g, null);
} catch (RuntimeException ex) {
exceptionCaught = true;
}
Assert.assertTrue(exceptionCaught);
}
});
}
@Test
public void testV2() {
final SimpleDateFormat dateFormat = new SimpleDateFormat("d/MM/yyyy|HH:mm");
final Graph g = new GraphBuilder().withPlugin(new ImporterPlugin()).build();
g.connect(connectionResult -> {
Node newNode = g.newNode(0, 0);
final Task t = readLines("smarthome/smarthome_mini_1.T15.txt")
.foreach(
ifThen(ctx -> !ctx.result().get(0).toString().startsWith("1:Date"),
split(" ")
.then(context -> {
TaskResult<String> line = context.result();
try {
context.setGlobalVariable("time", context.wrap(dateFormat.parse(line.get(0) + "|" + line.get(1)).getTime()));
context.setGlobalVariable("value", context.wrap(Double.parseDouble(line.get(2))));
context.continueWith(null);
} catch (ParseException e) {
e.printStackTrace();
context.continueWith(null);
}
})
.setTime("{{time}}")
.lookup("0", "{{time}}", "" + newNode.id())
.setProperty("value", Type.DOUBLE, "{{value}}")
//.print("insertedNode: {{result}} {{value}}")
));
t.execute(g, null);
//t.executeWith(g, null, null, true, null); //with debug
});
}
}
|
package dr.evomodel.tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.inference.model.*;
import dr.math.Polynomial;
import dr.math.MathUtils;
import dr.math.LogTricks;
import dr.xml.*;
import java.util.*;
import java.util.logging.Logger;
//import org.jscience.mathematics.number.Rational;
/**
* Two priors for the tree that are relatively non-informative on the internal node heights given the root height.
* The first further assumes that the root height is truncated uniform, see Nicholls, G. & R.D. Gray (2004) for details.
* The second allows any marginal specification over the root height given that it is larger than the oldest
* sampling time (Bloomquist and Suchard, unpublished).
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Erik Bloomquist
* @author Marc Suchard
* @version $Id: UniformRootPrior.java,v 1.10 2005/05/24 20:25:58 rambaut Exp $
*/
public class UniformNodeHeightPrior extends AbstractModelLikelihood {
// PUBLIC STUFF
public static final String UNIFORM_ROOT_PRIOR = "uniformRootPrior";
public static final String UNIFORM_NODE_HEIGHT_PRIOR = "uniformNodeHeightPrior";
public static final String MAX_ROOT_HEIGHT = "maxRootHeight";
public static final String ANALYTIC = "analytic";
public static final String MC_SAMPLE = "mcSampleSize";
public static final String MARGINAL = "marginal";
public static final int MAX_ANALYTIC_TIPS = 60; // TODO Determine this value!
public static final int DEFAULT_MC_SAMPLE = 100000;
private static final double tolerance = 1E-6;
private int k = 0;
private double logFactorialK;
private double maxRootHeight;
private boolean isNicholls;
private boolean useAnalytic;
private boolean useMarginal;
private int mcSampleSize;
Set<Double> tipDates = new TreeSet<Double>();
List<Double> reversedTipDateList = new ArrayList<Double>();
Map<Double, Integer> intervals = new TreeMap<Double, Integer>();
public UniformNodeHeightPrior(Tree tree, boolean useAnalytic, boolean marginal) {
this(UNIFORM_NODE_HEIGHT_PRIOR, tree, useAnalytic, DEFAULT_MC_SAMPLE, marginal);
}
private UniformNodeHeightPrior(Tree tree, boolean useAnalytic, int mcSampleSize) {
this(UNIFORM_NODE_HEIGHT_PRIOR,tree,useAnalytic,mcSampleSize, false);
}
private UniformNodeHeightPrior(String name, Tree tree, boolean useAnalytic, int mcSampleSize, boolean marginal) {
super(name);
this.tree = tree;
this.isNicholls = false;
this.useAnalytic = useAnalytic;
this.useMarginal = marginal;
this.mcSampleSize = mcSampleSize;
if (tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
for (int i = 0; i < tree.getExternalNodeCount(); i++) {
double h = tree.getNodeHeight(tree.getExternalNode(i));
tipDates.add(h);
}
if (tipDates.size() == 1) {
// the tips are contemporaneous so these are constant...
k = tree.getInternalNodeCount() - 1;
Logger.getLogger("dr.evomodel").info("Uniform Node Height Prior, Intervals = " + (k + 1));
logFactorialK = logFactorial(k);
} else {
reversedTipDateList.addAll(tipDates);
Collections.reverse(reversedTipDateList);
// Prune out intervals smaller in length than tolerance
double intervalStart = tree.getNodeHeight(tree.getRoot());
List<Double> pruneDates = new ArrayList<Double>();
for (Double intervalEnd : reversedTipDateList) {
if (intervalStart - intervalEnd < tolerance) {
pruneDates.add(intervalStart);
}
intervalStart = intervalEnd;
}
for (Double date : pruneDates)
reversedTipDateList.remove(date);
if (!useAnalytic) {
logLikelihoods = new double[mcSampleSize];
drawNodeHeights = new double[tree.getNodeCount()][mcSampleSize];
minNodeHeights = new double[tree.getNodeCount()];
}
}
// Leading coefficient on tree polynomial is X = (# internal nodes)!
// To keep X > 10E-40, should use log-space polynomials for more than ~30 tips
if (tree.getExternalNodeCount() < 30) {
polynomialType = Polynomial.Type.DOUBLE; // Much faster
} else if (tree.getExternalNodeCount() < 45){
polynomialType = Polynomial.Type.LOG_DOUBLE;
} else {
// polynomialType = Polynomial.Type.APDOUBLE;
polynomialType = Polynomial.Type.LOG_DOUBLE;
}
Logger.getLogger("dr.evomodel").info("Using "+polynomialType+" polynomials!");
}
public UniformNodeHeightPrior(Tree tree, double maxRootHeight) {
this(UNIFORM_NODE_HEIGHT_PRIOR, tree, maxRootHeight);
}
private UniformNodeHeightPrior(String name, Tree tree, double maxRootHeight) {
super(name);
this.tree = tree;
this.maxRootHeight = maxRootHeight;
isNicholls = true;
if (tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
}
UniformNodeHeightPrior(String name) {
super(name);
}
// Extendable methods
// ModelListener IMPLEMENTATION
protected final void handleModelChangedEvent(Model model, Object object, int index) {
likelihoodKnown = false;
treePolynomialKnown = false;
return;
// Only set treePolynomialKnown = false when a topology change occurs
// Only set likelihoodKnown = false when a topology change occurs or the rootHeight is changed
// if (model == tree) {
// if (object instanceof TreeModel.TreeChangedEvent) {
// TreeModel.TreeChangedEvent event = (TreeModel.TreeChangedEvent) object;
// if (event.isHeightChanged()) {
// if (event.getNode() == tree.getRoot()) {
// likelihoodKnown = false;
// return;
// } // else
// return;
// if (event.isNodeParameterChanged())
// return;
// // All others are probably tree structure changes
// likelihoodKnown = false;
// treePolynomialKnown = false;
// return;
// // TODO Why are not all node height changes invoking TreeChangedEvents?
// if (object instanceof Parameter.Default) {
// Parameter parameter = (Parameter) object;
// if (tree.getNodeHeight(tree.getRoot()) == parameter.getParameterValue(index)) {
// likelihoodKnown = false;
// treePolynomialKnown = false;
// return;
// return;
// throw new RuntimeException("Unexpected event!");
}
// VariableListener IMPLEMENTATION
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
}
// Model IMPLEMENTATION
/**
* Stores the precalculated state: in this case the intervals
*/
protected final void storeState() {
storedLikelihoodKnown = likelihoodKnown;
storedLogLikelihood = logLikelihood;
// storedTreePolynomialKnown = treePolynomialKnown;
// if (treePolynomial != null)
// storedTreePolynomial = treePolynomial.copy(); // TODO Swap pointers
}
/**
* Restores the precalculated state: that is the intervals of the tree.
*/
protected final void restoreState() {
likelihoodKnown = storedLikelihoodKnown;
logLikelihood = storedLogLikelihood;
// treePolynomialKnown = storedTreePolynomialKnown;
// treePolynomial = storedTreePolynomial;
}
protected final void acceptState() {
} // nothing to do
// Likelihood IMPLEMENTATION
public final Model getModel() {
return this;
}
public double getLogLikelihood() {
// return calculateLogLikelihood();
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
public final void makeDirty() {
likelihoodKnown = false;
treePolynomialKnown = false;
}
public double calculateLogLikelihood() {
double rootHeight = tree.getNodeHeight(tree.getRoot());
if (isNicholls) {
int nodeCount = tree.getExternalNodeCount();
if (rootHeight < 0 || rootHeight > (0.999 * maxRootHeight)) return Double.NEGATIVE_INFINITY;
// from Nicholls, G. & R.D. Gray (2004)
return rootHeight * (2 - nodeCount) - Math.log(maxRootHeight - rootHeight);
} else {
// the Bloomquist & Suchard variant
// Let the sampling times and rootHeight specify the boundaries between a fixed number of intervals.
// Internal node heights are equally likely to fall in any of these intervals and uniformly distributed
// in an interval before sorting (i.e. the intercoalescent times in an interval form a scaled Dirchelet(1,1,\ldots,1)
// This is a conditional density on the rootHeight, so it is possible to specify a marginal distribution
// on the rootHeight given it is greater than the oldest sampling time.
double logLike;
if (k > 0) {
// the tips are contemporaneous
logLike = logFactorialK - (double) k * Math.log(rootHeight);
} else {
// TODO Rewrite description above to discuss this new prior
if (useAnalytic) {
// long startTime1 = System.nanoTime();
if (useMarginal) {
if (!treePolynomialKnown) {
treePolynomial = recursivelyComputePolynomial(tree, tree.getRoot(), polynomialType).getPolynomial();
treePolynomialKnown = true;
}
logLike = -treePolynomial.logEvaluate(rootHeight);
if (Double.isNaN(logLike)) {
// Try using Horner's method
logLike = -treePolynomial.logEvaluateHorner(rootHeight);
if (Double.isNaN(logLike)) {
logLike = Double.NEGATIVE_INFINITY;
}
}
} else {
tmpLogLikelihood = 0;
recursivelyComputeDensity(tree, tree.getRoot(), 0);
logLike = tmpLogLikelihood;
}
// long stopTime1 = System.nanoTime();
} else {
// long startTime2 = System.nanoTime();
// Copy over current root height
final double[] drawRootHeight = drawNodeHeights[tree.getRoot().getNumber()];
Arrays.fill(drawRootHeight,rootHeight); // TODO Only update when rootHeight changes
// Determine min heights for each node in tree
recursivelyFindNodeMinHeights(tree,tree.getRoot()); // TODO Only update when topology changes
// Simulate from prior
Arrays.fill(logLikelihoods,0.0);
recursivelyComputeMCIntegral(tree, tree.getRoot(), tree.getRoot().getNumber()); // TODO Only update when topology or rootHeight changes
// Take average
logLike = -LogTricks.logSum(logLikelihoods) + Math.log(mcSampleSize);
// long stopTime2 = System.nanoTime();
}
}
assert !Double.isInfinite(logLike) && !Double.isNaN(logLike);
return logLike;
}
}
// Map<Double,Integer> boxCounts;
// private double recursivelyComputeMarcDensity(Tree tree, NodeRef node, double rootHeight) {
// if (tree.isExternal(node))
// return tree.getNodeHeight(node);
//// double thisHeight = tree.getNodeHeight(node);
//// double thisHeight = rootHeight;
// double heightChild1 = recursivelyComputeMarcDensity(tree, tree.getChild(node, 0), rootHeight);
// double heightChild2 = recursivelyComputeMarcDensity(tree, tree.getChild(node, 1), rootHeight);
// double minHeight = (heightChild1 > heightChild2) ? heightChild1 : heightChild2;
// if (!tree.isRoot(node)) {
// double diff = rootHeight - minHeight;
// if (diff <= 0)
// tmpLogLikelihood = Double.NEGATIVE_INFINITY;
// else
// tmpLogLikelihood -= Math.log(diff);
// Integer count = boxCounts.get(minHeight);
// if (count == null) {
// boxCounts.put(minHeight,1);
//// System.err.println("new height: "+minHeight);
// } else {
// boxCounts.put(minHeight,count+1);
//// System.err.println("old height: "+minHeight);
// // TODO Could do the logFactorial right here
// } else {
// // Do nothing
// return minHeight;
private double recursivelyComputeDensity(Tree tree, NodeRef node, double parentHeight) {
if (tree.isExternal(node))
return tree.getNodeHeight(node);
double thisHeight = tree.getNodeHeight(node);
double heightChild1 = recursivelyComputeDensity(tree, tree.getChild(node, 0), thisHeight);
double heightChild2 = recursivelyComputeDensity(tree, tree.getChild(node, 1), thisHeight);
double minHeight = (heightChild1 > heightChild2) ? heightChild1 : heightChild2;
if (!tree.isRoot(node)) {
double diff = parentHeight - minHeight;
if (diff <= 0)
tmpLogLikelihood = Double.NEGATIVE_INFINITY;
else
tmpLogLikelihood -= Math.log(diff);
// tmpLogLikelihood -= Math.log(parentHeight-minHeight);
} else {
// Do nothing
}
return minHeight;
}
private double recursivelyFindNodeMinHeights(Tree tree, NodeRef node) {
double minHeight;
if (tree.isExternal(node))
minHeight = tree.getNodeHeight(node);
else {
double minHeightChild0 = recursivelyFindNodeMinHeights(tree, tree.getChild(node,0));
double minHeightChild1 = recursivelyFindNodeMinHeights(tree, tree.getChild(node,1));
minHeight = (minHeightChild0 > minHeightChild1) ? minHeightChild0 : minHeightChild1;
}
minNodeHeights[node.getNumber()] = minHeight;
return minHeight;
}
private void recursivelyComputeMCIntegral(Tree tree, NodeRef node, int parentNodeNumber) {
if (tree.isExternal(node))
return;
final int nodeNumber = node.getNumber();
if (!tree.isRoot(node)) {
final double[] drawParentHeight = drawNodeHeights[parentNodeNumber];
final double[] drawThisNodeHeight = drawNodeHeights[nodeNumber];
final double minHeight = minNodeHeights[nodeNumber];
final boolean twoChild = (tree.isExternal(tree.getChild(node,0)) && tree.isExternal(tree.getChild(node,1)));
for(int i=0; i<mcSampleSize; i++) {
final double diff = drawParentHeight[i] - minHeight;
if (diff <= 0) {
logLikelihoods[i] = Double.NEGATIVE_INFINITY;
break;
}
if (!twoChild)
drawThisNodeHeight[i] = MathUtils.nextDouble() * diff + minHeight;
logLikelihoods[i] += Math.log(diff);
}
}
recursivelyComputeMCIntegral(tree, tree.getChild(node,0), nodeNumber);
recursivelyComputeMCIntegral(tree, tree.getChild(node,1), nodeNumber);
}
private static final double INV_PRECISION = 10;
private static double round(double x) {
return Math.round(x * INV_PRECISION) / INV_PRECISION;
}
private TipLabeledPolynomial recursivelyComputePolynomial(Tree tree, NodeRef node, Polynomial.Type type) {
if (tree.isExternal(node)) {
double[] value = new double[]{1.0};
double height = round(tree.getNodeHeight(node)); // Should help in numerical stability
return new TipLabeledPolynomial(value, height, type, true);
}
TipLabeledPolynomial childPolynomial1 = recursivelyComputePolynomial(tree, tree.getChild(node, 0), type);
TipLabeledPolynomial childPolynomial2 = recursivelyComputePolynomial(tree, tree.getChild(node, 1), type);
// TODO The partialPolynomial below *should* be cached in an efficient reuse scheme (at least for arbitrary precision)
TipLabeledPolynomial polynomial = childPolynomial1.multiply(childPolynomial2);
// See AbstractTreeLikelihood for an example of how to flag cached polynomials for re-evaluation
// System.err.println("B> "+polynomial);
if (!tree.isRoot(node)) {
polynomial = polynomial.integrateWithLowerBound(polynomial.label);
// System.err.println("<A "+polynomial);
} else {
// System.err.println("<= ROOT");
}
return polynomial;
}
// private void test() {
// double[] value = new double[]{2, 0, 2};
// Polynomial a = new Polynomial.Double(value);
// Polynomial a2 = a.multiply(a);
// System.err.println("a :" + a);
// System.err.println("a*a: " + a2);
// System.err.println("eval :" + a2.evaluate(2));
// Polynomial intA = a.integrate();
// System.err.println("intA: " + intA);
// Polynomial intA2 = a.integrateWithLowerBound(2.0);
// System.err.println("intA2: " + intA2);
// System.err.println("");
// Polynomial b = new Polynomial.APDouble(value);
// System.err.println("b : " + b);
// Polynomial b2 = b.multiply(b);
// System.err.println("b2 : " + b2);
// System.err.println("eval : " + b2.evaluate(2));
// Polynomial intB = b.integrate();
// System.err.println("intB: " + intB);
// Polynomial intB2 = b.integrateWithLowerBound(2.0);
// System.err.println("intB2: " + intB2);
// System.err.println("");
// Polynomial c = new Polynomial.LogDouble(value);
// System.err.println("c : " + c);
// System.err.println("c2 : " + c2);
// System.err.println("eval : " + c2.evaluate(2));
// Polynomial intC = c.integrate();
// System.err.println("intC: " + intC);
// Polynomial intC2 = c.integrateWithLowerBound(2.0);
// System.err.println("intC2: " + intC2);
// System.exit(-1);
class TipLabeledPolynomial extends Polynomial.Abstract {
TipLabeledPolynomial(double[] coefficients, double label, Polynomial.Type type, boolean isTip) {
switch (type) {
case DOUBLE:
polynomial = new Polynomial.Double(coefficients);
break;
case LOG_DOUBLE:
polynomial = new Polynomial.LogDouble(coefficients);
break;
case BIG_DOUBLE:
polynomial = new Polynomial.BigDouble(coefficients);
break;
// case APDOUBLE: polynomial = new Polynomial.APDouble(coefficients);
// break;
// case RATIONAL: polynomial = new Polynomial.RationalDouble(coefficients);
// break;
// case MARCRATIONAL: polynomial = new Polynomial.MarcRational(coefficients);
// break;
default:
throw new RuntimeException("Unknown polynomial type");
}
this.label = label;
this.isTip = isTip;
}
TipLabeledPolynomial(Polynomial polynomial, double label, boolean isTip) {
this.polynomial = polynomial;
this.label = label;
this.isTip = isTip;
}
public TipLabeledPolynomial copy() {
Polynomial copyPolynomial = polynomial.copy();
return new TipLabeledPolynomial(copyPolynomial, this.label, this.isTip);
}
public Polynomial getPolynomial() {
return polynomial;
}
public TipLabeledPolynomial multiply(TipLabeledPolynomial b) {
double maxLabel = Math.max(label, b.label);
return new TipLabeledPolynomial(polynomial.multiply(b), maxLabel, false);
}
public int getDegree() {
return polynomial.getDegree();
}
public Polynomial multiply(Polynomial b) {
return polynomial.multiply(b);
}
public Polynomial integrate() {
return polynomial.integrate();
}
public void expand(double x) {
polynomial.expand(x);
}
public double evaluate(double x) {
return polynomial.evaluate(x);
}
public double logEvaluate(double x) {
return polynomial.logEvaluate(x);
}
public double logEvaluateHorner(double x) {
return polynomial.logEvaluateHorner(x);
}
public void setCoefficient(int n, double x) {
polynomial.setCoefficient(n, x);
}
public TipLabeledPolynomial integrateWithLowerBound(double bound) {
return new TipLabeledPolynomial(polynomial.integrateWithLowerBound(bound), label, isTip);
}
public double getCoefficient(int n) {
return polynomial.getCoefficient(n);
}
public String toString() {
return polynomial.toString() + " {" + label + "}";
}
public String getCoefficientString(int n) {
return polynomial.getCoefficientString(n);
}
private double label;
private Polynomial polynomial;
private boolean isTip;
}
private double logFactorial(int n) {
if (n == 0 || n == 1) {
return 0;
}
double rValue = 0;
for (int i = n; i > 1; i
rValue += Math.log(i);
}
return rValue;
}
// XMLElement IMPLEMENTATION
public org.w3c.dom.Element createElement(org.w3c.dom.Document d) {
throw new RuntimeException("createElement not implemented");
}
// Private and protected stuff
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return UNIFORM_NODE_HEIGHT_PRIOR;
}
public String[] getParserNames() {
return new String[] {UNIFORM_ROOT_PRIOR, UNIFORM_NODE_HEIGHT_PRIOR};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Logger.getLogger("dr.evomodel").info("\nConstructing a uniform node height prior:");
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
if (xo.hasAttribute(MAX_ROOT_HEIGHT)) {
// the Nicholls & Gray variant
double maxRootHeight = xo.getDoubleAttribute(MAX_ROOT_HEIGHT);
Logger.getLogger("dr.evomodel").info("\tUsing joint variant with a max root height = "+maxRootHeight+"\n");
return new UniformNodeHeightPrior(treeModel, maxRootHeight);
} else {
// the Bloomquist & Suchard variant or Welch, Rambaut & Suchard variant
boolean useAnalytic = xo.getAttribute(ANALYTIC,true);
boolean marginal = xo.getAttribute(MARGINAL,true);
Logger.getLogger("dr.evomodel").info("\tUsing conditional variant with "+(useAnalytic ? "analytic" : "Monte Carlo integrated")+" expressions");
if (useAnalytic)
Logger.getLogger("dr.evomodel").info("\t\tSubvariant: "+(marginal ? "marginal" : "conditional"));
Logger.getLogger("dr.evomodel").info("\tPlease reference:");
Logger.getLogger("dr.evomodel").info("\t\t (1) Welch, Rambaut and Suchard (in preparation) and");
Logger.getLogger("dr.evomodel").info("\t\t (2) Bloomquist and Suchard (in press) Systematic Biology\n");
if (!useAnalytic) {
// if( treeModel.getExternalNodeCount() > MAX_ANALYTIC_TIPS)
// throw new XMLParseException("Analytic evaluation of UniformNodeHeight is unreliable for > "+MAX_ANALYTIC_TIPS+" taxa");
int mcSampleSize = xo.getAttribute(MC_SAMPLE,DEFAULT_MC_SAMPLE);
return new UniformNodeHeightPrior(treeModel,useAnalytic,mcSampleSize);
}
return new UniformNodeHeightPrior(treeModel, useAnalytic, marginal);
}
}
/**
* The tree.
*/
Tree tree = null;
double logLikelihood;
private double storedLogLikelihood;
boolean likelihoodKnown = false;
private boolean storedLikelihoodKnown = false;
private boolean treePolynomialKnown = false;
private boolean storedTreePolynomialKnown = false;
private Polynomial treePolynomial;
private Polynomial storedTreePolynomial;
private double tmpLogLikelihood;
// private Iterator<Polynomial.Type> typeIterator = EnumSet.allOf(Polynomial.Type.class).iterator();
// private Polynomial.Type polynomialType = typeIterator.next();
private Polynomial.Type polynomialType;
private double[] logLikelihoods;
private double[][] drawNodeHeights;
private double[] minNodeHeights;
}
|
package mpicbg.imglib.algorithm.gauss;
import java.util.concurrent.atomic.AtomicInteger;
import mpicbg.imglib.algorithm.Benchmark;
import mpicbg.imglib.algorithm.MultiThreaded;
import mpicbg.imglib.algorithm.OutputAlgorithm;
import mpicbg.imglib.algorithm.math.MathLib;
import mpicbg.imglib.container.array.Array3D;
import mpicbg.imglib.container.array.FloatArray3D;
import mpicbg.imglib.cursor.LocalizableByDimCursor;
import mpicbg.imglib.cursor.LocalizableByDimCursor3D;
import mpicbg.imglib.cursor.LocalizableCursor;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.multithreading.SimpleMultiThreading;
import mpicbg.imglib.outside.OutsideStrategyFactory;
import mpicbg.imglib.type.NumericType;
import mpicbg.imglib.type.numeric.FloatType;
public class GaussianConvolution< T extends NumericType<T>> implements MultiThreaded, OutputAlgorithm<T>, Benchmark
{
final Image<T> image, convolved;
final OutsideStrategyFactory<T> outsideFactory;
final int numDimensions;
final double[] sigma;
final double[][] kernel;
long processingTime;
int numThreads;
String errorMessage = "";
public GaussianConvolution( final Image<T> image, final OutsideStrategyFactory<T> outsideFactory, final double[] sigma )
{
this.image = image;
this.convolved = image.createNewImage();
this.sigma = sigma;
this.processingTime = -1;
setNumThreads();
this.outsideFactory = outsideFactory;
this.numDimensions = image.getNumDimensions();
this.kernel = new double[ numDimensions ][];
for ( int d = 0; d < numDimensions; ++d )
this.kernel[ d ] = MathLib.createGaussianKernel1DDouble( sigma[ d ], true );
}
public GaussianConvolution( final Image<T> image, final OutsideStrategyFactory<T> outsideFactory, final double sigma )
{
this ( image, outsideFactory, createArray(image, sigma));
}
protected static double[] createArray( final Image<?> image, final double sigma )
{
final double[] sigmas = new double[ image.getNumDimensions() ];
for ( int d = 0; d < image.getNumDimensions(); ++d )
sigmas[ d ] = sigma;
return sigmas;
}
@Override
public long getProcessingTime() { return processingTime; }
@Override
public void setNumThreads() { this.numThreads = Runtime.getRuntime().availableProcessors(); }
@Override
public void setNumThreads( final int numThreads ) { this.numThreads = numThreads; }
@Override
public int getNumThreads() { return numThreads; }
/**
* The sigma the image was convolved with
* @return - double sigma
*/
public double[] getSigmas() { return sigma; }
@Override
public Image<T> getResult() { return convolved; }
@Override
public boolean checkInput()
{
if ( errorMessage.length() > 0 )
{
return false;
}
else if ( image == null )
{
errorMessage = "GaussianConvolution: [Image<T> img] is null.";
return false;
}
else if ( outsideFactory == null )
{
errorMessage = "GaussianConvolution: [OutsideStrategyFactory<T>] is null.";
return false;
}
else
return true;
}
@Override
public String getErrorMessage() { return errorMessage; }
@Override
public boolean process()
{
final long startTime = System.currentTimeMillis();
if ( Array3D.class.isInstance( image.getContainer() ) && FloatType.class.isInstance( image.createType() ))
{
//System.out.println( "GaussianConvolution: Input is instance of Image<Float> using an Array3D, fast forward algorithm");
computeGaussFloatArray3D();
processingTime = System.currentTimeMillis() - startTime;
return true;
}
final Image<T> temp = image.createNewImage();
final long imageSize = image.getNumPixels();
// Folding loop
for ( int dim = 0; dim < numDimensions; dim++ )
{
final int currentDim = dim;
final AtomicInteger ai = new AtomicInteger(0);
final Thread[] threads = SimpleMultiThreading.newThreads( numThreads );
final long threadChunkSize = imageSize / threads.length;
final long threadChunkMod = imageSize % threads.length;
for (int ithread = 0; ithread < threads.length; ++ithread)
threads[ithread] = new Thread(new Runnable()
{
public void run()
{
// Thread ID
final int myNumber = ai.getAndIncrement();
//System.out.println("Thread " + myNumber + " folds in dimension " + currentDim);
final LocalizableByDimCursor<T> inputIterator;
final LocalizableCursor<T> outputIterator;
if ( numDimensions % 2 == 0 ) // even number of dimensions ( 2d, 4d, 6d, ... )
{
if ( currentDim == 0 ) // first dimension convolve to the temporary image
{
inputIterator = image.createLocalizableByDimCursor( outsideFactory );
outputIterator = temp.createLocalizableCursor();
}
else if ( currentDim % 2 == 1 ) // for odd dimension ids we convolve to the output image, because that might be the last convolution
{
inputIterator = temp.createLocalizableByDimCursor( outsideFactory );
outputIterator = convolved.createLocalizableCursor();
}
else //if ( currentDim % 2 == 0 ) // for even dimension ids we convolve to the temp image, it is not the last convolution for sure
{
inputIterator = convolved.createLocalizableByDimCursor( outsideFactory );
outputIterator = temp.createLocalizableCursor();
}
}
else // ( numDimensions % 2 != 0 ) // even number of dimensions ( 1d, 3d, 5d, ... )
{
if ( currentDim == 0 ) // first dimension convolve to the output image, in the 1d case we are done then already
{
inputIterator = image.createLocalizableByDimCursor( outsideFactory );
outputIterator = convolved.createLocalizableCursor();
}
else if ( currentDim % 2 == 1 ) // for odd dimension ids we convolve to the output image, because that might be the last convolution
{
inputIterator = convolved.createLocalizableByDimCursor( outsideFactory );
outputIterator = temp.createLocalizableCursor();
}
else //if ( currentDim % 2 == 0 ) // for even dimension ids we convolve to the temp image, it is not the last convolution for sure
{
inputIterator = temp.createLocalizableByDimCursor( outsideFactory );
outputIterator = convolved.createLocalizableCursor();
}
}
// move to the starting position of the current thread
final long startPosition = myNumber * threadChunkSize;
// the last thread may has to run longer if the number of pixels cannot be divided by the number of threads
final long loopSize;
if ( myNumber == numThreads - 1 )
loopSize = threadChunkSize + threadChunkMod;
else
loopSize = threadChunkSize;
// convolve the image in the current dimension using the given cursors
float[] kernelF = new float[ kernel[ currentDim ].length ];
for ( int i = 0; i < kernelF.length; ++i )
kernelF[ i ] = (float)kernel[ currentDim ][ i ];
convolve( inputIterator, outputIterator, currentDim, kernelF, startPosition, loopSize );
inputIterator.close();
outputIterator.close();
}
});
SimpleMultiThreading.startAndJoin(threads);
}
// close temporary datastructure
temp.close();
processingTime = System.currentTimeMillis() - startTime;
return true;
}
protected static <T extends NumericType<T>> void convolve( final LocalizableByDimCursor<T> inputIterator, final LocalizableCursor<T> outputIterator,
final int dim, final float[] kernel,
final long startPos, final long loopSize )
{
// move to the starting position of the current thread
outputIterator.fwd( startPos );
final int filterSize = kernel.length;
final int filterSizeMinus1 = filterSize - 1;
final int filterSizeHalf = filterSize / 2;
final int filterSizeHalfMinus1 = filterSizeHalf - 1;
final int numDimensions = inputIterator.getImage().getNumDimensions();
final int iteratorPosition = filterSizeHalf;
final int[] to = new int[ numDimensions ];
final T sum = inputIterator.getType().createVariable();
final T tmp = inputIterator.getType().createVariable();
// do as many pixels as wanted by this thread
for ( long j = 0; j < loopSize; ++j )
{
outputIterator.fwd();
// set the sum to zero
sum.setZero();
// we move filtersize/2 of the convolved pixel in the input image
// get the current positon in the output image
outputIterator.getPosition( to );
// position in the input image is filtersize/2 to the left
to[ dim ] -= iteratorPosition;
// set the input cursor to this very position
inputIterator.setPosition( to );
// iterate over the kernel length across the input image
for ( int f = -filterSizeHalf; f <= filterSizeHalfMinus1; ++f )
{
// get value from the input image
tmp.set( inputIterator.getType() );
// multiply the kernel
tmp.mul( kernel[ f + filterSizeHalf ] );
// add up the sum
sum.add( tmp );
// move the cursor forward for the next iteration
inputIterator.fwd( dim );
}
// for the last pixel we do not move forward
// get value from the input image
tmp.set( inputIterator.getType() );
// multiply the kernel
tmp.mul( kernel[ filterSizeMinus1 ] );
// add up the sum
sum.add( tmp );
outputIterator.getType().set( sum );
}
}
/**
* This class does the gaussian filtering of an image. On the edges of
* the image it does mirror the pixels. It also uses the seperability of
* the gaussian convolution.
*
* @param input FloatProcessor which should be folded (will not be touched)
* @param sigma Standard Derivation of the gaussian function
* @return FloatProcessor The folded image
*
* @author Stephan Preibisch
*/
@SuppressWarnings("unchecked")
public void computeGaussFloatArray3D()
{
/* inconvertible types due to javac bug 6548436: final OutsideStrategyFactory<FloatType> outsideFactoryFloat = (OutsideStrategyFactory<FloatType>)outsideFactory; */
final OutsideStrategyFactory<FloatType> outsideFactoryFloat = (OutsideStrategyFactory)outsideFactory;
/* inconvertible types due to javac bug 6548436: final Image<FloatType> imageFloat = (Image<FloatType>) image; */
final Image<FloatType> imageFloat = (Image)image;
/* inconvertible types due to javac bug 6548436: final Image<FloatType> convolvedFloat = (Image<FloatType>) convolved; */
final Image<FloatType> convolvedFloat = (Image)convolved;
final FloatArray3D<FloatType> input = (FloatArray3D<FloatType>) imageFloat.getContainer();
final FloatArray3D<FloatType> output = (FloatArray3D<FloatType>) convolvedFloat.getContainer();
final int width = input.getWidth();
final int height = input.getHeight();
final int depth = input.getDepth();
final AtomicInteger ai = new AtomicInteger(0);
final Thread[] threads = SimpleMultiThreading.newThreads( numThreads );
final int numThreads = threads.length;
for (int ithread = 0; ithread < threads.length; ++ithread)
threads[ithread] = new Thread(new Runnable()
{
public void run()
{
final int myNumber = ai.getAndIncrement();
double avg;
final float[] in = input.getCurrentStorageArray( null );
final float[] out = output.getCurrentStorageArray( null );
final double[] kernel1 = kernel[ 0 ].clone();
final int filterSize = kernel[ 0 ].length;
final int filterSizeHalf = filterSize / 2;
final LocalizableByDimCursor3D<FloatType> it = (LocalizableByDimCursor3D<FloatType>)imageFloat.createLocalizableByDimCursor( outsideFactoryFloat );
// fold in x
int kernelPos, count;
// precompute direct positions inside image data when multiplying with kernel
final int posLUT[] = new int[kernel1.length];
for (int f = -filterSizeHalf; f <= filterSizeHalf; f++)
posLUT[f + filterSizeHalf] = f;
// precompute wheater we have to use mirroring or not (mirror when kernel goes outside image range)
final boolean directlyComputable[] = new boolean[width];
for (int x = 0; x < width; x++)
directlyComputable[x] = (x - filterSizeHalf >= 0 && x + filterSizeHalf < width);
for (int z = 0; z < depth; z++)
if (z % numThreads == myNumber)
{
count = input.getPos(0, 0, z);
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
avg = 0;
if (directlyComputable[x])
for (kernelPos = 0; kernelPos < filterSize; kernelPos++)
avg += in[count + posLUT[kernelPos]] * kernel1[kernelPos];
else
{
kernelPos = 0;
it.setPosition(x - filterSizeHalf - 1, y, z);
for (int f = -filterSizeHalf; f <= filterSizeHalf; f++)
{
it.fwdX();
avg += it.getType().get() * kernel1[kernelPos++];
}
}
out[count++] = (float) avg;
}
}
it.close();
}
});
SimpleMultiThreading.startAndJoin(threads);
ai.set(0);
// fold in y
for (int ithread = 0; ithread < threads.length; ++ithread)
threads[ithread] = new Thread(new Runnable()
{
public void run()
{
final int myNumber = ai.getAndIncrement();
double avg;
int kernelPos, count;
final float[] out = output.getCurrentStorageArray( null );
final LocalizableByDimCursor3D<FloatType> it = (LocalizableByDimCursor3D<FloatType>)convolvedFloat.createLocalizableByDimCursor( outsideFactoryFloat );
final double[] kernel1 = kernel[ 1 ].clone();
final int filterSize = kernel[ 1 ].length;
final int filterSizeHalf = filterSize / 2;
final int inc = output.getPos(0, 1, 0);
final int posLUT[] = new int[kernel1.length];
for (int f = -filterSizeHalf; f <= filterSizeHalf; f++)
posLUT[f + filterSizeHalf] = f * inc;
final boolean[] directlyComputable = new boolean[height];
for (int y = 0; y < height; y++)
directlyComputable[y] = (y - filterSizeHalf >= 0 && y + filterSizeHalf < height);
final float[] tempOut = new float[height];
for (int z = 0; z < depth; z++)
if (z % numThreads == myNumber)
for (int x = 0; x < width; x++)
{
count = output.getPos(x, 0, z);
for (int y = 0; y < height; y++)
{
avg = 0;
if (directlyComputable[y]) for (kernelPos = 0; kernelPos < filterSize; kernelPos++)
avg += out[count + posLUT[kernelPos]] * kernel1[kernelPos];
else
{
kernelPos = 0;
it.setPosition(x, y - filterSizeHalf - 1, z);
for (int f = -filterSizeHalf; f <= filterSizeHalf; f++)
{
it.fwdY();
avg += it.getType().get() * kernel1[kernelPos++];
}
}
tempOut[y] = (float) avg;
count += inc;
}
count = output.getPos(x, 0, z);
for (int y = 0; y < height; y++)
{
out[count] = tempOut[y];
count += inc;
}
}
it.close();
}
});
SimpleMultiThreading.startAndJoin(threads);
ai.set(0);
for (int ithread = 0; ithread < threads.length; ++ithread)
threads[ithread] = new Thread(new Runnable()
{
public void run()
{
final int myNumber = ai.getAndIncrement();
double avg;
int kernelPos, count;
final double[] kernel1 = kernel[ 2 ].clone();
final int filterSize = kernel[ 2 ].length;
final int filterSizeHalf = filterSize / 2;
final float[] out = output.getCurrentStorageArray( null );
final LocalizableByDimCursor3D<FloatType> it = (LocalizableByDimCursor3D<FloatType>)convolvedFloat.createLocalizableByDimCursor( outsideFactoryFloat );
final int inc = output.getPos(0, 0, 1);
final int posLUT[] = new int[kernel1.length];
for (int f = -filterSizeHalf; f <= filterSizeHalf; f++)
posLUT[f + filterSizeHalf] = f * inc;
final boolean[] directlyComputable = new boolean[depth];
for (int z = 0; z < depth; z++)
directlyComputable[z] = (z - filterSizeHalf >= 0 && z + filterSizeHalf < depth);
final float[] tempOut = new float[depth];
// fold in z
for (int x = 0; x < width; x++)
if (x % numThreads == myNumber)
for (int y = 0; y < height; y++)
{
count = output.getPos(x, y, 0);
for (int z = 0; z < depth; z++)
{
avg = 0;
if (directlyComputable[z]) for (kernelPos = 0; kernelPos < filterSize; kernelPos++)
avg += out[count + posLUT[kernelPos]] * kernel1[kernelPos];
else
{
kernelPos = 0;
it.setPosition(x, y, z - filterSizeHalf - 1);
for (int f = -filterSizeHalf; f <= filterSizeHalf; f++)
{
it.fwdZ();
avg += it.getType().get() * kernel1[kernelPos++];
}
}
tempOut[z] = (float) avg;
count += inc;
}
count = output.getPos(x, y, 0);
for (int z = 0; z < depth; z++)
{
out[count] = tempOut[z];
count += inc;
}
}
it.close();
}
});
SimpleMultiThreading.startAndJoin(threads);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems.fake;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class FakeDrivetrain extends Subsystem {
public static class SpeedRamp {
public static double profileSpeed_Bravo(double distToFinish, double totalDistToTravel, int direction) {
return 0;
}
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public FakeDrivetrain() {
}
/**
* Gets the analog voltage of the MaxBotics ultrasonic sensor, and debounces the input
* @return Analog voltage reading from 0 to 5
*/
public double getSonarVoltage() {
return 0;
}
/**
* Scales sonar voltage reading to centimeters
* @return distance from alliance wall in centimeters, as measured by sonar sensor
*/
public double getSonarDistance_in() {
return 0;
}
public void initDefaultCommand() {
}
public Command getDefaultCommand(){
return super.getDefaultCommand();
}
public void tankDrive(double leftValue, double rightValue) {
System.out.println("tankDrive");
}
public void setGear(boolean high) {
}
public boolean getGear() {
return false;
}
public void initController() {
}
public void endController() {
}
/**
* Sets the ramping distance and direction by constructing a new PID controller.
* @param distance inches to travel
*/
public void setDriveStraightDistanceAndDirection(final double distance, final int direction) {
System.out.println("setDriveStraightDistanceAndDirection");
}
public void driveStraight() {
System.out.println("DriveStraight");
}
/**
* Calculate average distance of the two encoders.
* @return Average of the distances (inches) read by each encoder since they were last reset.
*/
public double getAvgDistance() {
return 0;
}
public double getLeftEncoderDistance() {
return 0;
}
public double getRightEncoderDistance() {
return 0;
}
/**
* Reset both encoders's tick, distance, etc. count to zero
*/
public void resetEncoders() {
System.out.println("Drivetrain resetEncoder");
}
public double getGyroAngle() {
return 0;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.DriverStationLCD.Line;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Talon;
/**
*
* @author RoboHawks
*/
public class Shooter {
Relay shootSpike = new Relay(2);
Talon stageOneTalon = new Talon(5); //Creates instance of StageOne PWM
Talon stageTwoTalon = new Talon(6); //Creates instance of StageTwo PWM
AnalogChannel elevatorPot = new AnalogChannel(6);
DigitalInput shootLimit = new DigitalInput(7);
double percentageScaler = 0.5;
double stageTwoVoltageOut = 0.0;
double stageOneVoltageOut = 0.0;
int elevatorStatus = 0;
public void start(){
percentageScaler = 0.5;
stageTwoVoltageOut = 0.1;
stageOneVoltageOut = stageTwoVoltageOut * percentageScaler;
stageOneTalon.set(stageOneVoltageOut);
stageTwoTalon.set(stageTwoVoltageOut);
}
public void increaseSpeed(){ //increases stage 2 by 1/10 of possible speed
stageTwoVoltageOut += 0.1;
if (stageTwoVoltageOut >= 1){ stageTwoVoltageOut = 1;}
stageOneVoltageOut = stageTwoVoltageOut * percentageScaler;
stageOneTalon.set(stageOneVoltageOut);
stageTwoTalon.set(stageTwoVoltageOut);
}
public void decreaseSpeed(){//decreases stage 2 by 1/10 of possible speed
stageTwoVoltageOut -= 0.1;
if (stageTwoVoltageOut <= 0){ stageTwoVoltageOut = 0;}
stageOneVoltageOut = stageTwoVoltageOut * percentageScaler;
stageOneTalon.set(stageOneVoltageOut);
stageTwoTalon.set(stageTwoVoltageOut);
}
public void increasePercentage(){//increases percentage of what stage 2 is multiplyied by to get 1
percentageScaler += 0.05;
if (percentageScaler >= 1){percentageScaler = 1;}
stageOneVoltageOut = stageTwoVoltageOut * percentageScaler;
stageOneTalon.set(stageOneVoltageOut);
stageTwoTalon.set(stageTwoVoltageOut);
}
public void decreasePercentage(){//decreases percentage of what stage 2 is multiplyied by to get 1
percentageScaler -= 0.05;
if (percentageScaler <= 0){percentageScaler = 0;}
stageOneVoltageOut = stageTwoVoltageOut * percentageScaler;
stageOneTalon.set(stageOneVoltageOut);
stageTwoTalon.set(stageTwoVoltageOut);
}
public void stop(){
stageOneVoltageOut = 0.0;
percentageScaler = 0.5;
stageTwoVoltageOut = stageOneVoltageOut * percentageScaler;
stageOneTalon.set(stageOneVoltageOut);
stageTwoTalon.set(stageTwoVoltageOut);
}
public void printLCD(DriverStationLCD LCD){
double Scaler = 5936; //converts voltage to RPM for display purposes only
double speedOne = stageOneTalon.get();
String speed1 = Double.toString(speedOne);
double speedTwo = stageTwoTalon.get();
String speed2 = Double.toString(speedTwo);
LCD.println(Line.kUser3, 1, ((stageOneTalon.get()/stageTwoTalon.get()) *100) + " %");
LCD.println(Line.kUser4, 1,"S1:" + speed1);
LCD.println(Line.kUser2, 1,"S2:" + speed2);
LCD.println(Line.kUser1, 1, "RPM1: " + (speedOne * Scaler));
LCD.println(Line.kUser2, 1, "RPM2: " + (speedTwo * Scaler));
LCD.updateLCD();
}
public void shoot(){
final Thread thread = new Thread(new Runnable() {
public void run(){
while(!shootLimit.get()){
shootSpike.set(Relay.Value.kForward);
}
}
});
thread.start();
}
public void loadFrisbee(){
final Thread thread = new Thread(new Runnable() {
public void run(){
shootSpike.set(Relay.Value.kReverse);
try{
Thread.sleep(500);
}
catch(InterruptedException e){}
shootSpike.set(Relay.Value.kOff);
}
});
thread.start();
}
}
|
package fi.metacity.klmobi;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.astuetz.viewpager.extensions.PagerSlidingTabStrip;
import com.googlecode.androidannotations.annotations.App;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.FragmentArg;
import com.googlecode.androidannotations.annotations.OptionsItem;
import com.googlecode.androidannotations.annotations.OptionsMenu;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.res.BooleanRes;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
@EFragment
@OptionsMenu(R.menu.routes)
public class RouteResultsFragment extends ListFragment {
private static final String TAG = "RouteResultsFragment";
@App
MHApp mGlobals;
@Pref
Preferences_ mPreferences;
@BooleanRes(R.bool.has_two_panes)
boolean mIsDualPane;
@FragmentArg(Constants.EXTRA_DATE)
String mDate;
@FragmentArg(Constants.EXTRA_TIME)
String mTime;
@FragmentArg(Constants.EXTRA_NUMBER_OF_ROUTES)
String mNumerOfRoutes;
@FragmentArg(Constants.EXTRA_ROUTING_TYPE)
String mRoutingType;
@FragmentArg(Constants.EXTRA_WALKING_SPEED)
String mWalkingSpeed;
@FragmentArg(Constants.EXTRA_MAX_WALKING_DISTANCE)
String mMaxWalkingDistance;
@FragmentArg(Constants.EXTRA_CHANGE_MARGIN)
String mChangeMargin;
@FragmentArg(Constants.EXTRA_TIME_DIRECTION)
String mTimeDirection;
@FragmentArg(Constants.EXTRA_ROUTE_INDEX)
int mInitialRouteIndex;
private ViewPager mPager;
private PagerSlidingTabStrip mTabs;
private Button mShowInMapBtn;
private RouteAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mGlobals.getStartAddress() == null) {
getActivity().finish();
return;
}
mPager = (ViewPager) getActivity().findViewById(R.id.pager);
mTabs = (PagerSlidingTabStrip) getActivity().findViewById(R.id.tabs);
mShowInMapBtn = (Button) getActivity().findViewById(R.id.showInMapBtn);
View header = View.inflate(getActivity(), R.layout.route_results_header, null);
header.setClickable(false);
header.setFocusable(false);
header.setBackgroundResource(R.color.background);
((TextView)header.findViewById(R.id.fromTextView)).setText(mGlobals.getStartAddress().shortName());
((TextView)header.findViewById(R.id.toTextView)).setText(mGlobals.getEndAddress().shortName());
ListView listView = getListView();
listView.addHeaderView(header);
listView.setBackgroundResource(R.color.background);
listView.setDivider(getResources().getDrawable(android.R.color.transparent));
if (mGlobals.getRoutes().isEmpty()) {
fetchRoutes();
} else {
setRoutesAdapter(mGlobals.getRoutes());
}
}
@Background
public void fetchRoutes() {
Map<String, String> params = new HashMap<String, String>();
String url = "";
if (mPreferences.selectedCityIndex().get() == 20) { // TURKU
url = Constants.TURKU_BASE_URL + "getroute.php";
putTurkuPostParams(params, mGlobals.getStartAddress(), mGlobals.getEndAddress());
} else {
url = mPreferences.baseUrl().get() + "ajaxRequest.php?token=" + mPreferences.token().get();
String naviciRequest = buildNaviciRequest(mGlobals.getStartAddress(), mGlobals.getEndAddress());
params.put("requestXml", naviciRequest);
}
try {
String naviciResponse = Utils.httpPost(url, params);
List<Route> routes = buildRouteList(naviciResponse);
setRoutesAdapter(routes);
} catch (IOException ioex) {
Log.e(TAG, ioex.toString());
showNetworkErrorDialog();
}
}
@UiThread
public void setRoutesAdapter(List<Route> routes) {
mGlobals.setRoutes(routes);
mAdapter = new RouteAdapter(getActivity(), routes);
setListAdapter(mAdapter);
setListShown(true);
if (mIsDualPane) {
setRightPane(mInitialRouteIndex);
setSelectionIndication(getListView(), mInitialRouteIndex);
} else { // Clear existing selection indications
for (Route route : mGlobals.getRoutes()) {
route.isSelected = false;
}
mAdapter.notifyDataSetChanged();
}
}
private String buildNaviciRequest(Address start, Address end) {
String startX = start.json.optString("x");
String startY = start.json.optString("y");
String startName = start.json.optString("name");
String startNumber = start.json.optString("number");
String startCity = start.json.optString("city");
String endX = end.json.optString("x");
String endY = end.json.optString("y");
String endName = end.json.optString("name");
String endNumber = end.json.optString("number");
String endCity = end.json.optString("city");
String naviciRequest =
"<navici_request>"
+ "<ajax_request_object object_id=\"1\" service=\"RouteRequests\">"
+ "<get_route id=\"1\" language=\"fi\" TimeDirection=\"" + mTimeDirection + "\" Date=\"" + mDate
+ "\" Time=\"" + mTime + "\" WalkSpeed=\"" + mWalkingSpeed + "\" MaxWalk=\""
+ mMaxWalkingDistance + "\" RoutingMethod=\"" + mRoutingType + "\" ChangeMargin=\""
+ mChangeMargin + "\" NumberRoutes=\"" + mNumerOfRoutes + "\" ExcludedLines=\"\" >"
+ "<output type=\"image_layer_objects\"/>"
+ "<output type=\"gui_objects\"/>"
+ "<location order=\"0\" x=\"" + startX + "\" y=\"" + startY + "\" name=\""
+ startName + "\" number=\"" + startNumber + "\" city=\"" + startCity + "\" />"
+ "<location order=\"1\" x=\"" + endX + "\" y=\"" + endY + "\" name=\"" + endName
+ "\" number=\"" + endNumber + "\" city=\"" + endCity + "\" />"
+ "</get_route>"
+ "</ajax_request_object>"
+ "</navici_request>";
return naviciRequest;
}
private void putTurkuPostParams(Map<String, String> targetParams, Address start, Address end) {
targetParams.put("request[changeMargin]", mChangeMargin);
targetParams.put("request[walkSpeed]", mWalkingSpeed);
targetParams.put("request[maxTotWalkDist]", mMaxWalkingDistance);
targetParams.put("request[timeDirection]", mTimeDirection);
targetParams.put("request[numberRoutes]", mNumerOfRoutes);
targetParams.put("request[routingMethod]", mRoutingType);
targetParams.put("request[start][x]", start.json.optString("x"));
targetParams.put("request[start][y]", start.json.optString("y"));
targetParams.put("request[end][x]", end.json.optString("x"));
targetParams.put("request[end][y]", end.json.optString("y"));
targetParams.put("token", mPreferences.token().get());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH);
String timestamp = "";
try {
timestamp = String.valueOf(sdf.parse(mDate + mTime).getTime()/1000);
targetParams.put("request[timestamp]", timestamp);
} catch (ParseException e) {
// Ignore
}
targetParams.put("request[via]", "null");
targetParams.put("request[excludedLines]", "null");
targetParams.put("request[includedLines]", "null");
// Also build the GET query string for transfer images
try {
String mapQueryString = "startlocation=" + URLEncoder.encode(mGlobals.getStartAddress().shortName(), "UTF-8") +
"&endlocation=" + URLEncoder.encode(mGlobals.getEndAddress().shortName(), "UTF-8") +
"&changeMargin=" + mChangeMargin + "&walkSpeed=" + mWalkingSpeed +
"&maxTotWalkDist=" + mMaxWalkingDistance + "&timeDirection=" + mTimeDirection +
"&numberRoutes=" + mNumerOfRoutes + "×tamp=" + timestamp +
"&routingMethod=" + mRoutingType + "&start[x]=" + start.json.optString("x") +
"&start[y]=" + start.json.optString("y") + "&end[x]=" + end.json.optString("x") +
"&end[y]=" + end.json.optString("y") + "&via=null" + "&excludedLines=null" +
"&includedLines=null";
mGlobals.setTurkuMapQueryString(mapQueryString);
} catch (UnsupportedEncodingException useex) {
// Ignore
}
}
private List<Route> buildRouteList(String naviciResponse) {
List<Route> routes = new ArrayList<Route>();
Document fullDoc = Jsoup.parse(naviciResponse, "", Parser.xmlParser());
fullDoc.outputSettings().charset("UTF-8").indentAmount(0).escapeMode(EscapeMode.xhtml);
Elements doc = fullDoc.select("MTRXML");
if (mPreferences.selectedCityIndex().get() != 20) { // If not TURKU
mGlobals.setDetailsXmlString(doc.toString());
}
Elements xmlRoutes = doc.select("ROUTE");
for (Element xmlRoute : xmlRoutes) {
List<RouteComponent> routeComponents = new ArrayList<RouteComponent>();
Element xmlLength = xmlRoute.select("LENGTH").first();
float duration = Float.parseFloat(xmlLength.attr("time"));
float distance = Float.parseFloat(xmlLength.attr("dist"));
Elements xmlRouteComponents = xmlRoute.select("WALK, LINE");
for (Element xmlComponent : xmlRouteComponents) {
String code = ("LINE".equals(xmlComponent.tagName()) ? xmlComponent.attr("code") : "W");
Element lengthTag = xmlComponent.select("LENGTH").first();
float componentDuration = Float.parseFloat(lengthTag.attr("time"));
float componentDistance = Float.parseFloat(lengthTag.attr("dist"));
String componentStartName = null;
String componentEndName = null;
Date componentStartDateTime = null;
Date componentEndDateTime = null;
Elements xmlWayPoints = xmlComponent.select("STOP, MAPLOC, POINT");
List<WayPoint> wayPoints = new ArrayList<WayPoint>();
int i = 0;
int xmlWayPointsLen = xmlWayPoints.size();
for (Element xmlWayPoint : xmlWayPoints) {
if ("STOP".equals(xmlWayPoint.tagName())) {
if (i == 0) {
// on first STOP tag, "end"/DEPARTURE-tag implies time correctly
componentStartDateTime = dateFromStopOrPoint(xmlWayPoint, false);
componentStartName = xmlWayPoint.select("NAME").first().attr("val");
} else if (i == xmlWayPointsLen-1) {
// on last STOP tag, "start"/ARRIVAL-tag implies time correctly
componentEndDateTime = dateFromStopOrPoint(xmlWayPoint, true);
componentEndName = xmlWayPoint.select("NAME").first().attr("val");
}
} else if ("POINT".equals(xmlWayPoint.tagName())) {
if ("start".equals(xmlWayPoint.attr("uid"))) {
componentStartName = mGlobals.getStartAddress().shortName();
componentStartDateTime = dateFromStopOrPoint(xmlWayPoint, true);
} else {
componentEndName = mGlobals.getEndAddress().shortName();
componentEndDateTime = dateFromStopOrPoint(xmlWayPoint, false);
}
}
Element nameTag = xmlWayPoint.select("NAME").first();
Elements digistopIdTags = xmlWayPoint.select("XTRA[name=digistop_id]");
String time = "";
if ("WALK".equals(xmlComponent.tagName()) && "STOP".equals(xmlWayPoint.tagName())) {
time = xmlWayPoint.select("ARRIVAL").first().attr("time");
} else {
time = xmlWayPoint.select("DEPARTURE").first().attr("time");
}
String wayPointName = (nameTag != null) ? nameTag.attr("val") : "";
if (digistopIdTags != null && digistopIdTags.size() > 0) {
wayPointName += " (" + digistopIdTags.first().attr("val") + ")";
}
wayPoints.add(new WayPoint(xmlWayPoint.attr("x"), xmlWayPoint.attr("y"),
wayPointName, time));
++i;
}
routeComponents.add(
new RouteComponent(
code,
componentStartName,
componentEndName,
componentStartDateTime,
componentEndDateTime,
componentDuration,
componentDistance,
wayPoints)
);
}
routes.add(new Route(routeComponents, duration, distance));
}
return routes;
}
private static Date dateFromStopOrPoint(Element element, boolean start) {
String date;
String time;
Element timeOfInterest = element.select(start ? "ARRIVAL" : "DEPARTURE").first();
date = timeOfInterest.attr("date");
time = timeOfInterest.attr("time");
try {
return Utils.dateTimeFormat.parse(date + ";" + time);
} catch (ParseException pex) {
return new Date();
}
}
@OptionsItem({R.id.earlier_lines, R.id.later_lines})
public void showEarlierOrLaterLines(MenuItem item) {
if (mGlobals.getRoutes().size() == 0)
return;
setListShown(false);
setListAdapter(null);
List<Route> routes = mGlobals.getRoutes();
Route lastRoute = routes.get(routes.size() - 1);
Date lastStart = lastRoute.routeComponents.get(0).startDateTime;
Date newDateTime;
if (item.getItemId() == R.id.earlier_lines) {
Route firstRoute = routes.get(0);
Date firstStart = firstRoute.routeComponents.get(0).startDateTime;
String currentDateTimeStr = mDate + ";" + mTime;
Date currentDate = null;
try {
currentDate = Utils.dateTimeFormat.parse(currentDateTimeStr);
} catch (ParseException pex) {
// Ignore
}
// Difference between the first and the last of current routes
long delta = lastStart.getTime() - firstStart.getTime();
newDateTime = new Date(currentDate.getTime() - delta);
} else {
newDateTime = new Date(lastStart.getTime() + 60 * 1000); // + 1 minute
}
SimpleDateFormat dateSdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
mDate = dateSdf.format(newDateTime);
SimpleDateFormat timeSdf = new SimpleDateFormat("HHmm", Locale.ENGLISH);
mTime = timeSdf.format(newDateTime);
mGlobals.getRoutes().clear();
fetchRoutes();
}
@Override
public void onListItemClick(ListView list, View v, int position, long id) {
super.onListItemClick(list, v, position, id);
if (position > 0) { // Ignore header click
if (mIsDualPane) { // SHOW RIGHT PANE
setSelectionIndication(list, position-1);
setRightPane(position-1); // Header is 0!
} else { // START DETAILS ACTIVITY
RouteDetailsActivity_.intent(getActivity()).mRouteIndex(position-1).start();
}
}
}
// Header excluded here already!
private void setRightPane(int position) {
if (mTabs != null && mPager != null) {
RouteDetailsPagerAdapter adapter = new RouteDetailsPagerAdapter(
getFragmentManager(),
new String[] {
getString(R.string.routeDetailsTitle),
getString(R.string.transferImages)
},
position
);
mPager.setAdapter(adapter);
mTabs.setViewPager(mPager);
mPager.setCurrentItem(0, true);
if (mShowInMapBtn != null) mShowInMapBtn.setVisibility(View.VISIBLE);
}
}
// Header excluded here already!
private void setSelectionIndication(ListView list, int position) {
if (position < mGlobals.getRoutes().size()) {
for (Route route : mGlobals.getRoutes()) {
route.isSelected = false;
}
mGlobals.getRoutes().get(position).isSelected = true;
mAdapter.notifyDataSetChanged();
}
}
@UiThread
public void showNetworkErrorDialog() {
new AlertDialog.Builder(getActivity())
.setMessage(R.string.networkErrorOccurred).setPositiveButton("OK", null).show();
setListShown(true);
}
}
|
package natlab.utils;
import java.util.List;
import nodecases.AbstractNodeCaseHandler;
import ast.ASTNode;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
/**
* A utility that finds nodes in an AST, optionally satisfying a given
* predicate, and optionally transforms them using a given function. For example, the
* following snippet searches <tt>tree</tt> for all functions that aren't nested, and
* returns a list of their names:
*
* <pre>
* NodeFinder.of(ast.Function.class)
* .filter(new Predicate<ast.Function>() {
* @Override public boolean apply(ast.Function f) {
* return !(f.getParent().getParent() instanceof ast.Function);
* }
* })
* .transform(new Function<ast.Function, String>() {
* @Override public String apply(ast.Function f) {
* return f.getName();
* }
* })
* .findIn(tree);
* </pre>
*/
public class NodeFinder<F extends ASTNode<?>, T> {
private Class<F> clazz;
private Predicate<F> predicate;
private Function<F, T> transformer;
/**
* Returns a finder that finds nodes of the given class.
*/
public static <F extends ASTNode<?>> NodeFinder<F, F> of(Class<F> clazz) {
return new NodeFinder<F, F>(clazz, Predicates.<F>alwaysTrue(), Functions.<F>identity());
}
private NodeFinder(Class<F> clazz, Predicate<F> predicate, Function<F, T> transformer) {
this.clazz = clazz;
this.predicate = predicate;
this.transformer = transformer;
}
/**
* Returns a finder with the same behavior as this finder, except omitting nodes
* that don't satisfy the given predicate. This predicate replaces any previous
* predicate, so there's no reason to call this more than once.
*/
public NodeFinder<F, T> filter(Predicate<F> predicate) {
return new NodeFinder<F, T>(clazz, Preconditions.checkNotNull(predicate), transformer);
}
/**
* Returns a finder with the same behavior as this finder, except that nodes
* found are transformed using the given function.
*/
public <S> NodeFinder<F, S> transform(Function<F, S> transformer) {
return new NodeFinder<F, S>(clazz, predicate, Preconditions.checkNotNull(transformer));
}
/**
* Returns a list of the nodes of this finder's type in <tt>tree</tt>;
* if a predicate was previously given, the nodes must satisfy it, and if a transformer was
* previously given, it is applied.
*/
// TODO(isbadawi): figure out how to make this return a lazy iterable
public List<T> findIn(ASTNode<?> tree) {
Preconditions.checkNotNull(tree);
final List<T> res = Lists.newLinkedList();
new AbstractNodeCaseHandler() {
public void caseASTNode(@SuppressWarnings("rawtypes") ASTNode n) {
if (clazz.isInstance(n)) {
F cast = clazz.cast(n);
if (predicate.apply(cast)) {
res.add(transformer.apply(cast));
}
}
for (int i = 0; i < n.getNumChild(); i++) {
caseASTNode(n.getChild(i));
}
}
}.caseASTNode(tree);
return res;
}
/**
* Returns the parent of the given node which is of this finder's type, or null if
* no such parent exists, or if it does but doesn't satisfy the previously provided
* predicate, if any. If a transformer was previously given, it is applied.
*/
public T findParent(ASTNode<?> node) {
Preconditions.checkNotNull(node);
while (node != null && (!clazz.isInstance(node))) {
node = node.getParent();
}
if (clazz.isInstance(node)) {
F cast = clazz.cast(node);
if (predicate.apply(cast)) {
return transformer.apply(cast);
}
}
return null;
}
/**
* Applies the given function (for its side effects)
* on children of <tt>tree</tt> with this finder's type.
*/
public void applyIn(ASTNode<?> tree, final AbstractNodeFunction<F> function) {
filter(new Predicate<F>() {
@Override public boolean apply(F node) {
boolean result = predicate.apply(node);
if (result) {
function.apply(node);
}
return result;
}
})
.findIn(tree);
}
/**
* Search <tt>n</tt> for nodes of type <tt>type</tt>.
* Equivalent to <tt>NodeFinder.of(type).findIn(n)</tt>.
*/
@Deprecated
public static <T extends ASTNode<?>> List<T> find(ASTNode<?> n, Class<T> type) {
return NodeFinder.of(type).findIn(n);
}
/**
* Walks up the tree to find a parent of the specified type.
* Returns null if no such parent exists.
* Equivalent to <tt>NodeFinder.of(type).findParent(n)</tt>.
*/
@Deprecated
public static <T extends ASTNode<?>> T findParent(ASTNode<?> n, Class<T> type) {
return NodeFinder.of(type).findParent(n);
}
/**
* Applies <tt>func</tt> to each node of type <tt>type</tt> in <tt>n</tt>.
* Equivalent to <tt>NodeFinder.of(type).applyIn(n, func)</tt>.
*/
@Deprecated
public static <T extends ASTNode<?>> void apply(final ASTNode<?> n, final Class<T> type,
final AbstractNodeFunction<T> func) {
NodeFinder.of(type).applyIn(n, func);
}
}
|
package edu.dynamic.dynamiz.storage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import edu.dynamic.dynamiz.controller.DataFileReadWrite;
import edu.dynamic.dynamiz.controller.WriteToFileThread;
import edu.dynamic.dynamiz.parser.OptionType;
import edu.dynamic.dynamiz.structure.MyDate;
import edu.dynamic.dynamiz.structure.EndDateComparator;
import edu.dynamic.dynamiz.structure.EventItem;
import edu.dynamic.dynamiz.structure.PriorityComparator;
import edu.dynamic.dynamiz.structure.StartDateComparator;
import edu.dynamic.dynamiz.structure.TaskItem;
import edu.dynamic.dynamiz.structure.ToDoItem;
/**
* Defines the storage class holding the list of tasks and events.
*
* Public Methods(currently that can be used)
* static Storage getInstance() //gets the Storage instance
* ToDoItem addItem(ToDoItem item) //Adds the given item to the list.
* ToDoItem[] getList(OptionType[] options) //Gets the full list of items.
* ToDoItem[] getList(String[] keywords, int[] priority, MyDate[] start, MyDate end, OptionsType[] optionsList)
* //Gets the filtered list of items.
* ToDoItem removeItem(String id) //Removes the item with the specified id from this storage.
* ToDoItem[] searchItems(String keyword, int priority, MyDate start, MyDate end, OptionType[] optList) //Gets a list of items with the given parameter values.
* ToDoItem[] updateItem(String id, String description, int priority, Date start, Date end) //Updates the ToDoItem with the given id with the specified details.
*
* @author zixian
*/
public class Storage {
private static final String COMPLETED_FILENAME = "completed.txt";
private static final String TODOLIST_FILENAME = "todo.txt";
private static final String OUTPUT_FILENAME = TODOLIST_FILENAME;
//Main data members
private ArrayList<ToDoItem> mainList; //The main list
private ArrayList<ToDoItem> toDoItemList; //Holds items without any dates
private ArrayList<EventItem> eventList; //Holds events
private ArrayList<TaskItem> taskList; //Holds deadline tasks
private TreeMap<String, ToDoItem> searchTree; //Maps each item to its ID for faster search by ID
private ArrayList<String> completedList; //The list of completed items in string representation.
private Stack<ToDoItem> completedBuffer; //Buffered list of items marked as completed.
private static Storage storage; //Holds the only instance of the Storage object
/**
* Creates a new instance of Storage.
*/
private Storage(){
mainList = DataFileReadWrite.getListFromFile(TODOLIST_FILENAME);
searchTree = new TreeMap<String, ToDoItem>();
toDoItemList = new ArrayList<ToDoItem>();
eventList = new ArrayList<EventItem>();
taskList = new ArrayList<TaskItem>();
completedBuffer = new Stack<ToDoItem>();
//Adds each item in mainList to ID search tree
for(ToDoItem temp: mainList){
searchTree.put(temp.getId(), temp);
if(temp instanceof TaskItem){
taskList.add((TaskItem)temp);
} else if(temp instanceof EventItem){
eventList.add((EventItem)temp);
} else{
toDoItemList.add(temp);
}
}
}
/**
* Gets the Storage instance.
* @return The only Storage instance of this class.
*/
public static Storage getInstance(){
if(storage==null)
storage = new Storage();
return storage;
}
/**
* Adds the given item to the list. For use by CommandDelete's undo method.
* @param item The ToDoItem to be added to the list.
* @return The TodoItem that is added to the list.
*/
public ToDoItem addItem(ToDoItem item){
//item must not be null.
assert item!=null;
mainList.add(item);
searchTree.put(item.getId(), item);
if(item instanceof TaskItem){
taskList.add((TaskItem)item);
} else if(item instanceof EventItem){
eventList.add((EventItem)item);
} else{
toDoItemList.add(item);
}
Thread writeToFile = new WriteToFileThread(mainList.toArray(new ToDoItem[mainList.size()]), OUTPUT_FILENAME);
writeToFile.run();
return item;
}
public ToDoItem[] updateItem(String id, String description, int priority, MyDate start, MyDate end) {
assert id!=null && !id.isEmpty();
ToDoItem[] list = new ToDoItem[2];
ToDoItem target = searchTree.get(id);
if(target==null){
throw new IllegalArgumentException("No such ID");
}
//Makes a copy of the current version of the object
list[0] = makeCopy(target);
if(description!=null && !description.isEmpty()){
target.setDescription(description);
}
if(ToDoItem.isValidPriority(priority)){
target.setPriority(priority);
}
if(start!=null && !(target instanceof EventItem)){
if(target instanceof TaskItem){
target = new EventItem((TaskItem)target, start);
} else{
target = new EventItem(target, start);
}
removeItem(target.getId());
addItem(target);
} else if(start!=null){
((EventItem)target).setStartDate(start);
}
if(end!=null){
if(target instanceof EventItem){
((EventItem)target).setEndDate(end);
} else if(target instanceof TaskItem){
((TaskItem)target).setDeadline(end);
} else{
target = new TaskItem(target, end);
removeItem(target.getId());
addItem(target);
}
}
list[1] = target;
Thread writeToFile = new WriteToFileThread(mainList.toArray(new ToDoItem[mainList.size()]), OUTPUT_FILENAME);
writeToFile.run();
return list;
}
/**
* Gets a list of ToDoItem objects whose description contains this keyword.
* @param keyword The keyword to search in the objects or null if no search by keyword is needed.
* @param priority The priority level to the item(s) to search or -1 if not needed.
* @param start the start date of the item(s) to search or null if search by start date is not needed.
* @param end The end date of the item(s) t search or null if search by end date is not needed.
* @param optList The list of options(in descending precedence) to sort search results by.
* @return An array of ToDoItem objects containing all of the given values or null
* if the list is empty.
*/
public ToDoItem[] searchItems(String keyword, int priority, MyDate start, MyDate end, OptionType[] optList){
ArrayList<ToDoItem> temp = mainList;;
if(keyword!=null && !keyword.isEmpty()){
temp = searchByKeyword(temp, keyword);
}
if(priority!=-1){
temp = searchByPriority(temp, priority);
}
if(start!=null){
temp = searchByStartDate(temp, start);
}
if(end!=null){
temp = searchByEndDate(temp, end);
}
if(temp.isEmpty()){
return null;
}
if(optList!=null){
int size = optList.length;
while(size
sortListByOption(temp, optList[size]);
}
}
return temp.toArray(new ToDoItem[temp.size()]);
}
/**
* Gets a list of items with the keyword in their description from the given list.
* @param list The list to perform search on.
* @return An ArrayList of ToDoItem objects whose description contain the keyword.
*/
private ArrayList<ToDoItem> searchByKeyword(ArrayList<ToDoItem> list, String keyword){
assert list!=null && keyword!=null && !keyword.isEmpty();
ArrayList<ToDoItem> temp = new ArrayList<ToDoItem>();
for(ToDoItem i: list){
if(i.getDescription().contains(keyword)){
temp.add(i);
}
}
return temp;
}
/**
* Gets a list of items with the given priority from the given list.
* @param list The list to perform search on.
* @param priority The priority value used to filter the items.
* @return An Arraylist of ToDoItem objects with the given priority level.
*/
private ArrayList<ToDoItem> searchByPriority(ArrayList<ToDoItem> list, int priority){
assert list!=null && priority>=0;
ArrayList<ToDoItem> temp = new ArrayList<ToDoItem>();
for(ToDoItem i: list){
if(i.getPriority()==priority){
temp.add(i);
}
}
return temp;
}
/**
* Gets a list of items with the given start date drom the given list.
* @param list The list to perform search on.
* @param start The start date value to search.
* @return An ArrayList of ToDoItem objects with the given start date.
*/
private ArrayList<ToDoItem> searchByStartDate(ArrayList<ToDoItem> list, MyDate start){
assert start!=null && list!=null;
ArrayList<ToDoItem> temp = new ArrayList<>();
for(ToDoItem i: list){
if((i instanceof EventItem) && ((EventItem)i).getStartDate().equals(start)){
temp.add(i);
}
}
return temp;
}
/**
* Gets a list of items with the given end date/deadline.
* @param list The list to perform search on.
* @param end The end date/deadline value to search.
*/
private ArrayList<ToDoItem> searchByEndDate(ArrayList<ToDoItem> list, MyDate end){
assert list!=null && end!=null;
ArrayList<ToDoItem> temp = new ArrayList<ToDoItem>();
for(ToDoItem i: list){
if(((i instanceof EventItem) && ((EventItem)i).getEndDate().equals(end)) ||
((i instanceof TaskItem) && ((TaskItem)i).getDeadline().equals(end))){
temp.add(i);
}
}
return temp;
}
/**
* Gets the list of tasks and events in an array sorted according to optionsList.
* @param options The list of data fields to sort the list by in descending order of precedence
* or null if no other sorting criteria is required.
* Eg. {a, b} means most importantly, sort by a. For all items with same value of a, sort by b.
* @return An array of ToDoItem objects sorted according to sorting criteria or null
* if the storage has no item.
*/
private ToDoItem[] getList(OptionType[] options){
if(mainList.isEmpty()){
return null;
}
Collections.sort(mainList);
if(options!=null){
int size = options.length;
while(size
sortListByOption(mainList, options[size]);
}
}
return mainList.toArray(new ToDoItem[mainList.size()]);
}
/**
* Gets the list of items filtered using the given field values, sorted using the given options list
* in descending order of precedence. If no filtering values are used at all, the full list of items
* will be returned instead.
* @param priority The list of priority values used for filtering or null if not used.
* @param start The list of start dates used for filtering or null if not used.
* @param end The list of end dates used for filtering or null if not used.
* @param options The list of field types in descending order of precedence used to sort the list.
* @return A filtered array of ToDoItem sorted using options.
*/
public ToDoItem[] getList(int[] priority, MyDate[] start, MyDate[] end, OptionType[] options){
if(priority==null && start==null && end==null){
return getList(options);
}
ArrayList<ToDoItem> temp = new ArrayList<ToDoItem>(); //To hold the resulting list
//Use BST for log(N) search time.
TreeSet<Integer> priorityList = new TreeSet<Integer>();
TreeSet<MyDate> startList = new TreeSet<MyDate>();
TreeSet<MyDate> endList = new TreeSet<MyDate>();
//Fills the hash tables with distinct values(if applicable).
if(priority!=null){
for(int i: priority){
if(!priorityList.contains(i)){
priorityList.add(i);
}
}
}
if(start!=null){
for(MyDate i: start){
if(!startList.contains(i)){
startList.add(i);
}
}
}
if(end!=null){
for(MyDate i: end){
if(!endList.contains(i)){
endList.add(i);
}
}
}
//Performs big union(OR) filtering by values.
Iterator<ToDoItem> itr = mainList.iterator();
ToDoItem item;
while(itr.hasNext()){
item = itr.next();
if(priorityList.contains(item.getPriority())){
temp.add(item);
continue;
}
if((item instanceof EventItem)){
if((startList.contains(((EventItem)item).getStartDate())) ||
endList.contains(endList.contains(((EventItem)item).getEndDate()))){
temp.add(item);
continue;
}
} else if((item instanceof TaskItem) && endList.contains(((TaskItem)item).getDeadline())){
temp.add(item);
continue;
}
}
//Sorts the filtered list.
Collections.sort(temp);
if(options!=null){
int size = options.length;
while(size
sortListByOption(temp, options[size]);
}
}
//Returns the filtered list as an array.
if(temp.isEmpty()){
return null;
}
return temp.toArray(new ToDoItem[temp.size()]);
}
/**
* Sorts the given list by the given option type.
* @param list The list to sort.
* @optType The option to sort the list by.
*/
private void sortListByOption(ArrayList<ToDoItem> list, OptionType optType){
switch(optType){
case PRIORITY: Collections.sort(list, Collections.reverseOrder(new PriorityComparator()));
break;
case START_TIME: Collections.sort(list, new StartDateComparator());
break;
case END_TIME: Collections.sort(list, new EndDateComparator());
break;
default: break;
}
}
/**
* Returns a list of events sorted in lexicographical order of their ID.
* @return An array of EventItem objects sorted in lexicographical order of their ID
* or null if the list is empty.
*/
public EventItem[] getEvents(){
if(eventList.isEmpty()){
return null;
}
return eventList.toArray(new EventItem[eventList.size()]);
}
/**
* Returns a list of deadline tasks in lexicographical order or their ID.
* @return An array of TaskItem objects sorted in lexicographical order of their ID
* or null if the list is empty.
*/
public TaskItem[] getTasks(){
if(taskList.isEmpty()){
return null;
}
return taskList.toArray(new TaskItem[taskList.size()]);
}
/**
* Gets the list of events sorted in ascending order of start date.
* @return An array of EventItem sorted in ascending order by start date
* or null if the list is empty.
* Implementation is currently only a stub, to be properly implemented when use case requirements
* are confirmed.
*/
public EventItem[] getEventsSortedByStartDate(){
if(eventList.isEmpty()){
return null;
}
Collections.sort(eventList, new StartDateComparator());
return eventList.toArray(new EventItem[eventList.size()]);
}
/**
* Gets the list of events sorted in ascending order of end date.
* @return An array of EventItem sorted in ascending order by start date
* or null if the list is empty.
* Implementation is currently only a stub, to be properly implemented when use case requirements
* are confirmed.
*/
public EventItem[] getEventsSortedByEndDate(){
if(eventList.isEmpty()){
return null;
}
Collections.sort(eventList, new EndDateComparator());
return eventList.toArray(new EventItem[eventList.size()]);
}
/**
* Gets the list of deadline tasks sorted in ascending order of their deadlines.
* @return An array of TaskItem objects sorted in ascending order of their deadlines.
*/
public TaskItem[] getTasksSortedByDeadline(){
if(taskList.isEmpty()){
return null;
}
Collections.sort(taskList, new EndDateComparator());
return taskList.toArray(new TaskItem[taskList.size()]);
}
public ToDoItem removeItem(String id){
assert id!=null && !id.isEmpty();
ToDoItem temp = searchTree.remove(id);
if(temp==null){
throw new IllegalArgumentException("No such ID.");
}
mainList.remove(temp);
if(temp instanceof TaskItem){
taskList.remove((TaskItem)temp);
} else if(temp instanceof EventItem){
eventList.remove((EventItem)temp);
} else{
toDoItemList.remove(temp);
}
Thread writeToFile = new WriteToFileThread(mainList.toArray(new ToDoItem[mainList.size()]), OUTPUT_FILENAME);
writeToFile.run();
return temp;
}
public ToDoItem completeItem(String id){
ToDoItem item = removeItem(id);
if(item!=null){
if(completedList==null){
completedList = DataFileReadWrite.getTextFileContentByLine(COMPLETED_FILENAME);
}
completedBuffer.push(item);
item = makeCopy(item);
item.setStatus(ToDoItem.STATUS_COMPLETED);
completedList.add(item.toFileString());
Thread writeToFile = new WriteToFileThread(completedList.toArray(new String[completedList.size()]), COMPLETED_FILENAME);
writeToFile.run();
}
return item;
}
/**
* Unmark the most recent item that is marked completed.
* Should only be called after a call to completeItem() method and number of calls
* to this method should not exceed that of completeItem() method.
* @return The ToDoItem object that is unmarked from completed list.
*/
public ToDoItem undoComplete(){
assert completedList!=null && !completedBuffer.isEmpty();
ToDoItem temp = completedBuffer.pop();
completedList.remove(completedList.size()-1); //The item being removed is always the last element
//as it is the most recently added item.
addItem(temp);
Thread writeToFile = new WriteToFileThread(completedList.toArray(new String[completedList.size()]), COMPLETED_FILENAME);
writeToFile.run();
return temp;
}
//Creates a duplicate copy of the given item.
private ToDoItem makeCopy(ToDoItem item){
assert item!=null;
if(item instanceof EventItem){
return new EventItem((EventItem)item);
} else if(item instanceof TaskItem){
return new TaskItem((TaskItem)item);
} else{
return new ToDoItem(item);
}
}
}
|
package edu.mit.streamjit.test.apps;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.UnmodifiableIterator;
import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider;
import edu.mit.streamjit.api.DuplicateSplitter;
import edu.mit.streamjit.api.Filter;
import edu.mit.streamjit.api.Identity;
import edu.mit.streamjit.api.Input;
import edu.mit.streamjit.api.OneToOneElement;
import edu.mit.streamjit.api.Pipeline;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitjoin;
import edu.mit.streamjit.api.StatefulFilter;
import edu.mit.streamjit.api.StreamCompiler;
import edu.mit.streamjit.api.WeightedRoundrobinJoiner;
import edu.mit.streamjit.api.WeightedRoundrobinSplitter;
import edu.mit.streamjit.impl.interp.DebugStreamCompiler;
import edu.mit.streamjit.test.Benchmark;
import edu.mit.streamjit.test.Benchmarker;
import edu.mit.streamjit.test.Datasets;
import edu.mit.streamjit.test.SuppliedBenchmark;
import java.nio.ByteOrder;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
/**
* Ported from streams/apps/benchmarks/asplos06/vocoder/streamit/VocoderTopLevel.str
*
* TODO: to verify this against classic StreamIt, implement prework in
* FirstDifference.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 2/11/2014
*/
public final class Vocoder {
private Vocoder() {}
public static void main(String[] args) throws InterruptedException {
StreamCompiler sc = new DebugStreamCompiler();
Benchmarker.runBenchmark(new VocoderBenchmark(), sc).get(0).print(System.out);
}
@ServiceProvider(Benchmark.class)
public static final class VocoderBenchmark extends SuppliedBenchmark {
private static final int COPIES = 1;
private static final Iterable<Integer> INPUT = ImmutableList.copyOf(Iterables.concat(
//simulating a Delay filter's prework
Collections.nCopies(VocoderTopLevel.DFT_LENGTH_NOM, 0),
//limit based on VocoderExample.in, not relevant to
//VocoderTopLevel.str, which takes its input from a StepSource
//source filter
Iterables.limit(new StepSource(100), 10000)
));
public VocoderBenchmark() {
super("Vocoder", VocoderTopLevel.class, new Dataset("StepSource", (Input)Datasets.nCopies(COPIES, (Input)Input.fromIterable(INPUT))
//classic StreamIt runs forever here, so length will vary.
// , (Supplier)Suppliers.ofInstance((Input)Input.fromBinaryFile(Paths.get("/home/jbosboom/streamit/streams/apps/benchmarks/asplos06/vocoder/streamit/VocoderTopLevel.out"), Integer.class, ByteOrder.LITTLE_ENDIAN))
));
}
}
private static final class VocoderTopLevel extends Pipeline<Float, Float> {
private static final int DFT_LENGTH_NOM = 28;
private static final int DFT_LENGTH = DFT_LENGTH_NOM/2 + 1;
private static final float FREQUENCY_FACTOR = 0.6f;
private static final float GLOTTAL_EXPANSION = 1f/1.2f;
private static final int NEW_LENGTH = (int)(DFT_LENGTH * GLOTTAL_EXPANSION / FREQUENCY_FACTOR);
private static final int DFT_LENGTH_REDUCED = 3;
private static final int NEW_LENGTH_REDUCED = 4;
private static final float SPEED_FACTOR = 1.0f;
private static final int n_LENGTH = 1;
private static final int m_LENGTH = 1;
public VocoderTopLevel() {
super(new IntToFloat(),
//TODO prework; for now prepended to input
//new Delay(DFT_LENGTH_NOM),
new FilterBank(DFT_LENGTH_NOM),
new RectangularToPolar(),
new Splitjoin<Float, Float>(new RoundrobinSplitter<Float>(), new RoundrobinJoiner<Float>(),
new MagnitudeStuff(DFT_LENGTH_REDUCED, NEW_LENGTH_REDUCED, m_LENGTH, n_LENGTH, DFT_LENGTH, NEW_LENGTH, SPEED_FACTOR),
new PhaseStuff(n_LENGTH, m_LENGTH, DFT_LENGTH_REDUCED, NEW_LENGTH_REDUCED, DFT_LENGTH, NEW_LENGTH, FREQUENCY_FACTOR, SPEED_FACTOR)
),
new PolarToRectangular(),
new SumReals(NEW_LENGTH),
new InvDelay((DFT_LENGTH - 2) * m_LENGTH / n_LENGTH),
new FloatToShort()
);
}
}
private static final class IntToFloat extends Filter<Integer, Float> {
private IntToFloat() {
super(1, 1);
}
@Override
public void work() {
push(pop().floatValue());
}
}
private static final class FilterBank extends Splitjoin<Float, Float> {
private FilterBank(int channels) {
super(new DuplicateSplitter<Float>(), new RoundrobinJoiner<Float>(2));
for (int k = 0; k <= channels/2; ++k)
add(new DFTFilter(channels, (float)(2*Math.PI*k/channels)));
}
}
private static final class DFTFilter extends StatefulFilter<Float, Float> {
private final int DFTLen;
//the rate by which to deteriorate, assuring stability
private final float deter;
//since the previous complex value is multiplied by the deter each
//time, by the time the last time sample is windowed out it's
//effect will have been multiplied by deter DFTLen times, hence it
//needs to be multiplied by deter^DFTLen before being subtracted
private final float detern;
private final float wR, wI; //represents w^(-k)
private float prevR, prevI;
private float nextR, nextI;
private DFTFilter(int DFTLen, float range) {
super(1, 2, DFTLen+1);
this.DFTLen = DFTLen;
deter = 0.999999f;
detern = 1.0f;
wR = (float)Math.cos(range);
wI = (float)-Math.sin(range);
prevR = 0;
prevI = 0;
}
@Override
public void work() {
float nextVal = peek(DFTLen);
float current = pop();
prevR = prevR * deter + (nextVal - (detern * current));
prevI = prevI * deter;
nextR = prevR * wR - prevI * wI;
nextI = prevR * wI + prevI * wR;
prevR = nextR;
prevI = nextI;
push(prevR);
push(prevI);
}
}
private static final class RectangularToPolar extends Filter<Float, Float> {
private RectangularToPolar() {
super(2, 2);
}
@Override
public void work() {
float x = pop();
float y = pop();
float r = (float)Math.sqrt(x * x + y * y);
float theta = (float)Math.atan2(y, x);
push(r);
push(theta);
}
}
private static final class MagnitudeStuff extends Pipeline<Float, Float> {
private MagnitudeStuff(int DFTLen_red, int newLen_red, int n_len, int m_len, int DFTLen, int newLen, float speed) {
super();
if (DFTLen != newLen) {
add(new Splitjoin<Float, Float>(new DuplicateSplitter<Float>(), new RoundrobinJoiner<Float>(),
new FIRSmoothingFilter(DFTLen),
new Identity<Float>()));
add(new Deconvolve());
add(new Splitjoin<Float, Float>(new RoundrobinSplitter<Float>(), new RoundrobinJoiner<Float>(),
new Duplicator(DFTLen_red, newLen_red),
Remapper(DFTLen_red, newLen_red)));
add(new Multiplier());
}
if (speed != 1.0) {
Splitjoin<Float, Float> sj = new Splitjoin<>(new RoundrobinSplitter<Float>(), new RoundrobinJoiner<Float>());
for(int i=0; i<DFTLen; i++)
sj.add(Remapper(n_len, m_len));
add(sj);
} else
add(new Identity<Float>());
}
}
private static final class FIRSmoothingFilter extends Filter<Float, Float> {
private static final float[] cosWin = {0.1951f, 0.3827f, 0.5556f, 0.7071f, 0.8315f, 0.9239f, 0.9808f, 1.0000f, 0.9808f, 0.9239f, 0.8315f, 0.7071f, 0.5556f, 0.3827f, 0.1951f};
private static final int offset = cosWin.length / 2;
private final int DFTLen;
private FIRSmoothingFilter(int DFTLen) {
super(DFTLen, DFTLen, cosWin.length);
this.DFTLen = DFTLen;
}
@Override
public void work() {
//note that h[k] = h[i + off]
for (int n = 0; n < DFTLen; n++) {
float y = 0;
for (int k = 0; k < cosWin.length; k++) {
int i = k - offset; //so that when i = 0, k will be at the center
if (((n - i) >= 0) && ((n - i) < DFTLen))
y += peek(n - i) * cosWin[k];
}
push(y);
}
for (int i = 0; i < DFTLen; i++)
pop();
}
}
private static final class Deconvolve extends Filter<Float, Float> {
private Deconvolve() {
super(2, 2);
}
@Override
public void work() {
float den = pop();
float num = pop();
push(den);
if (den == 0.0)
push(0.0f);
else
push(num / den);
}
}
private static final class Duplicator extends Filter<Float, Float> {
private final int oldLen, newLen;
private Duplicator(int oldLen, int newLen) {
super(oldLen, newLen);
this.oldLen = oldLen;
this.newLen = newLen;
}
@Override
public void work() {
if (newLen <= oldLen) {
for (int i = 0; i < newLen; i++)
push(pop());
for (int i = newLen; i < oldLen; i++)
pop();
} else {
//TODO: use peeking instead.
float[] orig = new float[oldLen];
for (int i = 0; i < oldLen; i++)
orig[i] = pop();
for (int i = 0; i < newLen; i++)
push(orig[i % oldLen]);
}
}
}
private static OneToOneElement<Float, Float> Remapper(int oldLen, int newLen) {
if (oldLen == newLen)
return new Identity<Float>();
Pipeline<Float, Float> p = new Pipeline<>();
if (newLen != 1)
p.add(new LinearInterpolator(newLen));
if (oldLen != 1)
p.add(new Decimator(oldLen));
return p;
}
private static final class LinearInterpolator extends Filter<Float, Float> {
private final int interp;
private LinearInterpolator(int interp) {
super(1, interp, 2);
this.interp = interp;
}
@Override
public void work() {
float base = pop();
float diff = peek(0) - base;
float interp_f = (float)interp;
float i_f;
push(base);
//already pushed 1, so just push another (interp - 1) floats
for (int i = 1; i < interp; i++) {
i_f = (float)i;
push(base + (i_f / interp_f) * diff);
}
}
}
private static final class Decimator extends Filter<Float, Float> {
private final int decim;
private Decimator(int decim) {
super(decim, 1);
this.decim = decim;
}
@Override
public void work() {
push(pop());
//for(int goal=decim-1; goal>0; goal--)
// pop();
for (int goal = 0; goal < decim - 1; goal++)
pop();
}
}
private static final class Multiplier extends Filter<Float, Float> {
private Multiplier() {
super(2, 1);
}
@Override
public void work() {
push(pop()*pop());
}
}
private static final class PhaseStuff extends Pipeline<Float, Float> {
private PhaseStuff(int n_len, int m_len, int DFTLen_red, int newLen_red, int DFTLen, int newLen, float c, float speed) {
super();
if (speed != 1.0 || c != 1.0) {
Splitjoin<Float, Float> sj = new Splitjoin<>(new RoundrobinSplitter<Float>(), new RoundrobinJoiner<Float>());
for (int i = 0; i < DFTLen; ++i)
sj.add(new InnerPhaseStuff(n_len, m_len, c, speed));
add(sj);
}
if (newLen != DFTLen)
add(new Duplicator(DFTLen_red, newLen_red));
else
add(new Identity<Float>());
}
}
private static final class InnerPhaseStuff extends Pipeline<Float, Float> {
private InnerPhaseStuff(int n_len, int m_len, float c, float speed) {
super();
add(new PhaseUnwrapper());
add(new FirstDifference());
if (c != 1.0)
add(new ConstMultiplier(c));
if (speed != 1.0)
add(Remapper(n_len, m_len));
add(new Accumulator());
}
}
/**
* Porting note: unused 'estimate' field removed.
*/
private static final class PhaseUnwrapper extends StatefulFilter<Float, Float> {
private static final float pi = (float)Math.PI;
private float previous = 0;
private PhaseUnwrapper() {
super(1, 1);
}
@Override
public void work() {
float unwrapped = pop();
float delta = unwrapped - previous;
while (delta > 2 * pi * (11.0 / 16.0)) {
unwrapped -= 2 * pi;
delta -= 2 * pi;
}
while (delta < -2 * pi * (11.0 / 16.0)) {
unwrapped += 2 * pi;
delta += 2 * pi;
}
previous = unwrapped;
push(unwrapped);
}
}
private static final class FirstDifference extends Filter<Float, Float> {
private FirstDifference() {
super(1, 1, 2);
}
// //TODO
// public void prework() {
// push(peek(0));
@Override
public void work() {
push(peek(1) - peek(0));
pop();
}
}
private static final class ConstMultiplier extends Filter<Float, Float> {
private final float mult;
private ConstMultiplier(float mult) {
super(1, 1);
this.mult = mult;
}
@Override
public void work() {
push(pop() * mult);
}
}
private static final class Accumulator extends StatefulFilter<Float, Float> {
private float val = 0;
private Accumulator() {
super(1, 1);
}
@Override
public void work() {
val += pop();
push(val);
}
}
private static final class PolarToRectangular extends Filter<Float, Float> {
private PolarToRectangular() {
super(2, 2);
}
@Override
public void work() {
float r = pop();
float theta = pop();
push(r * (float)Math.cos(theta));
push(r * (float)Math.sin(theta));
}
}
private static final class SumReals extends Splitjoin<Float, Float> {
private SumReals(int DFTLen) {
super(new RoundrobinSplitter<Float>(), new WeightedRoundrobinJoiner<Float>(1, 0),
new SumRealsRealHandler(DFTLen),
new FloatVoid());
}
}
private static final class SumRealsRealHandler extends Pipeline<Float, Float> {
private SumRealsRealHandler(int DFTLen) {
super();
add(new Splitjoin<Float, Float>(new WeightedRoundrobinSplitter<Float>(1, DFTLen-2, 1), new WeightedRoundrobinJoiner<Float>(1, DFTLen-2, 1),
new Identity<Float>(),
new Doubler(),
new Identity<Float>()));
if ((DFTLen % 2) != 0)
add(new Padder(DFTLen, 0, 1));
add(new Splitjoin<Float, Float>(new RoundrobinSplitter<Float>(), new RoundrobinJoiner<Float>(),
new Adder((DFTLen+1)/2),
new Adder((DFTLen+1)/2)));
add(new Subtractor());
add(new ConstMultiplier((float)(1.0/((DFTLen-1)*2))));
}
}
private static final class Doubler extends Filter<Float, Float> {
private Doubler() {
super(1, 1);
}
@Override
public void work() {
float x = pop();
push(x+x);
}
}
private static final class Padder extends Filter<Float, Float> {
private final int length, front, back;
private Padder(int length, int front, int back) {
super(length+front+back, length);
this.length = length;
this.front = front;
this.back = back;
}
@Override
public void work() {
for(int i = 0; i < front; i++)
push(0.0f);
for (int i = 0; i < length; i++)
push(pop());
for (int i = 0; i < back; i++)
push(0.0f);
}
}
private static final class Adder extends Filter<Float, Float> {
private final int length;
private Adder(int length) {
super(length, 1);
this.length = length;
}
@Override
public void work() {
float val = 0;
for (int i = 0; i < length; i++)
val += pop();
push(val);
}
}
private static final class Subtractor extends Filter<Float, Float> {
private Subtractor() {
super(2, 1);
}
@Override
public void work() {
push(pop() - pop());
}
}
private static final class FloatVoid extends Filter<Float, Float> {
private FloatVoid() {
super(1, 0);
}
@Override
public void work() {
pop();
}
}
private static final class InvDelay extends Filter<Float, Float> {
//TODO: prework that throws away the delay elements?
private final int n;
private InvDelay(int N) {
super(1, 1, N+1);
this.n = N;
}
@Override
public void work() {
push(peek(n));
pop();
}
}
private static final class FloatToShort extends Filter<Float, Integer> {
private FloatToShort() {
super(1, 1);
}
@Override
public void work() {
int s;
float fs = pop() + 0.5f;
fs = (fs > 32767.0f ? 32767.0f : (fs < -32767.0f ? -32767.0f : fs));
s = (int)fs;
push(s);
}
}
private static final class StepSource implements Iterable<Integer> {
private final int length;
private StepSource(int length) {
this.length = length;
}
@Override
public Iterator<Integer> iterator() {
return new UnmodifiableIterator<Integer>() {
private int x = 1;
private boolean up = true;
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
if (x == length)
up = false;
else if (x == 0)
up = true;
if (up)
return x++;
else
return x
}
};
}
}
}
|
package controllers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.Expression;
import com.avaje.ebean.FetchConfig;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;
import com.avaje.ebean.SqlUpdate;
import com.csvreader.CsvWriter;
import com.ecwid.mailchimp.*;
import com.ecwid.mailchimp.method.v2_0.lists.ListMethodResult;
import com.feth.play.module.pa.PlayAuthenticate;
import models.*;
import play.*;
import play.data.*;
import play.libs.Json;
import play.mvc.*;
import play.mvc.Http.Context;
@With(DumpOnError.class)
@Secured.Auth(UserRole.ROLE_ALL_ACCESS)
public class CRM extends Controller {
static Form<Person> personForm = Form.form(Person.class);
static Form<Comment> commentForm = Form.form(Comment.class);
static Form<Donation> donationForm = Form.form(Donation.class);
public static final String CACHE_RECENT_COMMENTS = "CRM-recentComments-";
public static Result recentComments() {
return ok(views.html.cached_page.render(
new CachedPage(CACHE_RECENT_COMMENTS,
"All people",
"crm",
"recent_comments") {
@Override
String render() {
List<Comment> recent_comments = Comment.find
.fetch("person")
.fetch("completed_tasks", new FetchConfig().query())
.fetch("completed_tasks.task", new FetchConfig().query())
.where().eq("person.organization", Organization.getByHost())
.orderBy("created DESC").setMaxRows(20).findList();
return views.html.people_index.render(recent_comments).toString();
}
}));
}
public static Result person(Integer id) {
Person the_person = Person.findById(id);
List<Person> family_members =
Person.find.where().isNotNull("family").eq("family", the_person.family).
ne("person_id", the_person.person_id).findList();
Set<Integer> family_ids = new HashSet<Integer>();
family_ids.add(the_person.person_id);
for (Person family : family_members) {
family_ids.add(family.person_id);
}
List<Comment> all_comments = Comment.find.where().in("person_id", family_ids).
order("created DESC").findList();
List<Donation> all_donations = Donation.find.where().in("person_id", family_ids).
order("date DESC").findList();
String comment_destination = "<No email set>";
boolean first = true;
for (NotificationRule rule :
NotificationRule.findByType(NotificationRule.TYPE_COMMENT)) {
if (first) {
comment_destination = rule.email;
first = false;
} else {
comment_destination += ", " + rule.email;
}
}
return ok(views.html.family.render(
the_person,
family_members,
all_comments,
comment_destination,
all_donations));
}
public static Result jsonPeople(String query) {
Expression search_expr = null;
HashSet<Person> selected_people = new HashSet<Person>();
boolean first_time = true;
for (String term : query.split(" ")) {
List<Person> people_matched_this_round;
Expression this_expr =
Expr.or(Expr.ilike("last_name", "%" + term + "%"),
Expr.ilike("first_name", "%" + term + "%"));
this_expr = Expr.or(this_expr,
Expr.ilike("address", "%" + term + "%"));
this_expr = Expr.or(this_expr,
Expr.ilike("email", "%" + term + "%"));
people_matched_this_round =
Person.find.where().add(this_expr)
.eq("organization", Organization.getByHost())
.eq("is_family", false)
.findList();
List<PhoneNumber> phone_numbers =
PhoneNumber.find.where().ilike("number", "%" + term + "%")
.eq("owner.organization", Organization.getByHost())
.findList();
for (PhoneNumber pn : phone_numbers) {
people_matched_this_round.add(pn.owner);
}
if (first_time) {
selected_people.addAll(people_matched_this_round);
} else {
selected_people.retainAll(people_matched_this_round);
}
first_time = false;
}
List<Map<String, String> > result = new ArrayList<Map<String, String> > ();
for (Person p : selected_people) {
HashMap<String, String> values = new HashMap<String, String>();
String label = p.first_name;
if (p.last_name != null) {
label = label + " " + p.last_name;
}
values.put("label", label);
values.put("id", "" + p.person_id);
result.add(values);
}
return ok(Json.stringify(Json.toJson(result)));
}
// personId should be -1 if the client doesn't care about a particular
// person, but just wants a list of available tags. In that case,
// the "create new tag" functionality is also disabled.
public static Result jsonTags(String term, Integer personId) {
String like_arg = "%" + term + "%";
List<Tag> selected_tags =
Tag.find.where()
.eq("organization", Organization.getByHost())
.ilike("title", "%" + term + "%").findList();
List<Tag> existing_tags = null;
if (personId >= 0) {
Person p = Person.findById(personId);
if (p != null) {
existing_tags = p.tags;
}
}
List<Map<String, String> > result = new ArrayList<Map<String, String> > ();
for (Tag t : selected_tags) {
if (existing_tags == null || !existing_tags.contains(t)) {
HashMap<String, String> values = new HashMap<String, String>();
values.put("label", t.title);
values.put("id", "" + t.id);
result.add(values);
}
}
boolean tag_already_exists = false;
for (Tag t : selected_tags) {
if (t.title.toLowerCase().equals(term.toLowerCase())) {
tag_already_exists = true;
}
}
if (personId >= 0 && !tag_already_exists) {
HashMap<String, String> values = new HashMap<String, String>();
values.put("label", "Create new tag: " + term);
values.put("id", "-1");
result.add(values);
}
return ok(Json.stringify(Json.toJson(result)));
}
public static Collection<Person> getTagMembers(Integer tagId, String familyMode) {
List<Person> people = Tag.findById(tagId).people;
Set<Person> selected_people = new HashSet<Person>();
selected_people.addAll(people);
if (!familyMode.equals("just_tags")) {
for (Person p : people) {
if (p.family != null) {
selected_people.addAll(p.family.family_members);
}
}
}
if (familyMode.equals("family_no_kids")) {
Set<Person> no_kids = new HashSet<Person>();
for (Person p2 : selected_people) {
if (p2.dob == null ||
CRM.calcAge(p2) > 18) {
no_kids.add(p2);
}
}
selected_people = no_kids;
}
return selected_people;
}
public static Result renderTagMembers(Integer tagId, String familyMode) {
Tag the_tag = Tag.findById(tagId);
return ok(views.html.to_address_fragment.render(the_tag.title,
getTagMembers(tagId, familyMode)));
}
public static Result addTag(Integer tagId, String title, Integer personId) {
CachedPage.remove(Application.CACHE_INDEX);
CachedPage.remove(Attendance.CACHE_INDEX);
Person p = Person.findById(personId);
if (p == null) {
return badRequest();
}
Tag the_tag;
if (tagId == null) {
the_tag = Tag.create(title);
} else {
the_tag = Tag.find.ref(tagId);
}
PersonTag pt = PersonTag.create(the_tag, p);
PersonTagChange ptc = PersonTagChange.create(
the_tag,
p,
Application.getCurrentUser(),
true);
p.tags.add(the_tag);
notifyAboutTag(the_tag, p, true);
return ok(views.html.tag_fragment.render(the_tag, p));
}
public static Result removeTag(Integer person_id, Integer tag_id) {
Tag t = Tag.findById(tag_id);
Person p = Person.findById(person_id);
if (Ebean.createSqlUpdate("DELETE from person_tag where person_id=" + person_id +
" AND tag_id=" + tag_id).execute() == 1) {
PersonTagChange ptc = PersonTagChange.create(
t,
p,
Application.getCurrentUser(),
false);
}
notifyAboutTag(t, p, false);
return ok();
}
public static void notifyAboutTag(Tag t, Person p, boolean was_add) {
for (NotificationRule rule : t.notification_rules) {
play.libs.mailer.Email mail = new play.libs.mailer.Email();
if (was_add) {
mail.setSubject(getInitials(p) + " added to tag " + t.title);
} else {
mail.setSubject(getInitials(p) + " removed from tag " + t.title);
}
mail.addTo(rule.email);
mail.setFrom("DemSchoolTools <noreply@demschooltools.com>");
mail.setBodyHtml(views.html.tag_email.render(t, p, was_add).toString());
play.libs.mailer.MailerPlugin.send(mail);
}
}
public static Result allPeople() {
return ok(views.html.all_people.render(Person.all()));
}
public static Result viewTag(Integer id) {
Tag the_tag = Tag.find
.fetch("people")
.fetch("people.phone_numbers", new FetchConfig().query())
.where().eq("organization", Organization.getByHost())
.eq("id", id).findUnique();
List<Person> people = the_tag.people;
Set<Person> people_with_family = new HashSet<Person>();
for (Person p : people) {
if (p.family != null) {
people_with_family.addAll(p.family.family_members);
}
}
return ok(views.html.tag.render(
the_tag, people, people_with_family, the_tag.use_student_display));
}
public static Result downloadTag(Integer id) throws IOException {
Tag the_tag = Tag.find
.fetch("people")
.fetch("people.phone_numbers", new FetchConfig().query())
.where().eq("organization", Organization.getByHost())
.eq("id", id).findUnique();
response().setHeader("Content-Type", "text/csv; charset=utf-8");
response().setHeader("Content-Disposition", "attachment; filename=" +
the_tag.title + ".csv");
List<Person> people = the_tag.people;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Charset charset = Charset.forName("UTF-8");
CsvWriter writer = new CsvWriter(baos, ',', charset);
writer.write("First name");
writer.write("Last name");
writer.write("Display (JC) name");
writer.write("Gender");
writer.write("DOB");
writer.write("Email");
writer.write("Phone 1");
writer.write("Phone 1 comment");
writer.write("Phone 2");
writer.write("Phone 2 comment");
writer.write("Phone 3");
writer.write("Phone 3 comment");
writer.write("Neighborhood");
writer.write("Street");
writer.write("City");
writer.write("State");
writer.write("ZIP");
writer.write("Notes");
writer.write("Previous school");
writer.write("School district");
writer.write("Grade");
writer.endRecord();
for (Person p : people) {
writer.write(p.first_name);
writer.write(p.last_name);
writer.write(p.getDisplayName());
writer.write(p.gender);
if (p.dob != null) {
writer.write(Application.yymmddDate(p.dob));
} else {
writer.write("");
}
writer.write(p.email);
for (int i = 0; i < 3; i++) {
if (i < p.phone_numbers.size()) {
writer.write(p.phone_numbers.get(i).number);
writer.write(p.phone_numbers.get(i).comment);
} else {
writer.write("");
writer.write("");
}
}
writer.write(p.neighborhood);
writer.write(p.address);
writer.write(p.city);
writer.write(p.state);
writer.write(p.zip);
writer.write(p.notes);
writer.write(p.previous_school);
writer.write(p.school_district);
writer.write(p.grade);
writer.endRecord();
}
writer.close();
// Adding the BOM here causes Excel 2010 on Windows to realize
// that the file is Unicode-encoded.
return ok("\ufeff" + new String(baos.toByteArray(), charset));
}
public static Result newPerson() {
return ok(views.html.new_person.render(personForm));
}
public static Result makeNewPerson() {
Form<Person> filledForm = personForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(
views.html.new_person.render(filledForm)
);
} else {
Person new_person = Person.create(filledForm);
return redirect(routes.CRM.person(new_person.person_id));
}
}
static Email getPendingEmail() {
return Email.find.where()
.eq("organization", Organization.getByHost())
.eq("deleted", false).eq("sent", false).orderBy("id ASC").setMaxRows(1).findUnique();
}
public static boolean hasPendingEmail() {
return getPendingEmail() != null;
}
public static Result viewPendingEmail() {
Email e = getPendingEmail();
if (e == null) {
return redirect(routes.CRM.recentComments());
}
Tag staff_tag = Tag.find.where()
.eq("organization", Organization.getByHost())
.eq("title", "Staff").findUnique();
List<Person> people = staff_tag.people;
ArrayList<String> test_addresses = new ArrayList<String>();
for (Person p : people) {
test_addresses.add(p.email);
}
test_addresses.add("staff@threeriversvillageschool.org");
ArrayList<String> from_addresses = new ArrayList<String>();
from_addresses.add("office@threeriversvillageschool.org");
from_addresses.add("evan@threeriversvillageschool.org");
from_addresses.add("jmp@threeriversvillageschool.org");
from_addresses.add("jancey@threeriversvillageschool.org");
from_addresses.add("info@threeriversvillageschool.org");
from_addresses.add("staff@threeriversvillageschool.org");
e.parseMessage();
return ok(views.html.view_pending_email.render(e, test_addresses, from_addresses));
}
public static Result sendTestEmail() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
Email e = Email.findById(Integer.parseInt(values.get("id")[0]));
e.parseMessage();
try {
MimeMessage to_send = new MimeMessage(e.parsedMessage);
to_send.addRecipient(Message.RecipientType.TO,
new InternetAddress(values.get("dest_email")[0]));
to_send.setFrom(new InternetAddress("Papal DB <noreply@threeriversvillageschool.org>"));
Transport.send(to_send);
} catch (MessagingException ex) {
ex.printStackTrace();
}
return ok();
}
public static Result sendEmail() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
Email e = Email.findById(Integer.parseInt(values.get("id")[0]));
e.parseMessage();
int tagId = Integer.parseInt(values.get("tagId")[0]);
Tag theTag = Tag.findById(tagId);
String familyMode = values.get("familyMode")[0];
Collection<Person> recipients = getTagMembers(tagId, familyMode);
boolean hadErrors = false;
for (Person p : recipients) {
if (p.email != null && !p.email.equals("")) {
try {
MimeMessage to_send = new MimeMessage(e.parsedMessage);
to_send.addRecipient(Message.RecipientType.TO,
new InternetAddress(p.email, p.first_name + " " + p.last_name));
to_send.setFrom(new InternetAddress(values.get("from")[0]));
Transport.send(to_send);
} catch (MessagingException ex) {
ex.printStackTrace();
hadErrors = true;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
hadErrors = true;
}
}
}
// Send confirmation email
try {
MimeMessage to_send = new MimeMessage(e.parsedMessage);
to_send.addRecipient(Message.RecipientType.TO,
new InternetAddress("Staff <staff@threeriversvillageschool.org>"));
String subject = "(Sent to " + theTag.title + " " + familyMode + ") " + to_send.getSubject();
if (hadErrors) {
subject = "***ERRORS*** " + subject;
}
to_send.setSubject(subject);
to_send.setFrom(new InternetAddress(values.get("from")[0]));
Transport.send(to_send);
} catch (MessagingException ex) {
ex.printStackTrace();
}
e.delete();
return ok();
}
public static Result deleteEmail() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
Email e = Email.findById(Integer.parseInt(values.get("id")[0]));
e.delete();
return ok();
}
public static Result deletePerson(Integer id) {
Person.delete(id);
return redirect(routes.CRM.recentComments());
}
public static Result editPerson(Integer id) {
return ok(views.html.edit_person.render(Person.findById(id).fillForm()));
}
public static Result savePersonEdits() {
CachedPage.remove(Application.CACHE_INDEX);
CachedPage.remove(Attendance.CACHE_INDEX);
Form<Person> filledForm = personForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(
views.html.edit_person.render(filledForm)
);
}
return redirect(routes.CRM.person(Person.updateFromForm(filledForm).person_id));
}
public static String getInitials(Person p) {
String result = "";
if (p.first_name != null && p.first_name.length() > 0) {
result += p.first_name.charAt(0);
}
if (p.last_name != null && p.last_name.length() > 0) {
result += p.last_name.charAt(0);
}
return result;
}
public static Result addComment() {
CachedPage.remove(CACHE_RECENT_COMMENTS);
Form<Comment> filledForm = commentForm.bindFromRequest();
Comment new_comment = new Comment();
new_comment.person = Person.findById(Integer.parseInt(filledForm.field("person").value()));
new_comment.user = Application.getCurrentUser();
new_comment.message = filledForm.field("message").value();
String task_id_string = filledForm.field("comment_task_ids").value();
if (task_id_string.length() > 0 || new_comment.message.length() > 0) {
new_comment.save();
String[] task_ids = task_id_string.split(",");
for (String id_string : task_ids) {
if (!id_string.isEmpty()) {
int id = Integer.parseInt(id_string);
if (id >= 1) {
CompletedTask.create(Task.findById(id), new_comment);
}
}
}
if (filledForm.field("send_email").value() != null) {
for (NotificationRule rule :
NotificationRule.findByType(NotificationRule.TYPE_COMMENT)) {
play.libs.mailer.Email mail = new play.libs.mailer.Email();
mail.setSubject("DemSchoolTools comment: " + new_comment.user.name + " & " + getInitials(new_comment.person));
mail.addTo(rule.email);
mail.setFrom("DemSchoolTools <noreply@demschooltools.com>");
mail.setBodyHtml(views.html.comment_email.render(Comment.find.byId(new_comment.id)).toString());
play.libs.mailer.MailerPlugin.send(mail);
}
}
return ok(views.html.comment_fragment.render(Comment.find.byId(new_comment.id), false));
} else {
return ok();
}
}
public static Result addDonation() {
Form<Donation> filledForm = donationForm.bindFromRequest();
Donation new_donation = new Donation();
new_donation.person = Person.findById(Integer.parseInt(filledForm.field("person").value()));
new_donation.description = filledForm.field("description").value();
String dollar_value = filledForm.field("dollar_value").value();
if (dollar_value.charAt(0) == '$') {
dollar_value = dollar_value.substring(1);
}
new_donation.dollar_value = Float.parseFloat(dollar_value);
try
{
new_donation.date = new SimpleDateFormat("yyyy-MM-dd").parse(filledForm.field("date").value());
// Set time to 12 noon so that time zone issues won't bump us to the wrong day.
new_donation.date.setHours(12);
}
catch (ParseException e)
{
new_donation.date = new Date();
}
new_donation.is_cash = filledForm.field("donation_type").value().equals("Cash");
if (filledForm.field("needs_thank_you").value() != null) {
new_donation.thanked = !filledForm.field("needs_thank_you").value().equals("on");
} else {
new_donation.thanked = true;
}
if (filledForm.field("needs_indiegogo_reward").value() != null) {
new_donation.indiegogo_reward_given = !filledForm.field("needs_indiegogo_reward").value().equals("on");
} else {
new_donation.indiegogo_reward_given = true;
}
new_donation.save();
for (NotificationRule rule :
NotificationRule.findByType(NotificationRule.TYPE_DONATION)) {
play.libs.mailer.Email mail = new play.libs.mailer.Email();
mail.setSubject("Donation recorded from " + new_donation.person.first_name + " " + new_donation.person.last_name);
mail.addTo(rule.email);
mail.setFrom("DemSchoolTools <noreply@demschooltools.com>");
mail.setBodyHtml(views.html.donation_email.render(new_donation).toString());
play.libs.mailer.MailerPlugin.send(mail);
}
return ok(views.html.donation_fragment.render(Donation.find.byId(new_donation.id)));
}
public static Result donationThankYou(int id)
{
Donation d = Donation.find.byId(id);
d.thanked = true;
d.thanked_by_user = Application.getCurrentUser();
d.thanked_time = new Date();
d.save();
return ok();
}
public static Result donationIndiegogoReward(int id)
{
Donation d = Donation.findById(id);
d.indiegogo_reward_given = true;
d.indiegogo_reward_by_user = Application.getCurrentUser();
d.indiegogo_reward_given_time = new Date();
d.save();
return ok();
}
public static Result donationsNeedingThankYou()
{
List<Donation> donations = Donation.find
.fetch("person")
.where()
.eq("person.organization", Organization.getByHost())
.eq("thanked", false).orderBy("date DESC").findList();
return ok(views.html.donation_list.render("Donations needing thank you", donations));
}
public static Result donationsNeedingIndiegogo()
{
List<Donation> donations = Donation.find
.fetch("person")
.where()
.eq("person.organization", Organization.getByHost())
.eq("indiegogo_reward_given", false).orderBy("date DESC").findList();
return ok(views.html.donation_list.render("Donations needing Indiegogo reward", donations));
}
public static Result donations()
{
return ok(views.html.donation_list.render("All donations",
Donation.find
.fetch("person")
.where()
.eq("person.organization", Organization.getByHost())
.orderBy("date DESC").findList()));
}
public static int calcAge(Person p) {
return (int)((new Date().getTime() - p.dob.getTime()) / 1000 / 60 / 60 / 24 / 365.25);
}
public static int calcAgeAtBeginningOfSchool(Person p) {
if (p.dob == null) {
return -1;
}
return (int)((Application.getStartOfYear().getTime() - p.dob.getTime()) / 1000 / 60 / 60 / 24 / 365.25);
}
public static String formatDob(Date d) {
if (d == null) {
return "
}
return new SimpleDateFormat("MM/dd/yy").format(d);
}
public static String formatDate(Date d) {
d = new Date(d.getTime() +
(Application.getConfiguration().getInt("time_zone_offset") * 1000L * 60 * 60));
Date now = new Date();
long diffHours = (now.getTime() - d.getTime()) / 1000 / 60 / 60;
// String format = "EEE MMMM d, h:mm a";
String format;
if (diffHours < 24) {
format = "h:mm a";
} else if (diffHours < 24 * 7) {
format = "EEEE, MMMM d";
} else {
format = "MM/d/yy";
}
return new SimpleDateFormat(format).format(d);
}
public static Result viewTaskList(Integer id) {
TaskList list = TaskList.findById(id);
List<Person> people = list.tag.people;
return ok(views.html.task_list.render(list, people));
}
public static Result viewMailchimpSettings() {
MailChimpClient mailChimpClient = new MailChimpClient();
Organization org = OrgConfig.get().org;
Map<String, ListMethodResult.Data> mc_list_map =
Public.getMailChimpLists(mailChimpClient, org.mailchimp_api_key);
return ok(views.html.view_mailchimp_settings.render(
Form.form(Organization.class), org,
MailchimpSync.find.where().eq("tag.organization", OrgConfig.get().org).findList(),
mc_list_map));
}
public static Result saveMailchimpSettings() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
if (values.containsKey("mailchimp_api_key")) {
OrgConfig.get().org.setMailChimpApiKey(values.get("mailchimp_api_key")[0]);
}
if (values.containsKey("mailchimp_updates_email")) {
OrgConfig.get().org.setMailChimpUpdatesEmail(values.get("mailchimp_updates_email")[0]);
}
if (values.containsKey("sync_type")) {
for (String tag_id : values.get("tag_id")) {
Tag t = Tag.findById(Integer.parseInt(tag_id));
MailchimpSync sync = MailchimpSync.create(t,
values.get("mailchimp_list_id")[0],
values.get("sync_type")[0].equals("local_add"),
values.get("sync_type")[0].equals("local_remove"));
}
}
if (values.containsKey("remove_sync_id")) {
MailchimpSync sync = MailchimpSync.find.byId(Integer.parseInt(
values.get("remove_sync_id")[0]));
sync.delete();
}
return redirect(routes.CRM.viewMailchimpSettings());
}
}
|
package com.sometrik.framework;
import java.io.IOException;
import java.io.InputStream;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ScaleDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class FWButton extends Button implements NativeCommandHandler {
FrameWork frame;
BitmapDrawable leftDraw;
BitmapDrawable rightDraw;
BitmapDrawable bottomDraw;
BitmapDrawable topDraw;
public FWButton(FrameWork frameWork) {
super(frameWork);
this.frame = frameWork;
this.setBackground(frame.getResources().getDrawable(android.R.drawable.dialog_holo_light_frame));
}
@Override
public void addChild(View view) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void addOption(int optionId, String text) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void setValue(String v) {
setText(v);
//FIXME Debug animation
RotateAnimation r = new RotateAnimation(-5f, 5f,50,50);
r.setDuration(100);
r.setRepeatCount(10);
r.setRepeatMode(RotateAnimation.REVERSE);
startAnimation(r);
}
@Override
public void setValue(int v) {
System.out.println("FWButton couldn't handle command");
}
@Override
public int getElementId() {
return getId();
}
@Override
public void setViewEnabled(Boolean enabled) {
setEnabled(enabled);
}
@Override
public void setStyle(String key, String value) {
System.out.println("Button style " + key + " " + value);
if (key.equals("font-size")){
if (value.equals("small")){
this.setTextSize(9);
} else if (value.equals("medium")){
this.setTextSize(12);
} else if (value.equals("large")){
this.setTextSize(15);
} else {
setTextSize(Integer.parseInt(value));
}
} else if (key.equals("gravity")) {
Log.d("button", "setting gravity: ");
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("bottom")) {
params.gravity = Gravity.BOTTOM;
Log.d("button", " to bottom");
} else if (value.equals("top")) {
params.gravity = Gravity.TOP;
} else if (value.equals("left")) {
params.gravity = Gravity.LEFT;
} else if (value.equals("right")) {
params.gravity = Gravity.RIGHT;
}
setLayoutParams(params);
} else if (key.equals("width")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("height")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
if (value.equals("wrap-content")) {
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
} else if (value.equals("match-parent")) {
params.height = LinearLayout.LayoutParams.MATCH_PARENT;
}
setLayoutParams(params);
} else if (key.equals("weight")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.weight = Integer.parseInt(value);
setLayoutParams(params);
System.out.println("button weight: " + params.weight);
} else if (key.equals("pressed")) {
if (value.equals("true") || value.equals("1")) {
this.setPressed(true);
this.setTextColor(Color.RED);
} else {
this.setTextColor(Color.BLACK);
this.setPressed(false);
}
} else if (key.equals("icon-left") || key.equals("icon-right") || key.equals("icon-top") || key.equals("icon-bottom")){
AssetManager mgr = frame.getAssets();
try {
InputStream stream = mgr.open(value);
BitmapDrawable draw = new BitmapDrawable(stream);
this.setGravity(Gravity.CENTER);
if (key.equals("icon-right")){
rightDraw = draw;
} else if (key.equals("icon-top")){
topDraw = draw;
} else if (key.equals("icon-bottom")){
bottomDraw = draw;
} else if (key.equals("icon-left")){
leftDraw = draw;
}
this.setCompoundDrawablesWithIntrinsicBounds(leftDraw, topDraw, rightDraw, bottomDraw);
} catch (IOException e) {
System.out.println("no picture found: " + value);
e.printStackTrace();
}
} else if (key.equals("borderless")) {
setBackgroundResource(0);
} else if (key.equals("single-line")) {
this.setSingleLine();
} else if (key.equals("text-color")) {
setTextColor(Color.parseColor(value));
} else if (key.equals("color")) {
setBackgroundColor(Color.parseColor(value));
} else if (key.equals("padding-top")) {
setPadding(getPaddingLeft(), Integer.parseInt(value), getPaddingRight(), getPaddingBottom());
} else if (key.equals("padding-bottom")) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), Integer.parseInt(value));
} else if (key.equals("padding-left")) {
setPadding(Integer.parseInt(value), getPaddingTop(), getPaddingRight(), getPaddingBottom());
} else if (key.equals("padding-right")) {
setPadding(getPaddingLeft(), getPaddingTop(), Integer.parseInt(value), getPaddingBottom());
} else if (key.equals("margin-right")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.rightMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-left")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.leftMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-top")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.topMargin = Integer.parseInt(value);
setLayoutParams(params);
} else if (key.equals("margin-bottom")) {
LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
params.bottomMargin = Integer.parseInt(value);
setLayoutParams(params);
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
System.out.println("FWButton couldn't handle command");
}
@Override
public void setViewVisibility(boolean visibility) {
if (visibility){
this.setVisibility(VISIBLE);
} else {
this.setVisibility(INVISIBLE);
}
}
@Override
public void clear() {
System.out.println("couldn't handle command");
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void setImage(byte[] bytes, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
}
|
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.String;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import au.com.bytecode.opencsv_voltpatches.CSVReader;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table
* (or pass it to any stored proc, but ignoring any result other than the success code.).
*
* TODO:
* - Nulls are not handled (or at least I didn't test them).
* - Assumes localhost
* - Assumes no username/password
* - Usage help is ugly and cryptic: options are listed but not described.
* - No associated test suite.
* - Forces JVM into UTC. All input date TZs assumed to be GMT+0
* - Requires canonical JDBC SQL timestamp format
*/
class CSVLoader {
public synchronized static void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
}
private static final AtomicLong inCount = new AtomicLong(0);
private static final AtomicLong outCount = new AtomicLong(0);
private static int reportEveryNRows = 10000;
private static int limitRows = Integer.MAX_VALUE;
private static int skipRows = 0;
private static int auditRows = 0;
private static int waitSeconds = 10;
private static boolean stripQuotes = false;
private static int[] colProjection = null;
private static String reportdir = ".";
private static int abortfailurecount = 100; // by default right now
private static List<Long> invalidLines = new ArrayList<Long>();
private static boolean setSkipEmptyRecords = false;
private static boolean setTrimWhiteSpace = false;
private static final class MyCallback implements ProcedureCallback {
private final long m_lineNum;
MyCallback(long lineNumber)
{
m_lineNum = lineNumber;
}
@Override
public void clientCallback(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
// if (m_lineNum == 0) {
// System.err.print("Line ~" + inCount.get() + "-" + outCount.get() + ":");
// } else {
// System.err.print("Line " + m_lineNum + ":");
System.err.println(response.getStatusString());
System.err.println("Stop at line " + (inCount.get()));
synchronized (invalidLines) {
if (!invalidLines.contains(m_lineNum))
invalidLines.add(m_lineNum);
if (invalidLines.size() >= abortfailurecount) {
System.err.println("The number of Failure row data exceeds " + abortfailurecount);
System.exit(1);
}
}
//System.exit(1);
return;
}
long currentCount = inCount.incrementAndGet();
System.out.println("Put line " + inCount.get() + " to databse");
if (currentCount % reportEveryNRows == 0) {
System.out.println("Inserted " + currentCount + " rows");
}
}
}
/**
* TODO(xin): add line number data into the callback and add the invalid line number
* into a list that will help us to produce a separate file to record the invalid line
* data in the csv file.
*
* Asynchronously invoking procedures to response the actual wrong line number and
* start from last wrong line in the csv file is not easy. You can not ensure the
* FIFO order of the callback.
* @param args
* @return long number of the actual rows acknowledged by the database server
*/
public static long main(String[] args) {
if (args.length < 2) {
System.err.println("Two arguments, csv filename and insert procedure name, required");
System.exit(1);
}
final String filename = args[0];
final String insertProcedure = args[1];
int argsUsed = 2;
processCommandLineOptions(argsUsed, args);
int waits = 0;
int shortWaits = 0;
try {
final CSVReader reader = new CSVReader(new FileReader(filename));
//final ProcedureCallback oneCallbackFitsAll = new MyCallback(0);
ProcedureCallback cb = null;
final Client client = ClientFactory.createClient();
client.createConnection("localhost");
boolean lastOK = true;
String line[] = null;
for (int i = 0; i < skipRows; ++i) {
reader.readNext();
// Keep these sync'ed with line numbers.
outCount.incrementAndGet();
inCount.incrementAndGet();
}
while ((limitRows-- > 0) && (line = reader.readNext()) != null) {
long counter = outCount.incrementAndGet();
boolean queued = false;
while (queued == false) {
String[] correctedLine = line;
if (colProjection != null) {
System.out.println(String.format("colProject:%s | correctedLine: %s", colProjection, correctedLine));
correctedLine = projectColumns(colProjection, correctedLine);
}
if (stripQuotes) {
correctedLine = stripMatchingColumnQuotes(correctedLine);
}
if (auditRows > 0) {
--auditRows;
System.err.println(joinIntoString(", ", line));
System.err.println(joinIntoString(", ", correctedLine));
System.err.println("
cb = new MyCallback(counter);
} else {
cb = new MyCallback(outCount.get());
}
// This message will be removed later
// print out the parameters right now
String msg = "<xin>params: ";
for (int i=0; i < correctedLine.length; i++) {
msg += correctedLine[i] + ",";
}
System.out.println(msg);
if(!checkLineFormat(correctedLine, client, insertProcedure )){
System.err.println("Stop at line " + (outCount.get()));
synchronized (invalidLines) {
if (!invalidLines.contains(outCount.get())) {
invalidLines.add(outCount.get());
}
if (invalidLines.size() >= abortfailurecount) {
System.err.println("The number of Failure row data exceeds " + abortfailurecount);
System.exit(1);
}
}
break;
}
queued = client.callProcedure(cb, insertProcedure, (Object[])correctedLine);
if (queued == false) {
++waits;
if (lastOK == false) {
++shortWaits;
}
Thread.sleep(waitSeconds);
}
lastOK = queued;
}
}
reader.close();
client.drain();
client.close();
produceInvalidRowsFile(filename);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Inserted " + (outCount.get() - skipRows) + " and acknowledged " + (inCount.get() - skipRows) + " rows (final)");
if (waits > 0) {
System.out.println("Waited " + waits + " times");
if (shortWaits > 0) {
System.out.println("Waited too briefly? " + shortWaits + " times");
}
}
return inCount.get() - skipRows;
}
/**
* Check for each line
* TODO(zheng):
* Use the client handler to get the schema of the table, and then check the number of
* parameters it expects with the input line fragements.
* Check the following:
* 1.blank line
* 2.# of attributes in the insertion procedure
* And does other pre-checks...(figure out it later)
* @param linefragement
*/
private static boolean checkLineFormat(Object[] linefragement,
Client client,
final String insertProcedure
) {
VoltTable colInfo = null;
int columnCnt = 0;
int posOfDot = insertProcedure.indexOf(".");
String tableName = insertProcedure.substring( 0, posOfDot );
try {
colInfo = client.callProcedure("@SystemCatalog",
"COLUMNS").getResults()[0];
while( colInfo.advanceRow() )
{
if( tableName.matches( (String) colInfo.get("TABLE_NAME", VoltType.STRING) ) )
{
columnCnt++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if( linefragement.length == 0 && !setSkipEmptyRecords )
{
for( int i = 0; i < columnCnt; i++)
linefragement[ i ] = "";
return true;
}
if( linefragement.length != columnCnt )//# attributes not match
return false;
else if( setTrimWhiteSpace )
{//trim white space for non in this line.
for(int i=0; i<linefragement.length;i++) {
linefragement[i] = ((String)linefragement[i]).replaceAll( "\\s+", "" );
}
}
return true;
}
/**
* TODO(xin): produce the invalid row file from
*
* @param inputFile
*/
private static void produceInvalidRowsFile(String inputFile) {
Collections.sort(invalidLines);
System.out.println("All the invalid row numbers are:" + invalidLines);
String line = "";
try {
FileWriter fstream = new FileWriter(reportdir);
BufferedWriter out = new BufferedWriter(fstream);
BufferedReader csvfile = new BufferedReader(new FileReader(inputFile));
long linect = 0;
for (Long irow : invalidLines) {
while ((line = csvfile.readLine()) != null) {
if (++linect == irow) {
out.write(line);
out.write("\n");
System.err.println("invalid row:" + line);
break;
}
}
}
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.err.println("CSV file '" + inputFile
+ "' could not be found.");
} catch (Exception x) {
System.err.println(x.getMessage());
}
}
private static void processCommandLineOptions(int argsUsed, String args[]) {
final String columnsMatch = "--columns";
final String failuerCountMatch = "--abortfailurecount";
final String reportDirMatch = "--reportdir";
final String setSkipEmptyRecordsMatch = "--setskipemptyrecords";
final String setTrimWhiteSpaceMatch = "--settrimwhitespace";
final String stripMatch = "--stripquotes";
final String waitMatch = "--wait";
final String auditMatch = "--audit";
final String limitMatch = "--limit";
final String skipMatch = "--skip";
final String reportMatch = "--report";
final String columnsStyle = "comma-separated-zero-based-column-numbers";
while (argsUsed < args.length) {
final String optionPrefix = args[argsUsed++];
if (optionPrefix.equalsIgnoreCase(columnsMatch)) {
if (argsUsed < args.length) {
final String colsListed = args[argsUsed++];
final String[] cols = colsListed.split(",");
if (cols != null && cols.length > 0) {
colProjection = new int[cols.length];
for (int i = 0; i < cols.length; i++) {
try {
colProjection[i] = Integer.parseInt(cols[i]);
continue;
} catch (NumberFormatException e) {
}
}
if (colProjection.length == cols.length) {
continue;
}
}
}
} else if (optionPrefix.equalsIgnoreCase(failuerCountMatch)) {
if (argsUsed < args.length) {
try {
abortfailurecount = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
System.err.println("Invalid input integer parameter of abortfailurecount");
}
continue;
}
} else if (optionPrefix.equalsIgnoreCase(reportDirMatch)) {
if (argsUsed < args.length) {
try {
reportdir = (args[argsUsed++]);
} catch (NumberFormatException e) {
}
continue;
}
else if (optionPrefix.equalsIgnoreCase(setSkipEmptyRecordsMatch)) {
if (argsUsed < args.length) {
try {
setSkipEmptyRecords = true;
} catch (NumberFormatException e) {
}
continue;
}
}
else if (optionPrefix.equalsIgnoreCase(setTrimWhiteSpaceMatch)) {
if (argsUsed < args.length) {
try {
setTrimWhiteSpace = true;
} catch (NumberFormatException e) {
}
continue;
}
}
} else if (optionPrefix.equalsIgnoreCase(waitMatch)) {
if (argsUsed < args.length) {
try {
waitSeconds = Integer.parseInt(args[argsUsed++]);
if (waitSeconds >= 0) {
continue;
}
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(auditMatch)) {
if (argsUsed < args.length) {
try {
auditRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(limitMatch)) {
if (argsUsed < args.length) {
try {
limitRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(skipMatch)) {
if (argsUsed < args.length) {
try {
skipRows = Integer.parseInt(args[argsUsed++]);
continue;
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(reportMatch)) {
if (argsUsed < args.length) {
try {
reportEveryNRows = Integer.parseInt(args[argsUsed++]);
if (reportEveryNRows > 0) {
continue;
}
} catch (NumberFormatException e) {
}
}
} else if (optionPrefix.equalsIgnoreCase(stripMatch)) {
stripQuotes = true;
continue;
}
// Fall through means an error.
System.err.println("Option arguments are invalid, expected csv filename and insert procedure name (required) and optionally" +
" '" + columnsMatch + " " + columnsStyle + "'," +
" '" + waitMatch + " s (default=10 seconds)'," +
" '" + auditMatch + " n (default=0 rows)'," +
" '" + limitMatch + " n (default=all rows)'," +
" '" + skipMatch + " n (default=0 rows)'," +
" '" + reportMatch + " n (default=10000)'," +
" and/or '" + stripMatch + " (disabled by default)'");
System.exit(2);
}
}
private static String[] stripMatchingColumnQuotes(String[] line) {
final String[] strippedLine = new String[line.length];
Pattern pattern = Pattern.compile("^([\"'])(.*)\\1$");
for (int i = 0; i < line.length; i++) {
Matcher matcher = pattern.matcher(line[i]);
if (matcher.find()) {
strippedLine[i] = matcher.group(2);
} else {
strippedLine[i] = line[i];
}
}
return strippedLine;
}
private static String[] projectColumns(int[] colSelection, String[] line) {
final String[] projectedLine = new String[colSelection.length];
for (int i = 0; i < projectedLine.length; i++) {
projectedLine[i] = line[colSelection[i]];
}
return projectedLine;
}
// This function borrowed/mutated from http:/stackoverflow.com/questions/1515437
static String joinIntoString(String glue, Object... elements)
{
int k = elements.length;
if (k == 0) {
return null;
}
StringBuilder out = new StringBuilder();
out.append(elements[0].toString());
for (int i = 1; i < k; ++i) {
out.append(glue).append(elements[i]);
}
return out.toString();
}
// This function borrowed/mutated from http:/stackoverflow.com/questions/1515437
static String joinIntoString(String glue, String... elements)
{
int k = elements.length;
if (k == 0) {
return null;
}
StringBuilder out = new StringBuilder();
out.append(elements[0]);
for (int i = 1; i < k; ++i) {
out.append(glue).append(elements[i]);
}
return out.toString();
}
}
|
package mn.devfest.map;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mn.devfest.R;
/**
* Fragment that displays an event map
*
* @author bherbst
*/
public class MapFragment extends Fragment implements OnMapReadyCallback, View.OnClickListener {
private static final int DEFAULT_VISIBLE_FLOOR_INDEX = 0;
private static final float CONFERENCE_CENTER_ZOOM_LEVEL = 18.5f;
private static final int[] FLOOR_OVERLAY_ID_ARRAY = {R.drawable.schultze_level_one, R.drawable.schultze_level_two, R.drawable.schultze_level_three};
@Bind(R.id.map_view)
MapView mMapView;
@Bind(R.id.floor_selector_layout)
LinearLayout mFloorSelectorLayout;
@Bind(R.id.map_recenter)
ImageView mMapRecenterView;
GoogleMap mMap;
ArrayList<GroundOverlay> mFloorOverlayArray = new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
for (int i = 0; i < FLOOR_OVERLAY_ID_ARRAY.length; i++) {
Button button = new Button(getActivity());
int floorNumber = i + 1;
button.setText(String.format(getResources().getString(R.string.floor_selection_button_text), floorNumber));
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f));
button.setTag(i);
button.setOnClickListener(this);
mFloorSelectorLayout.addView(button);
}
updateButtonAppearance(DEFAULT_VISIBLE_FLOOR_INDEX);
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mMapView != null) {
mMapView.onDestroy();
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Move the camera to focus on the conference center
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(getConferenceCenterBounds().getCenter(), CONFERENCE_CENTER_ZOOM_LEVEL));
//Add ground overlays
for (int i = 0; i < FLOOR_OVERLAY_ID_ARRAY.length; i++) {
GroundOverlayOptions floorOverlayOptions = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(FLOOR_OVERLAY_ID_ARRAY[i]))
.zIndex(i)
.visible((i == DEFAULT_VISIBLE_FLOOR_INDEX)) //Only the lowest floor is visible by default
.positionFromBounds(getConferenceCenterBounds());
mFloorOverlayArray.add(mMap.addGroundOverlay(floorOverlayOptions));
}
}
/**
* Provides the Lat-Long bounds of the conference center
*
* @return The Lat-Long bounds of the conference center
*/
private LatLngBounds getConferenceCenterBounds() {
float swLatitude = Float.parseFloat(getString(R.string.sw_corner_latitude));
float swLongitude = Float.parseFloat(getString(R.string.sw_corner_longitude));
float neLatitude = Float.parseFloat(getString(R.string.ne_corner_latitude));
float neLongitude = Float.parseFloat(getString(R.string.ne_corner_longitude));
return new LatLngBounds(
new LatLng(swLatitude, swLongitude),
new LatLng(neLatitude, neLongitude));
}
/**
* Resets the maps camera to it's original location
*/
@OnClick(R.id.map_recenter)
protected void onRecenterClicked() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(getConferenceCenterBounds().getCenter(), CONFERENCE_CENTER_ZOOM_LEVEL));
}
@Override
public void onClick(View v) {
//Only address views in the floor selector layout
if (v.getParent() == mFloorSelectorLayout) {
//Show/hide floor overlays to match new selection
for (int i = 0; i < FLOOR_OVERLAY_ID_ARRAY.length; i++) {
//Change the visibility of each overlay appropriately
GroundOverlay groundOverlay = mFloorOverlayArray.get(i);
groundOverlay.setVisible((Integer) i == v.getTag());
}
//Update the appearance of the buttons to reflect the new selection
updateButtonAppearance((Integer) v.getTag());
}
}
/**
* Update the appearance of all of the buttons to reflect which one is selected
*
* @param selectedButtonIndex the index of the button that should appear selected
*/
private void updateButtonAppearance(int selectedButtonIndex) {
Button button;
int backgroundColorId;
int backgroundColor;
int textColorId;
int textColor;
//Change the color of each button appropriately
for (int i = 0; i < FLOOR_OVERLAY_ID_ARRAY.length; i++) {
button = (Button) mFloorSelectorLayout.getChildAt(i);
if ((selectedButtonIndex == i)) {
backgroundColorId = R.color.colorAccent;
textColorId = R.color.colorBlack;
} else {
backgroundColorId = R.color.colorPrimary;
textColorId = R.color.colorWhite;
}
backgroundColor = ContextCompat.getColor(getContext(), backgroundColorId);
textColor = ContextCompat.getColor(getContext(), textColorId);
button.setBackgroundColor(backgroundColor);
button.setTextColor(textColor);
}
}
}
|
package io.flutter.console;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.filters.Filter;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.execution.filters.OpenFileHyperlinkInfo;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.FlutterMessages;
import io.flutter.FlutterUtils;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The FlutterConsoleFilter handles link detection in consoles for:
* <p>
* - linking an action to the term 'flutter doctor'
* - linking the text "Launching lib/main.dart" or "open ios/Runner.xcworkspace"
* - some embedded paths, like "MyApp.xzzzz (lib/main.dart:6)"
*/
public class FlutterConsoleFilter implements Filter {
private static class OpenExternalFileHyperlink implements HyperlinkInfo {
private final String myPath;
OpenExternalFileHyperlink(VirtualFile file) {
myPath = file.getPath();
}
@Override
public void navigate(Project project) {
try {
final GeneralCommandLine cmd = new GeneralCommandLine().withExePath("open").withParameters(myPath);
final OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull final ProcessEvent event) {
if (event.getExitCode() != 0) {
FlutterMessages.showError("Error Opening ", myPath);
}
}
});
handler.startNotify();
}
catch (ExecutionException e) {
FlutterMessages.showError(
"Error Opening External File",
"Exception: " + e.getMessage());
}
}
}
private final @NotNull Module module;
public FlutterConsoleFilter(@NotNull Module module) {
this.module = module;
}
@VisibleForTesting
@Nullable
public VirtualFile fileAtPath(@NotNull String pathPart) {
// "lib/main.dart:6"
pathPart = pathPart.split(":")[0];
// We require the pathPart reference to be a file reference, otherwise we'd match things like
// "Build: Running build completed, took 191ms".
if (pathPart.indexOf('.') == -1) {
return null;
}
final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();
for (VirtualFile root : roots) {
if (!pathPart.isEmpty()) {
final String baseDirPath = root.getPath();
final String path = baseDirPath + "/" + pathPart;
VirtualFile file = findFile(path);
if (file == null) {
// check example dir too
final String exampleDirRelativePath = baseDirPath + "/example/" + pathPart;
file = findFile(exampleDirRelativePath);
}
if (file != null) {
return file;
}
}
}
return null;
}
private static VirtualFile findFile(final String path) {
final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
return file != null && file.exists() ? file : null;
}
@Override
@Nullable
public Result applyFilter(final String line, final int entireLength) {
if (line.startsWith("Run \"flutter doctor\" for information about installing additional components.")) {
return getFlutterDoctorResult(line, entireLength - line.length());
}
int lineNumber = 0;
String pathPart = line.trim();
VirtualFile file = null;
int lineStart = -1;
int highlightLength = 0;
// Check for, e.g.,
// * "Launching lib/main.dart"
// * "open ios/Runner.xcworkspace"
if (pathPart.startsWith("Launching ") || pathPart.startsWith("open ")) {
final String[] parts = pathPart.split(" ");
if (parts.length > 1) {
pathPart = parts[1];
file = fileAtPath(pathPart);
if (file != null) {
lineStart = entireLength - line.length() + line.indexOf(pathPart);
highlightLength = pathPart.length();
}
}
}
// Check for embedded paths, e.g.,
final String[] parts = pathPart.split(" ");
for (String part : parts) {
// "(lib/main.dart:49)"
if (part.startsWith("(") && part.endsWith(")")) {
part = part.substring(1, part.length() - 1);
final String[] split = part.split(":");
if (split.length == 2) {
try {
// Reconcile line number indexing.
lineNumber = Math.max(0, Integer.parseInt(split[1]) - 1);
}
catch (NumberFormatException e) {
// Ignored.
}
pathPart = part;
lineStart = entireLength - line.length() + line.indexOf(pathPart);
highlightLength = pathPart.length();
break;
}
else if (split.length == 4 && split[0].equals("file")) {
// part = file:///Users/user/AndroidStudioProjects/flutter_app/test/widget_test.dart:23:18
try {
// Reconcile line number indexing.
lineNumber = Math.max(0, Integer.parseInt(split[2]) - 1);
}
catch (NumberFormatException e) {
// Ignored.
}
pathPart = findRelativePath(split[1]);
if (pathPart == null) {
return null;
}
lineStart = entireLength - line.length() + line.indexOf(part);
highlightLength = part.length();
break;
}
}
}
if (lineStart < 0) {
// lib/registerC.dart:104:73: Error: Expected ';' after this.
String filePathAndLineNumberExpr = "^.*?((?:[^/]*?/)*?)(.*?):(\\d+?):\\d+?:\\s*?Error";
Pattern pattern = Pattern.compile(filePathAndLineNumberExpr);
Matcher matcher = pattern.matcher(line);
boolean found = matcher.find();
if (found) {
String path = matcher.group(1) + matcher.group(2);
file = fileAtPath(path);
if (file == null) {
return null;
}
lineNumber = Integer.parseInt(matcher.group(3));
lineStart = entireLength - line.length();
highlightLength = path.length();
}
else {
return null;
}
}
if (file == null) {
file = fileAtPath(pathPart);
}
if (file != null) {
// "open ios/Runner.xcworkspace"
final boolean openAsExternalFile = FlutterUtils.isXcodeFileName(pathPart);
final HyperlinkInfo hyperlinkInfo =
openAsExternalFile ? new OpenExternalFileHyperlink(file) : new OpenFileHyperlinkInfo(module.getProject(), file, lineNumber, 0);
return new Result(lineStart, lineStart + highlightLength, hyperlinkInfo);
}
return null;
}
private String findRelativePath(String threeSlashFileName) {
final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();
for (VirtualFile root : roots) {
final String path = root.getPath();
int index = threeSlashFileName.indexOf(path);
if (index > 0) {
index += path.length();
return threeSlashFileName.substring(index + 1);
}
}
return null;
}
private static Result getFlutterDoctorResult(final String line, final int lineStart) {
final int commandStart = line.indexOf('"') + 1;
final int startOffset = lineStart + commandStart;
final int commandLength = "flutter doctor".length();
return new Result(startOffset, startOffset + commandLength, new FlutterDoctorHyperlinkInfo());
}
private static class FlutterDoctorHyperlinkInfo implements HyperlinkInfo {
@Override
public void navigate(final Project project) {
// TODO(skybrian) analytics for clicking the link? (We do log the command.)
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
Messages.showErrorDialog(project, "Flutter SDK not found", "Error");
return;
}
if (sdk.flutterDoctor().startInConsole(project) == null) {
Messages.showErrorDialog(project, "Failed to start 'flutter doctor'", "Error");
}
}
}
}
|
package org.commcare.android.view;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import org.commcare.android.models.AsyncEntity;
import org.commcare.android.models.Entity;
import org.commcare.android.tasks.ExceptionReportTask;
import org.commcare.android.util.InvalidStateException;
import org.commcare.android.util.StringUtils;
import org.commcare.dalvik.R;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.graph.GraphData;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.odk.collect.android.views.media.AudioButton;
import org.odk.collect.android.views.media.AudioController;
import org.odk.collect.android.views.media.ViewId;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.speech.tts.TextToSpeech;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* @author ctsims
*
*/
public class EntityView extends LinearLayout {
private View[] views;
private String[] forms;
private TextToSpeech tts;
private String[] searchTerms;
private String[] mHints;
private Context context;
private AudioController controller;
private Hashtable<Integer, Hashtable<Integer, View>> renderedGraphsCache; // index => { orientation => GraphView }
private long rowId;
public static final String FORM_AUDIO = "audio";
public static final String FORM_IMAGE = "image";
public static final String FORM_GRAPH = "graph";
public static final String FORM_CALLLOUT = "callout";
private boolean mFuzzySearchEnabled = true;
private boolean mIsAsynchronous = false;
/*
* Constructor for row/column contents
*/
public EntityView(Context context, Detail d, Entity e, TextToSpeech tts,
String[] searchTerms, AudioController controller, long rowId, boolean mFuzzySearchEnabled) {
super(context);
this.context = context;
//this is bad :(
mIsAsynchronous = e instanceof AsyncEntity;
this.searchTerms = searchTerms;
this.tts = tts;
this.controller = controller;
this.renderedGraphsCache = new Hashtable<Integer, Hashtable<Integer, View>>();
this.rowId = rowId;
this.views = new View[e.getNumFields()];
this.forms = d.getTemplateForms();
this.mHints = d.getTemplateSizeHints();
for (int i = 0; i < views.length; ++i) {
if (mHints[i] == null || !mHints[i].startsWith("0")) {
Object uniqueId = new ViewId(rowId, i, false);
views[i] = initView(e.getField(i), forms[i], uniqueId, e.getSortField(i));
views[i].setId(i);
}
}
refreshViewsForNewEntity(e, false, rowId);
for (int i = 0; i < views.length; i++) {
LayoutParams l = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
if (views[i] != null) {
addView(views[i], l);
}
}
this.mFuzzySearchEnabled = mFuzzySearchEnabled;
}
/*
* Constructor for row/column headers
*/
public EntityView(Context context, Detail d, String[] headerText, Integer textColor) {
super(context);
this.context = context;
this.views = new View[headerText.length];
this.mHints = d.getHeaderSizeHints();
String[] headerForms = d.getHeaderForms();
for (int i = 0 ; i < views.length ; ++i) {
if (mHints[i] == null || !mHints[i].startsWith("0")) {
LayoutParams l = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
ViewId uniqueId = new ViewId(rowId, i, false);
views[i] = initView(headerText[i], headerForms[i], uniqueId, null);
views[i].setId(i);
if(textColor != null) {
TextView tv = (TextView) views[i].findViewById(R.id.component_audio_text_txt);
if(tv != null) tv.setTextColor(textColor);
}
addView(views[i], l);
}
}
}
/*
* Creates up a new view in the view with ID uniqueid, based upon
* the entity's text and form
*/
private View initView(Object data, String form, Object uniqueId, String sortField) {
View retVal;
if (FORM_IMAGE.equals(form)) {
ImageView iv = (ImageView)View.inflate(context, R.layout.entity_item_image, null);
retVal = iv;
}
else if (FORM_AUDIO.equals(form)) {
String text = (String) data;
AudioButton b;
if (text != null & text.length() > 0) {
b = new AudioButton(context, text, uniqueId, controller, true);
}
else {
b = new AudioButton(context, text, uniqueId, controller, false);
}
retVal = b;
}
else if (FORM_GRAPH.equals(form) && data instanceof GraphData) {
View layout = View.inflate(context, R.layout.entity_item_graph, null);
retVal = layout;
}
else if (FORM_CALLLOUT.equals(form)) {
View layout = View.inflate(context, R.layout.entity_item_graph, null);
retVal = layout;
}
else {
View layout = View.inflate(context, R.layout.component_audio_text, null);
setupTextAndTTSLayout(layout, (String) data, sortField);
retVal = layout;
}
return retVal;
}
public void setSearchTerms(String[] terms) {
this.searchTerms = terms;
}
public void refreshViewsForNewEntity(Entity e, boolean currentlySelected, long rowId) {
for (int i = 0; i < e.getNumFields() ; ++i) {
Object field = e.getField(i);
View view = views[i];
String form = forms[i];
if (view == null) { continue; }
if (FORM_AUDIO.equals(form)) {
ViewId uniqueId = new ViewId(rowId, i, false);
setupAudioLayout(view, (String) field, uniqueId);
} else if(FORM_IMAGE.equals(form)) {
setupImageLayout(view, (String) field);
} else if (FORM_GRAPH.equals(form) && field instanceof GraphData) {
int orientation = getResources().getConfiguration().orientation;
GraphView g = new GraphView(context, "");
View rendered = null;
if (renderedGraphsCache.get(i) != null) {
rendered = renderedGraphsCache.get(i).get(orientation);
}
else {
renderedGraphsCache.put(i, new Hashtable<Integer, View>());
}
if (rendered == null) {
try {
rendered = g.getView((GraphData) field);
} catch (InvalidStateException ise) {
rendered = new TextView(context);
((TextView)rendered).setText(ise.getMessage());
}
renderedGraphsCache.get(i).put(orientation, rendered);
}
((LinearLayout) view).removeAllViews();
((LinearLayout) view).addView(rendered, g.getLayoutParams());
view.setVisibility(VISIBLE);
} else {
//text to speech
setupTextAndTTSLayout(view, (String) field, e.getSortField(i));
}
}
if (currentlySelected) {
this.setBackgroundResource(R.drawable.grey_bordered_box);
} else {
this.setBackgroundDrawable(null);
}
}
/*
* Updates the AudioButton layout that is passed in, based on the
* new id and source
*/
private void setupAudioLayout(View layout, String source, ViewId uniqueId) {
AudioButton b = (AudioButton)layout;
if (source != null && source.length() > 0) {
b.modifyButtonForNewView(uniqueId, source, true);
}
else {
b.modifyButtonForNewView(uniqueId, source, false);
}
}
/*
* Updates the text layout that is passed in, based on the new text
*/
private void setupTextAndTTSLayout(View layout, final String text, String searchField) {
TextView tv = (TextView)layout.findViewById(R.id.component_audio_text_txt);
tv.setVisibility(View.VISIBLE);
tv.setText(highlightSearches(this.getContext(), searchTerms, new SpannableString(text == null ? "" : text), searchField, mFuzzySearchEnabled, mIsAsynchronous));
ImageButton btn = (ImageButton)layout.findViewById(R.id.component_audio_text_btn_audio);
btn.setFocusable(false);
btn.setOnClickListener(new OnClickListener(){
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
String textToRead = text;
tts.speak(textToRead, TextToSpeech.QUEUE_FLUSH, null);
}
});
if (tts == null || text == null || text.equals("")) {
btn.setVisibility(View.INVISIBLE);
RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams();
params.width = 0;
btn.setLayoutParams(params);
} else {
btn.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams();
params.width = LayoutParams.WRAP_CONTENT;
btn.setLayoutParams(params);
}
}
/*
* Updates the ImageView layout that is passed in, based on the
* new id and source
*/
public void setupImageLayout(View layout, final String source) {
ImageView iv = (ImageView) layout;
Bitmap b;
if (!source.equals("")) {
try {
b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(source).getStream());
if (b == null) {
//Input stream could not be used to derive bitmap, so showing error-indicating image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
}
else {
iv.setImageBitmap(b);
}
} catch (IOException ex) {
ex.printStackTrace();
//Error loading image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
} catch (InvalidReferenceException ex) {
ex.printStackTrace();
//No image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
}
}
else {
iv.setImageDrawable(getResources().getDrawable(R.color.white));
}
}
//TODO: This method now really does two different things and should possibly be different
//methods.
/**
* Based on the search terms provided, highlight the aspects of the spannable provided which
* match. A background string can be provided which provides the exact data that is being
* matched.
*
* @param context
* @param searchTerms
* @param raw
* @param backgroundString
* @param fuzzySearchEnabled
* @param strictMode
* @return
*/
public static Spannable highlightSearches(Context context, String[] searchTerms, Spannable raw, String backgroundString, boolean fuzzySearchEnabled, boolean strictMode) {
if (searchTerms == null) {
return raw;
}
try {
//TOOD: Only do this if we're in strict mode
if(strictMode) {
if(backgroundString == null) {
return raw;
}
//make sure that we have the same consistency for our background match
backgroundString = StringUtils.normalize(backgroundString).trim();
} else {
//Otherwise we basically want to treat the "Search" string and the display string
//the same way.
backgroundString = StringUtils.normalize(raw.toString());
}
String normalizedDisplayString = StringUtils.normalize(raw.toString());
removeSpans(raw);
Vector<int[]> matches = new Vector<int[]>();
//Highlight direct substring matches
for (String searchText : searchTerms) {
if ("".equals(searchText)) {
continue;
}
//TODO: Assuming here that our background string exists and
//isn't null due to the background string check above
//check to see where we should start displaying this chunk
int offset = TextUtils.indexOf(normalizedDisplayString, backgroundString);
if (offset == -1) {
//We can't safely highlight any of this, due to this field not actually
//containing the same string we're searching by.
continue;
}
int index = backgroundString.indexOf(searchText);
//int index = TextUtils.indexOf(normalizedDisplayString, searchText);
while (index >= 0) {
//grab the display offset for actually displaying things
int displayIndex = index + offset;
raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.yellow)), displayIndex, displayIndex
+ searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
matches.add(new int[]{index, index + searchText.length()});
//index=TextUtils.indexOf(raw, searchText, index + searchText.length());
index = backgroundString.indexOf(searchText, index + searchText.length());
//we have a non-fuzzy match, so make sure we don't fuck with it
}
}
//now insert the spans for any fuzzy matches (if enabled)
if (fuzzySearchEnabled && backgroundString != null) {
backgroundString += " ";
for (String searchText : searchTerms) {
if ("".equals(searchText)) {
continue;
}
int curStart = 0;
int curEnd = backgroundString.indexOf(" ", curStart);
while (curEnd != -1) {
boolean skip = matches.size() != 0;
//See whether the fuzzy match overlaps at all with the concrete matches
for (int[] textMatch : matches) {
if (curStart < textMatch[0] && curEnd <= textMatch[0]) {
skip = false;
} else if (curStart >= textMatch[1] && curEnd > textMatch[1]) {
skip = false;
} else {
//We're definitely inside of this span, so
//don't do any fuzzy matching!
skip = true;
break;
}
}
if (!skip) {
//Walk the string to find words that are fuzzy matched
String currentSpan = backgroundString.substring(curStart, curEnd);
//First, figure out where we should be matching (if we don't
//have anywhere to match, that means there's nothing to display
//anyway)
int indexInDisplay = normalizedDisplayString.indexOf(currentSpan);
int length = (curEnd - curStart);
if (indexInDisplay != -1 && StringUtils.fuzzyMatch(currentSpan, searchText).first) {
raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.green)), indexInDisplay,
indexInDisplay + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
curStart = curEnd + 1;
curEnd = backgroundString.indexOf(" ", curStart);
}
}
}
} catch (Exception excp){
removeSpans(raw);
Logger.log("search-hl", excp.toString() + " " + ExceptionReportTask.getStackTrace(excp));
}
return raw;
}
/**
* Removes all background color spans from the Spannable
* @param raw Spannable to remove background colors from
*/
private static void removeSpans(Spannable raw) {
//Zero out the existing spans
BackgroundColorSpan[] spans=raw.getSpans(0,raw.length(), BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
}
private int[] calculateDetailWidths(int fullSize) {
// Convert any percentages to pixels
int[] hints = new int[mHints.length];
for (int i = 0; i < mHints.length; i++) {
if (mHints[i] == null) {
hints[i] = -1;
} else if (mHints[i].contains("%")) {
hints[i] = fullSize * Integer.parseInt(mHints[i].substring(0, mHints[i].indexOf("%"))) / 100;
}
else {
hints[i] = Integer.parseInt(mHints[i]);
}
}
// Determine how wide to make columns without a specified width
int[] widths = new int[hints.length];
int sharedBetween = 0;
for(int hint : hints) {
if(hint != -1) {
fullSize -= hint;
} else {
sharedBetween++;
}
}
// Set column widths
int defaultWidth = sharedBetween == 0 ? 0 : fullSize / sharedBetween;
for(int i = 0; i < hints.length; ++i) {
widths[i] = hints[i] == -1 ? defaultWidth : hints[i];
}
return widths;
}
/*
* (non-Javadoc)
* @see android.widget.LinearLayout#onMeasure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int[] widths = calculateDetailWidths(getMeasuredWidth());
for (int i = 0; i < views.length; i++) {
if (views[i] != null) {
LayoutParams params = (LinearLayout.LayoutParams) views[i].getLayoutParams();
params.width = widths[i];
views[i].setLayoutParams(params);
}
}
// Use children's new widths
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
|
package jade.wrapper.gateway;
//#J2ME_EXCLUDE_FILE
import jade.core.AID;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.util.Event;
import jade.util.Logger;
import jade.util.leap.Properties;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;
import jade.wrapper.ControllerException;
import jade.wrapper.StaleProxyException;
public class DynamicJadeGateway {
private ContainerController myContainer = null;
private AgentController myAgent = null;
private String agentType;
// jade profile properties
private ProfileImpl profile;
private Properties jadeProps;
private Object[] agentArguments;
private static Logger myLogger = Logger.getMyLogger(DynamicJadeGateway.class.getName());
/** Searches for the property with the specified key in the JADE Platform Profile.
* The method returns the default value argument if the property is not found.
* @param key - the property key.
* @param defaultValue - a default value
* @return the value with the specified key value
* @see java.util.Properties#getProperty(String, String)
**/
public final String getProfileProperty(String key, String defaultValue) {
return profile.getParameter(key, defaultValue);
}
/**
* execute a command.
* This method first check if the executor Agent is alive (if not it
* creates container and agent), then it forwards the execution
* request to the agent, finally it blocks waiting until the command
* has been executed (i.e. the method <code>releaseCommand</code>
* is called by the executor agent)
* @throws StaleProxyException if the method was not able to execute the Command
* @see jade.wrapper.AgentController#putO2AObject(Object, boolean)
**/
public final void execute(Object command) throws StaleProxyException,ControllerException,InterruptedException {
execute(command, 0);
}
/**
* Execute a command specifying a timeout.
* This method first check if the executor Agent is alive (if not it
* creates container and agent), then it forwards the execution
* request to the agent, finally it blocks waiting until the command
* has been executed. In case the command is a behaviour this method blocks
* until the behaviour has been completely executed.
* @throws InterruptedException if the timeout expires or the Thread
* executing this method is interrupted.
* @throws StaleProxyException if the method was not able to execute the Command
* @see jade.wrapper.AgentController#putO2AObject(Object, boolean)
**/
public final void execute(Object command, long timeout) throws StaleProxyException,ControllerException,InterruptedException {
Event e = null;
synchronized (this) {
checkJADE();
// incapsulate the command into an Event
e = new Event(-1, command);
try {
if (myLogger.isLoggable(Logger.INFO))
myLogger.log(Logger.INFO, "Requesting execution of command "+command);
myAgent.putO2AObject(e, AgentController.ASYNC);
} catch (StaleProxyException exc) {
exc.printStackTrace();
// in case an exception was thrown, restart JADE
// and then reexecute the command
restartJADE();
myAgent.putO2AObject(e, AgentController.ASYNC);
}
}
// wait until the answer is ready
e.waitUntilProcessed(timeout);
}
/**
* This method checks if both the container, and the agent, are up and running.
* If not, then the method is responsible for renewing myContainer.
* Normally programmers do not need to invoke this method explicitly.
**/
public final void checkJADE() throws StaleProxyException,ControllerException {
if (myContainer == null) {
initProfile();
myContainer = Runtime.instance().createAgentContainer(profile);
if (myContainer == null) {
throw new ControllerException("JADE startup failed.");
}
}
if (myAgent == null) {
myAgent = myContainer.createNewAgent("Control"+myContainer.getContainerName(), agentType, agentArguments);
myAgent.start();
}
}
/** Restart JADE.
* The method tries to kill both the agent and the container,
* then it puts to null the values of their controllers,
* and finally calls checkJADE
**/
final void restartJADE() throws StaleProxyException,ControllerException {
shutdown();
checkJADE();
}
/**
* Initialize this gateway by passing the proper configuration parameters
* @param agentClassName is the fully-qualified class name of the JadeGateway internal agent. If null is passed
* the default class will be used.
* @param agentArgs is the list of agent arguments
* @param jadeProfile the properties that contain all parameters for running JADE (see jade.core.Profile).
* Typically these properties will have to be read from a JADE configuration file.
* If jadeProfile is null, then a JADE container attaching to a main on the local host is launched
**/
public final void init(String agentClassName, Object[] agentArgs, Properties jadeProfile) {
agentType = agentClassName;
if (agentType == null) {
agentType = GatewayAgent.class.getName();
}
jadeProps = jadeProfile;
if (jadeProps != null) {
// Since we will create a non-main container --> force the "main" property to be false
jadeProps.setProperty(Profile.MAIN, "false");
}
agentArguments = agentArgs;
}
public final void init(String agentClassName, Properties jadeProfile) {
init(agentClassName, null, jadeProfile);
}
final void initProfile() {
// to initialize the profile every restart, otherwise an exception would be thrown by JADE
profile = (jadeProps == null ? new ProfileImpl(false) : new ProfileImpl(jadeProps));
}
/**
* Kill the JADE Container in case it is running.
*/
public final void shutdown() {
try { // try to kill, but neglect any exception thrown
if (myAgent != null)
myAgent.kill();
} catch (Exception e) {
}
try { // try to kill, but neglect any exception thrown
if (myContainer != null)
myContainer.kill();
} catch (Exception e) {
}
myAgent = null;
myContainer = null;
}
/**
* Return the state of JadeGateway
* @return true if the container and the gateway agent are active, false otherwise
*/
public final boolean isGatewayActive() {
return myContainer != null && myAgent != null;
}
public AID createAID(String localName) {
return new AID(localName+'@'+myContainer.getPlatformName(), AID.ISGUID);
}
}
|
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
package processing.app.debug;
/**
* An exception with a line number attached that occurs
* during either compile time or run time.
*/
@SuppressWarnings("serial")
public class RunnerException extends Exception {
protected String message;
protected int codeIndex;
protected int codeLine;
protected int codeColumn;
protected boolean showStackTrace;
public RunnerException(String message) {
this(message, true);
}
public RunnerException(String message, boolean showStackTrace) {
this(message, -1, -1, -1, showStackTrace);
}
public RunnerException(String message, int file, int line) {
this(message, file, line, -1, true);
}
public RunnerException(String message, int file, int line, int column) {
this(message, file, line, column, true);
}
public RunnerException(String message, int file, int line, int column,
boolean showStackTrace) {
this.message = message;
this.codeIndex = file;
this.codeLine = line;
this.codeColumn = column;
this.showStackTrace = showStackTrace;
}
public RunnerException(Exception e) {
super(e);
this.showStackTrace = true;
}
/**
* Override getMessage() in Throwable, so that I can set
* the message text outside the constructor.
*/
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getCodeIndex() {
return codeIndex;
}
public void setCodeIndex(int index) {
codeIndex = index;
}
public boolean hasCodeIndex() {
return codeIndex != -1;
}
public int getCodeLine() {
return codeLine;
}
public void setCodeLine(int line) {
this.codeLine = line;
}
public boolean hasCodeLine() {
return codeLine != -1;
}
public void setCodeColumn(int column) {
this.codeColumn = column;
}
public int getCodeColumn() {
return codeColumn;
}
public void showStackTrace() {
showStackTrace = true;
}
public void hideStackTrace() {
showStackTrace = false;
}
/**
* Nix the java.lang crap out of an exception message
* because it scares the children.
* <P>
* This function must be static to be used with super()
* in each of the constructors above.
*/
/*
static public final String massage(String msg) {
if (msg.indexOf("java.lang.") == 0) {
//int dot = msg.lastIndexOf('.');
msg = msg.substring("java.lang.".length());
}
return msg;
//return (dot == -1) ? msg : msg.substring(dot+1);
}
*/
public void printStackTrace() {
if (showStackTrace) {
super.printStackTrace();
}
}
}
|
// $Id: Sprite.java,v 1.59 2003/01/17 03:50:10 mdb Exp $
package com.threerings.media.sprite;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import com.threerings.util.DirectionCodes;
import com.threerings.media.AbstractMedia;
import com.threerings.media.Log;
import com.threerings.media.util.Path;
import com.threerings.media.util.Pathable;
/**
* The sprite class represents a single moveable object in an animated
* view. A sprite has a position and orientation within the view, and can
* be moved along a path.
*/
public abstract class Sprite extends AbstractMedia
implements DirectionCodes, Pathable
{
/**
* Constructs a sprite with an initially invalid location. Because
* sprite derived classes generally want to get in on the business
* when a sprite's location is set, it is not safe to do so in the
* constructor because their derived methods will be called before
* their constructor has been called. Thus a sprite should be fully
* constructed and <em>then</em> its location should be set.
*/
public Sprite ()
{
super(new Rectangle());
}
/**
* Returns the sprite's x position in screen coordinates. This is the
* x coordinate of the sprite's origin, not the upper left of its
* bounds.
*/
public int getX ()
{
return _ox;
}
/**
* Returns the sprite's y position in screen coordinates. This is the
* y coordinate of the sprite's origin, not the upper left of its
* bounds.
*/
public int getY ()
{
return _oy;
}
/**
* Returns the offset to the sprite's origin from the upper-left of
* the sprite's image.
*/
public int getXOffset ()
{
return _oxoff;
}
/**
* Returns the offset to the sprite's origin from the upper-left of
* the sprite's image.
*/
public int getYOffset ()
{
return _oyoff;
}
/**
* Returns the sprite's width in pixels.
*/
public int getWidth ()
{
return _bounds.width;
}
/**
* Returns the sprite's height in pixels.
*/
public int getHeight ()
{
return _bounds.height;
}
/**
* Sprites have an orientation in one of the eight cardinal
* directions: <code>NORTH</code>, <code>NORTHEAST</code>, etc.
* Derived classes can choose to override this member function and
* select a different set of images based on their orientation, or
* they can ignore the orientation information.
*
* @see DirectionCodes
*/
public void setOrientation (int orient)
{
_orient = orient;
}
/**
* Returns the sprite's orientation as one of the eight cardinal
* directions: <code>NORTH</code>, <code>NORTHEAST</code>, etc.
*
* @see DirectionCodes
*/
public int getOrientation ()
{
return _orient;
}
// documentation inherited
public void setLocation (int x, int y)
{
// start with our current bounds
Rectangle dirty = new Rectangle(_bounds);
// move ourselves
_ox = x;
_oy = y;
// we need to update our draw position which is based on the size
// of our current bounds
updateRenderOrigin();
// grow the dirty rectangle to incorporate our new bounds and pass
// the dirty region to our region manager
if (_mgr != null) {
// if our new bounds intersect our old bounds, grow a single
// dirty rectangle to incorporate them both
if (_bounds.intersects(dirty)) {
dirty.add(_bounds);
} else {
// otherwise invalidate our new bounds separately
_mgr.getRegionManager().invalidateRegion(_bounds);
}
_mgr.getRegionManager().addDirtyRegion(dirty);
}
}
// documentation inherited
public void paint (Graphics2D gfx)
{
gfx.drawRect(_bounds.x, _bounds.y, _bounds.width-1, _bounds.height-1);
}
/**
* Paint the sprite's path, if any, to the specified graphics context.
*
* @param gfx the graphics context.
*/
public void paintPath (Graphics2D gfx)
{
if (_path != null) {
_path.paint(gfx);
}
}
/**
* Returns true if the sprite's bounds contain the specified point,
* false if not.
*/
public boolean contains (int x, int y)
{
return _bounds.contains(x, y);
}
/**
* Returns true if the sprite's bounds contain the specified point,
* false if not.
*/
public boolean hitTest (int x, int y)
{
return _bounds.contains(x, y);
}
/**
* Returns whether the sprite is inside the given shape in pixel
* coordinates.
*/
public boolean inside (Shape shape)
{
return shape.contains(_ox, _oy);
}
/**
* Returns whether the sprite's drawn rectangle intersects the given
* shape in pixel coordinates.
*/
public boolean intersects (Shape shape)
{
return shape.intersects(_bounds);
}
/**
* Returns true if this sprite is currently following a path, false if
* it is not.
*/
public boolean isMoving ()
{
return (_path != null);
}
/**
* Set the sprite's active path and start moving it along its merry
* way. If the sprite is already moving along a previous path the old
* path will be lost and the new path will begin to be traversed.
*
* @param path the path to follow.
*/
public void move (Path path)
{
// save off this path
_path = path;
// we'll initialize it on our next tick thanks to a zero path stamp
_pathStamp = 0;
}
/**
* Cancels any path that the sprite may currently be moving along.
*/
public void cancelMove ()
{
// TODO: make sure we come to a stop on a full coordinate,
// even in the case where we aborted a path mid-traversal.
_path = null;
}
/**
* Returns the path being followed by this sprite or null if the
* sprite is not following a path.
*/
public Path getPath ()
{
return _path;
}
/**
* Called by the active path when it begins.
*/
public void pathBeginning ()
{
// nothing for now
}
/**
* Called by the active path when it has completed.
*/
public void pathCompleted (long timestamp)
{
// keep a reference to the path just completed
Path oldpath = _path;
// clear out the path we've now finished
_path = null;
// inform observers that we've finished our path
notifyObservers(new PathCompletedEvent(this, timestamp, oldpath));
}
// documentation inherited
public void tick (long tickStamp)
{
tickPath(tickStamp);
}
/**
* Ticks any path assigned to this sprite.
*
* @return true if the path relocated the sprite as a result of this
* tick, false if it remained in the same position.
*/
protected boolean tickPath (long tickStamp)
{
if (_path == null) {
return false;
}
// initialize the path if we haven't yet
if (_pathStamp == 0) {
_path.init(this, _pathStamp = tickStamp);
}
// it's possible that as a result of init() the path completed and
// removed itself with a call to pathCompleted(), so we have to be
// careful here
return (_path == null) ? true : _path.tick(this, tickStamp);
}
// documentation inherited
public void fastForward (long timeDelta)
{
// fast forward any path we're following
if (_path != null) {
_path.fastForward(timeDelta);
}
}
/**
* Update the coordinates at which the sprite image is drawn to
* reflect the sprite's current position.
*/
protected void updateRenderOrigin ()
{
// our bounds origin may differ from the sprite's origin
_bounds.x = _ox - _oxoff;
_bounds.y = _oy - _oyoff;
}
/**
* Add a sprite observer to observe this sprite's events.
*
* @param obs the sprite observer.
*/
public void addSpriteObserver (SpriteObserver obs)
{
addObserver(obs);
}
/**
* Remove a sprite observer.
*/
public void removeSpriteObserver (SpriteObserver obs)
{
removeObserver(obs);
}
/**
* Inform all sprite observers of a sprite event.
*
* @param event the sprite event.
*/
protected void notifyObservers (SpriteEvent event)
{
if (_observers != null) {
_mgr.queueNotification(_observers, event);
}
}
// documentation inherited
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", ox=").append(_ox);
buf.append(", oy=").append(_oy);
buf.append(", oxoff=").append(_oxoff);
buf.append(", oyoff=").append(_oyoff);
}
/** The location of the sprite's origin in pixel coordinates. If the
* sprite positions itself via a hotspot that is not the upper left
* coordinate of the sprite's bounds, the offset to the hotspot should
* be maintained in {@link #_oxoff} and {@link #_oyoff}. */
protected int _ox = Integer.MIN_VALUE, _oy = Integer.MIN_VALUE;
/** The offsets from our upper left coordinate to our origin (or hot
* spot). Derived classes will need to update these values if the
* sprite's origin is not coincident with the upper left coordinate of
* its bounds. */
protected int _oxoff, _oyoff;
/** The orientation of this sprite. */
protected int _orient = NONE;
/** When moving, the path the sprite is traversing. */
protected Path _path;
/** The timestamp at which we started along our path. */
protected long _pathStamp;
}
|
// $Id: Sprite.java,v 1.57 2003/01/13 23:53:34 mdb Exp $
package com.threerings.media.sprite;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import com.threerings.util.DirectionCodes;
import com.threerings.media.AbstractMedia;
import com.threerings.media.Log;
import com.threerings.media.util.Path;
import com.threerings.media.util.Pathable;
/**
* The sprite class represents a single moveable object in an animated
* view. A sprite has a position and orientation within the view, and can
* be moved along a path.
*/
public abstract class Sprite extends AbstractMedia
implements DirectionCodes, Pathable
{
/**
* Constructs a sprite with an initially invalid location. Because
* sprite derived classes generally want to get in on the business
* when a sprite's location is set, it is not safe to do so in the
* constructor because their derived methods will be called before
* their constructor has been called. Thus a sprite should be fully
* constructed and <em>then</em> its location should be set.
*/
public Sprite ()
{
super(new Rectangle());
}
/**
* Returns the sprite's x position in screen coordinates. This is the
* x coordinate of the sprite's origin, not the upper left of its
* bounds.
*/
public int getX ()
{
return _ox;
}
/**
* Returns the sprite's y position in screen coordinates. This is the
* y coordinate of the sprite's origin, not the upper left of its
* bounds.
*/
public int getY ()
{
return _oy;
}
/**
* Returns the offset to the sprite's origin from the upper-left of
* the sprite's image.
*/
public int getXOffset ()
{
return _oxoff;
}
/**
* Returns the offset to the sprite's origin from the upper-left of
* the sprite's image.
*/
public int getYOffset ()
{
return _oyoff;
}
/**
* Returns the sprite's width in pixels.
*/
public int getWidth ()
{
return _bounds.width;
}
/**
* Returns the sprite's height in pixels.
*/
public int getHeight ()
{
return _bounds.height;
}
/**
* Sprites have an orientation in one of the eight cardinal
* directions: <code>NORTH</code>, <code>NORTHEAST</code>, etc.
* Derived classes can choose to override this member function and
* select a different set of images based on their orientation, or
* they can ignore the orientation information.
*
* @see DirectionCodes
*/
public void setOrientation (int orient)
{
_orient = orient;
}
/**
* Returns the sprite's orientation as one of the eight cardinal
* directions: <code>NORTH</code>, <code>NORTHEAST</code>, etc.
*
* @see DirectionCodes
*/
public int getOrientation ()
{
return _orient;
}
// documentation inherited
public void setLocation (int x, int y)
{
// start with our current bounds
Rectangle dirty = new Rectangle(_bounds);
// move ourselves
_ox = x;
_oy = y;
// we need to update our draw position which is based on the size
// of our current bounds
updateRenderOrigin();
// grow the dirty rectangle to incorporate our new bounds and pass
// the dirty region to our region manager
if (_mgr != null) {
// if our new bounds intersect our old bounds, grow a single
// dirty rectangle to incorporate them both
if (_bounds.intersects(dirty)) {
dirty.add(_bounds);
} else {
// otherwise invalidate our new bounds separately
_mgr.getRegionManager().invalidateRegion(_bounds);
}
_mgr.getRegionManager().addDirtyRegion(dirty);
}
}
// documentation inherited
public void paint (Graphics2D gfx)
{
gfx.drawRect(_bounds.x, _bounds.y, _bounds.width-1, _bounds.height-1);
}
/**
* Paint the sprite's path, if any, to the specified graphics context.
*
* @param gfx the graphics context.
*/
public void paintPath (Graphics2D gfx)
{
if (_path != null) {
_path.paint(gfx);
}
}
/**
* Returns true if the sprite's bounds contain the specified point,
* false if not.
*/
public boolean contains (int x, int y)
{
return _bounds.contains(x, y);
}
/**
* Returns true if the sprite's bounds contain the specified point,
* false if not.
*/
public boolean hitTest (int x, int y)
{
return _bounds.contains(x, y);
}
/**
* Returns whether the sprite is inside the given shape in pixel
* coordinates.
*/
public boolean inside (Shape shape)
{
return shape.contains(_ox, _oy);
}
/**
* Returns whether the sprite's drawn rectangle intersects the given
* shape in pixel coordinates.
*/
public boolean intersects (Shape shape)
{
return shape.intersects(_bounds);
}
/**
* Returns true if this sprite is currently following a path, false if
* it is not.
*/
public boolean isMoving ()
{
return (_path != null);
}
/**
* Set the sprite's active path and start moving it along its merry
* way. If the sprite is already moving along a previous path the old
* path will be lost and the new path will begin to be traversed.
*
* @param path the path to follow.
*/
public void move (Path path)
{
// save off this path
_path = path;
// we'll initialize it on our next tick thanks to a zero path stamp
_pathStamp = 0;
}
/**
* Cancels any path that the sprite may currently be moving along.
*/
public void cancelMove ()
{
// TODO: make sure we come to a stop on a full coordinate,
// even in the case where we aborted a path mid-traversal.
_path = null;
}
/**
* Returns the path being followed by this sprite or null if the
* sprite is not following a path.
*/
public Path getPath ()
{
return _path;
}
/**
* Called by the active path when it begins.
*/
public void pathBeginning ()
{
// nothing for now
}
/**
* Called by the active path when it has completed.
*/
public void pathCompleted (long timestamp)
{
// keep a reference to the path just completed
Path oldpath = _path;
// clear out the path we've now finished
_path = null;
// inform observers that we've finished our path
notifyObservers(new PathCompletedEvent(this, timestamp, oldpath));
}
// documentation inherited
public void tick (long tickStamp)
{
tickPath(tickStamp);
}
/**
* Ticks any path assigned to this sprite.
*
* @return true if the path relocated the sprite as a result of this
* tick, false if it remained in the same position.
*/
protected boolean tickPath (long tickStamp)
{
if (_path == null) {
return false;
}
// initialize the path if we haven't yet
if (_pathStamp == 0) {
_path.init(this, _pathStamp = tickStamp);
}
// it's possible that as a result of init() the path completed and
// removed itself with a call to pathCompleted(), so we have to be
// careful here
return (_path == null) ? true : _path.tick(this, tickStamp);
}
// documentation inherited
public void fastForward (long timeDelta)
{
// fast forward any path we're following
if (_path != null) {
_path.fastForward(timeDelta);
}
}
/**
* Update the coordinates at which the sprite image is drawn to
* reflect the sprite's current position.
*/
protected void updateRenderOrigin ()
{
// our bounds origin may differ from the sprite's origin
_bounds.x = _ox - _oxoff;
_bounds.y = _oy - _oyoff;
}
/**
* Add a sprite observer to observe this sprite's events.
*
* @param obs the sprite observer.
*/
public void addSpriteObserver (SpriteObserver obs)
{
addObserver(obs);
}
/**
* Remove a sprite observer.
*/
public void removeSpriteObserver (SpriteObserver obs)
{
removeObserver(obs);
}
/**
* Inform all sprite observers of a sprite event.
*
* @param event the sprite event.
*/
protected void notifyObservers (SpriteEvent event)
{
if (_observers != null) {
_mgr.queueNotification(_observers, event);
}
}
// documentation inherited
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", ox=").append(_ox);
buf.append(", oy=").append(_oy);
buf.append(", oxoff=").append(_oxoff);
buf.append(", oyoff=").append(_oyoff);
}
/** The location of the sprite's origin in pixel coordinates. If the
* sprite positions itself via a hotspot that is not the upper left
* coordinate of the sprite's bounds, the offset to the hotspot should
* be maintained in {@link #_oxoff} and {@link #_oyoff}. */
protected int _ox = Integer.MIN_VALUE, _oy = Integer.MIN_VALUE;
/** The offsets from our upper left coordinate to our origin (or hot
* spot). Derived classes will need to update these values if the
* sprite's origin is not coincident with the upper left coordinate of
* its bounds. */
protected int _oxoff, _oyoff;
/** The orientation of this sprite. */
protected int _orient = NONE;
/** When moving, the path the sprite is traversing. */
protected Path _path;
/** The timestamp at which we started along our path. */
protected long _pathStamp;
}
|
package org.jsmpp.session;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.jsmpp.BindType;
import org.jsmpp.DefaultPDUReader;
import org.jsmpp.DefaultPDUSender;
import org.jsmpp.InterfaceVersion;
import org.jsmpp.InvalidCommandLengthException;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.NumberingPlanIndicator;
import org.jsmpp.PDUReader;
import org.jsmpp.PDUSender;
import org.jsmpp.PDUStringException;
import org.jsmpp.SMPPConstant;
import org.jsmpp.SynchronizedPDUReader;
import org.jsmpp.SynchronizedPDUSender;
import org.jsmpp.TypeOfNumber;
import org.jsmpp.bean.BindResp;
import org.jsmpp.bean.Command;
import org.jsmpp.bean.DataCoding;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.EnquireLinkResp;
import org.jsmpp.bean.QuerySmResp;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SubmitSmResp;
import org.jsmpp.bean.UnbindResp;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.PendingResponse;
import org.jsmpp.extra.ProcessMessageException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.state.SMPPSessionState;
import org.jsmpp.util.DefaultComposer;
import org.jsmpp.util.Sequence;
/**
* @author uudashr
* @version 2.0
*
*/
public class SMPPSession {
private static final Logger logger = Logger.getLogger(SMPPSession.class);
private static final PDUSender pduSender = new SynchronizedPDUSender(new DefaultPDUSender(new DefaultComposer()));
private static final PDUReader pduReader = new SynchronizedPDUReader(new DefaultPDUReader());
private static final AtomicInteger sessionIdSequence = new AtomicInteger();
private Socket socket = new Socket();
private DataInputStream in;
private OutputStream out;
private SessionState sessionState = SessionState.CLOSED;
private SMPPSessionState stateProcessor = SMPPSessionState.CLOSED;
private final Sequence sequence = new Sequence();
private final SMPPSessionHandler sessionHandler = new SMPPSessionHandlerImpl();
private final Hashtable<Integer, PendingResponse<? extends Command>> pendingResponse = new Hashtable<Integer, PendingResponse<? extends Command>>();
private int sessionTimer = 5000;
private long transactionTimer = 2000;
private int enquireLinkToSend;
private long lastActivityTimestamp;
private MessageReceiverListener messageReceiverListener;
private SessionStateListener sessionStateListener;
private IdleActivityChecker idleActivityChecker;
private EnquireLinkSender enquireLinkSender;
private int sessionId = sessionIdSequence.incrementAndGet();
public SMPPSession() {
}
public int getSessionId() {
return sessionId;
}
public void connectAndBind(String host, int port, BindType bindType,
String systemId, String password, String systemType,
TypeOfNumber addrTon, NumberingPlanIndicator addrNpi,
String addressRange) throws IOException {
if (sequence.currentValue() != 0)
throw new IOException("Failed connecting");
socket.connect(new InetSocketAddress(host, port));
if (socket.getInputStream() == null) {
logger.fatal("InputStream is null");
} else if (socket.isInputShutdown()) {
logger.fatal("Input shutdown");
}
logger.info("Connected");
changeState(SessionState.OPEN);
try {
in = new DataInputStream(socket.getInputStream());
new PDUReaderWorker().start();
new PDUReaderWorker().start();
new PDUReaderWorker().start();
out = socket.getOutputStream();
sendBind(bindType, systemId, password, systemType,
InterfaceVersion.IF_34, addrTon, addrNpi, addressRange);
changeToBoundState(bindType);
socket.setSoTimeout(sessionTimer);
enquireLinkSender = new EnquireLinkSender();
enquireLinkSender.start();
idleActivityChecker = new IdleActivityChecker();
idleActivityChecker.start();
} catch (PDUStringException e) {
logger.error("Failed sending bind command", e);
} catch (NegativeResponseException e) {
String message = "Receive negative bind response";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (InvalidResponseException e) {
String message = "Receive invalid response of bind";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (ResponseTimeoutException e) {
String message = "Waiting bind response take time to long";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (IOException e) {
logger.error("IO Error occure", e);
closeSocket();
throw e;
}
}
/**
* @param bindType
* @param systemId
* @param password
* @param systemType
* @param interfaceVersion
* @param addrTon
* @param addrNpi
* @param addressRange
* @return SMSC system id.
* @throws PDUStringException if we enter invalid bind parameter(s).
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws NegativeResponseException if we receive negative response.
* @throws IOException
*/
private String sendBind(BindType bindType, String systemId,
String password, String systemType,
InterfaceVersion interfaceVersion, TypeOfNumber addrTon,
NumberingPlanIndicator addrNpi, String addressRange)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<BindResp> pendingResp = new PendingResponse<BindResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendBind(out, bindType, seqNum, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange);
} catch (IOException e) {
logger.error("Failed sending bind command", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Bind response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(pendingResp.getResponse().getCommandStatus());
return pendingResp.getResponse().getSystemId();
}
/**
* Ensure we have proper link.
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws IOException
*/
private void enquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<EnquireLinkResp> pendingResp = new PendingResponse<EnquireLinkResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendEnquireLink(out, seqNum);
} catch (IOException e) {
logger.error("Failed sending enquire link", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Enquire link response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK) {
// this is ok
logger.warn("Receive NON-OK response of enquire link");
}
}
public void unbindAndClose() {
try {
unbind();
} catch (ResponseTimeoutException e) {
logger.error("Timeout waiting unbind response", e);
} catch (InvalidResponseException e) {
logger.error("Receive invalid unbind response", e);
} catch (IOException e) {
logger.error("IO error found ", e);
}
closeSocket();
}
private void unbind() throws ResponseTimeoutException, InvalidResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<UnbindResp> pendingResp = new PendingResponse<UnbindResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendUnbind(out, seqNum);
} catch (IOException e) {
logger.error("Failed sending unbind", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Unbind response received");
changeState(SessionState.UNBOUND);
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
logger.warn("Receive NON-OK response of unbind");
}
/**
* @param serviceType
* @param sourceAddrTon
* @param sourceAddrNpi
* @param sourceAddr
* @param destAddrTon
* @param destAddrNpi
* @param destinationAddr
* @param esmClass
* @param protocoId
* @param priorityFlag
* @param scheduleDeliveryTime
* @param validityPeriod
* @param registeredDelivery
* @param replaceIfPresent
* @param dataCoding
* @param smDefaultMsgId
* @param shortMessage
* @return message id.
* @throws PDUStringException if we enter invalid bind parameter(s).
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws NegativeResponseException if we receive negative response.
* @throws IOException
*/
public String submitShortMessage(String serviceType,
TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi,
String sourceAddr, TypeOfNumber destAddrTon,
NumberingPlanIndicator destAddrNpi, String destinationAddr,
ESMClass esmClass, byte protocoId, byte priorityFlag,
String scheduleDeliveryTime, String validityPeriod,
RegisteredDelivery registeredDelivery, byte replaceIfPresent,
DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<SubmitSmResp> pendingResp = new PendingResponse<SubmitSmResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendSubmitSm(out, seqNum, serviceType, sourceAddrTon,
sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi,
destinationAddr, esmClass, protocoId, priorityFlag,
scheduleDeliveryTime, validityPeriod, registeredDelivery,
replaceIfPresent, dataCoding, smDefaultMsgId, shortMessage);
} catch (IOException e) {
logger.error("Failed submit short message", e);
pendingResponse.remove(seqNum);
closeSocket();
throw e;
}
try {
pendingResp.waitDone();
logger.debug("Submit sm response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
logger.debug("Response timeout for submit_sm with sessionIdSequence number " + seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(pendingResp.getResponse().getCommandStatus());
return pendingResp.getResponse().getMessageId();
}
public QuerySmResult queryShortMessage(String messageId, TypeOfNumber sourceAddrTon,
NumberingPlanIndicator sourceAddrNpi, String sourceAddr)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<QuerySmResp> pendingResp = new PendingResponse<QuerySmResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendQuerySm(out, seqNum, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr);
} catch (IOException e) {
logger.error("Failed submit short message", e);
pendingResponse.remove(seqNum);
closeSocket();
throw e;
}
try {
pendingResp.waitDone();
logger.info("Query sm response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
QuerySmResp resp = pendingResp.getResponse();
if (resp.getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(resp.getCommandStatus());
if (resp.getMessageId().equals(messageId)) {
return new QuerySmResult(resp.getFinalDate(), resp.getMessageState(), resp.getErrorCode());
} else {
// message id requested not same as the returned
throw new InvalidResponseException("Requested message_id doesn't match with the result");
}
}
private void changeToBoundState(BindType bindType) {
if (bindType.equals(BindType.BIND_TX)) {
changeState(SessionState.BOUND_TX);
} else if (bindType.equals(BindType.BIND_RX)) {
changeState(SessionState.BOUND_RX);
} else if (bindType.equals(BindType.BIND_TRX)){
changeState(SessionState.BOUND_TRX);
} else {
throw new IllegalArgumentException("Bind type " + bindType + " not supported");
}
try {
socket.setSoTimeout(sessionTimer);
} catch (SocketException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
private synchronized void changeState(SessionState newState) {
if (sessionState != newState) {
final SessionState oldState = sessionState;
sessionState = newState;
// change the session state processor
if (sessionState == SessionState.OPEN) {
stateProcessor = SMPPSessionState.OPEN;
} else if (sessionState == SessionState.BOUND_RX) {
stateProcessor = SMPPSessionState.BOUND_RX;
} else if (sessionState == SessionState.BOUND_TX) {
stateProcessor = SMPPSessionState.BOUND_TX;
} else if (sessionState == SessionState.BOUND_TRX) {
stateProcessor = SMPPSessionState.BOUND_TRX;
} else if (sessionState == SessionState.UNBOUND) {
stateProcessor = SMPPSessionState.UNBOUND;
} else if (sessionState == SessionState.CLOSED) {
stateProcessor = SMPPSessionState.CLOSED;
}
fireChangeState(newState, oldState);
}
}
private void updateActivityTimestamp() {
lastActivityTimestamp = System.currentTimeMillis();
}
private void addEnquireLinkJob() {
enquireLinkToSend++;
}
public int getSessionTimer() {
return sessionTimer;
}
public void setSessionTimer(int sessionTimer) {
this.sessionTimer = sessionTimer;
if (sessionState.isBound()) {
try {
socket.setSoTimeout(sessionTimer);
} catch (SocketException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
}
public long getTransactionTimer() {
return transactionTimer;
}
public void setTransactionTimer(long transactionTimer) {
this.transactionTimer = transactionTimer;
}
public synchronized SessionState getSessionState() {
return sessionState;
}
public void setSessionStateListener(
SessionStateListener sessionStateListener) {
this.sessionStateListener = sessionStateListener;
}
public void setMessageReceiverListener(
MessageReceiverListener messageReceiverListener) {
this.messageReceiverListener = messageReceiverListener;
}
private void closeSocket() {
changeState(SessionState.CLOSED);
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Failed closing socket", e);
}
}
}
private synchronized boolean isReadPdu() {
return sessionState.isBound() || sessionState.equals(SessionState.OPEN);
}
private void readPDU() {
try {
Command pduHeader = null;
byte[] pdu = null;
synchronized (in) {
pduHeader = pduReader.readPDUHeader(in);
pdu = pduReader.readPDU(in, pduHeader);
}
switch (pduHeader.getCommandId()) {
case SMPPConstant.CID_BIND_RECEIVER_RESP:
case SMPPConstant.CID_BIND_TRANSMITTER_RESP:
case SMPPConstant.CID_BIND_TRANSCEIVER_RESP:
updateActivityTimestamp();
stateProcessor.processBindResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_GENERIC_NACK:
updateActivityTimestamp();
stateProcessor.processGenericNack(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_ENQUIRE_LINK:
updateActivityTimestamp();
stateProcessor.processEnquireLink(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_ENQUIRE_LINK_RESP:
updateActivityTimestamp();
stateProcessor.processEnquireLinkResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_SUBMIT_SM_RESP:
updateActivityTimestamp();
stateProcessor.processSubmitSmResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_QUERY_SM_RESP:
updateActivityTimestamp();
stateProcessor.processQuerySmResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_DELIVER_SM:
updateActivityTimestamp();
stateProcessor.processDeliverSm(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_UNBIND:
updateActivityTimestamp();
stateProcessor.processUnbind(pduHeader, pdu, sessionHandler);
changeState(SessionState.UNBOUND);
break;
case SMPPConstant.CID_UNBIND_RESP:
updateActivityTimestamp();
stateProcessor.processUnbindResp(pduHeader, pdu, sessionHandler);
break;
default:
stateProcessor.processUnknownCid(pduHeader, pdu, sessionHandler);
}
} catch (InvalidCommandLengthException e) {
logger.warn("Receive invalid command length", e);
// FIXME uud: response to this error, generick nack or close socket
} catch (SocketTimeoutException e) {
addEnquireLinkJob();
//try { Thread.sleep(1); } catch (InterruptedException ee) {}
} catch (IOException e) {
closeSocket();
}
}
@Override
protected void finalize() throws Throwable {
closeSocket();
}
private void fireAcceptDeliverSm(DeliverSm deliverSm) throws ProcessMessageException {
if (messageReceiverListener != null) {
messageReceiverListener.onAcceptDeliverSm(deliverSm);
} else {
logger.warn("Receive deliver_sm but MessageReceiverListener is null. Short message = " + new String(deliverSm.getShortMessage()));
}
}
private void fireChangeState(SessionState newState, SessionState oldState) {
if (sessionStateListener != null) {
sessionStateListener.onStateChange(newState, oldState, this);
} else {
logger.warn("SessionStateListener is null");
}
}
private class SMPPSessionHandlerImpl implements SMPPSessionHandler {
public void processDeliverSm(DeliverSm deliverSm) throws ProcessMessageException {
fireAcceptDeliverSm(deliverSm);
}
@SuppressWarnings("unchecked")
public PendingResponse<Command> removeSentItem(int sequenceNumber) {
return (PendingResponse<Command>)pendingResponse.remove(sequenceNumber);
}
public void sendDeliverSmResp(int sequenceNumber) throws IOException {
try {
pduSender.sendDeliverSmResp(out, sequenceNumber);
// FIXME uud: delete this log
logger.debug("deliver_sm_resp with seq_number " + sequenceNumber + " has been sent");
} catch (PDUStringException e) {
logger.fatal("Failed sending deliver_sm_resp", e);
}
}
public void sendEnquireLinkResp(int sequenceNumber) throws IOException {
pduSender.sendEnquireLinkResp(out, sequenceNumber);
}
public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException {
pduSender.sendGenericNack(out, commandStatus, sequenceNumber);
}
public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException {
pduSender.sendHeader(out, originalCommandId | SMPPConstant.MASK_CID_RESP, commandStatus, sequenceNumber);
}
public void sendUnbindResp(int sequenceNumber) throws IOException {
pduSender.sendUnbindResp(out, SMPPConstant.STAT_ESME_ROK, sequenceNumber);
}
}
private class PDUReaderWorker extends Thread {
@Override
public void run() {
logger.info("Starting PDUReaderWorker");
while (isReadPdu()) {
readPDU();
}
logger.info("PDUReaderWorker stop");
}
}
private class EnquireLinkSender extends Thread {
@Override
public void run() {
logger.info("Starting EnquireLinkSender");
while (isReadPdu()) {
long sleepTime = 1000;
if (enquireLinkToSend > 0) {
enquireLinkToSend
try {
enquireLink();
} catch (ResponseTimeoutException e) {
closeSocket();
} catch (InvalidResponseException e) {
// lets unbind gracefully
unbindAndClose();
} catch (IOException e) {
closeSocket();
}
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
logger.info("EnquireLinkSender stop");
}
}
private class IdleActivityChecker extends Thread {
@Override
public void run() {
logger.info("Starting IdleActivityChecker");
while (isReadPdu()) {
long timeLeftToEnquire = lastActivityTimestamp + sessionTimer - System.currentTimeMillis();
if (timeLeftToEnquire <= 0) {
try {
enquireLink();
} catch (ResponseTimeoutException e) {
closeSocket();
} catch (InvalidResponseException e) {
// lets unbind gracefully
unbindAndClose();
} catch (IOException e) {
closeSocket();
}
} else {
try {
Thread.sleep(timeLeftToEnquire);
} catch (InterruptedException e) {
}
}
}
logger.info("IdleActivityChecker stop");
}
}
}
|
package oemware.core.apictrl;
// OEMware
import oemware.core.util.JaxbUtils;
import oemware.core.Kernel;
// OEMware Jaxb
import oemware.core.apictrl.config.ControllersDef;
import oemware.core.apictrl.config.ControllerDef;
import oemware.core.apictrl.config.ConstructorArgDef;
import oemware.core.apictrl.config.ActionDef;
// Jakarta Commons
import org.apache.commons.beanutils.ConstructorUtils;
import org.apache.commons.beanutils.MethodUtils;;
import org.apache.commons.lang.StringUtils;
// Java
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
/**
* The api controller.
*
* @author Ryan Nitz
* @version $Id$
*/
public final class ApiController {
private Map<String, Controller> mControllers;
private final Object mMutex = new Object();
private final String mConfigFile;
private final String mName;
private static final String CONFIG_PACKAGE = "oemware.core.apictrl.config";
/**
* Construct with args.
* @param pName A unique name to identify problems in log files..
* @param pConfigFile The configuration file name. This file needs
* to be in the Java classpath.
*/
public ApiController(final String pName, final String pConfigFile) {
mName = pName;
mConfigFile = pConfigFile;
}
/**
* Execute the action.
* @param pContext The action context.
*/
public final void executeAction(final ActionContext pContext) {
executeAction( pContext.getControllerPath(),
pContext.getActionName(),
pContext);
}
/**
* Execute the action.
* @param pControllerPathThe controller path.
* @param pActionName The action name.
* @param pContext The action context.
*/
public final void executeAction(final String pControllerPath,
final String pActionName,
final ActionContext pContext)
{
try {
final Controller controller = getControllers().get(pControllerPath);
if (controller == null) {
throw new RuntimeException( "controller not found: "
+ pControllerPath);
}
final Action action = controller.findAction(pActionName);
if (action == null) {
throw new RuntimeException( "action not found: "
+ pActionName);
}
// Invoke the method on the controller.
MethodUtils.invokeExactMethod(controller, action.getName(), pContext);
} catch (final Throwable t)
{ throw new IllegalStateException(mName + " - " + t.getMessage(), t); }
}
/**
* Returns the controllers.
* @return The controllers.
*/
private Map<String, Controller> getControllers() {
if (mControllers != null) return mControllers;
synchronized(mMutex) {
if (mControllers != null) return mControllers;
final Map<String, Controller> controllers
= new HashMap<String, Controller>();
for (final ControllerDef def : loadControllerDefs(mConfigFile))
{ controllers.put(def.getPath(), loadController(def)); }
mControllers = controllers;
}
return mControllers;
}
/**
* Load the feature command.
* @param pControllerDef The controller definition.
* @return The object.
* @throws Exception
*/
private Controller loadController(final ControllerDef pControllerDef) {
try {
final Class clazz
= Thread.currentThread().getContextClassLoader().loadClass(pControllerDef.getClazz());
final LinkedList<Object> args = new LinkedList<Object>();
for (ConstructorArgDef argDef : pControllerDef.getConstructorArg()) {
final String componentId = StringUtils.trimToNull(argDef.getComponentId());
final String value = StringUtils.trimToNull(argDef.getValue());
final String valueType = StringUtils.trimToNull(argDef.getValueType());
if (componentId != null) {
args.addLast(Kernel.findComponent(componentId));
} else if (value != null) {
if (valueType == null) {
throw new IllegalStateException(mName
+ " - vaue requires value-type");
}
if (valueType.equals("int")) {
args.addLast(Integer.parseInt(value));
} else if (valueType.equals("double")) {
args.addLast(Double.parseDouble(value));
} else if (valueType.equals("long")) {
args.addLast(Long.parseLong(value));
} else if (valueType.equals("short")) {
args.addLast(Short.parseShort(value));
} else if (valueType.equals("float")) {
args.addLast(Float.parseFloat(value));
} else if (valueType.equals("bool")) {
args.addLast(Boolean.parseBoolean(value));
} else if (valueType.equals("string")) {
args.addLast(value);
}
} else {
throw new IllegalStateException(mName
+ " - requires component-id or value");
}
}
final Controller controller
= (Controller)ConstructorUtils.invokeConstructor(clazz, args.toArray(new Object[args.size()]));
for (final ActionDef actionDef : pControllerDef.getAction()) {
controller.addAction(createAction(actionDef));
}
return controller;
} catch (final Throwable t)
{ throw new IllegalStateException(mName + " - " + t.getMessage(), t); }
}
/**
* Create an action object.
* @param pActionDef The action definition.
*/
private Action createAction(final ActionDef pActionDef) {
final Action action = new Action(pActionDef.getName());
return action;
}
/**
* Returns the controlller definitions (loads).
* @param pConfigFile The configuration file.
*/
private List<ControllerDef> loadControllerDefs(final String pConfigFile) {
try {
// Load the controller definitions.
final ControllersDef def
= (ControllersDef)JaxbUtils.jaxbUnmarshal(pConfigFile, CONFIG_PACKAGE);
return def.getController();
} catch (final Throwable t)
{ throw new IllegalStateException(mName + " - " + t.getMessage(), t); }
}
}
|
package org.apache.velocity.test.misc;
import java.io.*;
import java.util.*;
import org.apache.velocity.Context;
import org.apache.velocity.Template;
import org.apache.velocity.io.*;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.test.provider.TestProvider;
/**
* This class the testbed for Velocity. It is used to
* test all the directives support by Velocity.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
* @version $Id: Test.java,v 1.8 2000/11/30 05:24:56 geirm Exp $
*/
public class Test
{
/**
* Cache of writers
*/
private static Stack writerStack = new Stack();
public Test(String templateFile)
{
Writer writer = null;
TestProvider provider = new TestProvider();
ArrayList al = provider.getCustomers();
Hashtable h = new Hashtable();
/*
* put this in to test introspection $h.Bar or $h.get("Bar") etc
*/
h.put("Bar", "this is from a hashtable!");
/*
* adding simple vector with strings for testing late introspection stuff
*/
Vector v = new Vector();
v.addElement( new String("hello") );
v.addElement( new String("hello2") );
try
{
/*
* this is another way to do properties when initializing Runtime.
* make a Properties
*/
Properties p = new Properties();
/*
* now, if you want to, load it from a file (or whatever)
*/
try
{
FileInputStream fis = new FileInputStream( new File("velocity.properties" ));
if( fis != null)
p.load( fis );
}
catch (Exception ex)
{
/* no worries. no file... */
}
/*
* add some individual properties if you wish
*/
p.setProperty(Runtime.RUNTIME_LOG_ERROR_STACKTRACE, "true");
p.setProperty(Runtime.RUNTIME_LOG_WARN_STACKTRACE, "true");
p.setProperty(Runtime.RUNTIME_LOG_INFO_STACKTRACE, "true");
/*
* and now call init
*/
Runtime.init(p);
/*
* now, do what we want to do. First, get the Template
*/
if (templateFile == null)
templateFile = "examples/example.vm";
Template template = Runtime.getTemplate(templateFile);
/*
* now, make a Context object and populate it.
*/
Context context = new Context();
context.put("provider", provider);
context.put("name", "jason");
context.put("providers", provider.getCustomers2());
context.put("list", al);
context.put("hashtable", h);
context.put("search", provider.getSearch());
context.put("relatedSearches", provider.getRelSearches());
context.put("searchResults", provider.getRelSearches());
context.put("menu", provider.getMenu());
context.put("stringarray", provider.getArray());
context.put("vector", v);
context.put("mystring", new String());
/*
* make a writer, and merge the template 'against' the context
*/
writer = new BufferedWriter(new OutputStreamWriter(System.out));
template.merge(context, writer);
writer.flush();
writer.close();
}
catch( Exception e )
{
Runtime.error(e);
}
}
public static void main(String[] args)
{
Test t;
t = new Test(args[0]);
}
}
|
package org.jivesoftware.util;
import java.util.*;
/**
* Centralized management of caches. Caches are essential for performance and scalability.
*
* @see Cache
* @author Matt Tucker
*/
public class CacheManager {
private static Map<String, Cache> caches = new HashMap<String, Cache>();
private static final long DEFAULT_EXPIRATION_TIME = JiveConstants.HOUR * 6;
/**
* Initializes a cache given it's name and max size. The default expiration time
* of six hours will be used. If a cache with the same name has already been initialized,
* this method returns the existing cache.<p>
*
* The size and expiration time for the cache can be overridden by setting Jive properties
* in the format:<ul>
*
* <li>Size: "cache.CACHE_NAME.size", in bytes.
* <li>Expiration: "cache.CACHE_NAME.expirationTime", in milleseconds.
* </ul>
* where CACHE_NAME is the name of the cache.
*
* @param name the name of the cache to initialize.
* @param size the size the cache can grow to, in bytes.
*/
public static Cache initializeCache(String name, int size) {
return initializeCache(name, size, DEFAULT_EXPIRATION_TIME);
}
/**
* Initializes a cache given it's name, max size, and expiration time. If a cache with
* the same name has already been initialized, this method returns the existing cache.<p>
*
* The size and expiration time for the cache can be overridden by setting Jive properties
* in the format:<ul>
*
* <li>Size: "cache.CACHE_NAME.size", in bytes.
* <li>Expiration: "cache.CACHE_NAME.expirationTime", in milleseconds.
* </ul>
* where CACHE_NAME is the name of the cache.
*
* @param name the name of the cache to initialize.
* @param size the size the cache can grow to, in bytes.
*/
public static Cache initializeCache(String name, int size, long expirationTime) {
Cache cache = caches.get(name);
if (cache == null) {
size = JiveGlobals.getIntProperty("cache." + name + ".size", size);
expirationTime = (long)JiveGlobals.getIntProperty("cache." + name + ".expirationTime",
(int)expirationTime);
caches.put(name, new Cache(name, size, expirationTime));
}
return cache;
}
/**
* Returns the cache specified by name. The cache must be initialized before this
* method can be called.
*
* @param name the name of the cache to return.
* @return the cache found, or <tt>null</tt> if no cache by that name
* has been initialized.
*/
public static Cache getCache(String name) {
return caches.get(name);
}
}
|
package jmetest.renderer.loader;
import com.jme.app.SimpleGame;
import com.jme.scene.model.XMLparser.JmeBinaryReader;
import com.jme.scene.model.XMLparser.BinaryToXML;
import com.jme.scene.model.XMLparser.Converters.MaxToJme;
import com.jme.scene.Node;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.scene.shape.Box;
import com.jme.math.Vector3f;
import com.jme.math.Quaternion;
import com.jme.math.FastMath;
import com.jme.bounding.BoundingBox;
import com.jme.renderer.ColorRGBA;
import java.io.*;
import java.net.URL;
public class TestMaxJmeWrite extends SimpleGame{
public static void main(String[] args) {
TestMaxJmeWrite app=new TestMaxJmeWrite();
app.setDialogBehaviour(SimpleGame.FIRSTRUN_OR_NOCONFIGFILE_SHOW_PROPS_DIALOG);
app.start();
}
Node globalLoad=null;
protected void simpleInitGame() {
MaxToJme C1=new MaxToJme();
try {
ByteArrayOutputStream BO=new ByteArrayOutputStream();
// URL maxFile=TestMaxJmeWrite.class.getClassLoader().getResource("jmetest/data/model/cutsphere.3DS");
URL maxFile=TestMaxJmeWrite.class.getClassLoader().getResource("jmetest/data/model/Character.3DS");
// URL maxFile = new File("3dsmodels/sphere.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/cobra.3DS").toURI().toURL();
// URL maxFile = new File("3dsmodels/movedpivot.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/Character.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/test1.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/cutsphere.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/cube.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/face.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/pitbull.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/celt.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/tpot.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/europe.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/sphere.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/cow.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/growingcube.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/simpani.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/tank.3ds").toURI().toURL();
// URL maxFile = new File("3dsmodels/simpmovement.3DS").toURI().toURL();
C1.convert(new BufferedInputStream(maxFile.openStream()),BO);
JmeBinaryReader jbr=new JmeBinaryReader();
// jbr.setProperty("texulr",new File("3dsmodels").toURL());
BinaryToXML btx=new BinaryToXML();
StringWriter SW=new StringWriter();
btx.sendBinarytoXML(new ByteArrayInputStream(BO.toByteArray()),SW);
System.out.println(SW);
jbr.setProperty("bound","box");
Node r=jbr.loadBinaryFormat(new ByteArrayInputStream(BO.toByteArray()));
r.setLocalScale(.1f);
if (r.getChild(0).getControllers().size()!=0)
r.getChild(0).getController(0).setSpeed(20);
Quaternion temp=new Quaternion();
temp.fromAngleAxis(FastMath.PI/2,new Vector3f(-1,0,0));
rootNode.setForceView(true);
rootNode.setLocalRotation(temp);
rootNode.attachChild(r);
} catch (IOException e) {
System.out.println("Damn exceptions:"+e);
e.printStackTrace();
}
drawAxis();
}
private void drawAxis() {
Box Xaxis=new Box("axisX",new Vector3f(5,0,0),5f,.1f,.1f);
Xaxis.setModelBound(new BoundingBox());
Xaxis.updateModelBound();
Xaxis.setSolidColor(ColorRGBA.red);
MaterialState red=display.getRenderer().getMaterialState();
red.setEmissive(ColorRGBA.red);
red.setEnabled(true);
Xaxis.setRenderState(red);
Box Yaxis=new Box("axisY",new Vector3f(0,5,0),.1f,5f,.1f);
Yaxis.setModelBound(new BoundingBox());
Yaxis.updateModelBound();
Yaxis.setSolidColor(ColorRGBA.green);
MaterialState green=display.getRenderer().getMaterialState();
green.setEmissive(ColorRGBA.green);
green.setEnabled(true);
Yaxis.setRenderState(green);
Box Zaxis=new Box("axisZ",new Vector3f(0,0,5),.1f,.1f,5f);
Zaxis.setSolidColor(ColorRGBA.blue);
Zaxis.setModelBound(new BoundingBox());
Zaxis.updateModelBound();
MaterialState blue=display.getRenderer().getMaterialState();
blue.setEmissive(ColorRGBA.blue);
blue.setEnabled(true);
Zaxis.setRenderState(blue);
rootNode.attachChild(Xaxis);
rootNode.attachChild(Yaxis);
rootNode.attachChild(Zaxis);
}
}
|
package name.cs.csutils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import name.cs.csutils.Platform.OS;
public class Launcher {
private static Launcher INSTANCE = newInstance();
private static Launcher PREFERRED_LAUNCHER = new Java6Launcher();
private static Launcher newInstance() {
if (Platform.isFlavor(OS.UnixFlavor)) {
return new UnixBrowserLauncher();
} else if (Platform.isFlavor(OS.MacOSFlavor)) {
return new MacBrowserLauncher();
} else if (Platform.isFlavor(OS.WindowsFlavor)) {
return new WindowsBrowserLauncher();
} else {
// no support
return new Launcher();
}
}
// hide constructor
private Launcher() {
super();
}
public static Launcher getInstance() {
return Launcher.INSTANCE;
}
public boolean launchURL(URL url) {
return Launcher.PREFERRED_LAUNCHER.launchURL(url);
}
public boolean isLaunchURLSupported() {
return Launcher.PREFERRED_LAUNCHER.isLaunchURLSupported();
}
public boolean launchMailto(URI mailtoURI) {
return Launcher.PREFERRED_LAUNCHER.launchMailto(mailtoURI);
}
public boolean isLaunchMailtoSupported() {
return Launcher.PREFERRED_LAUNCHER.isLaunchMailtoSupported();
}
private static boolean exec(String ... command) {
Process proc = null;
CSUtils.ProcessResult res = null;
try {
proc = new ProcessBuilder(command).start();
res = CSUtils.waitFor(proc, 6000, 250);
return !res.timeout && res.status == 0;
} catch (Exception ex) {
return false;
} finally {
if (proc != null) {
proc.destroy();
}
if (res != null && res.interrupted) {
Thread.currentThread().interrupt();
}
}
}
private final static class WindowsBrowserLauncher extends Launcher {
@Override
public boolean launchURL(URL url) {
if (super.launchURL(url)) {
return true;
}
return Launcher.exec(
"rundll32.exe", "url.dll,FileProtocolHandler",
url.toExternalForm());
}
@Override
public boolean isLaunchURLSupported() {
return true;
}
}
private final static class MacBrowserLauncher extends Launcher {
private static Log log = LogFactory.getLog(MacBrowserLauncher.class);
private static final String CLASS_FILEMANAGER = "com.apple.eio.FileManager";
@Override
public boolean launchURL(URL url) {
if (super.launchURL(url)) {
return true;
}
// try first launch-method
try {
Class<?> fileManager = Class.forName(CLASS_FILEMANAGER);
Method openURL = fileManager.getDeclaredMethod("openURL", new Class[] {String.class});
openURL.invoke(null, new Object[] {url.toExternalForm()});
return true;
} catch (ClassNotFoundException ex) {
if (log.isDebugEnabled()) {
log.debug("Could not launch url with "+CLASS_FILEMANAGER+". (Class not found)");
}
} catch (NoSuchMethodException ex) {
if (log.isDebugEnabled()) {
log.debug("Could not launch url with "+CLASS_FILEMANAGER
+". (openURL(java.lang.String) Method not found)");
}
} catch (IllegalAccessException ex) {
if (log.isErrorEnabled()) {
log.error("Could not launch url with "+CLASS_FILEMANAGER,
ex);
}
} catch (InvocationTargetException ex) {
if (log.isErrorEnabled()) {
log.error("Could not launch url with "+CLASS_FILEMANAGER,
ex.getTargetException());
}
} catch (RuntimeException ex) {
// no op
}
// try second launch-method
return Launcher.exec("open", url.toExternalForm());
}
@Override
public boolean isLaunchURLSupported() {
return true;
}
}
private final static class UnixBrowserLauncher extends Launcher {
private Boolean launchURLSupported = null;
// GNOME_DESKTOP_SESSION_ID
// $KDE_FULL_SESSION == 'true'
// $BROWSER
private boolean which(String executable) {
return Launcher.exec("which", executable);
}
private boolean launchURL_BROWSER_ENV_VARIABLE(String url) {
String BROWSER = System.getenv("BROWSER");
return (BROWSER != null) && Launcher.exec(BROWSER, url);
}
@Override
public synchronized boolean launchURL(URL url) {
if (super.launchURL(url)) {
return true;
}
if (!isUnixLaunchURLSupported()) {
return false;
}
final String u = url.toExternalForm();
if (launchURL_BROWSER_ENV_VARIABLE(u)) { // $BROWSER
return true;
// note: kfmclient openURL blocks and we don't get a return status == 0
// although the browser window may be opened.
// However kfmclient exec seems to work.
} else if (Platform.maybeDeskopKDE() && which("kfmclient")
&& Launcher.exec("kfmclient", "exec", u)) { // KDE
return true;
} else if (Platform.maybeDeskopGnome() && which("gnome-open")
&& Launcher.exec("gnome-open", u)) { // Gnome
return true;
}
// still not launched, find a browser
// TODO we should try the other browsers in case exec failed
// but this may cause multiple browser windows opening
if (which("firefox")) {
return Launcher.exec("firefox", u);
} else if (which("mozilla")) {
return Launcher.exec("mozilla", u);
} else if (which("konqueror")) {
return Launcher.exec("konqueror", u);
} else if (which("opera")) {
return Launcher.exec("opera", u);
} else if (which("epiphany")) {
return Launcher.exec("epiphany", u);
} else if (which("galeon")) {
return Launcher.exec("galeon", u);
} else if (which("netscape")) {
return Launcher.exec("netscape", "-remote", "openURL("+u+",new-window)");
}
return false;
}
@Override
public boolean isLaunchURLSupported() {
if (super.isLaunchURLSupported()) {
return true;
}
return isUnixLaunchURLSupported();
}
//kfmclient exec mailto:name@example.com
private synchronized boolean isUnixLaunchURLSupported() {
if (super.isLaunchURLSupported()) {
return true;
}
if (launchURLSupported != null) {
return launchURLSupported.booleanValue();
}
// we rely on the 'which' command
if (!which("which")) {
launchURLSupported = Boolean.FALSE;
return false;
}
if (System.getenv("BROWSER")!=null) { // $BROWSER
launchURLSupported = Boolean.TRUE;
return true;
} else { // KDE
if (Platform.maybeDeskopKDE() && which("kfmclient")) {
launchURLSupported = Boolean.TRUE;
return true;
}
if (Platform.maybeDeskopGnome() && which("gnome-open")) {
launchURLSupported = Boolean.TRUE;
return true;
}
String[] commands = {
"firefox", "mozilla",
"konqueror", "epiphany", "opera", "galeon",
"netscape"
};
for (String command: commands) {
if (which(command)) {
launchURLSupported = Boolean.TRUE;
return true;
}
}
if (launchURLSupported == null) {
launchURLSupported = Boolean.FALSE;
}
}
return launchURLSupported.booleanValue();
}
@Override
public boolean launchMailto(URI mailtoURI) {
if (super.launchMailto(mailtoURI)) {
return true;
}
if (Platform.maybeDeskopKDE()
&& Launcher.exec("kfmclient", "exec", mailtoURI.toString())) {
return true;
}
return false;
}
}
private static class Java6Launcher extends Launcher {
private boolean launchURL(URL url, boolean test) {
try {
// get the java.awt.Desktop class and test if this feature
// is supported
Class<?> classDesktop = Class.forName("java.awt.Desktop");
final boolean isDesktopSupported = Boolean.TRUE.equals(
classDesktop.getMethod("isDesktopSupported")
.invoke(null, new Object[0])
);
if (!isDesktopSupported) {
return false;
}
// get the java.awt.Desktop instance
Object objDesktop = classDesktop.getMethod("getDesktop").invoke(null);
// get the java.awt.Desktop$Action.BROWSE enum constant
Class<?> enumAction = Class.forName("java.awt.Desktop$Action");
Object[] enumConstants = enumAction.getEnumConstants();
if (enumConstants == null) {
return false;
}
// test if the browse action is supported
boolean browseSupported = false;
for (Object enumConstant: enumConstants) {
if ("BROWSE".equals(enumConstant.toString())) {
browseSupported = Boolean.TRUE.equals(
classDesktop.getMethod("isSupported", enumAction)
.invoke(objDesktop, enumConstant));
break;
}
}
if (!browseSupported) {
return false;
}
if (!test) {
// call browse
classDesktop.getMethod("browse", URI.class)
.invoke(objDesktop, url.toURI());
}
return true;
} catch (Throwable th) {
return false;
}
}
private boolean launchMailto(URI mailtoURI, boolean test) {
try {
// get the java.awt.Desktop class and test if this feature
// is supported
Class<?> classDesktop = Class.forName("java.awt.Desktop");
final boolean isDesktopSupported = Boolean.TRUE.equals(
classDesktop.getMethod("isDesktopSupported")
.invoke(null, new Object[0])
);
if (!isDesktopSupported) {
return false;
}
// get the java.awt.Desktop instance
Object objDesktop = classDesktop.getMethod("getDesktop").invoke(null);
// get the java.awt.Desktop$Action.BROWSE enum constant
Class<?> enumAction = Class.forName("java.awt.Desktop$Action");
Object[] enumConstants = enumAction.getEnumConstants();
if (enumConstants == null) {
return false;
}
// test if the browse action is supported
boolean browseSupported = false;
for (Object enumConstant: enumConstants) {
if ("MAIL".equals(enumConstant.toString())) {
browseSupported = Boolean.TRUE.equals(
classDesktop.getMethod("isSupported", enumAction)
.invoke(objDesktop, enumConstant));
break;
}
}
if (!browseSupported) {
return false;
}
if (!test) {
// call browse
classDesktop.getMethod("mail", URI.class)
.invoke(objDesktop, mailtoURI);
}
return true;
} catch (Throwable th) {
th.printStackTrace();
return false;
}
}
@Override
public boolean launchURL(URL url) {
if (url == null) {
throw new IllegalArgumentException("url==null");
}
return launchURL(url, false);
}
@Override
public boolean isLaunchURLSupported() {
return launchURL(null, true);
}
@Override
public boolean launchMailto(URI mailtoURI) {
return launchMailto(mailtoURI, false);
}
@Override
public boolean isLaunchMailtoSupported() {
return launchMailto(null, true);
}
}
}
|
package org.opencps.dossiermgt.search;
import java.util.ArrayList;
import java.util.List;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import org.opencps.datamgt.util.DataMgtUtil;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.util.DateTimeUtil;
import com.liferay.portal.kernel.dao.search.SearchContainer;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.ParamUtil;
/**
* @author trungnt
*/
public class DossierSearch extends SearchContainer<Dossier> {
static List<String> headerNames = new ArrayList<String>();
//static Map<String, String> orderableHeaders = new HashMap<String, String>();
static {
//comment to use ux theme
/*headerNames.add("#");
//headerNames.add("create-date");
headerNames.add("service-name");
headerNames.add("gov-agency-name");
headerNames.add("dossier-status");
headerNames.add("receive-datetime");
headerNames.add("reception-no");
headerNames.add("finish-date");
headerNames.add("action");
orderableHeaders
.put("gov-agency-name", DossierDisplayTerms.GOVAGENCY_NAME);
orderableHeaders
.put("receive-datetime", DossierDisplayTerms.RECEIVE_DATETIME);
orderableHeaders
.put("create-date", DossierDisplayTerms.CREATE_DATE);
orderableHeaders
.put("dossier-status", DossierDisplayTerms.DOSSIER_STATUS);*/
headerNames.add("dossier-info");
headerNames.add("dossier-status");
headerNames.add("action");
}
public static final String EMPTY_RESULTS_MESSAGE =
"no-dossier-were-found";
public DossierSearch(
PortletRequest portletRequest, int delta, PortletURL iteratorURL) {
super(
portletRequest, new DossierDisplayTerms(
portletRequest), new DossierSearchTerms(
portletRequest), DEFAULT_CUR_PARAM, delta, iteratorURL,
headerNames, EMPTY_RESULTS_MESSAGE);
DossierDisplayTerms displayTerms =
(DossierDisplayTerms) getDisplayTerms();
iteratorURL
.setParameter(DossierDisplayTerms.GOVAGENCY_NAME, displayTerms
.getGovAgencyName());
iteratorURL
.setParameter(DossierDisplayTerms.DOSSIER_STATUS, String.valueOf(displayTerms
.getDossierStatus()));
iteratorURL
.setParameter(DossierDisplayTerms.GROUP_ID, String
.valueOf(displayTerms
.getGroupId()));
iteratorURL
.setParameter(DossierDisplayTerms.CREATE_DATE, DateTimeUtil
.convertDateToString(displayTerms
.getCreateDate(), DateTimeUtil._VN_DATE_TIME_FORMAT));
iteratorURL
.setParameter(DossierDisplayTerms.RECEIVE_DATETIME, DateTimeUtil
.convertDateToString(displayTerms
.getReceiveDatetime(), DateTimeUtil._VN_DATE_TIME_FORMAT));
try {
String orderByCol = ParamUtil
.getString(portletRequest, "orderByCol");
String orderByType = ParamUtil
.getString(portletRequest, "orderByType");
OrderByComparator orderByComparator = DataMgtUtil
.getDictCollectionOrderByComparator(orderByCol, orderByType);
//setOrderableHeaders(orderableHeaders);
setOrderByCol(orderByCol);
setOrderByType(orderByType);
setOrderByComparator(orderByComparator);
}
catch (Exception e) {
_log
.error(e);
}
}
public DossierSearch(
PortletRequest portletRequest, PortletURL iteratorURL) {
this(
portletRequest, DEFAULT_DELTA, iteratorURL);
}
private static Log _log = LogFactoryUtil
.getLog(DossierSearch.class);
}
|
package com.liferay.webform.portlet;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.kernel.captcha.CaptchaTextException;
import com.liferay.portal.kernel.captcha.CaptchaUtil;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.mail.MailMessage;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ContentTypes;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.LocalizationUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.portlet.expando.model.ExpandoRow;
import com.liferay.portlet.expando.service.ExpandoRowLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil;
import com.liferay.portlet.expando.service.ExpandoValueLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.portlet.PortletResponseUtil;
import com.liferay.webform.util.WebFormUtil;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.internet.InternetAddress;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
/**
* @author Daniel Weisser
* @author Jorge Ferrer
* @author Alberto Montero
* @author Julio Camarero
* @author Brian Wing Shun Chan
*/
public class WebFormPortlet extends MVCPortlet {
public void deleteData(
ActionRequest actionRequest, ActionResponse actionResponse)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
WebKeys.THEME_DISPLAY);
PortletPreferences preferences =
PortletPreferencesFactoryUtil.getPortletSetup(actionRequest);
String databaseTableName = preferences.getValue(
"databaseTableName", StringPool.BLANK);
if (Validator.isNotNull(databaseTableName)) {
ExpandoTableLocalServiceUtil.deleteTable(
themeDisplay.getCompanyId(), WebFormUtil.class.getName(),
databaseTableName);
}
}
public void saveData(
ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(
WebKeys.THEME_DISPLAY);
String portletId = (String)resourceRequest.getAttribute(
WebKeys.PORTLET_ID);
String tempURL = ParamUtil.getString(resourceRequest, "referUrl");
String tempUsrName = ParamUtil.getString(resourceRequest, "usrName");
String tempScreenName = ParamUtil.getString(resourceRequest, "screenName");
String tempUsrDateStamp = ParamUtil.getString(resourceRequest, "dateStamp");
String tempSuccess = ParamUtil.getString(resourceRequest, "successURL");
System.out.println(">>>>>>>>>>>>>>>>>"+tempSuccess);
PortletPreferences preferences =
PortletPreferencesFactoryUtil.getPortletSetup(
resourceRequest, portletId);
preferences.setValue("tempURL", tempURL);
preferences.setValue("tempUsrName",tempUsrName);
preferences.setValue("tempUsrDateStamp", tempUsrDateStamp);
preferences.setValue("tempScreenName", tempScreenName);
preferences.setValue("successURL", tempSuccess);
boolean requireCaptcha = GetterUtil.getBoolean(
preferences.getValue("requireCaptcha", StringPool.BLANK));
String successURL = GetterUtil.getString(
preferences.getValue("successURL", StringPool.BLANK));
System.out.println(">>>>>>>>>>>>>>>>>"+successURL);
boolean sendAsEmail = GetterUtil.getBoolean(
preferences.getValue("sendAsEmail", StringPool.BLANK));
boolean saveToDatabase = GetterUtil.getBoolean(
preferences.getValue("saveToDatabase", StringPool.BLANK));
String databaseTableName = GetterUtil.getString(
preferences.getValue("databaseTableName", StringPool.BLANK));
boolean saveToFile = GetterUtil.getBoolean(
preferences.getValue("saveToFile", StringPool.BLANK));
String fileName = GetterUtil.getString(
preferences.getValue("fileName", StringPool.BLANK));
if (requireCaptcha) {
try {
CaptchaUtil.check(resourceRequest);
}
catch (CaptchaTextException cte) {
SessionErrors.add(
resourceRequest, CaptchaTextException.class.getName());
return;
}
}
Map<String,String> fieldsMap = new LinkedHashMap<String,String>();
for (int i = 1; true; i++) {
String fieldLabel = preferences.getValue(
"fieldLabel" + i, StringPool.BLANK);
if (Validator.isNull(fieldLabel)) {
break;
}
fieldsMap.put(fieldLabel, resourceRequest.getParameter("field" + i));
}
Set<String> validationErrors = null;
try {
validationErrors = validate(fieldsMap, preferences);
}
catch (Exception e) {
SessionErrors.add(
resourceRequest, "validation-script-error",
e.getMessage().trim());
return;
}
if (validationErrors.isEmpty()) {
boolean emailSuccess = true;
boolean databaseSuccess = true;
boolean fileSuccess = true;
if (sendAsEmail) {
emailSuccess = sendEmail(fieldsMap, preferences);
}
if (saveToDatabase) {
if (Validator.isNull(databaseTableName)) {
databaseTableName = WebFormUtil.getNewDatabaseTableName(
portletId);
preferences.setValue(
"databaseTableName", databaseTableName);
preferences.store();
}
databaseSuccess = saveDatabase(
themeDisplay.getCompanyId(), fieldsMap, preferences,
databaseTableName);
}
if (saveToFile) {
fileSuccess = saveFile(fieldsMap, fileName);
}
if (emailSuccess && databaseSuccess && fileSuccess) {
SessionMessages.add(resourceRequest, "success");
}
else {
SessionErrors.add(resourceRequest, "error");
}
}
else {
for (String badField : validationErrors) {
SessionErrors.add(resourceRequest, "error" + badField);
}
}
if (SessionErrors.isEmpty(resourceRequest) &&
Validator.isNotNull(successURL)) {
System.out.println(">>>>>>>>>>>>>>>>>!!!update d"+successURL);
getPortletContext().getRequestDispatcher(resourceResponse.encodeURL("/success.jsp")).include(resourceRequest, resourceResponse);
}
}
public void serveResource(
ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
String cmd = ParamUtil.getString(resourceRequest, Constants.CMD);
try {
if (cmd.equals("captcha")) {
serveCaptcha(resourceRequest, resourceResponse);
}
else if (cmd.equals("export")) {
exportData(resourceRequest, resourceResponse);
}else if (cmd.equals("saveData")) {
saveData(resourceRequest, resourceResponse);
}
}
catch (Exception e) {
_log.error(e, e);
}
}
protected void exportData(
ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception {
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(
WebKeys.THEME_DISPLAY);
PortletPreferences preferences =
PortletPreferencesFactoryUtil.getPortletSetup(resourceRequest);
String databaseTableName = preferences.getValue(
"databaseTableName", StringPool.BLANK);
String title = preferences.getValue("title", "no-title");
StringBuilder sb = new StringBuilder();
List<String> fieldLabels = new ArrayList<String>();
for (int i = 1; true; i++) {
String fieldLabel = preferences.getValue(
"fieldLabel" + i, StringPool.BLANK);
String localizedfieldLabel = LocalizationUtil.getPreferencesValue(
preferences, "fieldLabel" + i, themeDisplay.getLanguageId());
if (Validator.isNull(fieldLabel)) {
break;
}
fieldLabels.add(fieldLabel);
sb.append("\"");
sb.append(localizedfieldLabel.replaceAll("\"", "\\\""));
sb.append("\";");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
if (Validator.isNotNull(databaseTableName)) {
List<ExpandoRow> rows = ExpandoRowLocalServiceUtil.getRows(
themeDisplay.getCompanyId(), WebFormUtil.class.getName(),
databaseTableName, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
for (ExpandoRow row : rows) {
for (String fieldName : fieldLabels) {
String data = ExpandoValueLocalServiceUtil.getData(
themeDisplay.getCompanyId(),
WebFormUtil.class.getName(), databaseTableName,
fieldName, row.getClassPK(), StringPool.BLANK);
data = data.replaceAll("\"", "\\\"");
sb.append("\"");
sb.append(data);
sb.append("\";");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
}
}
String fileName = title + ".csv";
byte[] bytes = sb.toString().getBytes();
String contentType = ContentTypes.APPLICATION_TEXT;
PortletResponseUtil.sendFile(
resourceResponse, fileName, bytes, contentType);
}
protected String getMailBody(Map<String,String> fieldsMap) {
StringBuilder sb = new StringBuilder();
for (String fieldLabel : fieldsMap.keySet()) {
String fieldValue = fieldsMap.get(fieldLabel);
sb.append(fieldLabel);
sb.append(" : ");
sb.append(fieldValue);
sb.append("\n");
}
return sb.toString();
}
protected boolean saveDatabase(
long companyId, Map<String,String> fieldsMap,
PortletPreferences preferences, String databaseTableName)
throws Exception {
WebFormUtil.checkTable(companyId, databaseTableName, preferences);
long classPK = CounterLocalServiceUtil.increment(
WebFormUtil.class.getName());
try {
for (String fieldLabel : fieldsMap.keySet()) {
String fieldValue = fieldsMap.get(fieldLabel);
ExpandoValueLocalServiceUtil.addValue(
companyId, WebFormUtil.class.getName(), databaseTableName,
fieldLabel, classPK, fieldValue);
}
return true;
}
catch (Exception e) {
_log.error(
"The web form data could not be saved to the database", e);
return false;
}
}
protected boolean saveFile(Map<String,String> fieldsMap, String fileName) {
// Save the file as a standard Excel CSV format. Use ; as a delimiter,
// quote each entry with double quotes, and escape double quotes in
// values a two double quotes.
StringBuilder sb = new StringBuilder();
for (String fieldLabel : fieldsMap.keySet()) {
String fieldValue = fieldsMap.get(fieldLabel);
sb.append("\"");
sb.append(StringUtil.replace(fieldValue, "\"", "\"\""));
sb.append("\";");
}
String s = sb.substring(0, sb.length() - 1) + "\n";
try {
FileUtil.write(fileName, s, false, true);
return true;
}
catch (Exception e) {
_log.error("The web form data could not be saved to a file", e);
return false;
}
}
protected boolean sendEmail(
Map<String,String> fieldsMap, PortletPreferences preferences) {
try {
String subject = preferences.getValue("subject", StringPool.BLANK);
String emailAddress = preferences.getValue(
"emailAddress", StringPool.BLANK);
if (Validator.isNull(emailAddress)) {
_log.error(
"The web form email cannot be sent because no email " +
"address is configured");
return false;
}
String body="Dear Administrator: \n"+"\nA user in your school(s) or district has reported the following problem:\n";
body+="\nUser Name : "+preferences.getValue("tempUsrName" ,StringPool.BLANK)+"\nScreen Name : "+preferences.getValue("tempScreenName",StringPool.BLANK);
body+="\n"+getMailBody(fieldsMap);
body+="URL : "+preferences.getValue("tempURL",StringPool.BLANK)+"\nDate : "+preferences.getValue("tempUsrDateStamp",StringPool.BLANK);
InternetAddress fromAddress = null;
try {
String smtpUser = PropsUtil.get(
PropsKeys.MAIL_SESSION_MAIL_SMTP_USER);
if (Validator.isNotNull(smtpUser)) {
fromAddress = new InternetAddress(smtpUser);
}
}
catch (Exception e) {
_log.error(e, e);
}
if (fromAddress == null) {
fromAddress = new InternetAddress(emailAddress);
}
InternetAddress toAddress = new InternetAddress(emailAddress);
MailMessage mailMessage = new MailMessage(
fromAddress, toAddress, subject, body, false);
MailServiceUtil.sendEmail(mailMessage);
return true;
}
catch (Exception e) {
_log.error("The web form email could not be sent", e);
return false;
}
}
protected void serveCaptcha(
ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws Exception {
CaptchaUtil.serveImage(resourceRequest, resourceResponse);
}
protected Set<String> validate(
Map<String,String> fieldsMap, PortletPreferences preferences)
throws Exception {
Set<String> validationErrors = new HashSet<String>();
for (int i = 0; i < fieldsMap.size(); i++) {
String fieldType = preferences.getValue(
"fieldType" + (i + 1), StringPool.BLANK);
String fieldLabel = preferences.getValue(
"fieldLabel" + (i + 1), StringPool.BLANK);
String fieldValue = fieldsMap.get(fieldLabel);
boolean fieldOptional = GetterUtil.getBoolean(
preferences.getValue(
"fieldOptional" + (i + 1), StringPool.BLANK));
if (Validator.equals(fieldType, "paragraph")) {
continue;
}
if (!fieldOptional && Validator.isNotNull(fieldLabel) &&
Validator.isNull(fieldValue)) {
validationErrors.add(fieldLabel);
continue;
}
String validationScript = GetterUtil.getString(
preferences.getValue(
"fieldValidationScript" + (i + 1), StringPool.BLANK));
if (Validator.isNotNull(validationScript) &&
!WebFormUtil.validate(
fieldValue, fieldsMap, validationScript)) {
validationErrors.add(fieldLabel);
continue;
}
}
return validationErrors;
}
private static Log _log = LogFactoryUtil.getLog(WebFormPortlet.class);
}
|
package com.domker.marmot.core;
import com.domker.marmot.log.MLog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.widget.Toast;
/**
*
*
* @author wanlipeng
* @date 201715 6:05:29
*/
public final class Watcher {
private static Context sContext = null;
/**
* ApplicationContext
*
* @param applicationContext
*/
public static void initContext(Context applicationContext) {
sContext = applicationContext;
}
/**
* ApplicationContext
*
* @return
*/
public static Context getApplicationContext() {
return sContext;
}
/**
* Intent
*
* @param context
* @param cls
* @return
*/
public static Intent createIntent(Context context, Class<?> cls) {
return new Intent(context, cls);
}
/**
*
*
* @param context
* @param intent
* @return
*/
public static ComponentName startService(Context context, Intent intent) {
MLog.i("startService: " + intent.getComponent().getClassName());
return context.startService(intent);
}
/**
* Toast
*
* @param context
* @param message
*/
public static void toast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* Sd
*
* @return
*/
public static String getSdcardPath() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return Environment.getExternalStorageDirectory().toString();
}
if (sContext != null) {
return sContext.getFilesDir().getPath();
}
return null;
}
}
|
package gov.nih.nci.cabig.caaers.web.ae;
import gov.nih.nci.cabig.caaers.dao.AdverseEventDao;
import gov.nih.nci.cabig.caaers.dao.AdverseEventReportingPeriodDao;
import gov.nih.nci.cabig.caaers.dao.CtcCategoryDao;
import gov.nih.nci.cabig.caaers.dao.CtcTermDao;
import gov.nih.nci.cabig.caaers.dao.ParticipantDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao;
import gov.nih.nci.cabig.caaers.dao.TreatmentAssignmentDao;
import gov.nih.nci.cabig.caaers.dao.meddra.LowLevelTermDao;
import gov.nih.nci.cabig.caaers.dao.report.ReportDefinitionDao;
import gov.nih.nci.cabig.caaers.domain.AdverseEventReportingPeriod;
import gov.nih.nci.cabig.caaers.domain.Attribution;
import gov.nih.nci.cabig.caaers.domain.Grade;
import gov.nih.nci.cabig.caaers.domain.Hospitalization;
import gov.nih.nci.cabig.caaers.service.EvaluationService;
import gov.nih.nci.cabig.caaers.tools.spring.tabbedflow.AutomaticSaveAjaxableFormController;
import gov.nih.nci.cabig.caaers.web.ControllerTools;
import gov.nih.nci.cabig.ctms.web.tabs.Flow;
import gov.nih.nci.cabig.ctms.web.tabs.FlowFactory;
import gov.nih.nci.cabig.ctms.web.tabs.Tab;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
public class CaptureAdverseEventController extends AutomaticSaveAjaxableFormController<CaptureAdverseEventInputCommand, AdverseEventReportingPeriod, AdverseEventReportingPeriodDao> {
private static final String AJAX_SUBVIEW_PARAMETER = "subview";
private static final int ADVERSE_EVENT_CONFIRMATION_TAB_NUMBER = 2;
private ParticipantDao participantDao;
private StudyDao studyDao;
private StudyParticipantAssignmentDao assignmentDao;
private TreatmentAssignmentDao treatmentAssignmentDao;
private CtcTermDao ctcTermDao;
private CtcCategoryDao ctcCategoryDao;
private LowLevelTermDao lowLevelTermDao;
private AdverseEventDao adverseEventDao;
private AdverseEventReportingPeriodDao adverseEventReportingPeriodDao;
private EvaluationService evaluationService;
private ReportDefinitionDao reportDefinitionDao;
public CaptureAdverseEventController(){
setBindOnNewForm(true);
setCommandClass(CaptureAdverseEventInputCommand.class);
}
/*@Override
protected void onBindAndValidate(HttpServletRequest request, Object command,
BindException errors, int page) throws Exception {
String action = (String) findInRequest(request, "_action");
if(org.apache.commons.lang.StringUtils.isEmpty(action))
super.onBindAndValidate(request, command, errors, page);
}*/
@Override
protected AdverseEventReportingPeriodDao getDao() {
return null;
}
@Override
protected void onBindOnNewForm(HttpServletRequest request, Object command,BindException errors) throws Exception {
super.onBindOnNewForm(request, command, errors);
String rpId = request.getParameter("adverseEventReportingPeriod");
CaptureAdverseEventInputCommand cmd = (CaptureAdverseEventInputCommand) command;
if(!StringUtils.isEmpty(rpId)) {
cmd.refreshAssignment(Integer.decode(rpId));
}
}
/**
* createBinder method is over-ridden. In this use-case, we need to bind only the adverseEventReportingPeriod to the command object
* incase the submit occurs on change in the Select(reporting period) dropdown. So a hidden attribute "_action" is checked (which is
* set in the onchange handler of the select dropdown. Incase the submit occurs due to "Save" then the entire form alongwith the adverse
* events will be bound to the command object.
*/
@Override
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object command) throws Exception{
CaptureAdverseEventInputCommand aeCommand = (CaptureAdverseEventInputCommand) command;
ServletRequestDataBinder binder = super.createBinder(request, aeCommand);
binder.setDisallowedFields(new String[]{"adverseEventReportingPeriod"});
prepareBinder(binder);
initBinder(request,binder, aeCommand);
return binder;
}
@Override
@SuppressWarnings("unchecked")
protected boolean isFormSubmission(HttpServletRequest request) {
Set<String> paramNames = request.getParameterMap().keySet();
boolean fromListPage = false;
fromListPage = paramNames.contains("displayReportingPeriod");
if(fromListPage)
return true;
else
return super.isFormSubmission(request);
}
/**
* Will return the {@link AdverseEventReportingPeriod}
*/
@Override
protected AdverseEventReportingPeriod getPrimaryDomainObject(CaptureAdverseEventInputCommand cmd) {
return cmd.getAdverseEventReportingPeriod();
}
@SuppressWarnings("unchecked")
@Override
protected Map referenceData(HttpServletRequest request, Object o, Errors errors, int page) throws Exception {
CaptureAdverseEventInputCommand command = (CaptureAdverseEventInputCommand) o;
Map referenceData = super.referenceData(request, command, errors, page);
Map<String, String> summary = new LinkedHashMap<String, String>();
summary.put("Participant", (command.getParticipant() == null) ? "" : command.getParticipant().getFullName() );
summary.put("Study", (command.getStudy() == null) ? "" : command.getStudy().getLongTitle());
//put summary only if page is greater than 0
if(page > 0){
referenceData.put("aesummary", summary);
}
return referenceData;
}
@Override
protected ModelAndView processFinish(HttpServletRequest request, HttpServletResponse response, Object oCommand, BindException errors) throws Exception {
//save the expdited report information
CaptureAdverseEventInputCommand command = (CaptureAdverseEventInputCommand) oCommand;
AdverseEventConfirmTab tab = (AdverseEventConfirmTab) getFlow(command).getTab(ADVERSE_EVENT_CONFIRMATION_TAB_NUMBER);
tab.saveExpeditedReport(request, command, errors);
Map<String, Object> model = new ModelMap("participant", command.getParticipant().getId());
model.put("study", command.getStudy().getId());
return new ModelAndView("redirectToAeList", model);
}
/**
* The binder for reporting period, should look in the command and fetch the object.
*
* @param request
* @param binder
* @param command
* @throws Exception
*/
protected void initBinder(final HttpServletRequest request,final ServletRequestDataBinder binder, final CaptureAdverseEventInputCommand command) throws Exception {
ControllerTools.registerDomainObjectEditor(binder, "participant", participantDao);
ControllerTools.registerDomainObjectEditor(binder, "study", studyDao);
ControllerTools.registerDomainObjectEditor(binder, "adverseEvent", adverseEventDao);
ControllerTools.registerDomainObjectEditor(binder, ctcTermDao);
ControllerTools.registerDomainObjectEditor(binder, ctcCategoryDao);
ControllerTools.registerDomainObjectEditor(binder, lowLevelTermDao);
binder.registerCustomEditor(Date.class, ControllerTools.getDateEditor(false));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
ControllerTools.registerEnumEditor(binder, Grade.class);
ControllerTools.registerEnumEditor(binder, Hospitalization.class);
ControllerTools.registerEnumEditor(binder, Attribution.class);
}
@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
CaptureAdverseEventInputCommand cmd = new CaptureAdverseEventInputCommand(adverseEventReportingPeriodDao,assignmentDao, evaluationService, reportDefinitionDao);
return cmd;
}
@Override
public FlowFactory<CaptureAdverseEventInputCommand> getFlowFactory() {
return new FlowFactory<CaptureAdverseEventInputCommand>() {
public Flow<CaptureAdverseEventInputCommand> createFlow(CaptureAdverseEventInputCommand cmd) {
Flow<CaptureAdverseEventInputCommand> flow = new Flow<CaptureAdverseEventInputCommand>("Capture Adverse Event Flow");
flow.addTab(new BeginTab<CaptureAdverseEventInputCommand>());
flow.addTab(new AdverseEventCaptureTab());
flow.addTab(new AdverseEventConfirmTab("Overview", "Overview", "ae/ae_reviewsummary"));
return flow;
}
};
}
/**
* Supress the validation in the following cases.
* 1 - When we go back
* 2 - When it is an Ajax request, which dont has form submission
*/
@Override
protected boolean suppressValidation(final HttpServletRequest request) {
Object isAjax = findInRequest(request, AJAX_SUBVIEW_PARAMETER);
if (isAjax != null) return true;
//Object isFromManageReport = findInRequest(request, "fromManageReport");
//if(isFromManageReport != null) return true;
//check current page and next page
int currPage = getCurrentPage(request);
int targetPage = getTargetPage(request, currPage);
return targetPage < currPage;
}
/**
* Returns the value associated with the <code>attributeName</code>, if present in
* HttpRequest parameter, if not available, will check in HttpRequest attribute map.
*/
protected Object findInRequest(final ServletRequest request, final String attributName) {
Object attr = request.getParameter(attributName);
if (attr == null) {
attr = request.getAttribute(attributName);
}
return attr;
}
/**
* Adds ajax sub-page view capability. TODO: factor this into main tabbed flow controller.
*/
@Override
protected String getViewName(HttpServletRequest request, Object command, int page) {
String subviewName = request.getParameter(AJAX_SUBVIEW_PARAMETER);
if (subviewName != null) {
// for side-effects:
super.getViewName(request, command, page);
return "ae/ajax/" + subviewName;
} else {
return super.getViewName(request, command, page);
}
}
@Override
protected boolean shouldSave(HttpServletRequest request,CaptureAdverseEventInputCommand command,Tab<CaptureAdverseEventInputCommand> tab) {
Object isAjax = findInRequest(request, AJAX_SUBVIEW_PARAMETER);
if (isAjax != null || 1 != getCurrentPage(request)) {
return false;
}
return true;
}
@Override
protected CaptureAdverseEventInputCommand save(final CaptureAdverseEventInputCommand command, final Errors errors){
if(!errors.hasErrors())
command.save();
return command;
}
public ParticipantDao getParticipantDao() {
return participantDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public StudyDao getStudyDao() {
return studyDao;
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public void setAssignmentDao(StudyParticipantAssignmentDao assignmentDao){
this.assignmentDao = assignmentDao;
}
public void setTreatmentAssignmentDao(
TreatmentAssignmentDao treatmentAssignmentDao) {
this.treatmentAssignmentDao = treatmentAssignmentDao;
}
public TreatmentAssignmentDao getTreatmentAssignmentDao() {
return treatmentAssignmentDao;
}
public CtcTermDao getCtcTermDao() {
return ctcTermDao;
}
public void setCtcTermDao(CtcTermDao ctcTermDao) {
this.ctcTermDao = ctcTermDao;
}
public CtcCategoryDao getCtcCategoryDao() {
return ctcCategoryDao;
}
public void setCtcCategoryDao(CtcCategoryDao ctcCategoryDao) {
this.ctcCategoryDao = ctcCategoryDao;
}
public LowLevelTermDao getLowLevelTermDao() {
return lowLevelTermDao;
}
public void setLowLevelTermDao(LowLevelTermDao lowLevelTermDao) {
this.lowLevelTermDao = lowLevelTermDao;
}
public AdverseEventReportingPeriodDao getAdverseEventReportingPeriodDao() {
return adverseEventReportingPeriodDao;
}
public void setAdverseEventReportingPeriodDao(
AdverseEventReportingPeriodDao adverseEventReportingPeriodDao) {
this.adverseEventReportingPeriodDao = adverseEventReportingPeriodDao;
}
public void setAdverseEventDao(AdverseEventDao adverseEventDao) {
this.adverseEventDao = adverseEventDao;
}
public AdverseEventDao getAdverseEventDao() {
return adverseEventDao;
}
public EvaluationService getEvaluationService() {
return evaluationService;
}
public void setEvaluationService(EvaluationService evaluationService) {
this.evaluationService = evaluationService;
}
public ReportDefinitionDao getReportDefinitionDao() {
return reportDefinitionDao;
}
public void setReportDefinitionDao(ReportDefinitionDao reportDefinitionDao){
this.reportDefinitionDao = reportDefinitionDao;
}
}
|
package org.purl.wf4ever.provtaverna.export;
import info.aduna.lang.service.ServiceRegistry;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.UUID;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import net.sf.taverna.raven.appconfig.ApplicationConfig;
import net.sf.taverna.t2.provenance.api.ProvenanceAccess;
import net.sf.taverna.t2.provenance.lineageservice.URIGenerator;
import net.sf.taverna.t2.provenance.lineageservice.utils.DataflowInvocation;
import net.sf.taverna.t2.provenance.lineageservice.utils.Port;
import net.sf.taverna.t2.provenance.lineageservice.utils.ProcessorEnactment;
import net.sf.taverna.t2.provenance.lineageservice.utils.ProvenanceProcessor;
import net.sf.taverna.t2.reference.IdentifiedList;
import net.sf.taverna.t2.reference.T2Reference;
import net.sf.taverna.t2.reference.T2ReferenceType;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.log4j.Logger;
import org.openrdf.OpenRDFException;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.query.parser.QueryParserRegistry;
import org.openrdf.query.parser.sparql.SPARQLParserFactory;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.contextaware.ContextAwareConnection;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.object.ObjectFactory;
import org.openrdf.repository.object.ObjectRepository;
import org.openrdf.repository.object.config.ObjectRepositoryFactory;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.sail.memory.MemoryStore;
import prov.Activity;
import prov.Agent;
import prov.Association;
import prov.AssociationOrEndOrGenerationOrInvalidationOrStartOrUsage;
import prov.Bundle;
import prov.Entity;
import prov.Generation;
import prov.Plan;
import prov.Role;
import prov.Usage;
import uk.org.taverna.scufl2.api.common.URITools;
public class W3ProvenanceExport {
private URITools uriTools = new URITools();
private static Logger logger = Logger.getLogger(W3ProvenanceExport.class);
protected Map<T2Reference, File> seenReferences = new HashMap<T2Reference, File>();
private static final int NANOSCALE = 9;
private static final URIImpl SAMEAS = new URIImpl(
"http://www.w3.org/2002/07/owl#sameAs");
private ProvenanceAccess provenanceAccess;
private DatatypeFactory datatypeFactory;
private ProvenanceURIGenerator uriGenerator = new ProvenanceURIGenerator();
private String workflowRunId;
private Map<File, T2Reference> fileToT2Reference = Collections.emptyMap();
private File baseFolder;
private File intermediatesDirectory;
private Saver saver;
private ObjectRepository objRepo;
private ObjectConnection objCon;
private ValueFactory valFact;
private ObjectFactory objFact;
public File getIntermediatesDirectory() {
return intermediatesDirectory;
}
public File getBaseFolder() {
return baseFolder;
}
public Map<File, T2Reference> getFileToT2Reference() {
return fileToT2Reference;
}
protected void makeObjectRepository() throws OpenRDFException {
Repository myRepository = new SailRepository(new MemoryStore());
myRepository.initialize();
ObjectRepositoryFactory factory = new ObjectRepositoryFactory();
objRepo = factory.createRepository(myRepository);
objCon = objRepo.getConnection();
valFact = objCon.getValueFactory();
objFact = objCon.getObjectFactory();
}
protected void initializeRegistries() {
// Thanks to info.aduna.lang.service.ServiceRegistry for passing down
// the classloader
// of the interface (!!) rather than the current thread's context class
// loader, we'll
// have to do this ourself for these registries to work within Raven or
// OSGi.
// These are all the subclasses of
// info.aduna.lang.service.ServiceRegistry<String, SailFactory>
// as far as Eclipse could find..
/*
* For some reason this fails with: ERROR 2012-07-04 16:06:22,830
* (net.sf.taverna.t2.workbench.ui.impl.Workbench:115) - Uncaught
* exception in Thread[SaveAllResults: Saving results to
* /home/stain/Desktop/popopopo.prov.ttl,6,main] java.lang.VerifyError:
* (class: no/s11/w3/prov/taverna/ui/W3ProvenanceExport, method:
* initializeRegistries signature: ()V) Incompatible argument to
* function at
* org.purl.wf4ever.provtaverna.export.SaveProvAction.saveData
* (SaveProvAction.java:65) at
* net.sf.taverna.t2.workbench.views.results.
* saveactions.SaveAllResultsSPI$2.run(SaveAllResultsSPI.java:177)
*
*
* or with java -noverify (..)
*
* ERROR 2012-07-04 16:28:47,814
* (net.sf.taverna.t2.workbench.ui.impl.Workbench:115) - Uncaught
* exception in Thread[SaveAllResults: Saving results to
* /home/stain/Desktop/ppp.prov.ttl,6,main]
* java.lang.AbstractMethodError:
* info.aduna.lang.service.ServiceRegistry
* .add(Ljava/lang/Object;)Ljava/lang/Object; at
* org.purl.wf4ever.provtaverna
* .export.W3ProvenanceExport.repopulateRegistry
* (W3ProvenanceExport.java:132) at
* org.purl.wf4ever.provtaverna.export.W3ProvenanceExport
* .initializeRegistries(W3ProvenanceExport.java:111) at
* org.purl.wf4ever
* .provtaverna.export.W3ProvenanceExport.<init>(W3ProvenanceExport
* .java:162) at
* org.purl.wf4ever.provtaverna.export.SaveProvAction.saveData
* (SaveProvAction.java:65) at
* net.sf.taverna.t2.workbench.views.results.
* saveactions.SaveAllResultsSPI$2.run(SaveAllResultsSPI.java:177)
*/
// repopulateRegistry(BooleanQueryResultParserRegistry.getInstance(),
// BooleanQueryResultParserFactory.class);
// repopulateRegistry(BooleanQueryResultWriterRegistry.getInstance(),
// BooleanQueryResultWriterFactory.class);
// repopulateRegistry(RDFParserRegistry.getInstance(),
// RDFParserFactory.class);
// repopulateRegistry(RDFWriterRegistry.getInstance(),
// RDFWriterFactory.class);
// repopulateRegistry(TupleQueryResultParserRegistry.getInstance(),
// TupleQueryResultParserFactory.class);
// repopulateRegistry(TupleQueryResultWriterRegistry.getInstance(),
// TupleQueryResultWriterFactory.class);
// repopulateRegistry(FunctionRegistry.getInstance(), Function.class);
// repopulateRegistry(QueryParserRegistry.getInstance(),
// QueryParserFactory.class);
// repopulateRegistry(RepositoryRegistry.getInstance(),
// RepositoryFactory.class);
// repopulateRegistry(SailRegistry.getInstance(), SailFactory.class);
/* So instead we just do a silly, minimal workaround for what we need */
QueryParserRegistry.getInstance().add(new SPARQLParserFactory());
}
protected <I> void repopulateRegistry(ServiceRegistry<?, I> registry,
Class<I> spi) {
ClassLoader cl = classLoaderForServiceLoader(spi);
logger.info("Selected classloader " + cl + " for registry of " + spi);
for (I service : ServiceLoader.load(spi, cl)) {
registry.add(service);
}
}
private ClassLoader classLoaderForServiceLoader(Class<?> mustHave) {
List<ClassLoader> possibles = Arrays.asList(Thread.currentThread()
.getContextClassLoader(), getClass().getClassLoader(), mustHave
.getClassLoader());
for (ClassLoader cl : possibles) {
if (cl == null) {
continue;
}
try {
if (cl.loadClass(mustHave.getCanonicalName()) == mustHave) {
return cl;
}
} catch (ClassNotFoundException e) {
}
}
// Final fall-back, the old..
return ClassLoader.getSystemClassLoader();
}
public W3ProvenanceExport(ProvenanceAccess provenanceAccess,
String workflowRunId, Saver saver) {
this.saver = saver;
this.setWorkflowRunId(workflowRunId);
this.setProvenanceAccess(provenanceAccess);
initializeRegistries();
try {
makeObjectRepository();
} catch (OpenRDFException e) {
throw new IllegalStateException("Could not make object repository", e);
}
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new IllegalStateException(
"Can't find a DatatypeFactory implementation", e);
}
}
private final class ProvenanceURIGenerator extends URIGenerator {
// Make URIs match with Scufl2
@Override
public String makeWorkflowURI(String workflowID) {
return makeWorkflowBundleURI(workflowRunId) + "workflow/"
+ provenanceAccess.getWorkflowNameByWorkflowID(workflowID)
+ "/";
}
public String makeWorkflowBundleURI(String workflowRunId) {
return "http://ns.taverna.org.uk/2010/workflowBundle/"
+ provenanceAccess.getTopLevelWorkflowID(workflowRunId)
+ "/";
}
public String makePortURI(String wfId, String pName, String vName,
boolean inputPort) {
String base;
if (pName == null) {
base = makeWorkflowURI(wfId);
} else {
base = makeProcessorURI(pName, wfId);
}
return base + (inputPort ? "in/" : "out/") + escape(vName);
}
public String makeDataflowInvocationURI(String workflowRunId,
String dataflowInvocationId) {
return makeWFInstanceURI(workflowRunId) + "workflow/"
+ dataflowInvocationId + "/";
}
public String makeProcessExecution(String workflowRunId,
String processEnactmentId) {
return makeWFInstanceURI(workflowRunId) + "process/"
+ processEnactmentId + "/";
}
}
enum Direction {
INPUTS("in"), OUTPUTS("out");
private final String path;
Direction(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
public void exportAsW3Prov(BufferedOutputStream outStream)
throws RepositoryException, RDFHandlerException, IOException {
// TODO: Make this thread safe using contexts?
objCon.clear();
GregorianCalendar startedProvExportAt = new GregorianCalendar();
String runURI = uriGenerator.makeWFInstanceURI(getWorkflowRunId());
// FIXME: Should this be "" to indicate the current file?
// FIXME: Should this not be an Account instead?
Bundle bundle = objFact.createObject(runURI + "bundle", Bundle.class);
objCon.addObject(bundle);
// Mini-provenance about this provenance trace. Unkown URI for agent/activity
Agent tavernaAgent = createObject(Agent.class);
Activity storeProvenance = createObject(Activity.class);
storeProvenance.getProvStartedAtTime().add(
datatypeFactory.newXMLGregorianCalendar(startedProvExportAt));
storeProvenance.getProvWasAssociatedWith().add(tavernaAgent);
// The agent is an execution of the Taverna software (e.g. also an
// Activity)
String versionName = ApplicationConfig.getInstance().getName();
// Qualify it to add the plan
Association association = createObject(Association.class);
association.getProvAgents_1().add(tavernaAgent);
storeProvenance.getProvQualifiedAssociations().add(association);
association.getProvHadPlans().add(
objFact.createObject("http://ns.taverna.org.uk/2011/software/" + versionName, Plan.class));
bundle.getProvWasGeneratedBy().add(storeProvenance);
// The store-provenance-process used the workflow run as input
storeProvenance.getProvWasInformedBy().add(
objFact.createObject(runURI, Activity.class));
Activity wfProcess = objFact.createObject(runURI,
Activity.class);
storeProvenance.getProvWasInformedBy().add(wfProcess);
DataflowInvocation dataflowInvocation = provenanceAccess
.getDataflowInvocation(getWorkflowRunId());
wfProcess.getProvWasAssociatedWith().add(tavernaAgent);
association = createObject(Association.class);
association.getProvAgents_1().add(tavernaAgent);
wfProcess.getProvQualifiedAssociations().add(association);
String wfUri = uriGenerator.makeWorkflowURI(dataflowInvocation
.getWorkflowId());
// TODO: Also make the recipe a Scufl2 Workflow?
Plan plan = objFact.createObject(wfUri, Plan.class);
association.getProvHadPlans().add(plan);
wfProcess.getProvStartedAtTime().add(
timestampToXmlGreg(dataflowInvocation.getInvocationStarted()));
wfProcess.getProvEndedAtTime().add(
timestampToXmlGreg(dataflowInvocation.getInvocationEnded()));
// Workflow inputs and outputs
storeEntitities(dataflowInvocation.getInputsDataBindingId(), wfProcess,
Direction.INPUTS,
getIntermediatesDirectory());
// FIXME: These entities come out as "generated" by multiple processes
storeEntitities(dataflowInvocation.getOutputsDataBindingId(),
wfProcess, Direction.OUTPUTS,
getIntermediatesDirectory());
// elmoManager.persist(wfProcess);
List<ProcessorEnactment> processorEnactments = provenanceAccess
.getProcessorEnactments(getWorkflowRunId());
// This will also include processor enactments in nested workflows
for (ProcessorEnactment pe : processorEnactments) {
String parentURI = pe.getParentProcessorEnactmentId();
if (parentURI == null) {
// Top-level workflow
parentURI = runURI;
} else {
// inside nested wf - this will be parent processenactment
parentURI = uriGenerator.makeProcessExecution(
pe.getWorkflowRunId(), pe.getProcessEnactmentId());
}
String processURI = uriGenerator.makeProcessExecution(
pe.getWorkflowRunId(), pe.getProcessEnactmentId());
Activity process = objFact.createObject(processURI,
Activity.class);
Activity parentProcess = objFact.createObject(
parentURI, Activity.class);
process.getProvWasInformedBy().add(parentProcess);
process.getProvStartedAtTime().add(
timestampToXmlGreg(pe.getEnactmentStarted()));
process.getProvEndedAtTime().add(
timestampToXmlGreg(pe.getEnactmentEnded()));
// TODO: Linking to the processor in the workflow definition?
ProvenanceProcessor provenanceProcessor = provenanceAccess
.getProvenanceProcessor(pe.getProcessorId());
String processorURI = uriGenerator.makeProcessorURI(
provenanceProcessor.getProcessorName(),
provenanceProcessor.getWorkflowId());
// TODO: Also make the plan a Scufl2 Processor
process.getProvQualifiedAssociations().add(association);
association = createObject(Association.class);
association.getProvAgents_1().add(tavernaAgent);
plan = objFact.createObject(processorURI, Plan.class);
association.getProvHadPlans().add(plan);
// TODO: How to link together iterations on a single processor and
// the collections
// they are iterating over and creating?
// Need 'virtual' ProcessExecution for iteration?
// TODO: Activity/service details from definition?
File path = getIntermediatesDirectory();
// Inputs and outputs
storeEntitities(pe.getInitialInputsDataBindingId(), process,
Direction.INPUTS, path);
storeEntitities(pe.getFinalOutputsDataBindingId(), process,
Direction.OUTPUTS, path);
// elmoManager.persist(process);
}
storeFileReferences();
GregorianCalendar endedProvExportAt = new GregorianCalendar();
storeProvenance.getProvEndedAtTime().add(
datatypeFactory.newXMLGregorianCalendar(endedProvExportAt));
// Save the whole thing
ContextAwareConnection connection = objCon;
connection.setNamespace("scufl2",
"http://ns.taverna.org.uk/2010/scufl2
connection.setNamespace("prov", "http://www.w3.org/ns/prov
connection.setNamespace("owl", "http://www.w3.org/2002/07/owl
// connection.export(new OrganizedRDFWriter(new
// RDFXMLPrettyWriter(outStream)));
// connection.export(new OrganizedRDFWriter(new
// RDFXMLPrettyWriter(outStream)));
connection.export(new TurtleWriterWithBase(
outStream, getBaseFolder().toURI()));
}
private <T> T createObject(Class<T> type) throws RepositoryException {
T obj = objCon.addDesignation(objFact.createObject(), type);
// A refresh to force set initialization
objCon.getObject(objCon.addObject(obj));
return obj;
}
protected XMLGregorianCalendar timestampToXmlGreg(
Timestamp invocationStarted) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(invocationStarted);
XMLGregorianCalendar xmlCal = datatypeFactory
.newXMLGregorianCalendar(cal);
// Chop of the trailing 0-s of non-precission
xmlCal.setFractionalSecond(BigDecimal.valueOf(
invocationStarted.getNanos() / 1000000, NANOSCALE - 6));
return xmlCal;
}
protected void storeFileReferences() {
for (Entry<File, T2Reference> entry : getFileToT2Reference().entrySet()) {
File file = entry.getKey();
T2Reference t2Ref = entry.getValue();
String dataURI = uriGenerator.makeT2ReferenceURI(t2Ref.toUri()
.toASCIIString());
// try {
Entity entity = objFact.createObject(dataURI, Entity.class);
entity.getProvAlternateOf().add(
entity = objFact.createObject(file.toURI().toASCIIString(),
Entity.class));
// elmoManager.getConnection().add(new URIImpl(dataURI), SAMEAS,
// new URIImpl(file.toURI().toASCIIString()));
// } catch (RepositoryException e) {
// // FIXME: Fail properly
// throw new RuntimeException("Can't store reference for " + file,
}
}
protected void storeEntitities(String dataBindingId, Activity activity,
Direction direction, File path) throws IOException, RepositoryException {
Map<Port, T2Reference> bindings = provenanceAccess
.getDataBindings(dataBindingId);
for (Entry<Port, T2Reference> binding : bindings.entrySet()) {
Port port = binding.getKey();
T2Reference t2Ref = binding.getValue();
String dataURI = uriGenerator.makeT2ReferenceURI(t2Ref.toUri()
.toASCIIString());
Entity entity = objFact.createObject(dataURI, Entity.class);
if (! seenReference(t2Ref)) {
saveReference(t2Ref);
}
String id = t2Ref.getLocalPart();
String prefix = id.substring(0, 2);
File prefixDir = new File(path, prefix);
if (direction == Direction.INPUTS) {
activity.getProvUsed().add(entity);
} else {
if (!entity.getProvWasGeneratedBy().isEmpty()) {
// Double-output, alias the entity with a fresh one
// to avoid double-generation
Entity viewOfEntity = createObject(Entity.class);
viewOfEntity.getProvAlternateOf().add(entity);
entity = viewOfEntity;
}
entity.getProvWasGeneratedBy().add(activity);
}
AssociationOrEndOrGenerationOrInvalidationOrStartOrUsage involvement;
if (direction == Direction.INPUTS) {
Usage usage = createObject(Usage.class);
involvement = usage;
activity.getProvQualifiedUsages().add(usage);
usage.getProvEntities_1().add(entity);
} else {
Generation generation = createObject(Generation.class);
involvement = generation;
entity.getProvQualifiedGenerations().add(generation);
generation.getProvActivities_1().add(activity);
}
String processerName = null;
if (port.getProcessorId() != null) {
// Not a workflow port
ProvenanceProcessor p = provenanceAccess
.getProvenanceProcessor(port.getProcessorId());
processerName = p.getProcessorName();
}
port.getProcessorId();
String portURI = uriGenerator.makePortURI(port.getWorkflowId(),
processerName, port.getPortName(), port.isInputPort());
Role portRole = objFact.createObject(portURI, Role.class);
involvement.getProvHadRoles().add(portRole);
// elmoManager.persist(entity);
}
}
private boolean seenReference(T2Reference t2Ref) {
return seenReferences.containsKey(t2Ref);
}
private File saveReference(T2Reference t2Ref) throws IOException {
// Avoid double-saving
File f = seenReferences.get(t2Ref);
if (f != null) {
return f;
}
File file = referencePath(t2Ref);
File parent = file.getParentFile();
parent.mkdirs();
if (t2Ref.getReferenceType() == T2ReferenceType.IdentifiedList) {
// Write a kind of text/uri-list (but with relative URIs)
IdentifiedList<T2Reference> list = saver.getReferenceService().getListService().getList(t2Ref);
file = new File(file.getParentFile(), file.getName() + ".list");
FileWriterWithEncoding writer = new FileWriterWithEncoding(file, "utf-8");
for (T2Reference ref : list) {
File refFile = saveReference(ref).getAbsoluteFile();
URI relRef = uriTools.relativePath(parent.getAbsoluteFile().toURI(), refFile.getAbsoluteFile().toURI());
writer.append(relRef.toASCIIString() + "\n");
}
writer.close();
} else {
String extension = "";
if (t2Ref.getReferenceType() == T2ReferenceType.ErrorDocument) {
extension = ".err";
}
// Capture filename with extension
file = saver.writeDataObject(parent, file.getName(), t2Ref, extension);
// FIXME: The above will save the same reference every time!
}
seenReference(t2Ref, file);
return file;
}
private File referencePath(T2Reference t2Ref) {
String local = t2Ref.getLocalPart();
try {
local = UUID.fromString(local).toString();
} catch (IllegalArgumentException ex) {
// Fallback - use full namespace/localpart
return new File(new File(getIntermediatesDirectory(), t2Ref.getNamespacePart()), t2Ref.getLocalPart());
}
return new File(new File(getIntermediatesDirectory(), local.substring(0, 2)), local);
}
private boolean seenReference(T2Reference t2Ref, File file) {
getFileToT2Reference().put(file, t2Ref);
if (seenReference(t2Ref)) {
return true;
}
return seenReferences.put(t2Ref, file) != null;
}
public ProvenanceAccess getProvenanceAccess() {
return provenanceAccess;
}
public void setProvenanceAccess(ProvenanceAccess provenanceAccess) {
this.provenanceAccess = provenanceAccess;
}
public String getWorkflowRunId() {
return workflowRunId;
}
public void setWorkflowRunId(String workflowRunId) {
this.workflowRunId = workflowRunId;
}
public void setFileToT2Reference(Map<File, T2Reference> fileToT2Reference) {
this.fileToT2Reference = new HashMap<File, T2Reference>();
for (Entry<File, T2Reference> entry : fileToT2Reference.entrySet()) {
seenReference(entry.getValue(), entry.getKey());
}
}
public void setBaseFolder(File baseFolder) {
this.baseFolder = baseFolder;
}
public void setIntermediatesDirectory(File intermediatesDirectory) {
this.intermediatesDirectory = intermediatesDirectory;
}
}
|
package org.sensorhub.impl.persistence.h2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.h2.mvstore.Cursor;
import org.h2.mvstore.MVMap;
import org.h2.mvstore.MVStore;
/**
* <p>
* Implementation of FoI observation periods
* </p>
*
* @author Alex Robin <alex.robin@sensiasoftware.com>
* @since Dec 10, 2017
*/
class MVFoiTimesStoreImpl
{
private static final String FOI_TIMES_MAP_NAME = "@foiTimes";
MVMap<String, FeatureEntry> idIndex;
Map<String, String> lastFois = new HashMap<>(); // last FOI for each producer
static class FeatureTimesDataType extends KryoDataType
{
FeatureTimesDataType()
{
// pre-register used types with Kryo
registeredClasses.put(10, FeatureEntry.class);
}
}
static class FeatureEntry
{
String uid;
List<double[]> timePeriods = new ArrayList<>();
FeatureEntry(String uid)
{
this.uid = uid;
}
}
static class FoiTimePeriod
{
String producerID;
String foiID;
double start;
double stop;
FoiTimePeriod(String producerID, String foiID, double start, double stop)
{
this.producerID = producerID;
this.foiID = foiID;
this.start = start;
this.stop = stop;
}
}
static class FoiTimePeriodComparator implements Comparator<FoiTimePeriod>
{
public int compare(FoiTimePeriod p0, FoiTimePeriod p1)
{
return Double.compare(p0.start, p1.start);
}
}
MVFoiTimesStoreImpl(MVStore mvStore, String seriesName)
{
String mapName = FOI_TIMES_MAP_NAME + ":" + seriesName;
this.idIndex = mvStore.openMap(mapName, new MVMap.Builder<String, FeatureEntry>().valueType(new FeatureTimesDataType()));
}
String getKey(String producerID, String foiID)
{
if (producerID == null)
return foiID;
else
return producerID + foiID;
}
String[] getProducerKeyRange(String producerID)
{
String from = getKey(producerID, "");
String to = getKey(producerID, "\uFFFF");
return new String[] {from, to};
}
int getNumFois(String producerID)
{
String[] keyRange = getProducerKeyRange(producerID);
String firstKey = idIndex.ceilingKey(keyRange[0]);
String lastKey = idIndex.floorKey(keyRange[1]);
if (firstKey == null || lastKey == null)
return 0;
long i0 = idIndex.getKeyIndex(firstKey);
long i1 = idIndex.getKeyIndex(lastKey);
return (int)(i1 - i0);
}
Iterator<String> getFoiIDs(String producerID)
{
String[] keyRange = getProducerKeyRange(producerID);
return new RangeCursor<>(idIndex, keyRange[0], keyRange[1]);
}
Set<FoiTimePeriod> getSortedFoiTimes(final String producerID, final Collection<String> foiIDs)
{
// create set with custom comparator for sorting FoiTimePeriod objects
TreeSet<FoiTimePeriod> foiTimes = new TreeSet<>(new FoiTimePeriodComparator());
// TODO handle case of overlaping FOI periods?
if (foiIDs != null)
{
for (String foiID: foiIDs)
{
String key = getKey(producerID, foiID);
FeatureEntry fEntry = idIndex.get(key);
if (fEntry == null)
continue;
// add each period to sorted set
for (double[] timePeriod: fEntry.timePeriods)
foiTimes.add(new FoiTimePeriod(producerID, foiID, timePeriod[0], timePeriod[1]));
}
}
else // no filtering on FOI ID -> select them all
{
for (FeatureEntry fEntry: idIndex.values())
{
String foiID = fEntry.uid;
// add each period to sorted set
for (double[] timePeriod: fEntry.timePeriods)
foiTimes.add(new FoiTimePeriod(producerID, foiID, timePeriod[0], timePeriod[1]));
}
}
return foiTimes;
}
void updateFoiPeriod(final String producerID, final String foiID, double timeStamp)
{
// if lastFois doesn't have it (after restart)
// add producer FOI for which we last received data
String lastFoi = lastFois.get(producerID);
if (lastFoi == null)
{
String firstKey = getKey(producerID, "");
Cursor<String, FeatureEntry> cursor = idIndex.cursor(firstKey);
double latestTime = Double.NEGATIVE_INFINITY;
while (cursor.hasNext() && cursor.next().startsWith(firstKey))
{
FeatureEntry entry = cursor.getValue();
int nPeriods = entry.timePeriods.size();
if (entry.timePeriods.get(nPeriods-1)[1] > latestTime)
lastFoi = entry.uid;
}
}
// create new entry if needed
String key = getKey(producerID, foiID);
FeatureEntry entry = idIndex.get(key);
if (entry == null)
entry = new FeatureEntry(foiID);
// if same foi, keep growing period
if (foiID.equals(lastFoi))
{
int numPeriods = entry.timePeriods.size();
double[] lastPeriod = entry.timePeriods.get(numPeriods-1);
double currentEndTime = lastPeriod[1];
if (timeStamp > currentEndTime)
lastPeriod[1] = timeStamp;
}
// otherwise start new period
else
entry.timePeriods.add(new double[] {timeStamp, timeStamp});
// replace old entry
idIndex.put(key, entry);
// remember current FOI
lastFois.put(producerID, foiID);
}
void remove(String producerID, String foiID)
{
String key = getKey(producerID, foiID);
idIndex.remove(key);
}
}
|
package fi.nls.oskari.search.channel;
import fi.mml.portti.service.search.ChannelSearchResult;
import fi.mml.portti.service.search.SearchCriteria;
import fi.mml.portti.service.search.SearchResultItem;
import fi.nls.oskari.annotation.Oskari;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.search.util.ELFGeoLocatorParser;
import fi.nls.oskari.search.util.ELFGeoLocatorQueryHelper;
import fi.nls.oskari.search.util.HitCombiner;
import fi.nls.oskari.service.ServiceRuntimeException;
import fi.nls.oskari.util.IOHelper;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.*;
/**
* Search channel for ELF Geolocator requests
*/
@Oskari(ELFGeoLocatorSearchChannel.ID)
public class ELFGeoLocatorSearchChannel extends SearchChannel implements SearchAutocomplete {
public static final String ID = "ELFGEOLOCATOR_CHANNEL";
public static final String PROPERTY_SERVICE_URL = "search.channel.ELFGEOLOCATOR_CHANNEL.service.url";
public static final String KEY_LANG_HOLDER = "_LANG_";
public static final String KEY_LATITUDE_HOLDER = "_LATITUDE_";
public static final String KEY_LONGITUDE_HOLDER = "_LONGITUDE_";
public static final String KEY_PLACE_HOLDER = "_PLACE_HOLDER_";
public static final String KEY_AU_HOLDER = "_AU_HOLDER_";
public static final String RESPONSE_CLEAN = "<?xml version='1.0' encoding='UTF-8'?>";
public static final String DEFAULT_REVERSEGEOCODE_TEMPLATE = "?SERVICE=WFS&REQUEST=ReverseGeocode&LAT=_LATITUDE_&LON=_LONGITUDE_&LANGUAGE=_LANG_";
public static final String DEFAULT_GETFEATUREAU_TEMPLATE = "?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeatureInAu&NAME=_PLACE_HOLDER_&AU=_AU_HOLDER_&LANGUAGE=_LANG_";
public static final String DEFAULT_FUZZY_TEMPLATE = "?SERVICE=WFS&VERSION=2.0.0&REQUEST=FuzzyNameSearch&LANGUAGE=_LANG_&NAME=";
public static final String DEFAULT_GETFEATURE_TEMPLATE = "?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=SI_LocationInstance&language=_LANG_&FILTER=";
public static final String JSONKEY_LOCATIONTYPES = "SI_LocationTypes";
public static final String LOCATIONTYPE_ID_PREFIX = "SI_LocationType.";
public static final String PARAM_COUNTRY = "country";
private static final String PROPERTY_SERVICE_SRS = "search.channel.ELFGEOLOCATOR_CHANNEL.service.srs";
private static final String PROPERTY_SERVICE_REVERSEGEOCODE_TEMPLATE = "search.channel.ELFGEOLOCATOR_CHANNEL.service.reversegeocode.template";
public static final String REQUEST_REVERSEGEOCODE_TEMPLATE = PropertyUtil.get(PROPERTY_SERVICE_REVERSEGEOCODE_TEMPLATE, DEFAULT_REVERSEGEOCODE_TEMPLATE);
private static final String PROPERTY_SERVICE_GETFEATUREAU_TEMPLATE = "search.channel.ELFGEOLOCATOR_CHANNEL.service.getfeatureau.template";
public static final String REQUEST_GETFEATUREAU_TEMPLATE = PropertyUtil.get(PROPERTY_SERVICE_GETFEATUREAU_TEMPLATE, DEFAULT_GETFEATUREAU_TEMPLATE);
private static final String PROPERTY_SERVICE_FUZZY_TEMPLATE = "search.channel.ELFGEOLOCATOR_CHANNEL.service.fuzzy.template";
public static final String REQUEST_FUZZY_TEMPLATE = PropertyUtil.get(PROPERTY_SERVICE_FUZZY_TEMPLATE, DEFAULT_FUZZY_TEMPLATE);
private static final String PROPERTY_SERVICE_GETFEATURE_TEMPLATE = "search.channel.ELFGEOLOCATOR_CHANNEL.service.getfeature.template";
public static final String REQUEST_GETFEATURE_TEMPLATE = PropertyUtil.get(PROPERTY_SERVICE_GETFEATURE_TEMPLATE, DEFAULT_GETFEATURE_TEMPLATE);
private static final String PROPERTY_SERVICE_GEOLOCATOR_LOCATIONTYPES = "search.channel.ELFGEOLOCATOR_CHANNEL.service.locationtype.json";
public static final String LOCATIONTYPE_ATTRIBUTES = PropertyUtil.get(PROPERTY_SERVICE_GEOLOCATOR_LOCATIONTYPES, ID + ".json");
public static final String PROPERTY_AUTOCOMPLETE_URL = PropertyUtil.getOptional("search.channel.ELFGEOLOCATOR_CHANNEL.autocomplete.url");
public static final String PROPERTY_AUTOCOMPLETE_USERNAME = PropertyUtil.getOptional("search.channel.ELFGEOLOCATOR_CHANNEL.autocomplete.userName");
public static final String PROPERTY_AUTOCOMPLETE_PASSWORD = PropertyUtil.getOptional("search.channel.ELFGEOLOCATOR_CHANNEL.autocomplete.password");
// Parameters
public static final String PARAM_NORMAL = "normal";
public static final String PARAM_REGION = "region";
public static final String PARAM_FILTER = "filter";
public static final String PARAM_FUZZY = "fuzzy";
private static final String LIKE_LITERAL_HOLDER = "_like-literal_";
private static Map<String, Double> elfScalesForType = new HashMap<>();
private static Map<String, Integer> elfLocationPriority = new HashMap<>();
private static JSONObject elfLocationTypes = null;
private static JSONObject elfNameLanguages = null;
private final String locationType = "ELFGEOLOCATOR_CHANNEL.json";
public String serviceURL = null;
public ELFGeoLocatorParser elfParser = null;
private Logger log = LogFactory.getLogger(this.getClass());
private HttpURLConnection conn;
private String likeQueryXMLtemplate = null;
public ELFGeoLocatorSearchChannel() {
}
public ELFGeoLocatorSearchChannel(HttpURLConnection conn) {
this.conn = conn;
}
@Override
public HttpURLConnection getConnection(final String url) {
if (conn != null) {
return conn;
}
return super.getConnection(url);
}
@Override
public void init() {
super.init();
serviceURL = PropertyUtil.getOptional(PROPERTY_SERVICE_URL);
if(serviceURL == null) {
throw new RuntimeException("ELFGeolocator didn't initialize - provide url with property: " + PROPERTY_SERVICE_URL);
}
log.debug("ServiceURL set to " + serviceURL);
readLocationTypes();
try (InputStream inp3 = this.getClass().getResourceAsStream("namelanguage.json")) {
if (inp3 != null) {
InputStreamReader reader = new InputStreamReader(inp3);
JSONTokener tokenizer = new JSONTokener(reader);
elfNameLanguages = JSONHelper.createJSONObject4Tokener(tokenizer);
}
} catch (IOException e) {
log.debug("Failed fetching namelanguages", e);
}
elfParser = new ELFGeoLocatorParser(PropertyUtil.getOptional(PROPERTY_SERVICE_SRS), this);
try {
likeQueryXMLtemplate = IOHelper.readString(getClass().getResourceAsStream("geolocator-wildcard.xml"));
} catch (Exception e) {
log.debug("Reading geolocator like search XML template failed", e);
}
}
private void readLocationTypes() {
if (this.elfScalesForType.size() > 0) {
return;
}
try (InputStream inp2 = getLocationTypeStream();
InputStreamReader reader = new InputStreamReader(inp2)) {
JSONTokener tokenizer = new JSONTokener(reader);
this.elfLocationTypes = JSONHelper.createJSONObject4Tokener(tokenizer);
if (elfLocationTypes == null) {
return;
}
JSONArray types = JSONHelper.getJSONArray(elfLocationTypes, JSONKEY_LOCATIONTYPES);
if (types == null) {
return;
}
// Set Map scale values
for (int i = 0; i < types.length(); i++) {
JSONObject jsobj = types.getJSONObject(i);
String type_range = JSONHelper.getStringFromJSON(jsobj, "gml_id", null);
Double scale = jsobj.optDouble("scale");
int priority = jsobj.optInt("priority");
if (type_range == null || scale == null) {
continue;
}
String[] sranges = type_range.split("-");
int i1 = Integer.parseInt(sranges[0]);
int i2 = sranges.length > 1 ? Integer.parseInt(sranges[1]) : i1;
for (int k = i1; k <= i2; k++) {
String key = LOCATIONTYPE_ID_PREFIX + String.valueOf(k);
this.elfScalesForType.put(key, scale);
this.elfLocationPriority.put(key, Integer.valueOf(priority));
}
}
} catch (Exception e) {
log.debug("Initializing Elf geolocator search configs failed", e);
}
}
private InputStream getLocationTypeStream() {
InputStream inp2 = this.getClass().getResourceAsStream(locationType);
if (inp2 != null) {
return inp2;
}
// Try to get user defined setup file
try {
return new FileInputStream(LOCATIONTYPE_ATTRIBUTES);
} catch (Exception e) {
log.info("No setup found for location type based scaling in geolocator seach", e);
}
throw new RuntimeException("No location types data");
}
public Capabilities getCapabilities() {
return Capabilities.BOTH;
}
public ChannelSearchResult reverseGeocode(SearchCriteria searchCriteria) {
StringBuffer buf = new StringBuffer(serviceURL);
// reverse geocoding
// Transform lon,lat
String[] lonlat = elfParser.transformLonLat("" + searchCriteria.getLon(), "" + searchCriteria.getLat(), searchCriteria.getSRS());
if (lonlat == null) {
log.warn("Invalid lon/lat coordinates", searchCriteria.getLon(), searchCriteria.getLat());
return null;
}
String request = REQUEST_REVERSEGEOCODE_TEMPLATE.replace(KEY_LATITUDE_HOLDER, lonlat[1]);
Locale locale = new Locale(searchCriteria.getLocale());
String lang3 = locale.getISO3Language();
request = request.replace(KEY_LONGITUDE_HOLDER, lonlat[0]);
request = request.replace(KEY_LANG_HOLDER, lang3);
buf.append(request);
String data;
try {
data = IOHelper.readString(getConnection(buf.toString()));
// Clean xml version for geotools parser for faster parse
data = data.replace(RESPONSE_CLEAN, "");
} catch (Exception e) {
log.warn("Unable to fetch data " + buf.toString());
log.error(e);
return new ChannelSearchResult();
}
boolean exonym = true;
// New definitions - no mode setups any more in UI - exonym is always true
ChannelSearchResult result = elfParser.parse(data, searchCriteria.getSRS(), locale, exonym);
// Add used search method
result.setSearchMethod(findSearchMethod(searchCriteria));
return result;
}
protected boolean hasWildcard(String query) {
return query != null && (query.contains("*") || query.contains("
}
protected String getWildcardQuery(SearchCriteria searchCriteria) {
String postData = likeQueryXMLtemplate;
return postData.replace(LIKE_LITERAL_HOLDER, searchCriteria.getSearchString());
}
/**
* Returns the search raw results.
*
* @param searchCriteria Search criteria.
* @return Result data in JSON format.
* @throws Exception
*/
public String getData(SearchCriteria searchCriteria)
throws Exception {
if (serviceURL == null) {
log.warn("ServiceURL not configured. Add property with key", PROPERTY_SERVICE_URL);
return null;
}
// wildcard search
String searchString = searchCriteria.getSearchString();
if (hasWildcard(searchString)) {
log.debug("Wildcard search: ", searchString);
String postData = getWildcardQuery(searchCriteria);
StringBuffer buf = new StringBuffer(serviceURL);
log.debug("Server request: " + buf.toString());
HttpURLConnection conn = getConnection(buf.toString());
IOHelper.writeToConnection(conn, postData);
String response = IOHelper.readString(conn);
log.debug("Server response: " + response);
return response;
}
// Language
Locale locale = new Locale(searchCriteria.getLocale());
String lang3 = locale.getISO3Language();
StringBuffer buf = new StringBuffer(serviceURL);
if ("true".equals(searchCriteria.getParamAsString(PARAM_FILTER))) {
log.debug("Exact search (AU)");
// Exact search limited to AU region - case sensitive - no fuzzy support
String request = REQUEST_GETFEATUREAU_TEMPLATE.replace(KEY_PLACE_HOLDER, URLEncoder.encode(searchCriteria.getSearchString(), "UTF-8"));
request = request.replace(KEY_AU_HOLDER, URLEncoder.encode(searchCriteria.getParam(PARAM_REGION).toString(), "UTF-8"));
request = request.replace(KEY_LANG_HOLDER, lang3);
buf.append(request);
} else if ("true".equals(searchCriteria.getParamAsString(PARAM_FUZZY))) {
log.debug("Fuzzy search");
// Fuzzy search
buf.append(REQUEST_FUZZY_TEMPLATE.replace(KEY_LANG_HOLDER, lang3));
buf.append(URLEncoder.encode(searchCriteria.getSearchString(), "UTF-8"));
// Location type
final String locationType = "locationtype";
if (hasParam(searchCriteria, locationType)) {
buf.append("&LOCATIONTYPE" + "=" + searchCriteria.getParam(locationType));
}
// Name language
final String nameLanguage = "namelanguage";
if (hasParam(searchCriteria, nameLanguage)) {
buf.append("&NAMELANGUAGE" + "=" + searchCriteria.getParam(nameLanguage));
}
// Nearest
final String nearest = "nearest";
if (hasParam(searchCriteria, nearest)) {
buf.append("&NEAREST=" + searchCriteria.getParam(nearest));
buf.append("&LON=" + searchCriteria.getParam("lon"));
buf.append("&LAT=" + searchCriteria.getParam("lat"));
// API supports EPSG:4258, EPSG:3034, EPSG:3035 ja EPSG:3857 coordinates
buf.append("&SRSNAME=" + searchCriteria.getSRS());
}
} else {
log.debug("Exact search");
// Exact search - case sensitive
String filter = getFilter(searchCriteria);
String request = REQUEST_GETFEATURE_TEMPLATE.replace(KEY_LANG_HOLDER, lang3);
buf.append(request);
buf.append(filter);
}
log.debug("Server request: " + buf.toString());
return IOHelper.readString(getConnection(buf.toString()));
}
protected String getFilter(SearchCriteria searchCriteria) {
String country = searchCriteria.getParamAsString(PARAM_COUNTRY);
try {
final String adminFilter = new ELFGeoLocatorQueryHelper().getFilter(searchCriteria.getSearchString(), country);
return URLEncoder.encode(adminFilter, IOHelper.CHARSET_UTF8);
} catch (ServiceRuntimeException | UnsupportedEncodingException e) {
log.error(e, "Couldn't create filter for country. Using default filter");
}
// will result in empty filter
return "";
}
/**
* Check if criteria has named extra parameter and it's not empty
*
* @param sc
* @param param
* @return
*/
public boolean hasParam(SearchCriteria sc, final String param) {
final Object obj = sc.getParam(param);
return obj != null && !obj.toString().isEmpty();
}
public JSONObject getElfLocationTypes() {
return this.elfLocationTypes;
}
public JSONObject getElfNameLanguages() {
return this.elfNameLanguages;
}
/**
* Returns the channel search results.
*
* @param searchCriteria Search criteria.
* @return Search results.
*/
public ChannelSearchResult doSearch(SearchCriteria searchCriteria) {
try {
String fuzzy = (String) searchCriteria.getParam(PARAM_FUZZY);
boolean fuzzyDone = false;
if (fuzzy != null && fuzzy.equals("true")) {
searchCriteria.addParam(PARAM_NORMAL, "false");
searchCriteria.addParam(PARAM_FUZZY, "true");
fuzzyDone = true;
}
String data = getData(searchCriteria);
Locale locale = new Locale(searchCriteria.getLocale());
// Clean xml version for geotools parser for faster parse
data = data.replace(RESPONSE_CLEAN, "");
boolean exonym = true;
// New definitions - no mode setups any more in UI - exonym is always true
ChannelSearchResult result = elfParser.parse(data, searchCriteria.getSRS(), locale, exonym);
// Execute fuzzy search, if no result in exact search (and fuzzy search has not been done already)
if (result.getSearchResultItems().size() == 0 && findSearchMethod(searchCriteria).equals(PARAM_NORMAL) && !fuzzyDone) {
// Try fuzzy search, if empty
searchCriteria.addParam(PARAM_NORMAL, "false");
searchCriteria.addParam(PARAM_FUZZY, "true");
result = doSearch(searchCriteria);
}
// Add used search method
result.setSearchMethod(findSearchMethod(searchCriteria));
return result;
} catch (Exception e) {
log.error(e, "Failed to search locations from register of ELF GeoLocator");
return new ChannelSearchResult();
}
}
private String findSearchMethod(SearchCriteria sc) {
String method = "unknown";
if ("true".equals(sc.getParamAsString(PARAM_FILTER))) {
// Exact search limited to AU region - case sensitive - no fuzzy support
method = PARAM_FILTER;
} else if ("true".equals(sc.getParamAsString(PARAM_FUZZY))) {
// Fuzzy search
method = PARAM_FUZZY;
} else {
// Exact search - case sensitive
method = PARAM_NORMAL;
}
return method;
}
public Map<String, Double> getElfScalesForType() {
return elfScalesForType;
}
public Map<String, Integer> getElfLocationPriority() {
return elfLocationPriority;
}
/**
* Skip scale setting in ELF
* Scale is not based on type value
*
* @param item
*/
@Override
public void calculateCommonFields(final SearchResultItem item) {
double scale = item.getZoomScale();
super.calculateCommonFields(item);
if (scale != -1) {
item.setZoomScale(scale);
}
}
public List<String> doSearchAutocomplete(String searchString) {
if(PROPERTY_AUTOCOMPLETE_URL == null || PROPERTY_AUTOCOMPLETE_URL.isEmpty()) {
return Collections.emptyList();
}
JSONObject jsonObject;
try {
log.info("Creating autocomplete search url with url:", PROPERTY_AUTOCOMPLETE_URL);
HttpURLConnection conn = IOHelper.getConnection(PROPERTY_AUTOCOMPLETE_URL,
PROPERTY_AUTOCOMPLETE_USERNAME, PROPERTY_AUTOCOMPLETE_PASSWORD);
IOHelper.writeToConnection(conn, getElasticQuery(searchString));
String result = IOHelper.readString(conn);
jsonObject = new JSONObject(result);
}
catch (Exception ex) {
log.error("Couldn't open or read from connection for search channel!");
throw new RuntimeException("Couldn't open or read from connection!", ex);
}
HitCombiner combiner = new HitCombiner();
try {
JSONArray fuzzyHits = jsonObject.getJSONArray("fuzzy_search").getJSONObject(0).getJSONArray("options");
for (int i = 0; i < fuzzyHits.length(); i++) {
combiner.addHit(fuzzyHits.getJSONObject(i), false);
}
JSONArray normalHits = jsonObject.getJSONArray("normal_search").getJSONObject(0).getJSONArray("options");
for (int i = 0; i < normalHits.length(); i++) {
JSONObject hit = normalHits.getJSONObject(i);
boolean isExact = searchString.trim().equalsIgnoreCase(hit.getString("text"));
combiner.addHit(hit, isExact);
}
}
catch (JSONException ex) {
log.error("Unexpected autocomplete service JSON response structure!", ex.getMessage());
}
return combiner.getSortedHits();
}
protected String getElasticQuery(String query) {
// {"normal_search":{"text":"[user input]","completion":{"field":"name_suggest","size":20}},"fuzzy_search":{"text":"[user input]","completion":{"field":"name_suggest","size":20,"fuzzy":{"fuzziness":5}}}}
JSONObject elasticQueryTemplate = JSONHelper.createJSONObject("{\"normal_search\":{\"completion\":{\"field\":\"name_suggest\",\"size\":20}},\"fuzzy_search\":{\"completion\":{\"field\":\"name_suggest\",\"size\":20,\"fuzzy\":{\"fuzziness\":5}}}}");
try {
// set the actual search query
elasticQueryTemplate.optJSONObject("normal_search").put("text", query);
elasticQueryTemplate.optJSONObject("fuzzy_search").put("text", query);
} catch(Exception ignored) {}
return elasticQueryTemplate.toString();
}
}
|
package com.mkl.eu.service.service.socket;
import com.mkl.eu.client.service.vo.diff.DiffResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Handles the socket to the clients mapping them by game.
*
* @author MKL.
*/
@Component
public class SocketHandler implements ApplicationListener<ContextRefreshedEvent> {
/** Logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(SocketHandler.class);
/** Map of active clients by id game. */
private Map<Long, List<GameSocket>> activeClients = new HashMap<>();
/** Flag saying that we want to terminate the sockets. */
private boolean terminate;
/**
* {@inheritDoc}
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
/**
* There is 2 application context created : a main one and one with cxf.
* The one with cxf has the main one has parent.
* Here, we want the socket server to be created after all web services have been created.
* Hence, we wait for the applicationContext with cxf to be initialized to init the socket server.
*/
if (event.getApplicationContext().getParent() != null) {
init();
}
}
/**
* Initialize the server socket.
*/
public void init() {
try {
ServerSocket server = new ServerSocket(2009);
LOGGER.info("Socket handler launched server socket on " + server.getLocalPort());
Thread t = new Thread(() -> {
try {
while (!terminate) {
Socket socket = server.accept();
LOGGER.info("Connexion accepted.");
new Thread(new GameSocket(socket, this)).start();
}
} catch (IOException e) {
LOGGER.error("Error when creating a socket from server.", e);
}
});
t.start();
} catch (IOException e) {
LOGGER.error("Error when creating server socket.", e);
}
}
/**
* Add a client for the given game.
*
* @param client to add.
* @param idGame id of the game.
*/
public synchronized void addActiveClient(GameSocket client, Long idGame) {
if (!activeClients.containsKey(idGame)) {
activeClients.put(idGame, new ArrayList<>());
}
activeClients.get(idGame).add(client);
}
/**
* Remove a client for the given game.
*
* @param client to remove.
* @param idGame id of the game.
*/
public synchronized void removeActiveClient(GameSocket client, Long idGame) {
if (activeClients.containsKey(idGame)) {
activeClients.get(idGame).remove(client);
}
}
/**
* Push a diff to all clients listening to this game.
*
* @param idGame id of the game.
* @param diff to push.
* @param idCountries List of countries that will receive this diff.
*/
public synchronized void push(Long idGame, DiffResponse diff, List<Long> idCountries) {
if (activeClients.containsKey(idGame)) {
activeClients.get(idGame).forEach(gameSocket -> gameSocket.push(diff, idCountries));
}
}
/** @param terminate the terminate to set. */
public void setTerminate(boolean terminate) {
this.terminate = terminate;
}
}
|
package pt.fccn.sobre.arquivo.pages;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import pt.fccn.arquivo.tests.util.AnalyzeURLs;
public class IndexSobrePage {
WebDriver driver;
private final int timeout = 50;
Map< String, String > textTolink;
private final String dir = "sobreTestsFiles";
/**
*
* @param driver
* @throws IOException
*/
public IndexSobrePage( WebDriver driver ) throws IOException {
this.driver = driver;
Properties prop = new Properties( );
InputStream input = null;
try {
input = new FileInputStream( "sobreTestsFiles/props_indexPage.properties" );
prop.load( new InputStreamReader( input, Charset.forName("UTF-8") ) ); //load a properties file
} catch ( FileNotFoundException e ) {
throw e;
} catch ( IOException e1) {
if( input != null) input.close( );
throw e1;
}
try {
Thread.sleep( 5000 ); //wait for page to load
} catch( InterruptedException ex ) {
Thread.currentThread( ).interrupt( );
}
// Check that we're on the right page.
String pageTitle= driver.getTitle( );
Charset.forName( "UTF-8" ).encode( pageTitle );
System.out.println( "Page title = " + pageTitle + " == " + prop.getProperty( "title_pt" ) );
if ( !( pageTitle.contentEquals( prop.getProperty( "title_pt" ) ) || (pageTitle.contentEquals("title_en") ) ) ){
throw new IllegalStateException("This is not the index page\n Title of current page: " + pageTitle);
}
}
/**
* Click the link to the footer of the page
* @throws FileNotFoundException
*/
public CommonQuestionsPage goToCommonQuestionsPage( ) throws FileNotFoundException{
try{
System.out.println( "Start goToCommonQuestionsPage( ) method" );
WebElement cQuestionsLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
/**
*
* @return
* @throws FileNotFoundException
*/
public CollaboratePage goToCollaboratePage( String language ) throws FileNotFoundException{
String idMenu = "";
if( language.equals( "EN" ) )
WebElement collaborateLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public SiteMapPage goToSiteMapPage( ) throws FileNotFoundException {
try{
System.out.println( "Start goToSiteMapPage() method" );
Actions actions = new Actions( driver );
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public PublicationsPage goToPublicationsPage( String language ) throws FileNotFoundException {
String idMenuPub = "";
String idMenuPubCien = "";
try{
System.out.println( "Start goToPublicationsPage( ) method" );
if( language.equals( "EN" ) ) {
idMenuPub = "menu-item-2363";
idMenuPubCien = "menu-item-3924";
} else {
idMenuPub = "menu-item-1869";
idMenuPubCien = "menu-item-3769";
}
Actions actions = new Actions( driver );
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public ReportsPage goToReportsPage( String language ) throws FileNotFoundException {
String idMenu = "";
String idSubMenu = "";
try{
System.out.println( "Start goToReportsPage() method" );
if( language.equals( "EN" ) ) {
idMenu = "menu-item-2363";
idSubMenu = "menu-item-3925";
} else {
idMenu = "menu-item-1869";
idSubMenu = "menu-item-3771";
}
Actions actions = new Actions( driver );
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public NewsOnMediaPage goToNewOnMediaPage( ) throws FileNotFoundException {
try{
System.out.println( "Start goToNewOnMediaPage() method" );
Actions actions = new Actions( driver );
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public AudioPage goToAudioPage( String language ) throws FileNotFoundException {
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public VideoPage goToVideoPage( String language ) throws FileNotFoundException {
String xpathVideo = "";
if( language.equals( "EN" ) )
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
* @throws FileNotFoundException
*/
public PresentationsPage goToPresentationsPage( String language ) throws FileNotFoundException {
String xpathDivMenu = "";
String xpathDibSubMenu = "";
if( language.equals( "PT" ) ) {
WebElement menuHoverLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
WebElement menuClickLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @return
*/
public ExamplesPage goToExamplePage( ) {
try{
System.out.println( "Start goToExamplePage() method" );
WebElement examplePageLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
/**
*
* @throws FileNotFoundException
*/
public NewsPage goToNewsPage( ) throws FileNotFoundException{
try{
System.out.println( "Start goToNewsPage( ) method" );
WebElement newsLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
/**
*
* @throws FileNotFoundException
*/
public AboutPage goToAboutPage( String language ) throws FileNotFoundException{
String idDiv = "";
if( language.equals( "PT" ) )
idDiv = "menu-item-3416";
else
idDiv = "menu-item-3449";
try{
System.out.println( "Start goToAboutPage( ) method" );
WebElement newsLink = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
.until(
ExpectedConditions.presenceOfElementLocated(
/**
* Change to the English version
*/
private void switchLanguage( ){
* @param l//*[@id=\"menu-item-1858\"]/aanguage
* @return
*/
public boolean checkFooterLinks( String language ) {
System.out.println( "[checkFooterLinks]" );
WebElement input = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
WebElement btnsearch = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/
/**
*
* @param filename
* @return
*/
private List< String > readFromFileToList( String filename ) {
List< String > searchTerms = new ArrayList< String >( );
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream (dir.concat( File.separator ).concat( filename ) ) , "UTF8" ) );
String line = "";
while( ( line = in.readLine( ) ) != null ) {
searchTerms.add( line );
}
in.close( );
System.out.println( "searchTerms => " + textTolink.toString( ) );
return searchTerms;
} catch ( FileNotFoundException e ) {
e.printStackTrace( );
return null;
} catch (IOException e) {
e.printStackTrace( );
return null;
}
}
/**
*
* @param filename
* @return
*/
private boolean readFromFileToMap( String filename ) {
textTolink = new HashMap< String , String >( );
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream (dir.concat( File.separator ).concat( filename ) ) , "UTF8" ) );
String line = "";
while( ( line = in.readLine( ) ) != null ) {
String parts[ ] = line.split( "," );
textTolink.put( parts[ 0 ], parts[ 1 ] );
}
in.close( );
System.out.println( "Map => " + textTolink.toString( ) );
return true;
} catch ( FileNotFoundException e ) {
e.printStackTrace( );
return false;
} catch (IOException e) {
e.printStackTrace( );
return false;
}
}
public static void sleepThread( ) {
try {
Thread.sleep( 4000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package org.opendaylight.ovsdb.southbound.it;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.CoreOptions.vmOption;
import static org.ops4j.pax.exam.CoreOptions.when;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.inject.Inject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
import org.opendaylight.ovsdb.southbound.SouthboundConstants;
import org.opendaylight.ovsdb.southbound.SouthboundMapper;
import org.opendaylight.ovsdb.southbound.SouthboundProvider;
import org.opendaylight.ovsdb.southbound.SouthboundUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathTypeBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.InterfaceTypeBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbFailModeBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbPortInterfaceAttributes.VlanMode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentationBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIds;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIdsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntryBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfoBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.DatapathTypeEntry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.InterfaceTypeEntryBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.OpenvswitchOtherConfigs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIds;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIdsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceOtherConfigs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceOtherConfigsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Options;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.OptionsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortExternalIds;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortExternalIdsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortOtherConfigs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortOtherConfigsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Trunks;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.TrunksBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
import org.opendaylight.yangtools.concepts.Builder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.karaf.options.KarafDistributionOption;
import org.ops4j.pax.exam.karaf.options.LogLevelOption;
import org.ops4j.pax.exam.options.MavenUrlReference;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Integration tests for southbound-impl
*
* @author Sam Hague (shague@redhat.com)
*/
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public class SouthboundIT extends AbstractMdsalTestBase {
private static final String NETDEV_DP_TYPE = "netdev";
private static final Logger LOG = LoggerFactory.getLogger(SouthboundIT.class);
private static final int OVSDB_UPDATE_TIMEOUT = 1000;
private static final String FORMAT_STR = "%s_%s_%d";
private static String addressStr;
private static int portNumber;
private static String connectionType;
private static Boolean setup = false;
private static MdsalUtils mdsalUtils = null;
// TODO Constants copied from AbstractConfigTestBase, need to be removed (see TODO below)
private static final String PAX_EXAM_UNPACK_DIRECTORY = "target/exam";
private static final String KARAF_DEBUG_PORT = "5005";
private static final String KARAF_DEBUG_PROP = "karaf.debug";
private static final String KEEP_UNPACK_DIRECTORY_PROP = "karaf.keep.unpack";
@Inject
private BundleContext bundleContext;
@Configuration
public Option[] config() {
// TODO Figure out how to use the parent Karaf setup, then just use super.config()
Option[] options = new Option[] {
when(Boolean.getBoolean(KARAF_DEBUG_PROP))
.useOptions(KarafDistributionOption.debugConfiguration(KARAF_DEBUG_PORT, true)),
karafDistributionConfiguration().frameworkUrl(getKarafDistro())
.unpackDirectory(new File(PAX_EXAM_UNPACK_DIRECTORY))
.useDeployFolder(false),
when(Boolean.getBoolean(KEEP_UNPACK_DIRECTORY_PROP)).useOptions(keepRuntimeFolder()),
// Works only if we don't specify the feature repo and name
getLoggingOption()};
Option[] propertyOptions = getPropertiesOptions();
Option[] otherOptions = getOtherOptions();
Option[] combinedOptions = new Option[options.length + propertyOptions.length + otherOptions.length];
System.arraycopy(options, 0, combinedOptions, 0, options.length);
System.arraycopy(propertyOptions, 0, combinedOptions, options.length, propertyOptions.length);
System.arraycopy(otherOptions, 0, combinedOptions, options.length + propertyOptions.length,
otherOptions.length);
return combinedOptions;
}
private Option[] getOtherOptions() {
return new Option[] {
vmOption("-javaagent:../jars/org.jacoco.agent.jar=destfile=../../jacoco-it.exec"),
keepRuntimeFolder()
};
}
@Override
public String getKarafDistro() {
return maven()
.groupId("org.opendaylight.ovsdb")
.artifactId("southbound-karaf")
.versionAsInProject()
.type("zip")
.getURL();
}
@Override
public String getModuleName() {
return "southbound-impl";
}
@Override
public String getInstanceName() {
return "southbound-default";
}
@Override
public MavenUrlReference getFeatureRepo() {
return maven()
.groupId("org.opendaylight.ovsdb")
.artifactId("southbound-features")
.classifier("features")
.type("xml")
.versionAsInProject();
}
@Override
public String getFeatureName() {
return "odl-ovsdb-southbound-impl-ui";
}
protected String usage() {
return "Integration Test needs a valid connection configuration as follows :\n"
+ "active connection : mvn -Dovsdbserver.ipaddress=x.x.x.x -Dovsdbserver.port=yyyy verify\n"
+ "passive connection : mvn -Dovsdbserver.connection=passive verify\n";
}
@Override
public Option getLoggingOption() {
return composite(
editConfigurationFilePut(SouthboundITConstants.ORG_OPS4J_PAX_LOGGING_CFG,
"log4j.logger.org.opendaylight.ovsdb",
LogLevelOption.LogLevel.TRACE.name()),
super.getLoggingOption());
}
private Option[] getPropertiesOptions() {
Properties props = new Properties(System.getProperties());
String addressStr = props.getProperty(SouthboundITConstants.SERVER_IPADDRESS,
SouthboundITConstants.DEFAULT_SERVER_IPADDRESS);
String portStr = props.getProperty(SouthboundITConstants.SERVER_PORT,
SouthboundITConstants.DEFAULT_SERVER_PORT);
String connectionType = props.getProperty(SouthboundITConstants.CONNECTION_TYPE,
SouthboundITConstants.CONNECTION_TYPE_ACTIVE);
LOG.info("getPropertiesOptions: Using the following properties: mode= {}, ip:port= {}:{}",
connectionType, addressStr, portStr);
return new Option[] {
editConfigurationFilePut(SouthboundITConstants.CUSTOM_PROPERTIES,
SouthboundITConstants.SERVER_IPADDRESS, addressStr),
editConfigurationFilePut(SouthboundITConstants.CUSTOM_PROPERTIES,
SouthboundITConstants.SERVER_PORT, portStr),
editConfigurationFilePut(SouthboundITConstants.CUSTOM_PROPERTIES,
SouthboundITConstants.CONNECTION_TYPE, connectionType),
};
}
@Before
@Override
public void setup() throws InterruptedException {
if (setup) {
LOG.info("Skipping setup, already initialized");
return;
}
try {
super.setup();
} catch (Exception e) {
e.printStackTrace();
}
//dataBroker = getSession().getSALService(DataBroker.class);
Thread.sleep(3000);
DataBroker dataBroker = SouthboundProvider.getDb();
Assert.assertNotNull("db should not be null", dataBroker);
addressStr = bundleContext.getProperty(SouthboundITConstants.SERVER_IPADDRESS);
String portStr = bundleContext.getProperty(SouthboundITConstants.SERVER_PORT);
try {
portNumber = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
fail("Invalid port number " + portStr + System.lineSeparator() + usage());
}
connectionType = bundleContext.getProperty(SouthboundITConstants.CONNECTION_TYPE);
LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}",
connectionType, addressStr, portNumber);
if (connectionType.equalsIgnoreCase(SouthboundITConstants.CONNECTION_TYPE_ACTIVE)) {
if (addressStr == null) {
fail(usage());
}
}
mdsalUtils = new MdsalUtils(dataBroker);
setup = true;
}
/**
* Test passive connection mode. The southbound starts in a listening mode waiting for connections on port
* 6640. This test will wait for incoming connections for {@link SouthboundITConstants#CONNECTION_INIT_TIMEOUT} ms.
*
* @throws InterruptedException
*/
@Test
public void testPassiveNode() throws InterruptedException {
if (connectionType.equalsIgnoreCase(SouthboundITConstants.CONNECTION_TYPE_PASSIVE)) {
//Wait for CONNECTION_INIT_TIMEOUT for the Passive connection to be initiated by the ovsdb-server.
Thread.sleep(SouthboundITConstants.CONNECTION_INIT_TIMEOUT);
}
}
private ConnectionInfo getConnectionInfo(final String addressStr, final int portNumber) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByName(addressStr);
} catch (UnknownHostException e) {
fail("Could not resolve " + addressStr + ": " + e);
}
IpAddress address = SouthboundMapper.createIpAddress(inetAddress);
PortNumber port = new PortNumber(portNumber);
final ConnectionInfo connectionInfo = new ConnectionInfoBuilder()
.setRemoteIp(address)
.setRemotePort(port)
.build();
LOG.info("connectionInfo: {}", connectionInfo);
return connectionInfo;
}
private String connectionInfoToString(final ConnectionInfo connectionInfo) {
return new String(connectionInfo.getRemoteIp().getValue()) + ":" + connectionInfo.getRemotePort().getValue();
}
@Test
public void testNetworkTopology() throws InterruptedException {
NetworkTopology networkTopology = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION,
InstanceIdentifier.create(NetworkTopology.class));
Assert.assertNotNull("NetworkTopology could not be found in " + LogicalDatastoreType.CONFIGURATION,
networkTopology);
networkTopology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL,
InstanceIdentifier.create(NetworkTopology.class));
Assert.assertNotNull("NetworkTopology could not be found in " + LogicalDatastoreType.OPERATIONAL,
networkTopology);
}
@Test
public void testOvsdbTopology() throws InterruptedException {
InstanceIdentifier<Topology> path = InstanceIdentifier
.create(NetworkTopology.class)
.child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
Topology topology = mdsalUtils.read(LogicalDatastoreType.CONFIGURATION, path);
Assert.assertNotNull("Topology could not be found in " + LogicalDatastoreType.CONFIGURATION,
topology);
topology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, path);
Assert.assertNotNull("Topology could not be found in " + LogicalDatastoreType.OPERATIONAL,
topology);
}
private boolean addOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
boolean result = mdsalUtils.put(LogicalDatastoreType.CONFIGURATION,
createInstanceIdentifier(connectionInfo),
createNode(connectionInfo));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
return result;
}
private InstanceIdentifier<Node> createInstanceIdentifier(
ConnectionInfo connectionInfo) {
return InstanceIdentifier
.create(NetworkTopology.class)
.child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID))
.child(Node.class,
createNodeKey(connectionInfo.getRemoteIp(), connectionInfo.getRemotePort()));
}
private Node getOvsdbNode(final ConnectionInfo connectionInfo) {
return mdsalUtils.read(LogicalDatastoreType.OPERATIONAL,
createInstanceIdentifier(connectionInfo));
}
private boolean deleteOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION,
createInstanceIdentifier(connectionInfo));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
return result;
}
private Node connectOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
Assert.assertTrue(addOvsdbNode(connectionInfo));
Node node = getOvsdbNode(connectionInfo);
Assert.assertNotNull(node);
LOG.info("Connected to {}", connectionInfoToString(connectionInfo));
return node;
}
private boolean disconnectOvsdbNode(final ConnectionInfo connectionInfo) throws InterruptedException {
Assert.assertTrue(deleteOvsdbNode(connectionInfo));
Node node = getOvsdbNode(connectionInfo);
Assert.assertNull(node);
//Assume.assumeNotNull(node); // Using assumeNotNull because there is no assumeNull
LOG.info("Disconnected from {}", connectionInfoToString(connectionInfo));
return true;
}
@Test
public void testAddDeleteOvsdbNode() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testDpdkSwitch() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
Node ovsdbNode = connectOvsdbNode(connectionInfo);
List<DatapathTypeEntry> datapathTypeEntries = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class)
.getDatapathTypeEntry();
if (datapathTypeEntries == null) {
LOG.info("DPDK not supported on this node.");
} else {
for (DatapathTypeEntry dpTypeEntry : datapathTypeEntries) {
Class<? extends DatapathTypeBase> dpType = dpTypeEntry.getDatapathType();
String dpTypeStr = SouthboundConstants.DATAPATH_TYPE_MAP.get(dpType);
LOG.info("dp type is {}", dpTypeStr);
if (dpTypeStr.equals(NETDEV_DP_TYPE)) {
LOG.info("Found a DPDK node; adding a corresponding netdev device");
InstanceIdentifier<Node> bridgeIid = createInstanceIdentifier(connectionInfo,
new OvsdbBridgeName(SouthboundITConstants.BRIDGE_NAME));
NodeId bridgeNodeId = createManagedNodeId(bridgeIid);
addBridge(connectionInfo, bridgeIid, SouthboundITConstants.BRIDGE_NAME, bridgeNodeId, false, null,
true, dpType, null, null, null);
// Verify that the device is netdev
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull(bridge);
Assert.assertEquals(dpType, bridge.getDatapathType());
// Add dpdk port
final String TEST_PORT_NAME = "testDPDKPort";
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericDpdkOvsdbTerminationPointAugmentationBuilder(TEST_PORT_NAME);
Assert.assertTrue(addTerminationPoint(bridgeNodeId, TEST_PORT_NAME, ovsdbTerminationBuilder));
// Verify that DPDK port was created
InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL,
terminationPointIid);
Assert.assertNotNull(terminationPointNode);
// Verify that each termination point has DPDK ifType
Class<? extends InterfaceTypeBase> dpdkIfType = SouthboundConstants.OVSDB_INTERFACE_TYPE_MAP
.get("dpdk");
List<TerminationPoint> terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation = terminationPoint
.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(TEST_PORT_NAME)) {
Class<? extends InterfaceTypeBase> opPort = ovsdbTerminationPointAugmentation
.getInterfaceType();
Assert.assertEquals(dpdkIfType, opPort);
}
}
Assert.assertTrue(deleteBridge(connectionInfo));
break;
}
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testOvsdbNodeOvsVersion() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
Node ovsdbNode = connectOvsdbNode(connectionInfo);
OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
Assert.assertNotNull(ovsdbNodeAugmentation);
assertNotNull(ovsdbNodeAugmentation.getOvsVersion());
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testOpenVSwitchOtherConfig() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
Node ovsdbNode = connectOvsdbNode(connectionInfo);
OvsdbNodeAugmentation ovsdbNodeAugmentation = ovsdbNode.getAugmentation(OvsdbNodeAugmentation.class);
Assert.assertNotNull(ovsdbNodeAugmentation);
List<OpenvswitchOtherConfigs> otherConfigsList = ovsdbNodeAugmentation.getOpenvswitchOtherConfigs();
if (otherConfigsList != null) {
for (OpenvswitchOtherConfigs otherConfig : otherConfigsList) {
if (otherConfig.getOtherConfigKey().equals("local_ip")) {
LOG.info("local_ip: {}", otherConfig.getOtherConfigValue());
break;
} else {
LOG.info("other_config {}:{}", otherConfig.getOtherConfigKey(), otherConfig.getOtherConfigValue());
}
}
} else {
LOG.info("other_config is not present");
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testOvsdbBridgeControllerInfo() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr,portNumber);
Node ovsdbNode = connectOvsdbNode(connectionInfo);
String controllerTarget = SouthboundUtil.getControllerTarget(ovsdbNode);
assertNotNull("Failed to get controller target", controllerTarget);
List<ControllerEntry> setControllerEntry = createControllerEntry(controllerTarget);
Uri setUri = new Uri(controllerTarget);
Assert.assertTrue(addBridge(connectionInfo, null, SouthboundITConstants.BRIDGE_NAME,null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null,
setControllerEntry, null));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull("bridge was not found: " + SouthboundITConstants.BRIDGE_NAME, bridge);
Assert.assertNotNull("ControllerEntry was not found: " + setControllerEntry.iterator().next(),
bridge.getControllerEntry());
List<ControllerEntry> getControllerEntries = bridge.getControllerEntry();
for (ControllerEntry entry : getControllerEntries) {
if (entry.getTarget() != null) {
Assert.assertEquals(setUri.toString(), entry.getTarget().toString());
}
}
Assert.assertTrue(deleteBridge(connectionInfo));
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
private List<ControllerEntry> createControllerEntry(String controllerTarget) {
List<ControllerEntry> controllerEntriesList = new ArrayList<>();
controllerEntriesList.add(new ControllerEntryBuilder()
.setTarget(new Uri(controllerTarget))
.build());
return controllerEntriesList;
}
private void setManagedBy(final OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
final ConnectionInfo connectionInfo) {
InstanceIdentifier<Node> connectionNodePath = createInstanceIdentifier(connectionInfo);
ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
}
private List<ProtocolEntry> createMdsalProtocols() {
List<ProtocolEntry> protocolList = new ArrayList<>();
ImmutableBiMap<String, Class<? extends OvsdbBridgeProtocolBase>> mapper =
SouthboundConstants.OVSDB_PROTOCOL_MAP.inverse();
protocolList.add(new ProtocolEntryBuilder().setProtocol(mapper.get("OpenFlow13")).build());
return protocolList;
}
private OvsdbTerminationPointAugmentationBuilder createGenericOvsdbTerminationPointAugmentationBuilder() {
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationPointAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
ovsdbTerminationPointAugmentationBuilder.setInterfaceType(
new InterfaceTypeEntryBuilder()
.setInterfaceType(
SouthboundMapper.createInterfaceType("internal"))
.build().getInterfaceType());
return ovsdbTerminationPointAugmentationBuilder;
}
private OvsdbTerminationPointAugmentationBuilder createGenericDpdkOvsdbTerminationPointAugmentationBuilder(
final String portName) {
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
ovsdbTerminationBuilder.setName(portName);
Class<? extends InterfaceTypeBase> ifType = SouthboundConstants.OVSDB_INTERFACE_TYPE_MAP
.get("dpdk");
ovsdbTerminationBuilder.setInterfaceType(ifType);
return ovsdbTerminationBuilder;
}
private boolean addTerminationPoint(final NodeId bridgeNodeId, final String portName,
final OvsdbTerminationPointAugmentationBuilder
ovsdbTerminationPointAugmentationBuilder)
throws InterruptedException {
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(bridgeNodeId);
NodeBuilder portNodeBuilder = new NodeBuilder();
NodeId portNodeId = SouthboundMapper.createManagedNodeId(portIid);
portNodeBuilder.setNodeId(portNodeId);
TerminationPointBuilder entry = new TerminationPointBuilder();
entry.setKey(new TerminationPointKey(new TpId(portName)));
entry.addAugmentation(
OvsdbTerminationPointAugmentation.class,
ovsdbTerminationPointAugmentationBuilder.build());
portNodeBuilder.setTerminationPoint(Lists.newArrayList(entry.build()));
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portNodeBuilder.build());
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
return result;
}
/*
* base method for adding test bridges. Other helper methods used to create bridges should utilize this method.
*
* @param connectionInfo
* @param bridgeIid if passed null, one is created
* @param bridgeName cannot be null
* @param bridgeNodeId if passed null, one is created based on <code>bridgeIid</code>
* @param setProtocolEntries toggles whether default protocol entries are set for the bridge
* @param failMode toggles whether default fail mode is set for the bridge
* @param setManagedBy toggles whether to setManagedBy for the bridge
* @param dpType if passed null, this parameter is ignored
* @param externalIds if passed null, this parameter is ignored
* @param otherConfigs if passed null, this parameter is ignored
* @return success of bridge addition
* @throws InterruptedException
*/
private boolean addBridge(final ConnectionInfo connectionInfo, InstanceIdentifier<Node> bridgeIid,
final String bridgeName, NodeId bridgeNodeId, final boolean setProtocolEntries,
final Class<? extends OvsdbFailModeBase> failMode, final boolean setManagedBy,
final Class<? extends DatapathTypeBase> dpType,
final List<BridgeExternalIds> externalIds,
final List<ControllerEntry> controllerEntries,
final List<BridgeOtherConfigs> otherConfigs) throws InterruptedException {
NodeBuilder bridgeNodeBuilder = new NodeBuilder();
if (bridgeIid == null) {
bridgeIid = createInstanceIdentifier(connectionInfo, new OvsdbBridgeName(bridgeName));
}
if (bridgeNodeId == null) {
bridgeNodeId = SouthboundMapper.createManagedNodeId(bridgeIid);
}
bridgeNodeBuilder.setNodeId(bridgeNodeId);
OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridgeName));
if (setProtocolEntries) {
ovsdbBridgeAugmentationBuilder.setProtocolEntry(createMdsalProtocols());
}
if (failMode != null) {
ovsdbBridgeAugmentationBuilder.setFailMode(failMode);
}
if (setManagedBy) {
setManagedBy(ovsdbBridgeAugmentationBuilder, connectionInfo);
}
if (dpType != null) {
ovsdbBridgeAugmentationBuilder.setDatapathType(dpType);
}
if (externalIds != null) {
ovsdbBridgeAugmentationBuilder.setBridgeExternalIds(externalIds);
}
if (controllerEntries != null) {
ovsdbBridgeAugmentationBuilder.setControllerEntry(controllerEntries);
}
if (otherConfigs != null) {
ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(otherConfigs);
}
bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
LOG.debug("Built with the intent to store bridge data {}",
ovsdbBridgeAugmentationBuilder.toString());
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
bridgeIid, bridgeNodeBuilder.build());
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
return result;
}
private boolean addBridge(final ConnectionInfo connectionInfo, final String bridgeName)
throws InterruptedException {
return addBridge(connectionInfo, null, bridgeName, null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null, null);
}
private OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo) {
return getBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME);
}
/**
* Extract the <code>store</code> type data store contents for the particular bridge identified by
* <code>bridgeName</code>.
*
* @param connectionInfo the connection information
* @param bridgeName the bridge name
* @param store defined by the <code>LogicalDatastoreType</code> enumeration
* @return <code>store</code> type data store contents
*/
private OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo, String bridgeName,
LogicalDatastoreType store) {
Node bridgeNode = getBridgeNode(connectionInfo, bridgeName, store);
Assert.assertNotNull(bridgeNode);
OvsdbBridgeAugmentation ovsdbBridgeAugmentation = bridgeNode.getAugmentation(OvsdbBridgeAugmentation.class);
Assert.assertNotNull(ovsdbBridgeAugmentation);
return ovsdbBridgeAugmentation;
}
/**
* extract the <code>LogicalDataStoreType.OPERATIONAL</code> type data store contents for the particular bridge
* identified by <code>bridgeName</code>
*
* @param connectionInfo the connection information
* @param bridgeName the bridge name
* @see <code>SouthboundIT.getBridge(ConnectionInfo, String, LogicalDatastoreType)</code>
* @return <code>LogicalDatastoreType.OPERATIONAL</code> type data store contents
*/
private OvsdbBridgeAugmentation getBridge(ConnectionInfo connectionInfo, String bridgeName) {
return getBridge(connectionInfo, bridgeName, LogicalDatastoreType.OPERATIONAL);
}
/**
* Extract the node contents from <code>store</code> type data store for the
* bridge identified by <code>bridgeName</code>
*
* @param connectionInfo the connection information
* @param bridgeName the bridge name
* @param store defined by the <code>LogicalDatastoreType</code> enumeration
* @return <code>store</code> type data store contents
*/
private Node getBridgeNode(ConnectionInfo connectionInfo, String bridgeName, LogicalDatastoreType store) {
InstanceIdentifier<Node> bridgeIid =
createInstanceIdentifier(connectionInfo,
new OvsdbBridgeName(bridgeName));
return mdsalUtils.read(store, bridgeIid);
}
/**
* Extract the node contents from <code>LogicalDataStoreType.OPERATIONAL</code> data store for the
* bridge identified by <code>bridgeName</code>
*
* @param connectionInfo the connection information
* @param bridgeName the bridge name
* @return <code>LogicalDatastoreType.OPERATIONAL</code> type data store contents
*/
private Node getBridgeNode(ConnectionInfo connectionInfo, String bridgeName) {
return getBridgeNode(connectionInfo, bridgeName, LogicalDatastoreType.OPERATIONAL);
}
private boolean deleteBridge(ConnectionInfo connectionInfo) throws InterruptedException {
return deleteBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME);
}
private boolean deleteBridge(final ConnectionInfo connectionInfo, final String bridgeName)
throws InterruptedException {
boolean result = mdsalUtils.delete(LogicalDatastoreType.CONFIGURATION,
createInstanceIdentifier(connectionInfo,
new OvsdbBridgeName(bridgeName)));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
return result;
}
@Test
public void testAddDeleteBridge() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
Assert.assertTrue(addBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull(bridge);
LOG.info("bridge: {}", bridge);
Assert.assertTrue(deleteBridge(connectionInfo));
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
private InstanceIdentifier<Node> getTpIid(ConnectionInfo connectionInfo, OvsdbBridgeAugmentation bridge) {
return createInstanceIdentifier(connectionInfo,
bridge.getBridgeName());
}
/**
* Extracts the <code>TerminationPointAugmentation</code> for the <code>index</code> <code>TerminationPoint</code>
* on <code>bridgeName</code>
*
* @param connectionInfo the connection information
* @param bridgeName the bridge name
* @param store defined by the <code>LogicalDatastoreType</code> enumeration
* @param index the index we're interested in
* @return the augmentation (or {@code null} if none)
*/
private OvsdbTerminationPointAugmentation getOvsdbTerminationPointAugmentation(
ConnectionInfo connectionInfo, String bridgeName, LogicalDatastoreType store, int index) {
List<TerminationPoint> tpList = getBridgeNode(connectionInfo, bridgeName, store).getTerminationPoint();
if (tpList == null) {
return null;
}
return tpList.get(index).getAugmentation(OvsdbTerminationPointAugmentation.class);
}
@Test
public void testCRDTerminationPointOfPort() throws InterruptedException {
final Long OFPORT_EXPECTED = 45002L;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// CREATE
Assert.assertTrue(addBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull(bridge);
LOG.info("bridge: {}", bridge);
NodeId nodeId = SouthboundMapper.createManagedNodeId(createInstanceIdentifier(
connectionInfo, bridge.getBridgeName()));
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
String portName = "testOfPort";
ovsdbTerminationBuilder.setName(portName);
ovsdbTerminationBuilder.setOfport(OFPORT_EXPECTED);
Assert.assertTrue(addTerminationPoint(nodeId, portName, ovsdbTerminationBuilder));
InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
Assert.assertNotNull(terminationPointNode);
// READ
List<TerminationPoint> terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
Long ofPort = ovsdbTerminationPointAugmentation.getOfport();
// if ephemeral port 45002 is in use, ofPort is set to 1
Assert.assertTrue(ofPort.equals(OFPORT_EXPECTED) || ofPort.equals(new Long(1)));
LOG.info("ofPort: {}", ofPort);
}
}
// UPDATE- Not Applicable. From the OpenVSwitch Documentation:
// the interface."
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo));
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testCRDTerminationPointOfPortRequest() throws InterruptedException {
final Long OFPORT_EXPECTED = 45008L;
final Long OFPORT_INPUT = 45008L;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// CREATE
Assert.assertTrue(addBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull(bridge);
NodeId nodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, bridge.getBridgeName()));
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
String portName = "testOfPortRequest";
ovsdbTerminationBuilder.setName(portName);
Integer ofPortRequestExpected = OFPORT_EXPECTED.intValue();
ovsdbTerminationBuilder.setOfport(OFPORT_INPUT);
ovsdbTerminationBuilder.setOfportRequest(ofPortRequestExpected);
Assert.assertTrue(addTerminationPoint(nodeId, portName, ovsdbTerminationBuilder));
InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
Assert.assertNotNull(terminationPointNode);
// READ
List<TerminationPoint> terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
Long ofPort = ovsdbTerminationPointAugmentation.getOfport();
// if ephemeral port 45008 is in use, ofPort is set to 1
Assert.assertTrue(ofPort.equals(OFPORT_EXPECTED) || ofPort.equals(new Long(1)));
LOG.info("ofPort: {}", ofPort);
Integer ofPortRequest = ovsdbTerminationPointAugmentation.getOfportRequest();
Assert.assertTrue(ofPortRequest.equals(ofPortRequestExpected));
LOG.info("ofPortRequest: {}", ofPortRequest);
}
}
// UPDATE- Not Applicable. From the OpenVSwitch documentation:
// the interface. "
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo));
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing PortExternalIds. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT port external_ids, or EXPECTED port external_ids
* INPUT is the List we use when calling
* <code>TerminationPointAugmentationBuilder.setPortExternalIds()</code>
* EXPECTED is the List we expect to receive after calling
* <code>TerminationPointAugmentationBuilder.getPortExternalIds()</code>
*/
private List<SouthboundTestCase<PortExternalIds>> generatePortExternalIdsTestCases() {
List<SouthboundTestCase<PortExternalIds>> testCases = new ArrayList<>();
final String PORT_EXTERNAL_ID_KEY = "PortExternalIdKey";
final String PORT_EXTERNAL_ID_VALUE = "PortExternalIdValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<PortExternalIds> builder = new SouthboundPortExternalIdsBuilder();
// Test Case 1: TestOneExternalId
// Test Type: Positive
// Description: Create a termination point with one PortExternalIds
// Expected: A port is created with the single external_ids specified below
final String testOneExternalIdName = "TestOneExternalId";
testCases.add(SouthboundIT.<PortExternalIds>testCase()
.name(testOneExternalIdName)
.input(builder.build(testOneExternalIdName, PORT_EXTERNAL_ID_KEY, PORT_EXTERNAL_ID_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFiveExternalId
// Test Type: Positive
// Description: Create a termination point with multiple (five) PortExternalIds
// Expected: A port is created with the five external_ids specified below
final String testFiveExternalIdName = "TestFiveExternalId";
builder.reset();
testCases.add(SouthboundIT.<PortExternalIds>testCase()
.name(testFiveExternalIdName)
.input(
builder.build(testFiveExternalIdName, PORT_EXTERNAL_ID_KEY, PORT_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, PORT_EXTERNAL_ID_KEY, PORT_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, PORT_EXTERNAL_ID_KEY, PORT_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, PORT_EXTERNAL_ID_KEY, PORT_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, PORT_EXTERNAL_ID_KEY, PORT_EXTERNAL_ID_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodExternalIdOneMalformedExternalIdValue
// Test Type: Negative
// Description:
// One perfectly fine PortExternalId
// (TestOneGoodExternalIdOneMalformedExternalIdValue_PortExternalIdKey_1,
// TestOneGoodExternalIdOneMalformedExternalId_PortExternalIdValue_1)
// and one malformed PortExternalId which only has key specified
// (TestOneGoodExternalIdOneMalformedExternalIdValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A port is created without any external_ids
final String testOneGoodExternalIdOneMalformedExternalIdValueName =
"TestOneGoodExternalIdOneMalformedExternalIdValue";
builder.reset();
testCases.add(SouthboundIT.<PortExternalIds>testCase()
.name(testOneGoodExternalIdOneMalformedExternalIdValueName)
.input(
builder.build(testOneGoodExternalIdOneMalformedExternalIdValueName, GOOD_KEY, GOOD_VALUE),
builder.build(testOneGoodExternalIdOneMalformedExternalIdValueName, NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDPortExternalIds()</code>
* This is helper test method to compare a test "set" of BridgeExternalIds against an expected "set"
*/
private void assertExpectedPortExternalIdsExist( List<PortExternalIds> expected,
List<PortExternalIds> test ) {
if (expected != null) {
for (PortExternalIds expectedExternalId : expected) {
Assert.assertTrue("The retrieved ids don't contain " + expectedExternalId,
test.contains(expectedExternalId));
}
}
}
/*
* Tests the CRUD operations for <code>Port</code> <code>external_ids</code>.
*
* @see <code>SouthboundIT.generatePortExternalIdsTestCases()</code> for specific test case information
*/
@Test
public void testCRUDTerminationPointPortExternalIds() throws InterruptedException {
final String TEST_PREFIX = "CRUDTPPortExternalIds";
final int TERMINATION_POINT_TEST_INDEX = 0;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<PortExternalIds>> updateFromTestCases = generatePortExternalIdsTestCases();
List<SouthboundTestCase<PortExternalIds>> updateToTestCases = generatePortExternalIdsTestCases();
for (SouthboundTestCase<PortExternalIds> updateFromTestCase : updateFromTestCases) {
List<PortExternalIds> updateFromInputExternalIds = updateFromTestCase.inputValues;
List<PortExternalIds> updateFromExpectedExternalIds = updateFromTestCase.expectedValues;
for (SouthboundTestCase<PortExternalIds> updateToTestCase : updateToTestCases) {
String testBridgeAndPortName = String.format("%s_%s", TEST_PREFIX, updateToTestCase.name);
List<PortExternalIds> updateToInputExternalIds = updateToTestCase.inputValues;
List<PortExternalIds> updateToExpectedExternalIds = updateToTestCase.expectedValues;
// CREATE: Create the test bridge
Assert.assertTrue(addBridge(connectionInfo, null, testBridgeAndPortName, null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null, null));
NodeId testBridgeNodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, new OvsdbBridgeName(testBridgeAndPortName)));
OvsdbTerminationPointAugmentationBuilder tpCreateAugmentationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
tpCreateAugmentationBuilder.setName(testBridgeAndPortName);
tpCreateAugmentationBuilder.setPortExternalIds(updateFromInputExternalIds);
Assert.assertTrue(
addTerminationPoint(testBridgeNodeId, testBridgeAndPortName, tpCreateAugmentationBuilder));
// READ: Read the test port and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateFromConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateFromConfigurationTerminationPointAugmentation != null) {
List<PortExternalIds> updateFromConfigurationExternalIds =
updateFromConfigurationTerminationPointAugmentation.getPortExternalIds();
assertExpectedPortExternalIdsExist(updateFromExpectedExternalIds,
updateFromConfigurationExternalIds);
}
OvsdbTerminationPointAugmentation updateFromOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateFromOperationalTerminationPointAugmentation != null) {
List<PortExternalIds> updateFromOperationalExternalIds =
updateFromOperationalTerminationPointAugmentation.getPortExternalIds();
assertExpectedPortExternalIdsExist(updateFromExpectedExternalIds, updateFromOperationalExternalIds);
}
testBridgeNodeId = getBridgeNode(connectionInfo, testBridgeAndPortName).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setPortExternalIds(updateToInputExternalIds);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(testBridgeAndPortName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
Assert.assertTrue(mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build()));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
// READ: the test port and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateToConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateToConfigurationTerminationPointAugmentation != null) {
List<PortExternalIds> updateToConfigurationExternalIds =
updateToConfigurationTerminationPointAugmentation.getPortExternalIds();
assertExpectedPortExternalIdsExist(updateToExpectedExternalIds, updateToConfigurationExternalIds);
assertExpectedPortExternalIdsExist(updateFromExpectedExternalIds, updateToConfigurationExternalIds);
}
OvsdbTerminationPointAugmentation updateToOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateToOperationalTerminationPointAugmentation != null) {
List<PortExternalIds> updateToOperationalExternalIds =
updateToOperationalTerminationPointAugmentation.getPortExternalIds();
if (updateFromExpectedExternalIds != null ) {
assertExpectedPortExternalIdsExist(updateToExpectedExternalIds, updateToOperationalExternalIds);
assertExpectedPortExternalIdsExist(updateFromExpectedExternalIds,
updateToOperationalExternalIds);
}
// testCRUDTerminationPointInterfaceExternalIds()'s null assertion of updateToOperationalExternalIds
// fails here
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeAndPortName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing InterfaceExternalIds. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT interface external_ids, or EXPECTED interface external_ids
* INPUT is the List we use when calling
* <code>TerminationPointAugmentationBuilder.setInterfaceExternalIds()</code>
* EXPECTED is the List we expect to receive after calling
* <code>TerminationPointAugmentationBuilder.getInterfaceExternalIds()</code>
*/
private List<SouthboundTestCase<InterfaceExternalIds>> generateInterfaceExternalIdsTestCases() {
List<SouthboundTestCase<InterfaceExternalIds>> testCases = new ArrayList<>();
final String INTERFACE_EXTERNAL_ID_KEY = "IntExternalIdKey";
final String INTERFACE_EXTERNAL_ID_VALUE = "IntExternalIdValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<InterfaceExternalIds> builder = new SouthboundInterfaceExternalIdsBuilder();
// Test Case 1: TestOneExternalId
// Test Type: Positive
// Description: Create a termination point with one InterfaceExternalIds
// Expected: A termination point is created with the single external_ids specified below
final String testOneExternalIdName = "TestOneExternalId";
testCases.add(SouthboundIT.<InterfaceExternalIds>testCase()
.name(testOneExternalIdName)
.input(builder.build(testOneExternalIdName, INTERFACE_EXTERNAL_ID_KEY, INTERFACE_EXTERNAL_ID_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFiveExternalId
// Test Type: Positive
// Description: Create a termination point with multiple (five) InterfaceExternalIds
// Expected: A termination point is created with the five external_ids specified below
final String testFiveExternalIdName = "TestFiveExternalId";
builder.reset();
testCases.add(SouthboundIT.<InterfaceExternalIds>testCase()
.name(testFiveExternalIdName)
.input(
builder.build(testFiveExternalIdName, INTERFACE_EXTERNAL_ID_KEY, INTERFACE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, INTERFACE_EXTERNAL_ID_KEY, INTERFACE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, INTERFACE_EXTERNAL_ID_KEY, INTERFACE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, INTERFACE_EXTERNAL_ID_KEY, INTERFACE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, INTERFACE_EXTERNAL_ID_KEY, INTERFACE_EXTERNAL_ID_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodExternalIdOneMalformedExternalIdValue
// Test Type: Negative
// Description:
// One perfectly fine InterfaceExternalId
// (TestOneGoodExternalIdOneMalformedExternalIdValue_IntExternalIdKey_1,
// TestOneGoodExternalIdOneMalformedExternalId_IntExternalIdValue_1)
// and one malformed PortExternalId which only has key specified
// (TestOneGoodExternalIdOneMalformedExternalIdValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A termination point is created without any external_ids
final String testOneGoodExternalIdOneMalformedExternalIdValueName =
"TestOneGoodExternalIdOneMalformedExternalIdValue";
builder.reset();
testCases.add(SouthboundIT.<InterfaceExternalIds>testCase()
.name(testOneGoodExternalIdOneMalformedExternalIdValueName)
.input(
builder.build(testOneGoodExternalIdOneMalformedExternalIdValueName, GOOD_KEY, GOOD_VALUE),
builder.build(testOneGoodExternalIdOneMalformedExternalIdValueName, NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDInterfaceExternalIds()</code>
* This is helper test method to compare a test "set" of InterfaceExternalIds against an expected "set"
*/
private void assertExpectedInterfaceExternalIdsExist( List<InterfaceExternalIds> expected,
List<InterfaceExternalIds> test ) {
if (expected != null) {
for (InterfaceExternalIds expectedExternalId : expected) {
Assert.assertTrue(test.contains(expectedExternalId));
}
}
}
/*
* Tests the CRUD operations for <code>Interface</code> <code>external_ids</code>.
*
* @see <code>SouthboundIT.generateInterfaceExternalIdsTestCases()</code> for specific test case information
*/
@Test
public void testCRUDTerminationPointInterfaceExternalIds() throws InterruptedException {
final String TEST_PREFIX = "CRUDTPInterfaceExternalIds";
final int TERMINATION_POINT_TEST_INDEX = 0;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<InterfaceExternalIds>> updateFromTestCases = generateInterfaceExternalIdsTestCases();
List<SouthboundTestCase<InterfaceExternalIds>> updateToTestCases = generateInterfaceExternalIdsTestCases();
for (SouthboundTestCase<InterfaceExternalIds> updateFromTestCase : updateFromTestCases) {
List<InterfaceExternalIds> updateFromInputExternalIds = updateFromTestCase.inputValues;
List<InterfaceExternalIds> updateFromExpectedExternalIds = updateFromTestCase.expectedValues;
for (SouthboundTestCase<InterfaceExternalIds> updateToTestCase : updateToTestCases) {
String testBridgeAndPortName = String.format("%s_%s", TEST_PREFIX, updateToTestCase.name);
List<InterfaceExternalIds> updateToInputExternalIds = updateToTestCase.inputValues;
List<InterfaceExternalIds> updateToExpectedExternalIds = updateToTestCase.expectedValues;
// CREATE: Create the test interface
Assert.assertTrue(addBridge(connectionInfo, null, testBridgeAndPortName, null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null, null));
NodeId testBridgeNodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, new OvsdbBridgeName(testBridgeAndPortName)));
OvsdbTerminationPointAugmentationBuilder tpCreateAugmentationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
tpCreateAugmentationBuilder.setName(testBridgeAndPortName);
tpCreateAugmentationBuilder.setInterfaceExternalIds(updateFromInputExternalIds);
Assert.assertTrue(
addTerminationPoint(testBridgeNodeId, testBridgeAndPortName, tpCreateAugmentationBuilder));
// READ: Read the test interface and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateFromConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateFromConfigurationTerminationPointAugmentation != null) {
List<InterfaceExternalIds> updateFromConfigurationExternalIds =
updateFromConfigurationTerminationPointAugmentation.getInterfaceExternalIds();
assertExpectedInterfaceExternalIdsExist(updateFromExpectedExternalIds,
updateFromConfigurationExternalIds);
}
OvsdbTerminationPointAugmentation updateFromOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateFromOperationalTerminationPointAugmentation != null) {
List<InterfaceExternalIds> updateFromOperationalExternalIds =
updateFromOperationalTerminationPointAugmentation.getInterfaceExternalIds();
assertExpectedInterfaceExternalIdsExist(updateFromExpectedExternalIds,
updateFromOperationalExternalIds);
}
testBridgeNodeId = getBridgeNode(connectionInfo, testBridgeAndPortName).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setInterfaceExternalIds(updateToInputExternalIds);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(testBridgeAndPortName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
Assert.assertTrue(mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build()));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
// READ: the test interface and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateToConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateToConfigurationTerminationPointAugmentation != null) {
List<InterfaceExternalIds> updateToConfigurationExternalIds =
updateToConfigurationTerminationPointAugmentation.getInterfaceExternalIds();
assertExpectedInterfaceExternalIdsExist(updateToExpectedExternalIds,
updateToConfigurationExternalIds);
assertExpectedInterfaceExternalIdsExist(updateFromExpectedExternalIds,
updateToConfigurationExternalIds);
}
OvsdbTerminationPointAugmentation updateToOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateToOperationalTerminationPointAugmentation != null) {
List<InterfaceExternalIds> updateToOperationalExternalIds =
updateToOperationalTerminationPointAugmentation.getInterfaceExternalIds();
if (updateFromExpectedExternalIds != null) {
assertExpectedInterfaceExternalIdsExist(updateToExpectedExternalIds,
updateToOperationalExternalIds);
assertExpectedInterfaceExternalIdsExist(updateFromExpectedExternalIds,
updateToOperationalExternalIds);
} else {
Assert.assertNull(updateToOperationalExternalIds);
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeAndPortName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing TP Options. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT TP Options, or EXPECTED TP Options
* INPUT is the List we use when calling
* <code>TerminationPointAugmentationBuilder.setOptions()</code>
* EXPECTED is the List we expect to receive after calling
* <code>TerminationPointAugmentationBuilder.getOptions()</code>
*/
private List<SouthboundTestCase<Options>> generateTerminationPointOptionsTestCases() {
List<SouthboundTestCase<Options>> testCases = new ArrayList<>();
final String TP_OPTIONS_KEY = "TPOptionsKey";
final String TP_OPTIONS_VALUE = "TPOptionsValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<Options> builder = new SouthboundOptionsBuilder();
// Test Case 1: TestOneOptions
// Test Type: Positive
// Description: Create a termination point with one Options
// Expected: A termination point is created with the single Options specified below
final String testOneOptionsName = "TestOneOptions";
testCases.add(SouthboundIT.<Options>testCase()
.name(testOneOptionsName)
.input(builder.build(testOneOptionsName, TP_OPTIONS_KEY, TP_OPTIONS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFiveOptions
// Test Type: Positive
// Description: Create a termination point with multiple (five) Options
// Expected: A termination point is created with the five options specified below
final String testFiveOptionsName = "TestFiveOptions";
builder.reset();
testCases.add(SouthboundIT.<Options>testCase()
.name(testFiveOptionsName)
.input(
builder.build(testFiveOptionsName, TP_OPTIONS_KEY, TP_OPTIONS_VALUE),
builder.build(testFiveOptionsName, TP_OPTIONS_KEY, TP_OPTIONS_VALUE),
builder.build(testFiveOptionsName, TP_OPTIONS_KEY, TP_OPTIONS_VALUE),
builder.build(testFiveOptionsName, TP_OPTIONS_KEY, TP_OPTIONS_VALUE),
builder.build(testFiveOptionsName, TP_OPTIONS_KEY, TP_OPTIONS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodOptionsOneMalformedOptionsValue
// Test Type: Negative
// Description:
// One perfectly fine Options
// (TestOneGoodOptionsOneMalformedOptionsValue_OptionsKey_1,
// TestOneGoodOptionsOneMalformedOptions_OptionsValue_1)
// and one malformed Options which only has key specified
// (TestOneGoodOptionsOneMalformedOptionsValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A termination point is created without any options
final String testOneGoodOptionsOneMalformedOptionsValueName =
"TestOneGoodOptionsOneMalformedOptionsValue";
builder.reset();
testCases.add(SouthboundIT.<Options>testCase()
.name(testOneGoodOptionsOneMalformedOptionsValueName)
.input(
builder.build(testOneGoodOptionsOneMalformedOptionsValueName, GOOD_KEY, GOOD_VALUE),
builder.build(testOneGoodOptionsOneMalformedOptionsValueName, NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDTerminationPointOptions()</code>
* This is helper test method to compare a test "set" of Options against an expected "set"
*/
private void assertExpectedOptionsExist( List<Options> expected,
List<Options> test ) {
if (expected != null) {
for (Options expectedOption : expected) {
Assert.assertTrue(test.contains(expectedOption));
}
}
}
/*
* Tests the CRUD operations for <code>TerminationPoint</code> <code>options</code>.
*
* @see <code>SouthboundIT.generateTerminationPointOptions()</code> for specific test case information
*/
@Test
public void testCRUDTerminationPointOptions() throws InterruptedException {
final String TEST_PREFIX = "CRUDTPOptions";
final int TERMINATION_POINT_TEST_INDEX = 0;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<Options>> updateFromTestCases = generateTerminationPointOptionsTestCases();
List<SouthboundTestCase<Options>> updateToTestCases = generateTerminationPointOptionsTestCases();
for (SouthboundTestCase<Options> updateFromTestCase : updateFromTestCases) {
List<Options> updateFromInputOptions = updateFromTestCase.inputValues;
List<Options> updateFromExpectedOptions = updateFromTestCase.expectedValues;
for (SouthboundTestCase<Options> updateToTestCase : updateToTestCases) {
String testBridgeAndPortName = String.format("%s_%s", TEST_PREFIX, updateToTestCase.name);
List<Options> updateToInputOptions = updateToTestCase.inputValues;
List<Options> updateToExpectedOptions = updateToTestCase.expectedValues;
// CREATE: Create the test interface
Assert.assertTrue(addBridge(connectionInfo, null, testBridgeAndPortName, null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null, null));
NodeId testBridgeNodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, new OvsdbBridgeName(testBridgeAndPortName)));
OvsdbTerminationPointAugmentationBuilder tpCreateAugmentationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
tpCreateAugmentationBuilder.setName(testBridgeAndPortName);
tpCreateAugmentationBuilder.setOptions(updateFromInputOptions);
Assert.assertTrue(
addTerminationPoint(testBridgeNodeId, testBridgeAndPortName, tpCreateAugmentationBuilder));
// READ: Read the test interface and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateFromConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateFromConfigurationTerminationPointAugmentation != null) {
List<Options> updateFromConfigurationOptions =
updateFromConfigurationTerminationPointAugmentation.getOptions();
assertExpectedOptionsExist(updateFromExpectedOptions, updateFromConfigurationOptions);
}
OvsdbTerminationPointAugmentation updateFromOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateFromOperationalTerminationPointAugmentation != null) {
List<Options> updateFromOperationalOptions =
updateFromOperationalTerminationPointAugmentation.getOptions();
assertExpectedOptionsExist(updateFromExpectedOptions, updateFromOperationalOptions);
}
testBridgeNodeId = getBridgeNode(connectionInfo, testBridgeAndPortName).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setOptions(updateToInputOptions);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(testBridgeAndPortName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
Assert.assertTrue(mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build()));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
// READ: the test interface and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateToConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateToConfigurationTerminationPointAugmentation != null) {
List<Options> updateToConfigurationOptions =
updateToConfigurationTerminationPointAugmentation.getOptions();
assertExpectedOptionsExist(updateToExpectedOptions, updateToConfigurationOptions);
assertExpectedOptionsExist(updateFromExpectedOptions, updateToConfigurationOptions);
}
OvsdbTerminationPointAugmentation updateToOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateToOperationalTerminationPointAugmentation != null) {
List<Options> updateToOperationalOptions =
updateToOperationalTerminationPointAugmentation.getOptions();
if (updateFromExpectedOptions != null) {
assertExpectedOptionsExist(updateToExpectedOptions, updateToOperationalOptions);
assertExpectedOptionsExist(updateFromExpectedOptions, updateToOperationalOptions);
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeAndPortName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing Interface other_configs. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT interface other_configs, or EXPECTED interface other_configs
* INPUT is the List we use when calling
* <code>TerminationPointAugmentationBuilder.setInterfaceOtherConfigs()</code>
* EXPECTED is the List we expect to receive after calling
* <code>TerminationPointAugmentationBuilder.getInterfaceOtherConfigs()</code>
*/
private List<SouthboundTestCase<InterfaceOtherConfigs>> generateInterfaceOtherConfigsTestCases() {
List<SouthboundTestCase<InterfaceOtherConfigs>> testCases = new ArrayList<>();
final String INT_OTHER_CONFIGS_KEY = "IntOtherConfigsKey";
final String INT_OTHER_CONFIGS_VALUE = "IntOtherConfigsValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<InterfaceOtherConfigs> builder = new SouthboundInterfaceOtherConfigsBuilder();
// Test Case 1: TestOneOtherConfigs
// Test Type: Positive
// Description: Create an interface with one other_Configs
// Expected: An interface is created with the single other_configs specified below
final String testOneOtherConfigsName = "TestOneInterfaceOtherConfigs";
testCases.add(SouthboundIT.<InterfaceOtherConfigs>testCase()
.name(testOneOtherConfigsName)
.input(builder.build(testOneOtherConfigsName, INT_OTHER_CONFIGS_KEY, INT_OTHER_CONFIGS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFiveInterfaceOtherConfigs
// Test Type: Positive
// Description: Create a termination point with multiple (five) InterfaceOtherConfigs
// Expected: A termination point is created with the five InterfaceOtherConfigs specified below
final String testFiveInterfaceOtherConfigsName = "TestFiveInterfaceOtherConfigs";
builder.reset();
testCases.add(SouthboundIT.<InterfaceOtherConfigs>testCase()
.name(testFiveInterfaceOtherConfigsName)
.input(
builder.build(testFiveInterfaceOtherConfigsName, INT_OTHER_CONFIGS_KEY,
INT_OTHER_CONFIGS_VALUE),
builder.build(testFiveInterfaceOtherConfigsName, INT_OTHER_CONFIGS_KEY,
INT_OTHER_CONFIGS_VALUE),
builder.build(testFiveInterfaceOtherConfigsName, INT_OTHER_CONFIGS_KEY,
INT_OTHER_CONFIGS_VALUE),
builder.build(testFiveInterfaceOtherConfigsName, INT_OTHER_CONFIGS_KEY,
INT_OTHER_CONFIGS_VALUE),
builder.build(testFiveInterfaceOtherConfigsName, INT_OTHER_CONFIGS_KEY,
INT_OTHER_CONFIGS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValue
// Test Type: Negative
// Description:
// One perfectly fine InterfaceOtherConfigs
// (TestOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValue_InterfaceOtherConfigsKey_1,
// TestOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigs_InterfaceOtherConfigsValue_1)
// and one malformed InterfaceOtherConfigs which only has key specified
// (TestOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A termination point is created without any InterfaceOtherConfigs
final String testOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValueName =
"TestOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValue";
builder.reset();
testCases.add(SouthboundIT.<InterfaceOtherConfigs>testCase()
.name(testOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValueName)
.input(
builder.build(testOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValueName,
GOOD_KEY, GOOD_VALUE),
builder.build(testOneGoodInterfaceOtherConfigsOneMalformedInterfaceOtherConfigsValueName,
NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDInterfaceOtherConfigs()</code>
* This is helper test method to compare a test "set" of Options against an expected "set"
*/
private void assertExpectedInterfaceOtherConfigsExist( List<InterfaceOtherConfigs> expected,
List<InterfaceOtherConfigs> test ) {
if (expected != null && test != null) {
for (InterfaceOtherConfigs expectedOtherConfigs : expected) {
Assert.assertTrue(test.contains(expectedOtherConfigs));
}
}
}
/*
* Tests the CRUD operations for <code>Interface</code> <code>other_configs</code>.
*
* @see <code>SouthboundIT.generateInterfaceExternalIdsTestCases()</code> for specific test case information
*/
@Test
public void testCRUDTerminationPointInterfaceOtherConfigs() throws InterruptedException {
final String TEST_PREFIX = "CRUDTPInterfaceOtherConfigs";
final int TERMINATION_POINT_TEST_INDEX = 0;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<InterfaceOtherConfigs>> updateFromTestCases = generateInterfaceOtherConfigsTestCases();
List<SouthboundTestCase<InterfaceOtherConfigs>> updateToTestCases = generateInterfaceOtherConfigsTestCases();
for (SouthboundTestCase<InterfaceOtherConfigs> updateFromTestCase : updateFromTestCases) {
List<InterfaceOtherConfigs> updateFromInputOtherConfigs = updateFromTestCase.inputValues;
List<InterfaceOtherConfigs> updateFromExpectedOtherConfigs = updateFromTestCase.expectedValues;
for (SouthboundTestCase<InterfaceOtherConfigs> updateToTestCase : updateToTestCases) {
String testBridgeAndPortName = String.format("%s_%s", TEST_PREFIX, updateToTestCase.name);
List<InterfaceOtherConfigs> updateToInputOtherConfigs = updateToTestCase.inputValues;
List<InterfaceOtherConfigs> updateToExpectedOtherConfigs = updateToTestCase.expectedValues;
// CREATE: Create the test interface
Assert.assertTrue(addBridge(connectionInfo, null, testBridgeAndPortName, null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null, null));
NodeId testBridgeNodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, new OvsdbBridgeName(testBridgeAndPortName)));
OvsdbTerminationPointAugmentationBuilder tpCreateAugmentationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
tpCreateAugmentationBuilder.setName(testBridgeAndPortName);
tpCreateAugmentationBuilder.setInterfaceOtherConfigs(updateFromInputOtherConfigs);
Assert.assertTrue(
addTerminationPoint(testBridgeNodeId, testBridgeAndPortName, tpCreateAugmentationBuilder));
// READ: Read the test interface and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateFromConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateFromConfigurationTerminationPointAugmentation != null) {
List<InterfaceOtherConfigs> updateFromConfigurationOtherConfigs =
updateFromConfigurationTerminationPointAugmentation.getInterfaceOtherConfigs();
assertExpectedInterfaceOtherConfigsExist(updateFromExpectedOtherConfigs,
updateFromConfigurationOtherConfigs);
}
OvsdbTerminationPointAugmentation updateFromOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateFromOperationalTerminationPointAugmentation != null) {
List<InterfaceOtherConfigs> updateFromOperationalOtherConfigs =
updateFromOperationalTerminationPointAugmentation.getInterfaceOtherConfigs();
assertExpectedInterfaceOtherConfigsExist(updateFromExpectedOtherConfigs,
updateFromOperationalOtherConfigs);
}
testBridgeNodeId = getBridgeNode(connectionInfo, testBridgeAndPortName).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setInterfaceOtherConfigs(updateToInputOtherConfigs);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(testBridgeAndPortName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
Assert.assertTrue(mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build()));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
// READ: the test interface and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateToConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateToConfigurationTerminationPointAugmentation != null) {
List<InterfaceOtherConfigs> updateToConfigurationOtherConfigs =
updateToConfigurationTerminationPointAugmentation.getInterfaceOtherConfigs();
assertExpectedInterfaceOtherConfigsExist(updateToExpectedOtherConfigs,
updateToConfigurationOtherConfigs);
assertExpectedInterfaceOtherConfigsExist(updateFromExpectedOtherConfigs,
updateToConfigurationOtherConfigs);
}
OvsdbTerminationPointAugmentation updateToOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateToOperationalTerminationPointAugmentation != null) {
List<InterfaceOtherConfigs> updateToOperationalOtherConfigs =
updateToOperationalTerminationPointAugmentation.getInterfaceOtherConfigs();
if (updateFromExpectedOtherConfigs != null) {
assertExpectedInterfaceOtherConfigsExist(updateToExpectedOtherConfigs,
updateToOperationalOtherConfigs);
assertExpectedInterfaceOtherConfigsExist(updateFromExpectedOtherConfigs,
updateToOperationalOtherConfigs);
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeAndPortName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing Port other_configs. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT port other_configs, or EXPECTED port other_configs
* INPUT is the List we use when calling
* <code>TerminationPointAugmentationBuilder.setPortOtherConfigs()</code>
* EXPECTED is the List we expect to receive after calling
* <code>TerminationPointAugmentationBuilder.getPortOtherConfigs()</code>
*/
private List<SouthboundTestCase<PortOtherConfigs>> generatePortOtherConfigsTestCases() {
List<SouthboundTestCase<PortOtherConfigs>> testCases = new ArrayList<>();
final String PORT_OTHER_CONFIGS_KEY = "PortOtherConfigsKey";
final String PORT_OTHER_CONFIGS_VALUE = "PortOtherConfigsValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<PortOtherConfigs> builder = new SouthboundPortOtherConfigsBuilder();
// Test Case 1: TestOneOtherConfigs
// Test Type: Positive
// Description: Create an port with one other_Configs
// Expected: A port is created with the single other_configs specified below
final String testOneOtherConfigsName = "TestOnePortOtherConfigs";
testCases.add(SouthboundIT.<PortOtherConfigs>testCase()
.name(testOneOtherConfigsName)
.input(builder.build(testOneOtherConfigsName, PORT_OTHER_CONFIGS_KEY, PORT_OTHER_CONFIGS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFivePortOtherConfigs
// Test Type: Positive
// Description: Create a termination point with multiple (five) PortOtherConfigs
// Expected: A termination point is created with the five PortOtherConfigs specified below
final String testFivePortOtherConfigsName = "TestFivePortOtherConfigs";
builder.reset();
testCases.add(SouthboundIT.<PortOtherConfigs>testCase()
.name(testFivePortOtherConfigsName)
.input(
builder.build(testFivePortOtherConfigsName, PORT_OTHER_CONFIGS_KEY, PORT_OTHER_CONFIGS_VALUE),
builder.build(testFivePortOtherConfigsName, PORT_OTHER_CONFIGS_KEY, PORT_OTHER_CONFIGS_VALUE),
builder.build(testFivePortOtherConfigsName, PORT_OTHER_CONFIGS_KEY, PORT_OTHER_CONFIGS_VALUE),
builder.build(testFivePortOtherConfigsName, PORT_OTHER_CONFIGS_KEY, PORT_OTHER_CONFIGS_VALUE),
builder.build(testFivePortOtherConfigsName, PORT_OTHER_CONFIGS_KEY, PORT_OTHER_CONFIGS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValue
// Test Type: Negative
// Description:
// One perfectly fine PortOtherConfigs
// (TestOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValue_PortOtherConfigsKey_1,
// TestOneGoodPortOtherConfigsOneMalformedPortOtherConfigs_PortOtherConfigsValue_1)
// and one malformed PortOtherConfigs which only has key specified
// (TestOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A termination point is created without any PortOtherConfigs
final String testOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValueName =
"TestOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValue";
builder.reset();
testCases.add(SouthboundIT.<PortOtherConfigs>testCase()
.name(testOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValueName)
.input(
builder.build(testOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValueName, GOOD_KEY,
GOOD_VALUE),
builder.build(testOneGoodPortOtherConfigsOneMalformedPortOtherConfigsValueName,
NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDPortOtherConfigs()</code>
* This is helper test method to compare a test "set" of Options against an expected "set"
*/
private void assertExpectedPortOtherConfigsExist( List<PortOtherConfigs> expected,
List<PortOtherConfigs> test ) {
if (expected != null && test != null) {
for (PortOtherConfigs expectedOtherConfigs : expected) {
Assert.assertTrue(test.contains(expectedOtherConfigs));
}
}
}
/*
* Tests the CRUD operations for <code>Port</code> <code>other_configs</code>.
*
* @see <code>SouthboundIT.generatePortExternalIdsTestCases()</code> for specific test case information
*/
@Test
public void testCRUDTerminationPointPortOtherConfigs() throws InterruptedException {
final String TEST_PREFIX = "CRUDTPPortOtherConfigs";
final int TERMINATION_POINT_TEST_INDEX = 0;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<PortOtherConfigs>> updateFromTestCases = generatePortOtherConfigsTestCases();
List<SouthboundTestCase<PortOtherConfigs>> updateToTestCases = generatePortOtherConfigsTestCases();
for (SouthboundTestCase<PortOtherConfigs> updateFromTestCase : updateFromTestCases) {
List<PortOtherConfigs> updateFromInputOtherConfigs = updateFromTestCase.inputValues;
List<PortOtherConfigs> updateFromExpectedOtherConfigs = updateFromTestCase.expectedValues;
for (SouthboundTestCase<PortOtherConfigs> updateToTestCase : updateToTestCases) {
String testBridgeAndPortName = String.format("%s_%s", TEST_PREFIX, updateToTestCase.name);
List<PortOtherConfigs> updateToInputOtherConfigs = updateToTestCase.inputValues;
List<PortOtherConfigs> updateToExpectedOtherConfigs = updateToTestCase.expectedValues;
// CREATE: Create the test port
Assert.assertTrue(addBridge(connectionInfo, null, testBridgeAndPortName, null, true,
SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"), true, null, null, null, null));
NodeId testBridgeNodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, new OvsdbBridgeName(testBridgeAndPortName)));
OvsdbTerminationPointAugmentationBuilder tpCreateAugmentationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
tpCreateAugmentationBuilder.setName(testBridgeAndPortName);
tpCreateAugmentationBuilder.setPortOtherConfigs(updateFromInputOtherConfigs);
Assert.assertTrue(
addTerminationPoint(testBridgeNodeId, testBridgeAndPortName, tpCreateAugmentationBuilder));
// READ: Read the test port and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateFromConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateFromConfigurationTerminationPointAugmentation != null) {
List<PortOtherConfigs> updateFromConfigurationOtherConfigs =
updateFromConfigurationTerminationPointAugmentation.getPortOtherConfigs();
assertExpectedPortOtherConfigsExist(updateFromExpectedOtherConfigs,
updateFromConfigurationOtherConfigs);
}
OvsdbTerminationPointAugmentation updateFromOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateFromOperationalTerminationPointAugmentation != null) {
List<PortOtherConfigs> updateFromOperationalOtherConfigs =
updateFromOperationalTerminationPointAugmentation.getPortOtherConfigs();
assertExpectedPortOtherConfigsExist(updateFromExpectedOtherConfigs,
updateFromOperationalOtherConfigs);
}
testBridgeNodeId = getBridgeNode(connectionInfo, testBridgeAndPortName).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setPortOtherConfigs(updateToInputOtherConfigs);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(testBridgeAndPortName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
Assert.assertTrue(mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build()));
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
// READ: the test port and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
OvsdbTerminationPointAugmentation updateToConfigurationTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.CONFIGURATION, TERMINATION_POINT_TEST_INDEX);
if (updateToConfigurationTerminationPointAugmentation != null) {
List<PortOtherConfigs> updateToConfigurationOtherConfigs =
updateToConfigurationTerminationPointAugmentation.getPortOtherConfigs();
assertExpectedPortOtherConfigsExist(updateToExpectedOtherConfigs,
updateToConfigurationOtherConfigs);
assertExpectedPortOtherConfigsExist(updateFromExpectedOtherConfigs,
updateToConfigurationOtherConfigs);
}
OvsdbTerminationPointAugmentation updateToOperationalTerminationPointAugmentation =
getOvsdbTerminationPointAugmentation(connectionInfo, testBridgeAndPortName,
LogicalDatastoreType.OPERATIONAL, TERMINATION_POINT_TEST_INDEX);
if (updateToOperationalTerminationPointAugmentation != null) {
List<PortOtherConfigs> updateToOperationalOtherConfigs =
updateToOperationalTerminationPointAugmentation.getPortOtherConfigs();
if (updateFromExpectedOtherConfigs != null) {
assertExpectedPortOtherConfigsExist(updateToExpectedOtherConfigs,
updateToOperationalOtherConfigs);
assertExpectedPortOtherConfigsExist(updateFromExpectedOtherConfigs,
updateToOperationalOtherConfigs);
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeAndPortName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testCRUDTerminationPointVlan() throws InterruptedException {
final Integer CREATED_VLAN_ID = 4000;
final Integer UPDATED_VLAN_ID = 4001;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// CREATE
Assert.assertTrue(addBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME);
Assert.assertNotNull(bridge);
NodeId nodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, bridge.getBridgeName()));
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
String portName = "testTerminationPointVlanId";
ovsdbTerminationBuilder.setName(portName);
ovsdbTerminationBuilder.setVlanTag(new VlanId(CREATED_VLAN_ID));
Assert.assertTrue(addTerminationPoint(nodeId, portName, ovsdbTerminationBuilder));
InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
Assert.assertNotNull(terminationPointNode);
// READ
List<TerminationPoint> terminationPoints = terminationPointNode.getTerminationPoint();
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation;
for (TerminationPoint terminationPoint : terminationPoints) {
ovsdbTerminationPointAugmentation = terminationPoint.getAugmentation(
OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
VlanId actualVlanId = ovsdbTerminationPointAugmentation.getVlanTag();
Assert.assertNotNull(actualVlanId);
Integer actualVlanIdInt = actualVlanId.getValue();
Assert.assertEquals(CREATED_VLAN_ID, actualVlanIdInt);
}
}
// UPDATE
NodeId testBridgeNodeId = getBridgeNode(connectionInfo, SouthboundITConstants.BRIDGE_NAME).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setVlanTag(new VlanId(UPDATED_VLAN_ID));
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(portName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
tpUpdateBuilder.setTpId(new TpId(portName));
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build());
Assert.assertTrue(result);
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
ovsdbTerminationPointAugmentation = terminationPoint.getAugmentation(
OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
VlanId actualVlanId = ovsdbTerminationPointAugmentation.getVlanTag();
Assert.assertNotNull(actualVlanId);
Integer actualVlanIdInt = actualVlanId.getValue();
Assert.assertEquals(UPDATED_VLAN_ID, actualVlanIdInt);
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo));
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testCRUDTerminationPointVlanModes() throws InterruptedException {
final VlanMode UPDATED_VLAN_MODE = VlanMode.Access;
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
VlanMode []vlanModes = VlanMode.values();
for (VlanMode vlanMode : vlanModes) {
// CREATE
Assert.assertTrue(addBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull(bridge);
NodeId nodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, bridge.getBridgeName()));
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
String portName = "testTerminationPointVlanMode" + vlanMode.toString();
ovsdbTerminationBuilder.setName(portName);
ovsdbTerminationBuilder.setVlanMode(vlanMode);
Assert.assertTrue(addTerminationPoint(nodeId, portName, ovsdbTerminationBuilder));
InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
Assert.assertNotNull(terminationPointNode);
// READ
List<TerminationPoint> terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
//test
Assert.assertTrue(ovsdbTerminationPointAugmentation.getVlanMode().equals(vlanMode));
}
}
// UPDATE
NodeId testBridgeNodeId = getBridgeNode(connectionInfo, SouthboundITConstants.BRIDGE_NAME).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setVlanMode(UPDATED_VLAN_MODE);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(portName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
tpUpdateBuilder.setTpId(new TpId(portName));
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build());
Assert.assertTrue(result);
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
//test
Assert.assertEquals(UPDATED_VLAN_MODE, ovsdbTerminationPointAugmentation.getVlanMode());
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo));
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@SuppressWarnings("unchecked")
private List<Set<Integer>> generateVlanSets() {
int min = 0;
int max = 4095;
return Lists.newArrayList(
Collections.<Integer>emptySet(),
Sets.newHashSet(2222),
Sets.newHashSet(min, max, min + 1, max - 1, (max - min) / 2));
}
private List<Trunks> buildTrunkList(Set<Integer> trunkSet) {
List<Trunks> trunkList = Lists.newArrayList();
for (Integer trunk : trunkSet) {
TrunksBuilder trunkBuilder = new TrunksBuilder();
trunkBuilder.setTrunk(new VlanId(trunk));
trunkList.add(trunkBuilder.build());
}
return trunkList;
}
@Test
public void testCRUDTerminationPointVlanTrunks() throws InterruptedException {
final List<Trunks> UPDATED_TRUNKS = buildTrunkList(Sets.newHashSet(2011));
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
Iterable<Set<Integer>> vlanSets = generateVlanSets();
int testCase = 0;
for (Set<Integer> vlanSet : vlanSets) {
++testCase;
// CREATE
Assert.assertTrue(addBridge(connectionInfo, SouthboundITConstants.BRIDGE_NAME));
OvsdbBridgeAugmentation bridge = getBridge(connectionInfo);
Assert.assertNotNull(bridge);
NodeId nodeId = createManagedNodeId(createInstanceIdentifier(
connectionInfo, bridge.getBridgeName()));
OvsdbTerminationPointAugmentationBuilder ovsdbTerminationBuilder =
createGenericOvsdbTerminationPointAugmentationBuilder();
String portName = "testTerminationPointVlanTrunks" + testCase;
ovsdbTerminationBuilder.setName(portName);
List<Trunks> trunks = buildTrunkList(vlanSet);
ovsdbTerminationBuilder.setTrunks(trunks);
Assert.assertTrue(addTerminationPoint(nodeId, portName, ovsdbTerminationBuilder));
InstanceIdentifier<Node> terminationPointIid = getTpIid(connectionInfo, bridge);
Node terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
Assert.assertNotNull(terminationPointNode);
// READ
List<TerminationPoint> terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
List<Trunks> actualTrunks = ovsdbTerminationPointAugmentation.getTrunks();
for (Trunks trunk : trunks) {
Assert.assertTrue(actualTrunks.contains(trunk));
}
}
}
// UPDATE
NodeId testBridgeNodeId = getBridgeNode(connectionInfo, SouthboundITConstants.BRIDGE_NAME).getNodeId();
OvsdbTerminationPointAugmentationBuilder tpUpdateAugmentationBuilder =
new OvsdbTerminationPointAugmentationBuilder();
tpUpdateAugmentationBuilder.setTrunks(UPDATED_TRUNKS);
InstanceIdentifier<Node> portIid = SouthboundMapper.createInstanceIdentifier(testBridgeNodeId);
NodeBuilder portUpdateNodeBuilder = new NodeBuilder();
NodeId portUpdateNodeId = createManagedNodeId(portIid);
portUpdateNodeBuilder.setNodeId(portUpdateNodeId);
TerminationPointBuilder tpUpdateBuilder = new TerminationPointBuilder();
tpUpdateBuilder.setKey(new TerminationPointKey(new TpId(portName)));
tpUpdateBuilder.addAugmentation(
OvsdbTerminationPointAugmentation.class,
tpUpdateAugmentationBuilder.build());
tpUpdateBuilder.setTpId(new TpId(portName));
portUpdateNodeBuilder.setTerminationPoint(Lists.newArrayList(tpUpdateBuilder.build()));
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION,
portIid, portUpdateNodeBuilder.build());
Assert.assertTrue(result);
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
terminationPointNode = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, terminationPointIid);
terminationPoints = terminationPointNode.getTerminationPoint();
for (TerminationPoint terminationPoint : terminationPoints) {
OvsdbTerminationPointAugmentation ovsdbTerminationPointAugmentation =
terminationPoint.getAugmentation(OvsdbTerminationPointAugmentation.class);
if (ovsdbTerminationPointAugmentation.getName().equals(portName)) {
//test
Assert.assertEquals(UPDATED_TRUNKS, ovsdbTerminationPointAugmentation.getTrunks());
}
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo));
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
@Test
public void testGetOvsdbNodes() throws InterruptedException {
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
InstanceIdentifier<Topology> topologyPath = InstanceIdentifier
.create(NetworkTopology.class)
.child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID));
Topology topology = mdsalUtils.read(LogicalDatastoreType.OPERATIONAL, topologyPath);
InstanceIdentifier<Node> expectedNodeIid = createInstanceIdentifier(connectionInfo);
NodeId expectedNodeId = expectedNodeIid.firstKeyOf(Node.class, NodeKey.class).getNodeId();
Node foundNode = null;
Assert.assertNotNull("Expected to find topology: " + topologyPath, topology);
Assert.assertNotNull("Expected to find some nodes" + topology.getNode());
LOG.info("expectedNodeId: {}, getNode: {}", expectedNodeId, topology.getNode());
for (Node node : topology.getNode()) {
if (node.getNodeId().getValue().equals(expectedNodeId.getValue())) {
foundNode = node;
break;
}
}
Assert.assertNotNull("Expected to find Node: " + expectedNodeId, foundNode);
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing BridgeOtherConfigs. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT bridge other_configs, or EXPECTED bridge other_configs
* INPUT is the List we use when calling BridgeAugmentationBuilder.setBridgeOtherConfigs()
* EXPECTED is the List we expect to receive after calling BridgeAugmentationBuilder.getBridgeOtherConfigs()
*/
private List<SouthboundTestCase<BridgeOtherConfigs>> generateBridgeOtherConfigsTestCases() {
List<SouthboundTestCase<BridgeOtherConfigs>> testCases = new ArrayList<>();
final String BRIDGE_OTHER_CONFIGS_KEY = "BridgeOtherConfigKey";
final String BRIDGE_OTHER_CONFIGS_VALUE = "BridgeOtherConfigValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<BridgeOtherConfigs> builder = new SouthboundBridgeOtherConfigsBuilder();
// Test Case 1: TestOneOtherConfig
// Test Type: Positive
// Description: Create a bridge with one other_config
// Expected: A bridge is created with the single other_config specified below
final String testOneOtherConfigName = "TestOneOtherConfig";
testCases.add(SouthboundIT.<BridgeOtherConfigs>testCase()
.name(testOneOtherConfigName)
.input(builder.build(testOneOtherConfigName, BRIDGE_OTHER_CONFIGS_KEY, BRIDGE_OTHER_CONFIGS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFiveOtherConfig
// Test Type: Positive
// Description: Create a bridge with multiple (five) other_configs
// Expected: A bridge is created with the five other_configs specified below
final String testFiveOtherConfigName = "TestFiveOtherConfig";
builder.reset();
testCases.add(SouthboundIT.<BridgeOtherConfigs>testCase()
.name(testFiveOtherConfigName)
.input(
builder.build(testFiveOtherConfigName, BRIDGE_OTHER_CONFIGS_KEY, BRIDGE_OTHER_CONFIGS_VALUE),
builder.build(testFiveOtherConfigName, BRIDGE_OTHER_CONFIGS_KEY, BRIDGE_OTHER_CONFIGS_VALUE),
builder.build(testFiveOtherConfigName, BRIDGE_OTHER_CONFIGS_KEY, BRIDGE_OTHER_CONFIGS_VALUE),
builder.build(testFiveOtherConfigName, BRIDGE_OTHER_CONFIGS_KEY, BRIDGE_OTHER_CONFIGS_VALUE),
builder.build(testFiveOtherConfigName, BRIDGE_OTHER_CONFIGS_KEY, BRIDGE_OTHER_CONFIGS_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodOtherConfigOneMalformedOtherConfigValue
// Test Type: Negative
// Description:
// One perfectly fine BridgeOtherConfig
// (TestOneGoodOtherConfigOneMalformedOtherConfigValue_BridgeOtherConfigKey_1,
// TestOneGoodOtherConfigOneMalformedOtherConfig_BridgeOtherConfigValue_1)
// and one malformed BridgeOtherConfig which only has key specified
// (TestOneGoodOtherConfigOneMalformedOtherConfigValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A bridge is created without any other_config
final String testOneGoodOtherConfigOneMalformedOtherConfigValueName =
"TestOneGoodOtherConfigOneMalformedOtherConfigValue";
builder.reset();
testCases.add(SouthboundIT.<BridgeOtherConfigs>testCase()
.name(testOneGoodOtherConfigOneMalformedOtherConfigValueName)
.input(
builder.build(testOneGoodOtherConfigOneMalformedOtherConfigValueName, GOOD_KEY, GOOD_VALUE),
builder.build(testOneGoodOtherConfigOneMalformedOtherConfigValueName, NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDBridgeOtherConfigs()</code>
* This is helper test method to compare a test "set" of BridgeExternalIds against an expected "set"
*/
private void assertExpectedBridgeOtherConfigsExist( List<BridgeOtherConfigs> expected,
List<BridgeOtherConfigs> test ) {
if (expected != null) {
for (BridgeOtherConfigs expectedOtherConfig : expected) {
Assert.assertTrue(test.contains(expectedOtherConfig));
}
}
}
/*
* @see <code>SouthboundIT.generateBridgeOtherConfigsTestCases()</code> for specific test case information.
*/
@Test
public void testCRUDBridgeOtherConfigs() throws InterruptedException {
final String TEST_BRIDGE_PREFIX = "CRUDBridgeOtherConfigs";
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<BridgeOtherConfigs>> updateFromTestCases = generateBridgeOtherConfigsTestCases();
List<SouthboundTestCase<BridgeOtherConfigs>> updateToTestCases = generateBridgeOtherConfigsTestCases();
for (SouthboundTestCase<BridgeOtherConfigs> updateFromTestCase : updateFromTestCases) {
List<BridgeOtherConfigs> updateFromInputOtherConfigs = updateFromTestCase.inputValues;
List<BridgeOtherConfigs> updateFromExpectedOtherConfigs = updateFromTestCase.expectedValues;
for (SouthboundTestCase<BridgeOtherConfigs> updateToTestCase : updateToTestCases) {
String testBridgeName = String.format("%s_%s", TEST_BRIDGE_PREFIX, updateToTestCase.name);
List<BridgeOtherConfigs> updateToInputOtherConfigs = updateToTestCase.inputValues;
List<BridgeOtherConfigs> updateToExpectedOtherConfigs = updateToTestCase.expectedValues;
// CREATE: Create the test bridge
boolean bridgeAdded = addBridge(connectionInfo, null,
testBridgeName, null, true, SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"),
true, null, null, null, updateFromInputOtherConfigs);
Assert.assertTrue(bridgeAdded);
// READ: Read the test bridge and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
List<BridgeOtherConfigs> updateFromConfigurationOtherConfigs = getBridge(connectionInfo, testBridgeName,
LogicalDatastoreType.CONFIGURATION).getBridgeOtherConfigs();
assertExpectedBridgeOtherConfigsExist(updateFromExpectedOtherConfigs,
updateFromConfigurationOtherConfigs);
List<BridgeOtherConfigs> updateFromOperationalOtherConfigs = getBridge(connectionInfo, testBridgeName).getBridgeOtherConfigs();
assertExpectedBridgeOtherConfigsExist(updateFromExpectedOtherConfigs,
updateFromOperationalOtherConfigs);
OvsdbBridgeAugmentationBuilder bridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
bridgeAugmentationBuilder.setBridgeOtherConfigs(updateToInputOtherConfigs);
InstanceIdentifier<Node> bridgeIid =
createInstanceIdentifier(connectionInfo,
new OvsdbBridgeName(testBridgeName));
NodeBuilder bridgeNodeBuilder = new NodeBuilder();
Node bridgeNode = getBridgeNode(connectionInfo, testBridgeName);
bridgeNodeBuilder.setNodeId(bridgeNode.getNodeId());
bridgeNodeBuilder.setKey(bridgeNode.getKey());
bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, bridgeAugmentationBuilder.build());
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid,
bridgeNodeBuilder.build());
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
Assert.assertTrue(result);
// READ: the test bridge and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
List<BridgeOtherConfigs> updateToConfigurationOtherConfigs = getBridge(connectionInfo, testBridgeName,
LogicalDatastoreType.CONFIGURATION).getBridgeOtherConfigs();
assertExpectedBridgeOtherConfigsExist(updateToExpectedOtherConfigs, updateToConfigurationOtherConfigs);
assertExpectedBridgeOtherConfigsExist(updateFromExpectedOtherConfigs,
updateToConfigurationOtherConfigs);
List<BridgeOtherConfigs> updateToOperationalOtherConfigs = getBridge(connectionInfo, testBridgeName)
.getBridgeOtherConfigs();
if (updateFromExpectedOtherConfigs != null) {
assertExpectedBridgeOtherConfigsExist(updateToExpectedOtherConfigs,
updateToOperationalOtherConfigs);
assertExpectedBridgeOtherConfigsExist(updateFromExpectedOtherConfigs,
updateToOperationalOtherConfigs);
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
/*
* Generates the test cases involved in testing BridgeExternalIds. See inline comments for descriptions of
* the particular cases considered.
*
* The return value is a Map in the form (K,V)=(testCaseName,testCase).
* - testCaseName is a String
* - testCase is a Map in the form (K,V) s.t. K=(EXPECTED_VALUES_KEY|INPUT_VALUES_KEY) and V is a List of
* either corresponding INPUT bridge external ids, or EXPECTED bridge external ids
* INPUT is the List we use when calling BridgeAugmentationBuilder.setBridgeExternalIds()
* EXPECTED is the List we expect to receive after calling BridgeAugmentationBuilder.getBridgeExternalIds()
*/
private List<SouthboundTestCase<BridgeExternalIds>> generateBridgeExternalIdsTestCases() {
List<SouthboundTestCase<BridgeExternalIds>> testCases = new ArrayList<>();
final String BRIDGE_EXTERNAL_ID_KEY = "BridgeExternalIdKey";
final String BRIDGE_EXTERNAL_ID_VALUE = "BridgeExternalIdValue";
final String GOOD_KEY = "GoodKey";
final String GOOD_VALUE = "GoodValue";
final String NO_VALUE_FOR_KEY = "NoValueForKey";
KeyValueBuilder<BridgeExternalIds> builder = new SouthboundBridgeExternalIdsBuilder();
// Test Case 1: TestOneExternalId
// Test Type: Positive
// Description: Create a bridge with one BridgeExternalIds
// Expected: A bridge is created with the single external_ids specified below
final String testOneExternalIdName = "TestOneExternalId";
testCases.add(SouthboundIT.<BridgeExternalIds>testCase()
.name(testOneExternalIdName)
.input(builder.build(testOneExternalIdName, BRIDGE_EXTERNAL_ID_KEY, BRIDGE_EXTERNAL_ID_VALUE))
.expectInputAsOutput()
.build());
// Test Case 2: TestFiveExternalId
// Test Type: Positive
// Description: Create a bridge with multiple (five) BridgeExternalIds
// Expected: A bridge is created with the five external_ids specified below
final String testFiveExternalIdName = "TestFiveExternalId";
builder.reset();
testCases.add(SouthboundIT.<BridgeExternalIds>testCase()
.name(testFiveExternalIdName)
.input(
builder.build(testFiveExternalIdName, BRIDGE_EXTERNAL_ID_KEY, BRIDGE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, BRIDGE_EXTERNAL_ID_KEY, BRIDGE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, BRIDGE_EXTERNAL_ID_KEY, BRIDGE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, BRIDGE_EXTERNAL_ID_KEY, BRIDGE_EXTERNAL_ID_VALUE),
builder.build(testFiveExternalIdName, BRIDGE_EXTERNAL_ID_KEY, BRIDGE_EXTERNAL_ID_VALUE))
.expectInputAsOutput()
.build());
// Test Case 3: TestOneGoodExternalIdOneMalformedExternalIdValue
// Test Type: Negative
// Description:
// One perfectly fine BridgeExternalId
// (TestOneGoodExternalIdOneMalformedExternalIdValue_BridgeExternalIdKey_1,
// TestOneGoodExternalIdOneMalformedExternalId_BridgeExternalIdValue_1)
// and one malformed BridgeExternalId which only has key specified
// (TestOneGoodExternalIdOneMalformedExternalIdValue_NoValueForKey_2,
// UNSPECIFIED)
// Expected: A bridge is created without any external_ids
final String testOneGoodExternalIdOneMalformedExternalIdValueName =
"TestOneGoodExternalIdOneMalformedExternalIdValue";
builder.reset();
testCases.add(SouthboundIT.<BridgeExternalIds>testCase()
.name(testOneGoodExternalIdOneMalformedExternalIdValueName)
.input(
builder.build(testOneGoodExternalIdOneMalformedExternalIdValueName, GOOD_KEY, GOOD_VALUE),
builder.build(testOneGoodExternalIdOneMalformedExternalIdValueName, NO_VALUE_FOR_KEY, null))
.expectNoOutput()
.build());
return testCases;
}
/*
* @see <code>SouthboundIT.testCRUDBridgeExternalIds()</code>
* This is helper test method to compare a test "set" of BridgeExternalIds against an expected "set"
*/
private void assertExpectedBridgeExternalIdsExist( List<BridgeExternalIds> expected,
List<BridgeExternalIds> test ) {
if (expected != null) {
for (BridgeExternalIds expectedExternalId : expected) {
Assert.assertTrue(test.contains(expectedExternalId));
}
}
}
/*
* @see <code>SouthboundIT.generateBridgeExternalIdsTestCases()</code> for specific test case information
*/
@Test
public void testCRUDBridgeExternalIds() throws InterruptedException {
final String TEST_BRIDGE_PREFIX = "CRUDBridgeExternalIds";
ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
connectOvsdbNode(connectionInfo);
// updateFromTestCases represent the original test case value. updateToTestCases represent the new value after
// the update has been performed.
List<SouthboundTestCase<BridgeExternalIds>> updateFromTestCases = generateBridgeExternalIdsTestCases();
List<SouthboundTestCase<BridgeExternalIds>> updateToTestCases = generateBridgeExternalIdsTestCases();
for (SouthboundTestCase<BridgeExternalIds> updateFromTestCase : updateFromTestCases) {
List<BridgeExternalIds> updateFromInputExternalIds = updateFromTestCase.inputValues;
List<BridgeExternalIds> updateFromExpectedExternalIds = updateFromTestCase.expectedValues;
for (SouthboundTestCase<BridgeExternalIds> updateToTestCase : updateToTestCases) {
String testBridgeName = String.format("%s_%s", TEST_BRIDGE_PREFIX, updateToTestCase.name);
List<BridgeExternalIds> updateToInputExternalIds = updateToTestCase.inputValues;
List<BridgeExternalIds> updateToExpectedExternalIds = updateToTestCase.expectedValues;
// CREATE: Create the test bridge
boolean bridgeAdded = addBridge(connectionInfo, null,
testBridgeName, null, true, SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get("secure"),
true, null, updateFromInputExternalIds, null, null);
Assert.assertTrue(bridgeAdded);
// READ: Read the test bridge and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
List<BridgeExternalIds> updateFromConfigurationExternalIds = getBridge(connectionInfo, testBridgeName,
LogicalDatastoreType.CONFIGURATION).getBridgeExternalIds();
assertExpectedBridgeExternalIdsExist(updateFromExpectedExternalIds, updateFromConfigurationExternalIds);
List<BridgeExternalIds> updateFromOperationalExternalIds = getBridge(connectionInfo, testBridgeName).getBridgeExternalIds();
assertExpectedBridgeExternalIdsExist(updateFromExpectedExternalIds, updateFromOperationalExternalIds);
OvsdbBridgeAugmentationBuilder bridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
bridgeAugmentationBuilder.setBridgeExternalIds(updateToInputExternalIds);
InstanceIdentifier<Node> bridgeIid =
createInstanceIdentifier(connectionInfo,
new OvsdbBridgeName(testBridgeName));
NodeBuilder bridgeNodeBuilder = new NodeBuilder();
Node bridgeNode = getBridgeNode(connectionInfo, testBridgeName);
bridgeNodeBuilder.setNodeId(bridgeNode.getNodeId());
bridgeNodeBuilder.setKey(bridgeNode.getKey());
bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, bridgeAugmentationBuilder.build());
boolean result = mdsalUtils.merge(LogicalDatastoreType.CONFIGURATION, bridgeIid,
bridgeNodeBuilder.build());
Thread.sleep(OVSDB_UPDATE_TIMEOUT);
Assert.assertTrue(result);
// READ: the test bridge and ensure changes are propagated to the CONFIGURATION data store,
// then repeat for OPERATIONAL data store
List<BridgeExternalIds> updateToConfigurationExternalIds = getBridge(connectionInfo, testBridgeName,
LogicalDatastoreType.CONFIGURATION).getBridgeExternalIds();
assertExpectedBridgeExternalIdsExist(updateToExpectedExternalIds, updateToConfigurationExternalIds);
assertExpectedBridgeExternalIdsExist(updateFromExpectedExternalIds, updateToConfigurationExternalIds);
List<BridgeExternalIds> updateToOperationalExternalIds = getBridge(connectionInfo, testBridgeName)
.getBridgeExternalIds();
if (updateFromExpectedExternalIds != null) {
assertExpectedBridgeExternalIdsExist(updateToExpectedExternalIds, updateToOperationalExternalIds);
assertExpectedBridgeExternalIdsExist(updateFromExpectedExternalIds, updateToOperationalExternalIds);
}
// DELETE
Assert.assertTrue(deleteBridge(connectionInfo, testBridgeName));
}
}
Assert.assertTrue(disconnectOvsdbNode(connectionInfo));
}
public static InstanceIdentifier<Node> createInstanceIdentifier(ConnectionInfo key,OvsdbBridgeName bridgeName) {
return SouthboundMapper.createInstanceIdentifier(createManagedNodeId(key, bridgeName));
}
public static NodeId createManagedNodeId(ConnectionInfo key, OvsdbBridgeName bridgeName) {
return createManagedNodeId(key.getRemoteIp(), key.getRemotePort(), bridgeName);
}
public static NodeId createManagedNodeId(IpAddress ip, PortNumber port, OvsdbBridgeName bridgeName) {
return new NodeId(createNodeId(ip,port).getValue()
+ "/" + SouthboundConstants.BRIDGE_URI_PREFIX + "/" + bridgeName.getValue());
}
public static NodeId createNodeId(IpAddress ip, PortNumber port) {
String uriString = SouthboundConstants.OVSDB_URI_PREFIX + ":
+ new String(ip.getValue()) + ":" + port.getValue();
Uri uri = new Uri(uriString);
return new NodeId(uri);
}
public static NodeKey createNodeKey(IpAddress ip, PortNumber port) {
return new NodeKey(createNodeId(ip,port));
}
public static Node createNode(ConnectionInfo key) {
NodeBuilder nodeBuilder = new NodeBuilder();
nodeBuilder.setNodeId(createNodeId(key.getRemoteIp(),key.getRemotePort()));
nodeBuilder.addAugmentation(OvsdbNodeAugmentation.class, createOvsdbAugmentation(key));
return nodeBuilder.build();
}
public static OvsdbNodeAugmentation createOvsdbAugmentation(ConnectionInfo key) {
OvsdbNodeAugmentationBuilder ovsdbNodeBuilder = new OvsdbNodeAugmentationBuilder();
ovsdbNodeBuilder.setConnectionInfo(key);
return ovsdbNodeBuilder.build();
}
public static NodeId createManagedNodeId(InstanceIdentifier<Node> iid) {
NodeKey nodeKey = iid.firstKeyOf(Node.class, NodeKey.class);
return nodeKey.getNodeId();
}
/**
* <p>
* Representation of a southbound test case. Each test case has a name, a list of input values and a list of
* expected values. The input values are provided to the augmentation builder, and the expected values are checked
* against the output of the resulting augmentation.
* </p>
* <p>
* Instances of this class are immutable.
* </p>
*
* @param <T> The type of data used for the test case.
*/
private static final class SouthboundTestCase<T> {
private final String name;
private final List<T> inputValues;
private final List<T> expectedValues;
/**
* Creates an instance of a southbound test case.
*
* @param name The test case's name.
* @param inputValues The input values (provided as input to the underlying augmentation builder).
* @param expectedValues The expected values (checked against the output of the underlying augmentation).
*/
public SouthboundTestCase(
final String name, final List<T> inputValues, final List<T> expectedValues) {
this.name = name;
this.inputValues = inputValues;
this.expectedValues = expectedValues;
}
}
/**
* Southbound test case builder.
*
* @param <T> The type of data used for the test case.
*/
private static final class SouthboundTestCaseBuilder<T> {
private String name;
private List<T> inputValues;
private List<T> expectedValues;
/**
* Creates a builder. Builders may be reused, the generated immutable instances are independent of the
* builders. There are no default values.
*/
public SouthboundTestCaseBuilder() {
// Nothing to do
}
/**
* Sets the test case's name.
*
* @param name The test case's name.
* @return The builder.
*/
public SouthboundTestCaseBuilder<T> name(final String name) {
this.name = name;
return this;
}
/**
* Sets the input values.
*
* @param inputValues The input values.
* @return The builder.
*/
@SafeVarargs
public final SouthboundTestCaseBuilder<T> input(final T... inputValues) {
this.inputValues = Lists.newArrayList(inputValues);
return this;
}
/**
* Sets the expected output values.
*
* @param expectedValues The expected output values.
* @return The builder.
*/
@SafeVarargs
public final SouthboundTestCaseBuilder<T> expect(final T... expectedValues) {
this.expectedValues = Lists.newArrayList(expectedValues);
return this;
}
/**
* Indicates that the provided input values should be expected as output values.
*
* @return The builder.
*/
public SouthboundTestCaseBuilder<T> expectInputAsOutput() {
this.expectedValues = this.inputValues;
return this;
}
/**
* Indicates that no output should be expected.
*
* @return The builder.
*/
public SouthboundTestCaseBuilder<T> expectNoOutput() {
this.expectedValues = null;
return this;
}
/**
* Builds an immutable instance representing the test case.
*
* @return The test case.
*/
@SuppressWarnings("unchecked")
public SouthboundTestCase<T> build() {
return new SouthboundTestCase<>(name, inputValues, expectedValues);
}
}
private static <T> SouthboundTestCaseBuilder<T> testCase() {
return new SouthboundTestCaseBuilder<>();
}
private abstract static class KeyValueBuilder<T> {
private static final int COUNTER_START = 0;
private int counter = COUNTER_START;
protected abstract Builder<T> builder();
protected abstract void setKey(Builder<T> builder, String key);
protected abstract void setValue(Builder<T> builder, String value);
public final T build(final String testName, final String key, final String value) {
final Builder<T> builder = builder();
this.counter++;
if (key != null) {
setKey(builder, String.format(FORMAT_STR, testName, key, this.counter));
}
if (value != null) {
setValue(builder, String.format(FORMAT_STR, testName, value, this.counter));
}
return builder.build();
}
public final void reset() {
this.counter = COUNTER_START;
}
}
private static final class SouthboundPortExternalIdsBuilder extends KeyValueBuilder<PortExternalIds> {
@Override
protected Builder<PortExternalIds> builder() {
return new PortExternalIdsBuilder();
}
@Override
protected void setKey(Builder<PortExternalIds> builder, String key) {
((PortExternalIdsBuilder) builder).setExternalIdKey(key);
}
@Override
protected void setValue(Builder<PortExternalIds> builder, String value) {
((PortExternalIdsBuilder) builder).setExternalIdValue(value);
}
}
private static final class SouthboundInterfaceExternalIdsBuilder extends KeyValueBuilder<InterfaceExternalIds> {
@Override
protected Builder<InterfaceExternalIds> builder() {
return new InterfaceExternalIdsBuilder();
}
@Override
protected void setKey(Builder<InterfaceExternalIds> builder, String key) {
((InterfaceExternalIdsBuilder) builder).setExternalIdKey(key);
}
@Override
protected void setValue(Builder<InterfaceExternalIds> builder, String value) {
((InterfaceExternalIdsBuilder) builder).setExternalIdValue(value);
}
}
private static final class SouthboundOptionsBuilder extends KeyValueBuilder<Options> {
@Override
protected Builder<Options> builder() {
return new OptionsBuilder();
}
@Override
protected void setKey(Builder<Options> builder, String key) {
((OptionsBuilder) builder).setOption(key);
}
@Override
protected void setValue(Builder<Options> builder, String value) {
((OptionsBuilder) builder).setValue(value);
}
}
private static final class SouthboundInterfaceOtherConfigsBuilder extends KeyValueBuilder<InterfaceOtherConfigs> {
@Override
protected Builder<InterfaceOtherConfigs> builder() {
return new InterfaceOtherConfigsBuilder();
}
@Override
protected void setKey(Builder<InterfaceOtherConfigs> builder, String key) {
((InterfaceOtherConfigsBuilder) builder).setOtherConfigKey(key);
}
@Override
protected void setValue(Builder<InterfaceOtherConfigs> builder, String value) {
((InterfaceOtherConfigsBuilder) builder).setOtherConfigValue(value);
}
}
private static final class SouthboundPortOtherConfigsBuilder extends KeyValueBuilder<PortOtherConfigs> {
@Override
protected Builder<PortOtherConfigs> builder() {
return new PortOtherConfigsBuilder();
}
@Override
protected void setKey(Builder<PortOtherConfigs> builder, String key) {
((PortOtherConfigsBuilder) builder).setOtherConfigKey(key);
}
@Override
protected void setValue(Builder<PortOtherConfigs> builder, String value) {
((PortOtherConfigsBuilder) builder).setOtherConfigValue(value);
}
}
private static final class SouthboundBridgeOtherConfigsBuilder extends KeyValueBuilder<BridgeOtherConfigs> {
@Override
protected Builder<BridgeOtherConfigs> builder() {
return new BridgeOtherConfigsBuilder();
}
@Override
protected void setKey(Builder<BridgeOtherConfigs> builder, String key) {
((BridgeOtherConfigsBuilder) builder).setBridgeOtherConfigKey(key);
}
@Override
protected void setValue(Builder<BridgeOtherConfigs> builder, String value) {
((BridgeOtherConfigsBuilder) builder).setBridgeOtherConfigValue(value);
}
}
private static final class SouthboundBridgeExternalIdsBuilder extends KeyValueBuilder<BridgeExternalIds> {
@Override
protected Builder<BridgeExternalIds> builder() {
return new BridgeExternalIdsBuilder();
}
@Override
protected void setKey(Builder<BridgeExternalIds> builder, String key) {
((BridgeExternalIdsBuilder) builder).setBridgeExternalIdKey(key);
}
@Override
protected void setValue(Builder<BridgeExternalIds> builder, String value) {
((BridgeExternalIdsBuilder) builder).setBridgeExternalIdValue(value);
}
}
}
|
package ibis.impl.messagePassing;
import ibis.impl.util.IbisIdentifierTable;
import ibis.io.Conversion;
import java.io.IOException;
import java.io.StreamCorruptedException;
/**
* messagePassing IbisIdentifier.
* Assumes closed world, so CPUs can be simply ranked.
*/
// Make this final, make inlining possible
final class IbisIdentifier
extends ibis.ipl.IbisIdentifier
implements java.io.Serializable {
private int cpu;
private transient byte[] serialForm;
private static IbisIdentifierTable cache = new IbisIdentifierTable();
IbisIdentifier(String name, int cpu) throws IOException {
super(name);
this.cpu = cpu;
makeSerialForm();
}
static IbisIdentifier createIbisIdentifier(byte[] serialForm)
throws IOException {
IbisIdentifier id;
try {
id = (IbisIdentifier) Conversion.byte2object(serialForm);
} catch (ClassNotFoundException e) {
throw new StreamCorruptedException("serialForm corrupted " + e);
}
id.serialForm = serialForm;
return id;
}
// no need to serialize super class fields, this is done automatically
// We handle the address field special.
// Do not do a writeObject on it (or a defaultWriteObject of the current object),
// because InetAddress might not be rewritten as it is in the classlibs --Rob
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
int handle = cache.getHandle(out, this);
out.writeInt(handle);
// Rob, somehow you should tell the partner the CPU number
// the first time. It is not part of the superclass so you
// must do it yourself.
if (handle < 0) {
out.defaultWriteObject();
}
}
// no need to serialize super class fields, this is done automatically
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
int handle = in.readInt();
if (handle < 0) {
in.defaultReadObject();
cache.addIbis(in, -handle, this);
} else {
IbisIdentifier ident = (IbisIdentifier)cache.getIbis(in, handle);
name = ident.name;
cluster = ident.cluster;
cpu = ident.cpu;
}
}
public void free() {
cache.removeIbis(this);
}
private void makeSerialForm() throws IOException {
serialForm = Conversion.object2byte(this);
}
byte[] getSerialForm() throws IOException {
if (serialForm == null) {
makeSerialForm();
}
return serialForm;
}
// Compare ranks here, much faster. This is method critical for Satin. --Rob
public boolean equals(IbisIdentifier other) {
return (cpu == other.cpu);
}
public boolean equals(Object o) {
if (o == this) return true;
if (o instanceof IbisIdentifier) {
IbisIdentifier other = (IbisIdentifier)o;
// there is only one messagePassing.Ibis per cpu, so this should be ok
return (cpu == other.cpu);
}
return false;
}
public String toString() {
return ("(IbisIdent: name = \"" + name + "\")");
}
public String name() {
return name;
}
public int hashCode() {
return cpu;
}
int getCPU() {
return cpu;
}
}
|
package info.curtbinder.reefangel.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class RADbHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "radata.db";
private static final int DB_VERSION = 9;
// Version 5 - ErrorTable added
// Version 6 - NotificationTable added
// Version 7 - StatusTable updated
// Version 8 - StatusTable updated
// Version 9 - StatusTable updated
public RADbHelper ( Context context ) {
super( context, DB_NAME, null, DB_VERSION );
}
@Override
public void onCreate ( SQLiteDatabase db ) {
// create the tables here
StatusTable.onCreate( db );
ErrorTable.onCreate( db );
NotificationTable.onCreate( db );
}
@Override
public void onDowngrade ( SQLiteDatabase db, int oldVersion, int newVersion ) {
ErrorTable.onDowngrade( db, oldVersion, newVersion );
NotificationTable.onDowngrade( db, oldVersion, newVersion );
}
@Override
public void onUpgrade ( SQLiteDatabase db, int oldVersion, int newVersion ) {
StatusTable.onUpgrade( db, oldVersion, newVersion );
ErrorTable.onUpgrade( db, oldVersion, newVersion );
NotificationTable.onUpgrade( db, oldVersion, newVersion );
}
}
|
package io.flutter.run.daemon;
import com.google.gson.*;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.util.TimeoutUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
/**
* Keeper of running Flutter apps.
* TODO(messick) Clean up myResponses as things change
*/
public class FlutterAppManager {
private static final String CMD_APP_START = "app.start";
private static final String CMD_APP_STOP = "app.stop";
private static final String CMD_APP_RESTART = "app.restart";
private static final String CMD_DEVICE_ENABLE = "device.enable";
private static final Gson GSON = new Gson();
private Logger myLogger = Logger.getInstance("#io.flutter.run.daemon.FlutterAppManager");
private FlutterDaemonService myService;
private List<FlutterApp> myApps = new ArrayList<>();
private Map<Integer, List<Command>> myPendingCommands = new THashMap<>();
private int myCommandId = 0;
private final Object myLock = new Object();
private Map<Method, FlutterJsonObject> myResponses = new THashMap<>();
private ProgressHandler myProgressHandler;
FlutterAppManager(@NotNull FlutterDaemonService service) {
this.myService = service;
}
@Nullable
public FlutterApp startApp(@NotNull FlutterDaemonController controller,
@NotNull String deviceId,
@NotNull RunMode mode,
@NotNull Project project,
boolean isPaused,
boolean isHot,
@Nullable String target) {
if (isAppRunning(deviceId, controller)) {
throw new ProcessCanceledException();
}
myProgressHandler = new ProgressHandler(project);
if (!waitForDevice(deviceId)) {
return null;
}
FlutterDaemonService service;
synchronized (myLock) {
service = myService;
}
RunningFlutterApp app = new RunningFlutterApp(service, controller, this, mode, project, isHot, target, null);
AppStart appStart = new AppStart(deviceId, controller.getProjectDirectory(), isPaused, null, mode.mode(), target, isHot);
Method cmd = makeMethod(CMD_APP_START, appStart);
CompletableFuture
.supplyAsync(() -> sendCommand(controller, cmd))
.thenApplyAsync(this::waitForResponse)
.thenAcceptAsync((started) -> {
if (started instanceof AppStartEvent) {
AppStartEvent appStarted = (AppStartEvent)started;
app.setApp(appStarted);
}
});
synchronized (myLock) {
myApps.add(app);
}
return app;
}
private boolean isAppRunning(String deviceId, FlutterDaemonController controller) {
Stream<FlutterApp> apps;
synchronized (myLock) {
apps = myApps.stream();
}
return apps.anyMatch((app) -> app.getController() == controller && app.hasAppId() && app.deviceId().equals(deviceId));
}
private boolean waitForDevice(@NotNull String deviceId) {
long timeout = 5000L;
Boolean[] resp = {false};
TimeoutUtil.executeWithTimeout(timeout, () -> {
while (!resp[0]) {
Stream<ConnectedDevice> stream;
synchronized (myLock) {
stream = myService.getConnectedDevices().stream();
}
if (stream.anyMatch(d -> d.deviceId().equals(deviceId))) {
resp[0] = true;
}
}
});
return resp[0];
}
@Nullable
private RunningFlutterApp waitForApp(@NotNull FlutterDaemonController controller, @NotNull String appId) {
long timeout = 10000L;
RunningFlutterApp[] resp = {null};
TimeoutUtil.executeWithTimeout(timeout, () -> {
while (resp[0] == null) {
RunningFlutterApp app = findApp(controller, appId);
if (app != null) {
resp[0] = app;
}
}
});
return resp[0];
}
@Nullable
private FlutterJsonObject waitForResponse(@NotNull Method cmd) {
final long timeout = 10000L;
FlutterJsonObject[] resp = {null};
try {
TimeoutUtil.executeWithTimeout(timeout, () -> {
while (resp[0] == null) {
synchronized (myLock) {
resp[0] = myResponses.get(cmd);
if (resp[0] != null) {
myResponses.remove(cmd);
}
}
}
});
}
catch (ThreadDeath ex) {
// Can happen if external process is killed, but we don't care.
}
return resp[0];
}
void startDevicePoller(@NotNull FlutterDaemonController pollster) {
final Project project = null;
try {
pollster.forkProcess(project);
}
catch (ExecutionException e) {
// User notification comes in the way of editor toasts.
// See: IncompatibleDartPluginNotification.
myLogger.warn(e);
}
}
void processInput(@NotNull String string, @NotNull FlutterDaemonController controller) {
try {
JsonParser jp = new JsonParser();
JsonElement elem = jp.parse(string);
JsonObject obj = elem.getAsJsonObject();
JsonPrimitive primId = obj.getAsJsonPrimitive("id");
if (primId == null) {
handleEvent(obj, controller, string);
}
else {
handleResponse(primId.getAsInt(), obj, controller);
}
}
catch (JsonSyntaxException ex) {
myLogger.error(ex);
}
}
void handleResponse(int cmdId, @NotNull JsonObject obj, @NotNull FlutterDaemonController controller) {
Command cmd = findPendingCmd(cmdId, controller);
try {
cmd.method.process(obj, this, controller);
}
finally {
removePendingCmd(cmdId, cmd);
}
}
void handleEvent(@NotNull JsonObject obj, @NotNull FlutterDaemonController controller, @NotNull String json) {
JsonPrimitive primEvent = obj.getAsJsonPrimitive("event");
if (primEvent == null) {
myLogger.error("Invalid JSON from flutter: " + json);
return;
}
String eventName = primEvent.getAsString();
JsonObject params = obj.getAsJsonObject("params");
if (eventName == null || params == null) {
myLogger.error("Bad event from flutter: " + json);
return;
}
Event eventHandler = eventHandler(eventName, json);
if (eventHandler == null) return;
eventHandler.from(params).process(this, controller);
}
void stopApp(@NotNull FlutterApp app) {
myProgressHandler.cancel();
if (app.hasAppId()) {
if (app.isSessionPaused()) {
app.forceResume();
}
AppStop appStop = new AppStop(app.appId());
Method cmd = makeMethod(CMD_APP_STOP, appStop);
// This needs to run synchronously. The next thing that happens is the process
// streams are closed which immediately terminates the process.
CompletableFuture
.completedFuture(sendCommand(app.getController(), cmd))
.thenApply(this::waitForResponse)
.thenAccept((stopped) -> {
synchronized (myLock) {
myApps.remove(app);
}
app.getController().removeDeviceId(app.deviceId());
});
}
}
void restartApp(@NotNull RunningFlutterApp app, boolean isFullRestart, boolean pauseAfterRestart) {
AppRestart appStart = new AppRestart(app.appId(), isFullRestart, pauseAfterRestart);
Method cmd = makeMethod(CMD_APP_RESTART, appStart);
sendCommand(app.getController(), cmd);
}
private void appStopped(AppStop started, FlutterDaemonController controller) {
Stream<Command> starts = findAllPendingCmds(controller).stream().filter(c -> {
Params p = c.method.params;
if (p instanceof AppStop) {
AppStop a = (AppStop)p;
if (a.appId.equals(started.appId)) return true;
}
return false;
});
Optional<Command> opt = starts.findFirst();
assert (opt.isPresent());
Command cmd = opt.get();
synchronized (myLock) {
myResponses.put(cmd.method, started);
myService.schedulePolling();
}
}
void enableDevicePolling(@NotNull FlutterDaemonController controller) {
Method method = makeMethod(CMD_DEVICE_ENABLE, null);
sendCommand(controller, method);
}
void aboutToTerminateAll(FlutterDaemonController controller) {
List<FlutterApp> apps;
synchronized (myLock) {
apps = new ArrayList<>(myApps);
}
for (FlutterApp app : apps) {
if (app.getController() == controller) {
stopApp(app);
}
}
}
@NotNull
private Method makeMethod(@NotNull String methodName, @Nullable Params params) {
return new Method(methodName, params, myCommandId++);
}
private Method sendCommand(@NotNull FlutterDaemonController controller, @NotNull Method method) {
controller.sendCommand(GSON.toJson(method), this);
addPendingCmd(method.id, new Command(method, controller));
return method;
}
@NotNull
private List<Command> findAllPendingCmds(@NotNull FlutterDaemonController controller) {
List<Command> result = new ArrayList<>();
for (List<Command> list : myPendingCommands.values()) {
for (Command cmd : list) {
if (cmd.controller == controller) result.add(cmd);
}
}
return result;
}
@NotNull
private Command findPendingCmd(int id, @NotNull FlutterDaemonController controller) {
List<Command> list = myPendingCommands.get(id);
for (Command cmd : list) {
if (cmd.controller == controller) return cmd;
}
throw new IllegalStateException("no matching pending command");
}
private void removePendingCmd(int id, @NotNull Command command) {
List<Command> list = myPendingCommands.get(id);
list.remove(command);
if (list.isEmpty()) {
myPendingCommands.remove(id);
}
}
private void addPendingCmd(int id, @NotNull Command command) {
List<Command> list = myPendingCommands.get(id);
if (list == null) {
list = new ArrayList<>();
myPendingCommands.put(id, list);
}
list.add(command);
}
@Nullable
private Event eventHandler(@NotNull String eventName, @Nullable String json) {
switch (eventName) {
case "device.added":
return new DeviceAddedEvent();
case "device.removed":
return new DeviceRemovedEvent();
case "app.start":
return new AppStartEvent();
case "app.started":
return new AppStartedEvent();
case "app.debugPort":
return new AppDebugPortEvent();
case "app.log":
return new AppLogEvent();
case "app.progress":
return new AppProgressEvent();
case "app.stop":
return new AppStoppedEvent();
case "daemon.logMessage":
return new LogMessageEvent();
default:
return null;
}
}
private void eventLogMessage(@NotNull LogMessageEvent message, @NotNull FlutterDaemonController controller) {
myLogger.info(message.message);
}
private void eventLogMessage(@NotNull AppLogEvent message, @NotNull FlutterDaemonController controller) {
RunningFlutterApp app = findApp(controller, message.appId);
if (app == null) {
return;
}
app.getConsole().print(message.log + "\n", ConsoleViewContentType.NORMAL_OUTPUT);
}
private void eventProgressMessage(@NotNull AppProgressEvent message, @NotNull FlutterDaemonController controller) {
RunningFlutterApp app = findApp(controller, message.appId);
if (app == null) {
return;
}
if (message.finished) {
myProgressHandler.done();
}
else {
myProgressHandler.start(message.message);
}
}
private void eventDeviceAdded(@NotNull DeviceAddedEvent added, @NotNull FlutterDaemonController controller) {
synchronized (myLock) {
myService.addConnectedDevice(new FlutterDevice(added.name, added.id, added.platform, added.emulator));
}
}
private void eventDeviceRemoved(@NotNull DeviceRemovedEvent removed, @NotNull FlutterDaemonController controller) {
synchronized (myLock) {
for (ConnectedDevice device : myService.getConnectedDevices()) {
if (device.deviceName().equals(removed.name) &&
device.deviceId().equals(removed.id) &&
device.platform().equals(removed.platform)) {
myService.removeConnectedDevice(device);
}
}
}
}
private void eventAppStarted(@NotNull AppStartEvent started, @NotNull FlutterDaemonController controller) {
assert started.directory.equals(controller.getProjectDirectory());
Stream<Command> starts = findAllPendingCmds(controller).stream().filter(c -> {
Params p = c.method.params;
if (p instanceof AppStart) {
AppStart a = (AppStart)p;
if (a.deviceId.equals(started.deviceId)) return true;
}
return false;
});
Optional<Command> opt = starts.findFirst();
assert (opt.isPresent());
Command cmd = opt.get();
synchronized (myLock) {
myResponses.put(cmd.method, started);
}
}
private void eventAppStopped(@NotNull AppStoppedEvent stopped, @NotNull FlutterDaemonController controller) {
// TODO(devoncarew): Terminate the launch.
myProgressHandler.cancel();
}
private void eventDebugPort(@NotNull AppDebugPortEvent port, @NotNull FlutterDaemonController controller) {
RunningFlutterApp app = waitForApp(controller, port.appId);
if (app != null) {
app.setPort(port.port);
String uri = port.baseUri;
if (uri != null) {
if (uri.startsWith("file:")) {
// Convert the file: url to a path.
try {
uri = new URL(uri).getPath();
if (uri.endsWith(File.separator)) {
uri = uri.substring(0, uri.length() - 1);
}
}
catch (MalformedURLException e) {
// ignore
}
}
app.setBaseUri(uri);
}
}
}
private void error(JsonObject json) {
System.out.println(json.toString()); // TODO error handling
}
private RunningFlutterApp findApp(FlutterDaemonController controller, String appId) {
synchronized (myLock) {
for (FlutterApp app : myApps) {
if (app.getController() == controller && app.hasAppId() && app.appId().equals(appId)) {
return (RunningFlutterApp)app;
}
}
}
return null;
}
private static class Command {
@NotNull Method method;
@NotNull FlutterDaemonController controller;
Command(@NotNull Method method, @NotNull FlutterDaemonController controller) {
this.method = method;
this.controller = controller;
}
}
private abstract static class FlutterJsonObject {
// Placeholder for any abstractions applicable to all JSON to/from Flutter.
// ALL field names in subclasses are defined by the JSON protocol used by Flutter.
}
private static class Method extends FlutterJsonObject {
Method(String method, Params params, int cmdId) {
this.method = method;
this.params = params;
this.id = cmdId;
}
@SuppressWarnings("unused") private String method;
@SuppressWarnings("unused") private Params params;
@SuppressWarnings("unused") private int id;
void process(JsonObject obj, FlutterAppManager manager, FlutterDaemonController controller) {
if (params != null) params.process(obj, manager, controller);
}
}
private abstract static class Params extends FlutterJsonObject {
abstract void process(JsonObject obj, FlutterAppManager manager, FlutterDaemonController controller);
}
private static class AppStart extends Params {
// "method":"app.start"
AppStart(String deviceId, String projectDirectory, boolean startPaused, String route, String mode, String target, boolean hot) {
this.deviceId = deviceId;
this.projectDirectory = projectDirectory;
this.startPaused = startPaused;
this.route = route;
this.mode = mode;
this.target = target;
this.hot = hot;
}
@SuppressWarnings("unused") private String deviceId;
@SuppressWarnings("unused") private String projectDirectory;
@SuppressWarnings("unused") private boolean startPaused = true;
@SuppressWarnings("unused") private String route;
@SuppressWarnings("unused") private String mode;
@SuppressWarnings("unused") private String target;
@SuppressWarnings("unused") private boolean hot;
void process(JsonObject obj, FlutterAppManager manager, FlutterDaemonController controller) {
JsonObject result = obj.getAsJsonObject("result");
if (result == null) {
manager.error(obj);
return;
}
AppStartEvent app = new AppStartEvent();
app.appId = result.getAsJsonPrimitive("appId").getAsString();
app.deviceId = result.getAsJsonPrimitive("deviceId").getAsString();
app.directory = result.getAsJsonPrimitive("directory").getAsString();
app.supportsRestart = result.getAsJsonPrimitive("supportsRestart").getAsBoolean();
manager.eventAppStarted(app, controller);
}
}
private static class AppRestart extends Params {
// "method":"app.restart"
AppRestart(String appId, boolean fullRestart, boolean pause) {
this.appId = appId;
this.fullRestart = fullRestart;
this.pause = pause;
}
@SuppressWarnings("unused") private String appId;
@SuppressWarnings("unused") private boolean fullRestart;
@SuppressWarnings("unused") private boolean pause;
void process(JsonObject obj, FlutterAppManager manager, FlutterDaemonController controller) {
// This can return a boolean (for older versions) or a status object { code (int), message (string) }.
}
}
private static class AppStop extends Params {
// "method":"app.stop"
AppStop(String appId) {
this.appId = appId;
}
@SuppressWarnings("unused") private String appId;
void process(JsonObject obj, FlutterAppManager manager, FlutterDaemonController controller) {
JsonPrimitive prim = obj.getAsJsonPrimitive("result");
if (prim != null) {
if (prim.getAsBoolean()) {
manager.appStopped(this, controller);
}
}
else {
prim = obj.getAsJsonPrimitive("error");
if (prim != null) {
// Apparently the daemon does not find apps started in release mode.
manager.appStopped(this, controller);
}
}
}
}
private abstract static class Event extends FlutterJsonObject {
Event from(JsonElement element) {
return GSON.fromJson(element, (Type)this.getClass());
}
abstract void process(FlutterAppManager manager, FlutterDaemonController controller);
}
private static class LogMessageEvent extends Event {
// "event":"daemon.eventLogMessage"
@SuppressWarnings("unused") private String level;
@SuppressWarnings("unused") private String message;
@SuppressWarnings("unused") private String stackTrace;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventLogMessage(this, controller);
}
}
private static class AppLogEvent extends Event {
// "event":"app.log"
@SuppressWarnings("unused") private String appId;
@SuppressWarnings("unused") private String log;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventLogMessage(this, controller);
}
}
private static class AppProgressEvent extends Event {
// "event":"app.progress"
@SuppressWarnings("unused") private String appId;
@SuppressWarnings("unused") private String message;
@SuppressWarnings("unused") private boolean finished;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventProgressMessage(this, controller);
}
}
private static class DeviceAddedEvent extends Event {
// "event":"device.added"
@SuppressWarnings("unused") private String id;
@SuppressWarnings("unused") private String name;
@SuppressWarnings("unused") private String platform;
@SuppressWarnings("unused") private boolean emulator;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventDeviceAdded(this, controller);
}
}
private static class DeviceRemovedEvent extends Event {
// "event":"device.removed"
@SuppressWarnings("unused") private String id;
@SuppressWarnings("unused") private String name;
@SuppressWarnings("unused") private String platform;
@SuppressWarnings("unused") private boolean emulator;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventDeviceRemoved(this, controller);
}
}
static class AppStartEvent extends Event {
// "event":"app.start"
@SuppressWarnings("unused") String appId;
@SuppressWarnings("unused") String deviceId;
@SuppressWarnings("unused") String directory;
@SuppressWarnings("unused") boolean supportsRestart;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
// This event is ignored. The app.start command response is used instead.
}
}
static class AppStartedEvent extends Event {
// "event":"app.started"
@SuppressWarnings("unused") String appId;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
}
}
private static class AppStoppedEvent extends Event {
// "event":"app.stop"
@SuppressWarnings("unused") private String appId;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventAppStopped(this, controller);
}
}
private static class AppDebugPortEvent extends Event {
// "event":"app.eventDebugPort"
@SuppressWarnings("unused") private String appId;
@SuppressWarnings("unused") private int port;
@SuppressWarnings("unused") private String baseUri;
void process(FlutterAppManager manager, FlutterDaemonController controller) {
manager.eventDebugPort(this, controller);
}
}
}
|
package net.sf.picard.sam;
import net.sf.picard.PicardException;
import net.sf.picard.metrics.MetricBase;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.reference.ReferenceSequence;
import net.sf.picard.reference.ReferenceSequenceFile;
import net.sf.picard.reference.ReferenceSequenceFileWalker;
import net.sf.picard.util.Histogram;
import net.sf.picard.util.Log;
import net.sf.samtools.*;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import net.sf.samtools.SAMValidationError.Type;
import net.sf.samtools.util.*;
import java.io.*;
import java.util.*;
/**
* Validates SAM files as follows:
* <ul>
* <li>checks sam file header for sequence dictionary</li>
* <li>checks sam file header for read groups</li>
* <li>for each sam record
* <ul>
* <li>reports error detected by SAMRecord.isValid()</li>
* <li>validates NM (nucleotide differences) exists and matches reality</li>
* <li>validates mate fields agree with data in the mate record</li>
* </ul>
* </li>
* </ul>
*
* @see SAMRecord#isValid()
* @author Doug Voet
*/
public class SamFileValidator {
private Histogram<Type> errorsByType = new Histogram<Type>();
private final PrintWriter out;
private Map<String, PairEndInfo> pairEndInfoByName;
private ReferenceSequenceFileWalker refFileWalker = null;
private boolean verbose = false;
private int maxVerboseOutput = 100;
private SAMSortOrderChecker orderChecker;
private Set<Type> errorsToIgnore = EnumSet.noneOf(Type.class);
private boolean ignoreWarnings = false;
private boolean bisulfiteSequenced = false;
private boolean sequenceDictionaryEmptyAndNoWarningEmitted = false;
private final static Log log = Log.getInstance(SamFileValidator.class);
public SamFileValidator(final PrintWriter out) {
this.out = out;
}
/** Sets one or more error types that should not be reported on. */
public void setErrorsToIgnore(final Collection<Type> types) {
if (!types.isEmpty()) {
this.errorsToIgnore = EnumSet.copyOf(types);
}
}
public void setIgnoreWarnings(final boolean ignoreWarnings) {
this.ignoreWarnings = ignoreWarnings;
}
/**
* Outputs validation summary report to out.
*
* @param samReader records to validate
* @param reference if null, NM tag validation is skipped
* @return boolean true if there are no validation errors, otherwise false
*/
public boolean validateSamFileSummary(final SAMFileReader samReader, final ReferenceSequenceFile reference) {
init(reference);
validateSamFile(samReader, out);
boolean result = errorsByType.isEmpty();
if (errorsByType.getCount() > 0) {
// Convert to a histogram with String IDs so that WARNING: or ERROR: can be prepended to the error type.
final Histogram<String> errorsAndWarningsByType = new Histogram<String>("Error Type", "Count");
for (final Histogram<SAMValidationError.Type>.Bin bin : errorsByType.values()) {
errorsAndWarningsByType.increment(bin.getId().getHistogramString(), bin.getValue());
}
final MetricsFile<ValidationMetrics, String> metricsFile = new MetricsFile<ValidationMetrics, String>();
errorsByType.setBinLabel("Error Type");
errorsByType.setValueLabel("Count");
metricsFile.setHistogram(errorsAndWarningsByType);
metricsFile.write(out);
}
cleanup();
return result;
}
/**
* Outputs validation error details to out.
*
* @param samReader records to validate
* @param reference if null, NM tag validation is skipped
* processing will stop after this threshold has been reached
* @return boolean true if there are no validation errors, otherwise false
*/
public boolean validateSamFileVerbose(final SAMFileReader samReader, final ReferenceSequenceFile reference) {
init(reference);
try {
validateSamFile(samReader, out);
} catch (MaxOutputExceededException e) {
out.println("Maximum output of [" + maxVerboseOutput + "] errors reached.");
}
boolean result = errorsByType.isEmpty();
cleanup();
return result;
}
public void validateBamFileTermination(final File inputFile) {
BufferedInputStream inputStream = null;
try {
inputStream = IOUtil.toBufferedStream(new FileInputStream(inputFile));
if (!BlockCompressedInputStream.isValidFile(inputStream)) {
return;
}
final BlockCompressedInputStream.FileTermination terminationState =
BlockCompressedInputStream.checkTermination(inputFile);
if (terminationState.equals(BlockCompressedInputStream.FileTermination.DEFECTIVE)) {
addError(new SAMValidationError(Type.TRUNCATED_FILE, "BAM file has defective last gzip block",
inputFile.getPath()));
} else if (terminationState.equals(BlockCompressedInputStream.FileTermination.HAS_HEALTHY_LAST_BLOCK)) {
addError(new SAMValidationError(Type.BAM_FILE_MISSING_TERMINATOR_BLOCK,
"Older BAM file -- does not have terminator block",
inputFile.getPath()));
}
} catch (IOException e) {
throw new PicardException("IOException", e);
} finally {
if (inputStream != null) {
CloserUtil.close(inputStream);
}
}
}
private void validateSamFile(final SAMFileReader samReader, final PrintWriter out) {
try {
samReader.setValidationStringency(ValidationStringency.SILENT);
validateHeader(samReader.getFileHeader());
orderChecker = new SAMSortOrderChecker(samReader.getFileHeader().getSortOrder());
validateSamRecords(samReader);
if (errorsByType.isEmpty()) {
out.println("No errors found");
}
} finally {
out.flush();
}
}
private void validateSamRecords(final Iterable<SAMRecord> samRecords) {
long recordNumber = 1;
try {
for (final SAMRecord record : samRecords) {
final Collection<SAMValidationError> errors = record.isValid();
if (errors != null) {
for (final SAMValidationError error : errors) {
error.setRecordNumber(recordNumber);
addError(error);
}
}
validateMateFields(record, recordNumber);
validateSortOrder(record, recordNumber);
final boolean cigarIsValid = validateCigar(record, recordNumber);
if (cigarIsValid) {
validateNmTag(record, recordNumber);
}
validateSecondaryBaseCalls(record, recordNumber);
validateTags(record, recordNumber);
if (sequenceDictionaryEmptyAndNoWarningEmitted && !record.getReadUnmappedFlag()) {
addError(new SAMValidationError(Type.MISSING_SEQUENCE_DICTIONARY, "Sequence dictionary is empty", null));
sequenceDictionaryEmptyAndNoWarningEmitted = false;
}
recordNumber++;
if (recordNumber % 10000000 == 0) {
log.info(recordNumber + " reads validated.");
}
}
} catch (SAMFormatException e) {
// increment record number because the iterator behind the SAMFileReader
// reads one record ahead so we will get this failure one record ahead
out.println("SAMFormatException on record " + ++recordNumber);
throw new PicardException("SAMFormatException on record " + recordNumber, e);
} catch (FileTruncatedException e) {
addError(new SAMValidationError(Type.TRUNCATED_FILE, "File is truncated", null));
}
}
/**
* Report error if a tag value is a Long.
*/
private void validateTags(final SAMRecord record, final long recordNumber) {
for (final SAMRecord.SAMTagAndValue tagAndValue : record.getAttributes()) {
if (tagAndValue.value instanceof Long) {
addError(new SAMValidationError(Type.TAG_VALUE_TOO_LARGE,
"Numeric value too large for tag " + tagAndValue.tag,
record.getReadName(), recordNumber));
}
}
}
private void validateSecondaryBaseCalls(final SAMRecord record, final long recordNumber) {
final String e2 = (String)record.getAttribute(SAMTag.E2.name());
if (e2 != null) {
if (e2.length() != record.getReadLength()) {
addError(new SAMValidationError(Type.MISMATCH_READ_LENGTH_AND_E2_LENGTH,
String.format("E2 tag length (%d) != read length (%d)", e2.length(), record.getReadLength()),
record.getReadName(), recordNumber));
}
final byte[] bases = record.getReadBases();
final byte[] secondaryBases = StringUtil.stringToBytes(e2);
for (int i = 0; i < Math.min(bases.length, secondaryBases.length); ++i) {
if (SequenceUtil.isNoCall(bases[i]) || SequenceUtil.isNoCall(secondaryBases[i])) {
continue;
}
if (SequenceUtil.basesEqual(bases[i], secondaryBases[i])) {
addError(new SAMValidationError(Type.E2_BASE_EQUALS_PRIMARY_BASE,
String.format("Secondary base call (%c) == primary base call (%c)",
(char)secondaryBases[i], (char)bases[i]),
record.getReadName(), recordNumber));
break;
}
}
}
final String u2 = (String)record.getAttribute(SAMTag.U2.name());
if (u2 != null && u2.length() != record.getReadLength()) {
addError(new SAMValidationError(Type.MISMATCH_READ_LENGTH_AND_U2_LENGTH,
String.format("U2 tag length (%d) != read length (%d)", u2.length(), record.getReadLength()),
record.getReadName(), recordNumber));
}
}
private boolean validateCigar(final SAMRecord record, final long recordNumber) {
if (record.getReadUnmappedFlag()) {
return true;
}
final ValidationStringency savedStringency = record.getValidationStringency();
record.setValidationStringency(ValidationStringency.LENIENT);
final List<SAMValidationError> errors = record.validateCigar(recordNumber);
record.setValidationStringency(savedStringency);
if (errors == null) {
return true;
}
boolean valid = true;
for (final SAMValidationError error : errors) {
addError(error);
valid = false;
}
return valid;
}
private void validateSortOrder(final SAMRecord record, final long recordNumber) {
final SAMRecord prev = orderChecker.getPreviousRecord();
if (!orderChecker.isSorted(record)) {
addError(new SAMValidationError(
Type.RECORD_OUT_OF_ORDER,
String.format(
"The record is out of [%s] order, prior read name [%s], prior coodinates [%d:%d]",
record.getHeader().getSortOrder().name(),
prev.getReadName(),
prev.getReferenceIndex(),
prev.getAlignmentStart()),
record.getReadName(),
recordNumber));
}
}
private void init(final ReferenceSequenceFile reference) {
this.pairEndInfoByName = new HashMap<String, PairEndInfo>();
if (reference != null) {
this.refFileWalker = new ReferenceSequenceFileWalker(reference);
}
}
private void cleanup() {
this.errorsByType = null;
this.pairEndInfoByName = null;
this.refFileWalker = null;
}
private void validateNmTag(final SAMRecord record, final long recordNumber) {
if (!record.getReadUnmappedFlag()) {
final Integer tagNucleotideDiffs = record.getIntegerAttribute(ReservedTagConstants.NM);
if (tagNucleotideDiffs == null) {
addError(new SAMValidationError(
Type.MISSING_TAG_NM,
"NM tag (nucleotide differences) is missing",
record.getReadName(),
recordNumber));
} else if (refFileWalker != null) {
final ReferenceSequence refSequence = refFileWalker.get(record.getReferenceIndex());
final int actualNucleotideDiffs = SequenceUtil.calculateSamNmTag(record, refSequence.getBases(),
0, isBisulfiteSequenced());
if (!tagNucleotideDiffs.equals(actualNucleotideDiffs)) {
addError(new SAMValidationError(
Type.INVALID_TAG_NM,
"NM tag (nucleotide differences) in file [" + tagNucleotideDiffs +
"] does not match reality [" + actualNucleotideDiffs + "]",
record.getReadName(),
recordNumber));
}
}
}
}
private void validateMateFields(final SAMRecord record, final long recordNumber) {
if (!record.getReadPairedFlag() || record.getNotPrimaryAlignmentFlag()) {
return;
}
final PairEndInfo pairEndInfo = pairEndInfoByName.remove(record.getReadName());
if (pairEndInfo == null) {
pairEndInfoByName.put(record.getReadName(), new PairEndInfo(record, recordNumber));
} else {
final List<SAMValidationError> errors =
pairEndInfo.validateMates(new PairEndInfo(record, recordNumber), record.getReadName());
for (final SAMValidationError error : errors) {
addError(error);
}
}
}
private void validateHeader(final SAMFileHeader fileHeader) {
for (final SAMValidationError error : fileHeader.getValidationErrors()) {
addError(error);
}
if (fileHeader.getVersion() == null) {
addError(new SAMValidationError(Type.MISSING_VERSION_NUMBER, "Header has no version number", null));
} else if (!fileHeader.getVersion().equals(SAMFileHeader.CURRENT_VERSION)) {
addError(new SAMValidationError(Type.INVALID_VERSION_NUMBER, "Header version: " +
fileHeader.getVersion() + " does not match expected version: " + SAMFileHeader.CURRENT_VERSION,
null));
}
if (fileHeader.getSequenceDictionary().isEmpty()) {
sequenceDictionaryEmptyAndNoWarningEmitted = true;
}
if (fileHeader.getReadGroups().isEmpty()) {
addError(new SAMValidationError(Type.MISSING_READ_GROUP, "Read groups is empty", null));
}
}
private void addError(final SAMValidationError error) {
// Just ignore an error if it's of a type we're not interested in
if (this.errorsToIgnore.contains(error.getType())) return;
if (this.ignoreWarnings && error.getType().severity == SAMValidationError.Severity.WARNING) return;
this.errorsByType.increment(error.getType());
if (verbose) {
out.println(error);
out.flush();
if (this.errorsByType.getCount() >= maxVerboseOutput) {
throw new MaxOutputExceededException();
}
}
}
/**
* Control verbosity
* @param verbose True in order to emit a message per error or warning.
* @param maxVerboseOutput If verbose, emit no more than this many messages. Ignored if !verbose.
*/
public void setVerbose(final boolean verbose, final int maxVerboseOutput) {
this.verbose = verbose;
this.maxVerboseOutput = maxVerboseOutput;
}
public boolean isBisulfiteSequenced() { return bisulfiteSequenced; }
public void setBisulfiteSequenced(boolean bisulfiteSequenced) { this.bisulfiteSequenced = bisulfiteSequenced; }
public static class ValidationMetrics extends MetricBase {
}
/**
* This class is used so we don't have to store the entire SAMRecord in memory while we wait
* to find a record's mate and also to store the record number.
*/
private static class PairEndInfo {
private final int readAlignmentStart;
private final int readReferenceIndex;
private final boolean readNegStrandFlag;
private final boolean readUnmappedFlag;
private final int mateAlignmentStart;
private final int mateReferenceIndex;
private final boolean mateNegStrandFlag;
private final boolean mateUnmappedFlag;
private final long recordNumber;
public PairEndInfo(final SAMRecord record, final long recordNumber) {
this.recordNumber = recordNumber;
this.readAlignmentStart = record.getAlignmentStart();
this.readNegStrandFlag = record.getReadNegativeStrandFlag();
this.readReferenceIndex = record.getReferenceIndex();
this.readUnmappedFlag = record.getReadUnmappedFlag();
this.mateAlignmentStart = record.getMateAlignmentStart();
this.mateNegStrandFlag = record.getMateNegativeStrandFlag();
this.mateReferenceIndex = record.getMateReferenceIndex();
this.mateUnmappedFlag = record.getMateUnmappedFlag();
}
public List<SAMValidationError> validateMates(final PairEndInfo mate, final String readName) {
final List<SAMValidationError> errors = new ArrayList<SAMValidationError>();
validateMateFields(this, mate, readName, errors);
validateMateFields(mate, this, readName, errors);
return errors;
}
private void validateMateFields(final PairEndInfo end1, final PairEndInfo end2, final String readName, final List<SAMValidationError> errors) {
if (end1.mateAlignmentStart != end2.readAlignmentStart) {
errors.add(new SAMValidationError(
Type.MISMATCH_MATE_ALIGNMENT_START,
"Mate alignment does not match alignment start of mate",
readName,
end1.recordNumber));
}
if (end1.mateNegStrandFlag != end2.readNegStrandFlag) {
errors.add(new SAMValidationError(
Type.MISMATCH_FLAG_MATE_NEG_STRAND,
"Mate negative strand flag does not match read negative strand flag of mate",
readName,
end1.recordNumber));
}
if (end1.mateReferenceIndex != end2.readReferenceIndex) {
errors.add(new SAMValidationError(
Type.MISMATCH_MATE_REF_INDEX,
"Mate reference index (MRNM) does not match reference index of mate",
readName,
end1.recordNumber));
}
if (end1.mateUnmappedFlag != end2.readUnmappedFlag) {
errors.add(new SAMValidationError(
Type.MISMATCH_FLAG_MATE_UNMAPPED,
"Mate unmapped flag does not match read unmapped flag of mate",
readName,
end1.recordNumber));
}
}
}
/** Thrown in addError indicating that maxVerboseOutput has been exceeded and processing should stop */
private static class MaxOutputExceededException extends PicardException {
MaxOutputExceededException() {
super("maxVerboseOutput exceeded.");
}
}
}
|
package org.apache.commons.lang;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* <p><code>ArrayUtils</code> contains utility methods for working with
* arrays.</p>
*
* @author Stephen Colebourne
* @author Moritz Petersen
* @author <a href="mailto:fredrik@westermarck.com">Fredrik Westermarck</a>
* @author Nikolay Metchev
* @since 2.0
* @version $Id: ArrayUtils.java,v 1.13 2003/06/20 08:03:51 scolebourne Exp $
*/
public class ArrayUtils {
/** An empty immutable object array */
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/** An empty immutable class array */
public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
/** An empty immutable string array */
public static final String[] EMPTY_STRING_ARRAY = new String[0];
/** An empty immutable long array */
public static final long[] EMPTY_LONG_ARRAY = new long[0];
/** An empty immutable int array */
public static final int[] EMPTY_INT_ARRAY = new int[0];
/** An empty immutable short array */
public static final short[] EMPTY_SHORT_ARRAY = new short[0];
/** An empty immutable byte array */
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/** An empty immutable double array */
public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
/** An empty immutable float array */
public static final float[] EMPTY_FLOAT_ARRAY = new float[0];
/** An empty immutable boolean array */
public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];
/**
* <p>ArrayUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>ArrayUtils.clone(new int[] {2})</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public ArrayUtils() {
}
// Basic methods handling multi-dimensional arrays
/**
* <p>Outputs an array as a String, treating <code>null</code> as an empty array.</p>
*
* <p>Multi-dimensional arrays are handled correctly, including
* multi-dimensional primitive arrays.</p>
*
* <p>The format is that of Java source code, for example {a,b}.</p>
*
* @param array the array to get a toString for, may be <code>null</code>
* @return a String representation of the array, '{}' if <code>null</code> passed in
*/
public static String toString(Object array) {
return toString(array, "{}");
}
/**
* <p>Outputs an array as a String handling <code>null</code>s.</p>
*
* <p>Multi-dimensional arrays are handled correctly, including
* multi-dimensional primitive arrays.</p>
*
* <p>The format is that of Java source code, for example {a,b}.</p>
*
* @param array the array to get a toString for, may be <code>null</code>
* @param stringIfNull the String to return if the array is <code>null</code>
* @return a String representation of the array
*/
public static String toString(Object array, String stringIfNull) {
if (array == null) {
return stringIfNull;
}
return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString();
}
/**
* <p>Get a hashCode for an array handling multi-dimensional arrays correctly.</p>
*
* <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p>
*
* @param array the array to get a hashCode for, may be <code>null</code>
* @return a hashCode for the array
*/
public static int hashCode(Object array) {
return new HashCodeBuilder().append(array).toHashCode();
}
/**
* <p>Compares two arrays, using equals(), handling multi-dimensional arrays
* correctly.</p>
*
* <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p>
*
* @param array1 the array to get a hashCode for, may be <code>null</code>
* @param array2 the array to get a hashCode for, may be <code>null</code>
* @return <code>true</code> if the arrays are equal
*/
public static boolean isEquals(Object array1, Object array2) {
return new EqualsBuilder().append(array1, array2).isEquals();
}
public static Map toMap(Object[] array) {
if (array == null) {
throw new IllegalArgumentException("The array must not be null");
}
Map map = new HashMap((int) (array.length * 1.5));
for (int i = 0; i < array.length; i++) {
Object object = array[i];
if (object instanceof Map.Entry) {
Map.Entry entry = (Map.Entry) object;
map.put(entry.getKey(), entry.getValue());
} else if (object instanceof Object[]) {
Object[] entry = (Object[]) object;
if (entry.length < 2) {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', has a length less than 2");
}
map.put(entry[0], entry[1]);
} else {
throw new IllegalArgumentException("Array element " + i + ", '"
+ object
+ "', is neither of type Map.Entry nor an Array");
}
}
return map;
}
/**
* <p>Shallow clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>The objecs in the array are not cloned, thus there is no special
* handling for multi-dimensional arrays.</p>
*
* @param array the array to shallow clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static Object[] clone(Object[] array) {
if (array == null) {
return null;
}
return (Object[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static long[] clone(long[] array) {
if (array == null) {
return null;
}
return (long[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static int[] clone(int[] array) {
if (array == null) {
return null;
}
return (int[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static short[] clone(short[] array) {
if (array == null) {
return null;
}
return (short[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static char[] clone(char[] array) {
if (array == null) {
return null;
}
return (char[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static byte[] clone(byte[] array) {
if (array == null) {
return null;
}
return (byte[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static double[] clone(double[] array) {
if (array == null) {
return null;
}
return (double[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static float[] clone(float[] array) {
if (array == null) {
return null;
}
return (float[]) array.clone();
}
/**
* <p>Clones an array returning a typecast result and handling
* <code>null</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array the array to clone, may be <code>null</code>
* @return the cloned array, or <code>null</code> if <code>null</code>
* passed in
*/
public static boolean[] clone(boolean[] array) {
if (array == null) {
return null;
}
return (boolean[]) array.clone();
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(Object[] array1, Object[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(long[] array1, long[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(int[] array1, int[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(short[] array1, short[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(char[] array1, char[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(byte[] array1, byte[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(double[] array1, double[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored</p>.
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(float[] array1, float[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
/**
* <p>Checks whether two arrays are the same length, treating
* <code>null</code> arrays as length <code>0</code>.</p>
*
* <p>Any multi-dimensional aspects of the arrays are ignored.</p>
*
* @param array1 the first array, may be <code>null</code>
* @param array2 the second array, may be <code>null</code>
* @return <code>true</code> if length of arrays matches, treating
* <code>null</code> as an empty array
*/
public static boolean isSameLength(boolean[] array1, boolean[] array2) {
if ((array1 == null && array2 != null && array2.length > 0) ||
(array2 == null && array1 != null && array1.length > 0) ||
(array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
public static boolean isSameType(Object array1, Object array2) {
if (array1 == null || array2 == null) {
throw new IllegalArgumentException("The array must not be null");
}
return array1.getClass().getName().equals(array2.getClass().getName());
}
/**
* Reverses the order of the given array.
* <p>
* There is no special handling for multi-dimensional arrays.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(Object[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
Object tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(long[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
long tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* There is no special handling for multi-dimensional arrays.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(short[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
short tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(char[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
char tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(byte[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(double[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
double tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(float[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
float tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Reverses the order of the given array.
* <p>
* The method does nothing if <code>null</code> is passed in.
*
* @param array the array to reverse, may be <code>null</code>
*/
public static void reverse(boolean[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
boolean tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j
i++;
}
}
/**
* Find the index of the given object in the array.
* <p>
* The method returns -1 if a <code>null</code> array is passed in.
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @return the index of the object within the array, or -1 if not found
*/
public static int indexOf(Object[] array, Object objectToFind) {
return indexOf(array, objectToFind, 0);
}
/**
* Find the index of the given object in the array starting at the given index.
* <p>
* The method returns -1 if a <code>null</code> array is passed in.
* <p>
* A negative startIndex is treated as zero. A startIndex larger than the array
* length will return -1.
*
* @param array the array to search through for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the index to start searching at
* @return the index of the object within the array starting at the
* given index, or -1 if not found
*/
public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
/**
* Find the last index of the given object within the array.
* <p>
* The method returns -1 if a <code>null</code> array is passed in.
*
* @param array the array to travers backwords looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @return the last index of the object to find, or -1 if not found
*/
public static int lastIndexOf(Object[] array, Object objectToFind) {
if (array == null) {
return -1;
}
return lastIndexOf(array, objectToFind, array.length - 1);
}
/**
* Find the last index of the given object in the array starting at the given index.
* <p>
* The method returns -1 if a <code>null</code> array is passed in.
* <p>
* A negative startIndex will return -1. A startIndex larger than the array
* length will search from the end of the array.
*
* @param array the array to traverse for looking for the object, may be <code>null</code>
* @param objectToFind the object to find, may be <code>null</code>
* @param startIndex the start index to travers backwards from
* @return the last index of the object within the array starting at the given index,
* or -1 if not found
*/
public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return -1;
}
if (startIndex < 0) {
return -1;
} else if (startIndex >= array.length) {
startIndex = array.length - 1;
}
if (objectToFind == null) {
for (int i = startIndex; i >= 0; i
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i >= 0; i
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return -1;
}
/**
* Checks if the object is in the given array.
* <p>
* The method returns <code>false</code> if a <code>null</code> array is passed in.
*
* @param array the array to search through
* @param objectToFind the object to find
* @return <code>true</code> if the array contains the object
*/
public static boolean contains(Object[] array, Object objectToFind) {
return (indexOf(array, objectToFind) != -1);
}
}
|
package org.jsimpledb;
import com.google.common.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.regex.Pattern;
import org.jsimpledb.util.AnnotationScanner;
/**
* Support superclass for field annotation scanners.
*/
abstract class AbstractFieldScanner<T, A extends Annotation> extends AnnotationScanner<T, A> {
private final boolean autogenFields;
AbstractFieldScanner(JClass<T> jclass, Class<A> annotationType, boolean autogenFields) {
super(jclass, annotationType);
this.autogenFields = autogenFields;
}
protected abstract A getDefaultAnnotation();
@Override
protected A getAnnotation(Method method) {
// Look for existing annotation
final A annotation = super.getAnnotation(method);
if (annotation != null)
return annotation;
// Check for auto-generated bean property getter method
if (this.isAutoPropertyCandidate(method))
return this.getDefaultAnnotation();
// Skip this method
return null;
}
protected boolean isAutoPropertyCandidate(Method method) {
if (!this.autogenFields)
return false;
if (this.isOverriddenByConcreteMethod(method))
return false;
if ((method.getModifiers() & (Modifier.ABSTRACT | Modifier.STATIC)) != Modifier.ABSTRACT)
return false;
if ((method.getModifiers() & (Modifier.PROTECTED | Modifier.PUBLIC)) == 0)
return false;
if ((method.getModifiers() & Modifier.PRIVATE) != 0)
return false;
if (!Pattern.compile("(is|get)(.+)").matcher(method.getName()).matches())
return false;
if (method.getParameterTypes().length != 0)
return false;
if (method.getReturnType() == Void.TYPE)
return false;
return true;
}
private boolean isOverriddenByConcreteMethod(Method method) {
if ((method.getModifiers() & Modifier.ABSTRACT) == 0) // quick check
return true;
final Class<?> methodType = method.getDeclaringClass();
for (TypeToken<?> typeToken : TypeToken.of(this.jclass.type).getTypes()) {
final Class<?> type = typeToken.getRawType();
if (!methodType.isAssignableFrom(type) || type.equals(methodType)) // i.e., type > methodType
continue;
final Method otherMethod;
try {
otherMethod = type.getDeclaredMethod(method.getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
continue;
}
if ((otherMethod.getModifiers() & Modifier.ABSTRACT) == 0)
return true;
}
return false;
}
}
|
package test.org.relique.jdbc.csv;
import junit.framework.*;
/**This class is used to test the CsvJdbc driver.
*
* @author Jonathan Ackerman
* @version $Id: RunTests.java,v 1.11 2010/09/24 13:02:43 mfrasca Exp $
*/
public class RunTests
{
public static String DEFAULT_FILEPATH="../src/testdata";
public static Test suite()
{
TestSuite suite= new TestSuite();
suite.addTestSuite(TestSqlParser.class);
suite.addTestSuite(TestCsvDriver.class);
suite.addTestSuite(TestScrollableDriver.class);
suite.addTestSuite(TestFileSetInputStream.class);
suite.addTestSuite(TestJoinedTables.class);
return suite;
}
public static void main(String[] args)
{
String filePath = args[0];
if (filePath == null)
filePath=DEFAULT_FILEPATH;
// set the file location as a property so that it is easy to pass around
System.setProperty(TestCsvDriver.SAMPLE_FILES_LOCATION_PROPERTY,filePath);
// get the driver manager to log to sysout
//DriverManager.setLogWriter( new PrintWriter(System.out));
// kick off the tests. Note call main() instead of run() so that error codes
// are returned so that they can be trapped by ant
junit.textui.TestRunner.main(new String[]{"test.org.relique.jdbc.csv.RunTests"});
}
}
|
package pkCustomerProfile;
public class ProductProfile {
public String id;
public String title;
public String avgRating;
public String similarProductIDs;
}
|
package org.piwik.sdk;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@Config(emulateSdk = 18, manifest = Config.NONE)
@RunWith(FullEnvTestRunner.class)
public class TrackerTest {
final static String testAPIUrl = "http://example.com";
public Tracker createTracker() throws MalformedURLException {
return Piwik.getInstance(Robolectric.application).newTracker(testAPIUrl, 1);
}
@Before
public void setup() {
Piwik.getInstance(Robolectric.application).setDryRun(true);
Piwik.getInstance(Robolectric.application).setAppOptOut(true);
}
@Test
public void testPiwikAutoBindActivities() throws Exception {
Application app = Robolectric.application;
Piwik piwik = Piwik.getInstance(app);
piwik.setDryRun(true);
piwik.setAppOptOut(true);
Tracker tracker = piwik.newTracker(testAPIUrl, 1);
//auto attach tracking screen view
QuickTrack.bindToApp(app, tracker);
// emulate default trackScreenView
Robolectric.buildActivity(TestActivity.class).create().start().resume().visible().get();
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
validateDefaultQuery(queryParams);
assertEquals(queryParams.get(QueryParams.ACTION_NAME), TestActivity.getTestTitle());
}
@Test
public void testPiwikApplicationGetTracker() throws Exception {
PiwikApplication app = new TestPiwikApplication();
assertEquals(app.getTracker(), app.getTracker());
}
@Test
public void testEmptyQueueDispatch() throws Exception {
assertFalse(Piwik.getInstance(new TestPiwikApplication()).newTracker("http://example.com", 1).dispatch());
}
@Test
public void testSetDispatchInterval() throws Exception {
Tracker tracker = createTracker();
tracker.setDispatchInterval(1);
assertEquals(tracker.getDispatchInterval(), 1);
}
@Test
public void testGetDispatchIntervalMillis() throws Exception {
Tracker tracker = createTracker();
tracker.setDispatchInterval(1);
assertEquals(tracker.getDispatchIntervalMillis(), 1000);
}
@Test
public void testDispatchingFlow() throws Exception {
Tracker tracker = createTracker();
tracker.dispatchingStarted();
assertTrue(tracker.isDispatching());
tracker.dispatchingCompleted(1);
assertFalse(tracker.isDispatching());
}
@Test
public void testSet() throws Exception {
Tracker tracker = createTracker();
tracker.set(QueryParams.HOURS, "0")
.set(QueryParams.MINUTES, (Integer) null)
.set(QueryParams.SECONDS, (String) null)
.set(QueryParams.FIRST_VISIT_TIMESTAMP, (String) null)
.set(QueryParams.PREVIOUS_VISIT_TIMESTAMP, (String) null)
.set(QueryParams.TOTAL_NUMBER_OF_VISITS, (String) null)
.set(QueryParams.GOAL_ID, (String) null)
.set(QueryParams.LATITUDE, (String) null)
.set(QueryParams.LONGITUDE, (String) null)
.set(QueryParams.SEARCH_KEYWORD, (String) null)
.set(QueryParams.SEARCH_CATEGORY, (String) null)
.set(QueryParams.SEARCH_NUMBER_OF_HITS, (String) null)
.set(QueryParams.REFERRER, (String) null)
.set(QueryParams.CAMPAIGN_NAME, (String) null)
.set(QueryParams.CAMPAIGN_KEYWORD, (String) null);
assertEquals(tracker.getQuery(), "?new_visit=1&h=0");
}
@Test
public void testSetURL() throws Exception {
Tracker tracker = createTracker();
tracker.setApplicationDomain("test.com");
assertEquals(tracker.getApplicationDomain(), "test.com");
assertEquals(tracker.getApplicationBaseURL(), "http://test.com");
assertEquals(tracker.getParamURL(), "http://test.com/");
tracker.set(QueryParams.URL_PATH, "me");
assertEquals(tracker.getParamURL(), "http://test.com/me");
// override protocol
tracker.set(QueryParams.URL_PATH, "https://my.com/secure");
assertEquals(tracker.getParamURL(), "https://my.com/secure");
}
@Test
public void testSetApplicationDomain() throws Exception {
Tracker tracker = createTracker();
tracker
.setApplicationDomain("my-domain.com")
.trackScreenView("test/test", "Test title");
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
validateDefaultQuery(queryParams);
assertTrue(queryParams.get(QueryParams.URL_PATH).equals("http://my-domain.com/test/test"));
}
@Test(expected = IllegalArgumentException.class)
public void testSetTooShortVistorId() throws MalformedURLException {
Tracker tracker = createTracker();
String tooShortVisitorId = "0123456789ab";
tracker.setVisitorId(tooShortVisitorId);
assertNotEquals(tooShortVisitorId, tracker.getVisitorId());
}
@Test(expected = IllegalArgumentException.class)
public void testSetTooLongVistorId() throws MalformedURLException {
Tracker tracker = createTracker();
String tooLongVisitorId = "0123456789abcdefghi";
tracker.setVisitorId(tooLongVisitorId);
assertNotEquals(tooLongVisitorId, tracker.getVisitorId());
}
@Test(expected = IllegalArgumentException.class)
public void testSetVistorIdWithInvalidCharacters() throws MalformedURLException {
Tracker tracker = createTracker();
String invalidCharacterVisitorId = "01234-6789-ghief";
tracker.setVisitorId(invalidCharacterVisitorId);
assertNotEquals(invalidCharacterVisitorId, tracker.getVisitorId());
}
@Test
public void testSetVistorId() throws Exception {
Tracker tracker = createTracker();
String visitorId = "0123456789abcdef";
tracker.setVisitorId(visitorId);
assertEquals(visitorId, tracker.getVisitorId());
tracker.beforeTracking();
assertTrue(tracker.getQuery().contains("_id=" + visitorId));
}
@Test
public void testSetUserId() throws Exception {
Tracker tracker = createTracker();
tracker.setUserId("test");
assertEquals(tracker.getUserId(), "test");
tracker.clearUserId();
assertNull(tracker.getUserId());
tracker.setUserId("");
assertNull(tracker.getUserId());
tracker.setUserId(null);
assertNull(tracker.getUserId());
tracker.setUserId("X98F6bcd4621d373");
assertEquals(tracker.getUserId(), "X98F6bcd4621d373");
}
@Test
public void testSetUserIdLong() throws Exception {
Tracker tracker = createTracker();
tracker.setUserId(123456);
assertEquals(tracker.getUserId(), "123456");
}
@Test
public void testGetResolution() throws Exception {
Tracker tracker = createTracker();
tracker.setResolution(100, 200);
assertEquals(tracker.getQuery(), "?res=100x200&new_visit=1");
}
@Test
public void testSetUserCustomVariable() throws Exception {
Tracker tracker = createTracker();
tracker.setUserCustomVariable(1, "2& ?", "3@
tracker.trackScreenView("");
String event = tracker.getLastEvent();
Map<String, String> queryParams = parseEventUrl(event);
assertEquals(queryParams.get("_cvar"), "{'1':['2& ?','3@#']}".replaceAll("'", "\""));
// check url encoding
assertTrue(event.contains("_cvar=%7B%221%22%3A%5B%222%26%20%3F%22%2C%223%40%23%22%5D%7D"));
}
@Test
public void testSetScreenCustomVariable() throws Exception {
Tracker tracker = createTracker();
tracker.setScreenCustomVariable(1, "2", "3");
tracker.trackScreenView("");
String event = tracker.getLastEvent();
Map<String, String> queryParams = parseEventUrl(event);
assertEquals(queryParams.get("cvar"), "{'1':['2','3']}".replaceAll("'", "\""));
}
@Test
public void testSetNewSession() throws Exception {
Tracker tracker = createTracker();
assertEquals(tracker.getQuery(), "?new_visit=1");
tracker.trackScreenView("");
assertEquals(tracker.getQuery(), "");
tracker.trackScreenView("");
assertEquals(tracker.getQuery(), "");
tracker.setNewSession();
assertEquals(tracker.getQuery(), "?new_visit=1");
}
@Test
public void testSetSessionTimeout() throws Exception {
Tracker tracker = createTracker();
tracker.setSessionTimeout(10);
assertFalse(tracker.isExpired());
tracker.setSessionTimeout(0);
Thread.sleep(1, 0);
assertTrue(tracker.isExpired());
tracker.setSessionTimeout(10);
assertFalse(tracker.isExpired());
}
@Test
public void testCheckSessionTimeout() throws Exception {
Tracker tracker = createTracker();
tracker.setSessionTimeout(0);
assertEquals(tracker.getQuery(), "?new_visit=1");
tracker.afterTracking();
Thread.sleep(1, 0);
tracker.checkSessionTimeout();
assertEquals(tracker.getQuery(), "?new_visit=1");
}
@Test
public void testTrackScreenView() throws Exception {
Tracker tracker = createTracker();
tracker.trackScreenView("/test/test");
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertTrue(queryParams.get(QueryParams.URL_PATH).endsWith("/test/test"));
validateDefaultQuery(queryParams);
}
@Test
public void testTrackScreenWithTitleView() throws Exception {
Tracker tracker = createTracker();
tracker.trackScreenView("test/test", "Test title");
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertTrue(queryParams.get(QueryParams.URL_PATH).endsWith("/test/test"));
assertEquals(queryParams.get(QueryParams.ACTION_NAME), "Test title");
validateDefaultQuery(queryParams);
}
private void checkEvent(QueryHashMap<String, String> queryParams, String name, String value) {
assertEquals(queryParams.get(QueryParams.EVENT_CATEGORY), "category");
assertEquals(queryParams.get(QueryParams.EVENT_ACTION), "test action");
assertEquals(queryParams.get(QueryParams.EVENT_NAME), name);
assertEquals(queryParams.get(QueryParams.EVENT_VALUE), value);
validateDefaultQuery(queryParams);
}
@Test
public void testTrackEvent() throws Exception {
Tracker tracker = createTracker();
tracker.trackEvent("category", "test action");
checkEvent(parseEventUrl(tracker.getLastEvent()), null, null);
}
@Test
public void testTrackEventName() throws Exception {
Tracker tracker = createTracker();
String name = "test name2";
tracker.trackEvent("category", "test action", name);
checkEvent(parseEventUrl(tracker.getLastEvent()), name, null);
}
@Test
public void testTrackEventNameAndValue() throws Exception {
Tracker tracker = createTracker();
String name = "test name3";
tracker.trackEvent("category", "test action", name, 1);
checkEvent(parseEventUrl(tracker.getLastEvent()), name, "1");
}
@Test
public void testTrackGoal() throws Exception {
Tracker tracker = createTracker();
tracker.trackGoal(1);
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertNull(queryParams.get(QueryParams.REVENUE));
assertEquals(queryParams.get(QueryParams.GOAL_ID), "1");
validateDefaultQuery(queryParams);
}
@Test
public void testTrackGoalRevenue() throws Exception {
Tracker tracker = createTracker();
tracker.trackGoal(1, 100);
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertEquals(queryParams.get(QueryParams.GOAL_ID), "1");
assertEquals(queryParams.get(QueryParams.REVENUE), "100");
validateDefaultQuery(queryParams);
}
@Test
public void testTrackGoalInvalidId() throws Exception {
Tracker tracker = createTracker();
tracker.trackGoal(-1, 100);
assertNull(tracker.getLastEvent());
}
private boolean checkNewAppDownload(QueryHashMap<String, String> queryParams) {
assertTrue(queryParams.get(QueryParams.DOWNLOAD).length() > 0);
assertTrue(queryParams.get(QueryParams.URL_PATH).length() > 0);
assertEquals(queryParams.get(QueryParams.EVENT_CATEGORY), "Application");
assertEquals(queryParams.get(QueryParams.EVENT_ACTION), "downloaded");
assertEquals(queryParams.get(QueryParams.ACTION_NAME), "application/downloaded");
validateDefaultQuery(queryParams);
return true;
}
@Test
public void testTrackAppDownload() throws Exception {
Tracker tracker = createTracker();
tracker.trackAppDownload();
checkNewAppDownload(parseEventUrl(tracker.getLastEvent()));
tracker.clearLastEvent();
// track only once
tracker.trackAppDownload();
assertNull(tracker.getLastEvent());
}
@Test
public void testTrackNewAppDownload() throws Exception {
Tracker tracker = createTracker();
tracker.trackNewAppDownload(Robolectric.application);
checkNewAppDownload(parseEventUrl(tracker.getLastEvent()));
tracker.clearLastEvent();
tracker.trackNewAppDownload(Robolectric.application);
checkNewAppDownload(parseEventUrl(tracker.getLastEvent()));
}
@Test
public void testTrackContentImpression() throws Exception {
Tracker tracker = createTracker();
String name = "test name2";
tracker.trackContentImpression(name, "test", "test2");
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertEquals(queryParams.get(QueryParams.CONTENT_NAME), name);
assertEquals(queryParams.get(QueryParams.CONTENT_PIECE), "test");
assertEquals(queryParams.get(QueryParams.CONTENT_TARGET), "test2");
validateDefaultQuery(queryParams);
}
@Test
public void testTrackContentInteraction() throws Exception {
Tracker tracker = createTracker();
String interaction = "interaction";
String name = "test name2";
tracker.trackContentInteraction(interaction, name, "test", "test2");
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertEquals(queryParams.get(QueryParams.CONTENT_INTERACTION), interaction);
assertEquals(queryParams.get(QueryParams.CONTENT_NAME), name);
assertEquals(queryParams.get(QueryParams.CONTENT_PIECE), "test");
assertEquals(queryParams.get(QueryParams.CONTENT_TARGET), "test2");
validateDefaultQuery(queryParams);
}
@Test
public void testTrackException() throws Exception {
Tracker tracker = createTracker();
tracker.trackException("ClassName:10+2 2", "<Null> exception", false);
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
assertEquals(queryParams.get(QueryParams.EVENT_CATEGORY), "Exception");
assertEquals(queryParams.get(QueryParams.EVENT_ACTION), "ClassName:10+2 2");
assertEquals(queryParams.get(QueryParams.EVENT_NAME), "<Null> exception");
validateDefaultQuery(queryParams);
}
@Test
public void testTrackUncaughtExceptionHandler() throws Exception {
Tracker tracker = createTracker();
try {
//noinspection NumericOverflow
int i = 1 / 0;
assertNotEquals(i, 0);
} catch (Exception e) {
tracker.customUEH.uncaughtException(Thread.currentThread(), e);
}
QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
validateDefaultQuery(queryParams);
assertEquals(queryParams.get(QueryParams.EVENT_CATEGORY), "Exception");
assertTrue(queryParams.get(QueryParams.EVENT_ACTION)
.startsWith("org.piwik.sdk.TrackerTest/testTrackUncaughtExceptionHandler"));
assertEquals(queryParams.get(QueryParams.EVENT_NAME), "/ by zero");
assertEquals(queryParams.get(QueryParams.EVENT_VALUE), "1");
}
@Test
public void testGetParamUlr() throws Exception {
Tracker tracker = createTracker();
String[] paths = new String[]{null, "", "/",};
for (String path : paths) {
tracker.trackScreenView(path);
assertEquals(tracker.getParamURL(), "http://org.piwik.sdk.test/");
}
}
@Test
public void testSetAPIUrl() throws Exception {
Tracker tracker = createTracker();
try {
tracker.setAPIUrl(null);
} catch (MalformedURLException e) {
assertTrue(e.getMessage().contains("provide the Piwik Tracker URL!"));
}
String[] urls = new String[]{
"https://demo.org/piwik/piwik.php",
"https://demo.org/piwik/",
"https://demo.org/piwik",
};
for (String url : urls) {
tracker.setAPIUrl(url);
assertEquals(tracker.getAPIUrl(), "https://demo.org/piwik/piwik.php");
}
tracker.setAPIUrl("http://demo.org/piwik-proxy.php");
assertEquals(tracker.getAPIUrl(), "http://demo.org/piwik-proxy.php");
}
@Test
public void testSetUserAgent() throws MalformedURLException {
Tracker tracker = createTracker();
String defaultUserAgent = "aUserAgent";
String customUserAgent = "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0";
System.setProperty("http.agent", "aUserAgent");
assertEquals(tracker.getUserAgent(), defaultUserAgent);
tracker.setUserAgent(customUserAgent);
assertEquals(tracker.getUserAgent(), customUserAgent);
tracker.setUserAgent(null);
assertEquals(tracker.getUserAgent(), defaultUserAgent);
}
private static class QueryHashMap<String, V> extends HashMap<String, V> {
private QueryHashMap() {
super(10);
}
public V get(QueryParams key) {
return get(key.toString());
}
}
private static QueryHashMap<String, String> parseEventUrl(String url) throws Exception {
QueryHashMap<String, String> values = new QueryHashMap<String, String>();
List<NameValuePair> params = URLEncodedUtils.parse(new URI("http://localhost/" + url), "UTF-8");
for (NameValuePair param : params) {
values.put(param.getName(), param.getValue());
}
return values;
}
private static void validateDefaultQuery(QueryHashMap<String, String> params) {
assertEquals(params.get(QueryParams.SITE_ID), "1");
assertEquals(params.get(QueryParams.RECORD), "1");
assertEquals(params.get(QueryParams.SEND_IMAGE), "0");
assertEquals(params.get(QueryParams.VISITOR_ID).length(), 16);
assertEquals(params.get(QueryParams.LANGUAGE), "en");
assertTrue(params.get(QueryParams.URL_PATH).startsWith("http:
assertTrue(Integer.parseInt(params.get(QueryParams.RANDOM_NUMBER)) > 0);
}
}
|
package git4idea.log;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile;
import com.intellij.util.NotNullFunction;
import com.intellij.vcs.log.*;
import com.intellij.vcs.log.impl.VcsRefImpl;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.util.List;
import static junit.framework.Assert.assertEquals;
/**
* @author erokhins
*/
public class RefParserTest {
public String toStr(VcsRef ref) {
return String.format("%s TAG %s", ref.getCommitHash().asString(), ref.getName());
}
public void runTest(String inputStr, String outStr) {
List<VcsRef> refs = new RefParser(new TestLogObjectsFactory()).parseCommitRefs(inputStr, NullVirtualFile.INSTANCE);
StringBuilder s = new StringBuilder();
for (VcsRef ref : refs) {
if (s.length() > 0) {
s.append("\n");
}
s.append(toStr(ref));
}
assertEquals(outStr, s.toString());
}
@Test
public void tagTest() {
runTest("22762ebf7203f6a2888425a3207d2ddc63085dd7 (tag: refs/tags/v3.6-rc1, refs/heads/br)",
"22762ebf7203f6a2888425a3207d2ddc63085dd7 TAG v3.6-rc1");
}
@Test
public void severalRefsTest() {
runTest("f85125c (refs/tags/v3.6-rc1, HEAD)", "f85125c TAG v3.6-rc1");
}
@Test
public void severalRefsTest2() {
runTest("ed7a0d14da090ea256d68a06c6f8dd7311de192e (refs/tags/category/v3.6-rc1, HEAD, refs/remotes/origin/graph_fix)",
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG category/v3.6-rc1");
}
@Test
public void severalRefsTest3() {
runTest("ed7a0d14da090ea256d68a06c6f8dd7311de192e (tag: refs/tags/web/130.1599, tag: refs/tags/ruby/130.1597, " +
"tag: refs/tags/py/130.1598, " +
"tag: refs/tags/php/130.1596, tag: refs/tags/idea/130.1601, tag: refs/tags/app/130.1600)",
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG web/130.1599\n" +
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG ruby/130.1597\n" +
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG py/130.1598\n" +
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG php/130.1596\n" +
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG idea/130.1601\n" +
"ed7a0d14da090ea256d68a06c6f8dd7311de192e TAG app/130.1600"
);
}
private class TestLogObjectsFactory implements VcsLogObjectsFactory {
@NotNull
@Override
public Hash createHash(@NotNull String stringHash) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public VcsCommit createCommit(@NotNull Hash hash, @NotNull List<Hash> parents) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public TimedVcsCommit createTimedCommit(@NotNull Hash hash, @NotNull List<Hash> parents, long timeStamp) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public VcsShortCommitDetails createShortDetails(@NotNull Hash hash, @NotNull List<Hash> parents, long timeStamp, VirtualFile root,
@NotNull String subject, @NotNull String authorName, String authorEmail) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public VcsFullCommitDetails createFullDetails(@NotNull Hash hash, @NotNull List<Hash> parents, long authorTime, VirtualFile root,
@NotNull String subject, @NotNull String authorName, @NotNull String authorEmail,
@NotNull String message, @NotNull String committerName, @NotNull String committerEmail,
long commitTime, @NotNull List<Change> changes,
@NotNull ContentRevisionFactory contentRevisionFactory) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public VcsUser createUser(@NotNull String name, @NotNull String email) {
throw new UnsupportedOperationException();
}
@NotNull
@Override
public VcsRef createRef(@NotNull Hash commitHash, @NotNull String name, @NotNull VcsRefType type, @NotNull VirtualFile root) {
return new VcsRefImpl(new NotNullFunction<Hash, Integer>() {
@NotNull
@Override
public Integer fun(Hash dom) {
return Integer.parseInt(dom.asString().substring(0, Math.min(4, dom.asString().length())), 16);
}
}, commitHash, name, type, root);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.